harperdb 4.2.0-alpha.11 → 4.2.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +32 -32
- package/bin/lite.js +19 -19
- package/index.js +0 -1
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +16 -16
- package/launchServiceScripts/launchNatsReplyService.js +16 -16
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +16 -16
- package/package.json +6 -6
- package/resources/analytics.d.ts +9 -0
- package/resources/databases.d.ts +7 -0
- package/server/jobs/jobProcess.js +16 -16
- package/server/threads/threadServer.js +19 -19
- package/utility/scripts/restartHdb.js +16 -16
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
"use strict";var bB=Object.create;var xa=Object.defineProperty;var yB=Object.getOwnPropertyDescriptor;var IB=Object.getOwnPropertyNames;var wB=Object.getPrototypeOf,CB=Object.prototype.hasOwnProperty;var o=(e,t)=>xa(e,"name",{value:t,configurable:!0});var pe=(e,t)=>()=>(e&&(t=e(e=0)),t);var m=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ze=(e,t)=>{for(var r in t)xa(e,r,{get:t[r],enumerable:!0})},QT=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of IB(t))!CB.call(e,n)&&n!==r&&xa(e,n,{get:()=>t[n],enumerable:!(s=yB(t,n))||s.enumerable});return e};var D=(e,t,r)=>(r=e!=null?bB(wB(e)):{},QT(t||!e||!e.__esModule?xa(r,"default",{value:e,enumerable:!0}):r,e)),re=e=>QT(xa({},"__esModule",{value:!0}),e);var XT=m((cte,JT)=>{var UB=require("fast-glob"),{statSync:nE,existsSync:iE,readFileSync:DB,writeFileSync:LB}=require("fs"),{spawnSync:MB,spawn:PB}=require("child_process"),{isMainThread:vB}=require("worker_threads"),{join:Os,relative:zT}=require("path"),{PACKAGE_ROOT:mr}=g(),{tmpdir:BB}=require("os");require("source-map-support").install();var HB=["resources","server","dataLayer"],ka="ts-build",aE,FB=__filename.endsWith("tsBuild.js");if(FB){if(vB){let r;try{nE(Os(mr,ka)),r=!0}catch{}if(r)for(let s of UB.sync(HB.map(n=>n+"/**/*.ts"),{cwd:mr})){let n=0,i=0;try{n=nE(Os(mr,s)).mtimeMs-5e3,i=nE(Os(mr,ka,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),aE=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),aE=!0;if(aE){let s=MB(process.argv[0],[Os(mr,"node_modules/.bin/tsc")],{cwd:mr});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let n=Os(BB(),"harperdb-tsc.pid"),i;if(iE(n))try{process.kill(+DB(n,{encoding:"utf8"}),0),i=!0}catch{}if(!i){console.log("starting tsc background process");let a=PB(process.argv[0],[Os(mr,"node_modules/.bin/tsc"),"--watch"],{cwd:mr,detached:!0,stdio:"ignore"});LB(n,a.pid.toString()),a.unref()}}}}let e=JT.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(mr)&&!s[0].includes("node_modules")){let i=zT(mr,s[0]),a;i.startsWith(ka)?a=Os(mr,zT(ka,i)):a=Os(mr,ka,i);let c=Os(a,r),u=c+".js";if(iE(u))return u;if(c.includes(".")&&iE(c))return c}return t(r,s,n)}}});var g=m((_te,_R)=>{"use strict";var Sr=require("path"),qB=require("fs"),{relative:ute,join:lte}=Sr,{existsSync:GB}=qB;function xB(){let e=__dirname;for(;!GB(Sr.join(e,"package.json"));){let t=Sr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}o(xB,"getHDBPackageRoot");var nn=xB(),ZT="js",nu=ZT,kB="harperdb-config.yaml",VB="defaultConfig.yaml",$B="hdb",jT=`harperdb.${nu}`,eR=`customFunctionsServer.${nu}`,YB=`restartHdb.${nu}`,cE="HarperDB",su="Custom Functions",iu="Clustering Hub",au="Clustering Leaf",KB="Clustering Ingest Service",WB="Clustering Reply Service",QB="foreground.pid",zB="hdb.pid",JB="data",XB={HDB:cE,CLUSTERING_HUB:iu,CLUSTERING_LEAF:au,CLUSTERING_INGEST_SERVICE:KB,CLUSTERING_REPLY_SERVICE:WB,CUSTOM_FUNCTIONS:su,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},ZB={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},jB={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},eH={harperdb:cE,"clustering hub":iu,"clustering leaf":au,"custom functions":su,custom_functions:su,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},tH={CLUSTERING_HUB_PROC_DESCRIPTOR:iu,CLUSTERING_LEAF_PROC_DESCRIPTOR:au},oE={HDB:Sr.join(nn,"server/harperdb"),CUSTOM_FUNCTIONS:Sr.join(nn,"server/customFunctions"),CLUSTERING_HUB:Sr.join(nn,"server/nats"),CLUSTERING_LEAF:Sr.join(nn,"server/nats")},rH={HDB:Sr.join(oE.HDB,jT),CUSTOM_FUNCTIONS:Sr.join(oE.CUSTOM_FUNCTIONS,eR)},sH={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Sr.join(nn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Sr.join(nn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Sr.join(nn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},nH={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},tR="support@harperdb.io",iH="customer-success@harperdb.io",rR=1,aH=4141,sR="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",oH="https://www.harperdb.io/product",cH=`For support, please submit a request at ${sR} or contact ${tR}`,nR=`For license support, please contact ${iH}`,uH="None of the specified records were found.",lH="hash attribute not found",_H=`Your current license only supports ${rR} role. ${nR}`,dH="Your current license only supports 3 connections to a node.",EH="127.0.0.1",fH=1,hH=/^\.$/,mH=/^\.\.$/,SH="U+002E",pH=/\//g,TH="U+002F",RH=/U\+002F/g,gH=/^U\+002E$/,AH=/^U\+002EU\+002E$/,OH="d",NH=999999,bH="*",yH="--max-old-space-size=",IH="system",wH="__hdb_hash",CH=".harperdb",UH=".hdb",DH="keys",LH="hdb_boot_properties.file",MH=".updateConfig.json",PH="SIGTSTP",vH=24,BH=6e4,HH=448,FH="blob",qH="trash",GH="database",xH="schema",kH="transactions",VH=".count",$H="id",YH="PROCESS_NAME",iR={SETTINGS_PATH_KEY:"settings_path"},aR=require("lodash"),KH={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"},WH={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},QH={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},zH={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"},JH={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},tr="hdb_internal:",XH={CREATE_SCHEMA:tr+"create_schema",CREATE_TABLE:tr+"create_table",CREATE_ATTRIBUTE:tr+"create_attribute",ADD_USER:tr+"add_user",ALTER_USER:tr+"alter_user",DROP_USER:tr+"drop_user",HDB_NODES:tr+"hdb_nodes",HDB_USERS:tr+"hdb_users",HDB_WORKERS:tr+"hdb_workers",CATCHUP:tr+"catchup",SCHEMA_CATCHUP:tr+"schema_catchup",WORKER_ROOM:tr+"cluster_workers"},ZH={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"},jH="060493.ks",e0=".license",t0={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},$={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},r0={CSV:".csv",JSON:".json"},s0={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},n0={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Va={};Va[$.INSERT]=$.INSERT;Va[$.UPDATE]=$.UPDATE;Va[$.UPSERT]=$.UPSERT;Va[$.DELETE]=$.DELETE;var Ae=Object.create(null);Ae[$.DESCRIBE_ALL]=$.DESCRIBE_ALL;Ae[$.DESCRIBE_TABLE]=$.DESCRIBE_TABLE;Ae[$.DESCRIBE_SCHEMA]=$.DESCRIBE_SCHEMA;Ae[$.READ_LOG]=$.READ_LOG;Ae[$.ADD_NODE]=$.ADD_NODE;Ae[$.LIST_USERS]=$.LIST_USERS;Ae[$.LIST_ROLES]=$.LIST_ROLES;Ae[$.USER_INFO]=$.USER_INFO;Ae[$.SQL]=$.SQL;Ae[$.GET_JOB]=$.GET_JOB;Ae[$.SEARCH_JOBS_BY_START_DATE]=$.SEARCH_JOBS_BY_START_DATE;Ae[$.DELETE_FILES_BEFORE]=$.DELETE_FILES_BEFORE;Ae[$.EXPORT_LOCAL]=$.EXPORT_LOCAL;Ae[$.EXPORT_TO_S3]=$.EXPORT_TO_S3;Ae[$.CLUSTER_STATUS]=$.CLUSTER_STATUS;Ae[$.REMOVE_NODE]=$.REMOVE_NODE;Ae[$.RESTART]=$.RESTART;Ae[$.CUSTOM_FUNCTIONS_STATUS]=$.CUSTOM_FUNCTIONS_STATUS;Ae[$.GET_CUSTOM_FUNCTIONS]=$.GET_CUSTOM_FUNCTIONS;Ae[$.GET_CUSTOM_FUNCTION]=$.GET_CUSTOM_FUNCTION;Ae[$.SET_CUSTOM_FUNCTION]=$.SET_CUSTOM_FUNCTION;Ae[$.DROP_CUSTOM_FUNCTION]=$.DROP_CUSTOM_FUNCTION;Ae[$.ADD_CUSTOM_FUNCTION_PROJECT]=$.ADD_CUSTOM_FUNCTION_PROJECT;Ae[$.DROP_CUSTOM_FUNCTION_PROJECT]=$.DROP_CUSTOM_FUNCTION_PROJECT;Ae[$.PACKAGE_CUSTOM_FUNCTION_PROJECT]=$.PACKAGE_CUSTOM_FUNCTION_PROJECT;Ae[$.DEPLOY_CUSTOM_FUNCTION_PROJECT]=$.DEPLOY_CUSTOM_FUNCTION_PROJECT;var i0={DEBUG:"debug",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status"},a0={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},oR={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},o0=aR.invert(oR),R={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root",HTTP_THREADS:"http_threads",HTTP_SESSION_AFFINITY:"http_sessionAffinity",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT:"operationsApi_authentication_operationTokenTimeout",OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT:"operationsApi_authentication_refreshTokenTimeout",OPERATIONSAPI_FOREGROUND:"operationsApi_foreground",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERT_AUTH:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",OPERATIONSAPI_NODEENV:"operationsApi_nodeEnv",ROOTPATH:"rootPath",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",SCHEMAS:"schemas",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication"},cR={settings_path:iR.SETTINGS_PATH_KEY,hdb_root_key:R.ROOTPATH,hdb_root:R.ROOTPATH,server_port_key:R.OPERATIONSAPI_NETWORK_PORT,server_port:R.OPERATIONSAPI_NETWORK_PORT,cert_key:R.OPERATIONSAPI_TLS_CERTIFICATE,certificate:R.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:R.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:R.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:R.OPERATIONSAPI_NETWORK_HTTPS,https_on:R.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:R.OPERATIONSAPI_NETWORK_CORS,cors_on:R.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:R.LOGGING_LEVEL,log_level:R.LOGGING_LEVEL,log_path_key:R.LOGGING_ROOT,log_path:R.LOGGING_ROOT,props_env_key:R.OPERATIONSAPI_NODEENV,node_env:R.OPERATIONSAPI_NODEENV,clustering_node_name_key:R.CLUSTERING_NODENAME,node_name:R.CLUSTERING_NODENAME,clustering_enabled_key:R.CLUSTERING_ENABLED,clustering:R.CLUSTERING_ENABLED,max_http_threads:R.HTTP_THREADS,max_hdb_processes:R.HTTP_THREADS,server_timeout_key:R.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:R.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:R.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:R.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:R.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:R.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:R.LOGGING_AUDITLOG,disable_transaction_log:R.LOGGING_AUDITLOG,operation_token_timeout_key:R.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:R.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:R.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:R.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_enabled_key:R.CUSTOMFUNCTIONS_ENABLED,custom_functions:R.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:R.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:R.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:R.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:R.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:R.HTTP_THREADS,log_to_file:R.LOGGING_FILE,log_to_stdstreams:R.LOGGING_STDSTREAMS,run_in_foreground:R.OPERATIONSAPI_FOREGROUND,local_studio_on:R.LOCALSTUDIO_ENABLED,clustering_port:R.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:R.CLUSTERING_USER,clustering_enabled:R.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:R.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:R.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:R.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:R.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:R.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:R.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:R.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:R.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:R.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:R.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:R.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:R.CLUSTERING_NODENAME,clustering_tls_certificate:R.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:R.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:R.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:R.CLUSTERING_TLS_INSECURE,clustering_tls_verify:R.CLUSTERING_TLS_VERIFY,clustering_loglevel:R.CLUSTERING_LOGLEVEL,clustering_republishmessages:R.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:R.CLUSTERING_DATABASELEVEL,customfunctions_enabled:R.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:R.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:R.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:R.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:R.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:R.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:R.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:R.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:R.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:R.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:R.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:R.CUSTOMFUNCTIONS_NODEENV,http_threads:R.HTTP_THREADS,http_session_affinity:R.HTTP_SESSION_AFFINITY,customfunctions_processes:R.HTTP_THREADS,customfunctions_root:R.CUSTOMFUNCTIONS_ROOT,localstudio_enabled:R.LOCALSTUDIO_ENABLED,logging_file:R.LOGGING_FILE,logging_level:R.LOGGING_LEVEL,logging_root:R.LOGGING_ROOT,logging_rotation_enabled:R.LOGGING_ROTATION_ENABLED,logging_rotation_compress:R.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:R.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:R.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:R.LOGGING_ROTATION_PATH,logging_stdstreams:R.LOGGING_STDSTREAMS,logging_auditlog:R.LOGGING_AUDITLOG,logging_auditretention:R.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:R.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:R.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:R.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:R.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:R.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:R.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:R.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:R.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:R.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:R.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:R.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:R.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:R.OPERATIONSAPI_TLS_CERT_AUTH,operationsapi_network_timeout:R.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:R.OPERATIONSAPI_NODEENV,operationsapi_root:R.ROOTPATH,schemas:R.SCHEMAS,storage_path:R.STORAGE_PATH,ignorescripts:R.IGNORE_SCRIPTS,mqtt_network_port:R.MQTT_NETWORK_PORT,mqtt_websocket:R.MQTT_WEBSOCKET,mqtt_network_secureport:R.MQTT_NETWORK_SECUREPORT,mqtt_requireauthentication:R.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:R.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:R.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:R.AUTHENTICATION_CACHETTL,authentication_enablesessions:R.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:R.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:R.AUTHENTICATION_REFRESHTOKENTIMEOUT};for(let e in R){let t=R[e];cR[t.toLowerCase()]=t}var c0={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},u0={csv_file_load:"csv_file_load",csv_data_load:$.CSV_DATA_LOAD,csv_url_load:$.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"},l0={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"},_0={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},d0={VERSION_DEFAULT:"2.2.0"},E0={DEVELOPMENT:8192,DEFAULT:512},f0={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"},h0={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"},m0={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},uR={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},S0=Symbol("metadata"),p0="__clustering__",T0=Object.values(uR),R0=15984864e5,lR={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},g0=aR.invert(lR),A0={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"},O0=111,N0=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}
|
|
4
|
-
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),a=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=a}}))}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:sF.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"])}))}o(oF,"findPs")});var xe=m((Tte,wR)=>{"use strict";var cF="__dbis__",uF="__txns__",lF="__environment_name__",_F="__dbi_defintion__",dF={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"},EF=["__createdtime__","__updatedtime__"],fF="\uFFFF",IR={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},hF=Object.values(IR);wR.exports={AUDIT_STORE_NAME:uF,INTERNAL_DBIS_NAME:cF,DBI_DEFINITION_NAME:_F,SEARCH_TYPES:dF,TIMESTAMP_NAMES:EF,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:lF,TRANSACTIONS_DBI_NAMES_ENUM:IR,TRANSACTIONS_DBIS:hF,OVERFLOW_MARKER:fF}});var rr=m((Rte,HR)=>{"use strict";var CR=g(),UR=xe(),DR={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},LR=o(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),MR={500:LR("There was an error processing your request."),400:"Invalid request"},mF=MR[DR.INTERNAL_SERVER_ERROR],SF={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.`},pF={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},TF={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"},RF={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${UR.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${UR.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"},gF={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${CR.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 ${CR.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"},PR={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"},AF={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' not found`,SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},OF={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},NF={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},bF={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},yF={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`},vR={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.`},BR={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},IF={FUNCTION_STATUS:"Error getting custom function status, check the log for more details",GET_FUNCTIONS:"Error getting custom functions, check the log for more details",GET_FUNCTION:"Error getting custom function, check the log for more details",SET_FUNCTION:"Error setting custom function, check the log for more details",NO_PROJECT:"Project does not exist. Create one using 'add_custom_function_project'",PROJECT_EXISTS:"Project already exists",VALIDATION_ERR:"Error validating request, check the log for more details",NO_FILE:"File does not exist",BAD_FILE_NAME:"File name can only contain alphanumeric, dash and underscore characters",BAD_PROJECT_NAME:"Project name can only contain alphanumeric, dash and underscores characters",BAD_PACKAGE:"Packaged project must be base64-encoded tar file of project directory",DROP_FUNCTION:"Error dropping custom function, check the log for more details",ADD_FUNCTION:"Error adding custom function project, check the log for more details",DROP_FUNCTION_PROJECT:"Error dropping custom function project, check the log for more details",BAD_FILE_PATH:"Filepath must be valid, and contain the name of the tarball you wish to write",NOT_ENABLED:"Custom functions is not enabled, to enable set fastifyRoutes enabled to true in hdb/harperdb-config.yaml file."},wF={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},CF={...PR,...TF,...SF,...AF,...OF,...NF,...bF,...yF,...gF,...vR,...BR,...IF,...wF,...pF};HR.exports={CHECK_LOGS_WRAPPER:LR,HDB_ERROR_MSGS:CF,DEFAULT_ERROR_MSGS:MR,DEFAULT_ERROR_RESP:mF,HTTP_STATUS_CODES:DR,LMDB_ERRORS_ENUM:RF,AUTHENTICATION_ERROR_MSGS:PR,VALIDATION_ERROR_MSGS:vR,ITC_ERRORS:BR}});var W=m((Ate,GR)=>{"use strict";var Pi=rr(),UF=q(),DF=g(),_u=class extends Error{static{o(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,FR),this.http_resp_code=s||Pi.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Pi.DEFAULT_ERROR_MSGS[s]?Pi.DEFAULT_ERROR_MSGS[s]:Pi.DEFAULT_ERROR_MSGS[Pi.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&UF[n](i)}},SE=class extends Error{static{o(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.http_resp_code=r||400,t;super(t),this.http_resp_code=r||400}},pE=class extends Error{static{o(this,"ServerError")}constructor(t,r){super(t),this.http_resp_code=r||500}};function FR(e,t,r,s=DF.LOG_LEVELS.ERROR,n=null,i=!1){if(qR(e))return e;let a=new _u(e,t,r,s,n);return i&&delete a.stack,a}o(FR,"handleHDBError");function qR(e){return e.__proto__.constructor.name===_u.name}o(qR,"isHDBError");GR.exports={isHDBError:qR,handleHDBError:FR,ClientError:SE,ServerError:pE,hdb_errors:Pi}});var we=m((Nte,WR)=>{"use strict";var ja=g(),LF=x(),Pt=Q(),eo=require("path"),MF=require("minimist"),xR=require("fs-extra"),kR=require("lodash");Pt.initSync();var{CONFIG_PARAMS:an,SCHEMAS_PARAM_CONFIG:za,SYSTEM_SCHEMA_NAME:du}=ja,Ja,Xa,Za;function VR(){if(Ja!==void 0)return Ja;if(Pt.getHdbBasePath()!==void 0)return Ja=Pt.get(an.STORAGE_PATH)||eo.join(Pt.getHdbBasePath(),ja.DATABASES_DIR_NAME),Ja}o(VR,"getBaseSchemaPath");function $R(){if(Xa!==void 0)return Xa;if(Pt.getHdbBasePath()!==void 0)return Xa=KR(du),Xa}o($R,"getSystemSchemaPath");function YR(){if(Za!==void 0)return Za;if(Pt.getHdbBasePath()!==void 0)return Za=Pt.get(ja.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||eo.join(Pt.getHdbBasePath(),ja.TRANSACTIONS_DIR_NAME),Za}o(YR,"getTransactionAuditStoreBasePath");function PF(e,t){let r=Pt.get(an.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||eo.join(YR(),e.toString())}o(PF,"getTransactionAuditStorePath");function KR(e,t){e=e.toString(),t=t&&t.toString();let r=Pt.get(ja.CONFIG_PARAMS.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.path||r?.path||eo.join(VR(),e)}o(KR,"getSchemaPath");function vF(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,MF(process.argv));let s=r[an.SCHEMAS.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(a){if(!LF.isObject(s))throw a;i=s}for(let a of i){let c=a[du];if(!c)continue;let u=Pt.get(an.SCHEMAS);u=u??{};let l=c?.tables?.[t]?.[za.PATH];if(l)return kR.set(u,[du,za.TABLES,t,za.PATH],l),Pt.setProperty(an.SCHEMAS,u),l;let _=c?.[za.PATH];if(_)return kR.set(u,[du,za.PATH],_),Pt.setProperty(an.SCHEMAS,u),_}}let n=r[an.STORAGE_PATH.toUpperCase()];if(n){if(!xR.pathExistsSync(n))throw new Error(n+" does not exist");let i=eo.join(n,e);return xR.mkdirsSync(i),Pt.setProperty(an.STORAGE_PATH,n),i}return $R()}o(vF,"initSystemSchemaPaths");function BF(){Ja=void 0,Xa=void 0,Za=void 0}o(BF,"resetPaths");WR.exports={getBaseSchemaPath:VR,getSystemSchemaPath:$R,getTransactionAuditStorePath:PF,getTransactionAuditStoreBasePath:YR,getSchemaPath:KR,initSystemSchemaPaths:vF,resetPaths:BF}});var vt=m((wte,ZR)=>{"use strict";var HF=rr().LMDB_ERRORS_ENUM,yte=require("lmdb"),FF=xe(),Ite=require("buffer").Buffer,{OVERFLOW_MARKER:QR,MAX_SEARCH_KEY_LENGTH:Eu}=FF,zR=["number","string","symbol","boolean","bigint"];function qF(e){if(e=e?.primaryStore||e,!e)throw new Error(HF.ENV_REQUIRED)}o(qF,"validateEnv");function GF(e){if(e==null)return null;let t;try{t=typeof e=="object"?JSON.stringify(e):e.toString()}catch{t=e.toString()}return t}o(GF,"stringifyData");function xF(e){return e instanceof Date?e.valueOf():e}o(xF,"convertKeyValueToWrite");function kF(e){if(e==null)return;if(zR.includes(typeof e))return e.length>Eu?[e.slice(0,Eu)+QR]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];if(zR.includes(typeof n))n.length>Eu?t.push(n.slice(0,Eu)+QR):t.push(n);else if(n instanceof Date)return t.push(n.getTime())}}else if(e instanceof Date)return[e.getTime()];return t}o(kF,"getIndexedValues");var fu=0,JR=0;function XR(){JR=Date.now()-performance.now()}o(XR,"adjustStartTime");XR();var VF=6e4;setInterval(XR,VF).unref();function $F(){let e=performance.now()+JR;return e>fu?(fu=e,e):(fu+=488e-6,fu)}o($F,"getNextMonotonicTime");ZR.exports={validateEnv:qF,stringifyData:GF,convertKeyValueToWrite:xF,getNextMonotonicTime:$F,getIndexedValues:kF}});var jR,Jr,TE,to=pe(()=>{jR=require("events"),Jr=class extends jR.EventEmitter{static{o(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new TE;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},TE=class{static{o(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function ro(e){return e[Et]||(e[Et]=Object.create(null))}function Tu(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let a of n){let c=a.name,u={get(){let l=this[Et];if(l&&c in l)return l[c];let _=this[ce]?.[c];if(_&&typeof _=="object"){let d=eg(_,a);if(d)return l||(l=this[Et]=Object.create(null)),l[c]=d}return _},set(l){ro(this)[c]=l},enumerable:!0,configurable:!0};switch(u.get.isAttribute=!0,a.type){case"String":u.set=function(l){if(typeof l!="string")throw(0,hu.ClientError)(`${c} must be a string, attempt to assign ${l}`);ro(this)[c]=l};break;case"Int":u.set=function(l){if(typeof l!="number")throw(0,hu.ClientError)(`${c} must be a string, attempt to assign ${l}`);ro(this)[c]=l};break}s[c]=u,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,u)}i("getProperty",function(a){let c=s[a];if(c)return c.get.call(this);let u=this[Et];return u?.[a]!==void 0?u[a]:this[ce]?.[a]}),i("set",function(a,c){let u=s[a];if(u)return u.set.call(this,c);if(t.sealed)throw new hu.ClientError("Can not add a property to a sealed table schema");ro(this)[a]=c}),i("deleteProperty",function(a){ro(this)[a]=void 0}),i("toJSON",function(){let a=this[Et],c;for(let l in a)c||(c=Object.assign({},this[ce])),c[l]=a[l];return Object.keys(this).length>0&&(c||(c=Object.assign({},this[ce])),Object.assign(c,this)),c||this[ce]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(a,c){Object.defineProperty(r,a,{value:c,configurable:!0})}o(i,"setMethod")}function eg(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{o(this,"TrackedObject")}constructor(n){this[ce]=n}},Tu(r,t)),new r(e)):new mu(e);case Array:let s=new pu(e.length);s[ce]=e;for(let n=0,i=e.length;n<i;n++){let a=e[n];a&&typeof a=="object"&&(a=eg(a,t?.elements)),s[n]=a}return s}}function Ru(e){let t=e[Et],r;for(let n in t){r||(r=Object.assign({},e[ce]));let i=t[n];i&&typeof i=="object"&&(i=Ru(i)),r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[ce])),Object.assign(r,e)),r||e[ce]}function so(e){let t;if(e[ce]&&e.constructor===Array&&!Object.isFrozen(e)){t=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let a=so(i);a!==i&&t===e&&(t=e.slice(0)),i=a}t[s]=i}return Object.freeze(t)}let r=e[Et];for(let s in r){t||(t=Object.assign({},e[ce]));let n=r[s];n&&typeof n=="object"&&(n=so(n)),t[s]=n}return t?Object.freeze(t):e[ce]||Object.freeze(e)}function Su(e){let t=e[ce];if(!t)return!0;if(e.constructor===Array){if(e[qn]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[ce]===n){if(Su(i))return!0}else return!0}}else{let r=e[Et];for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[ce]===i){if(Su(n))return!0}else return!0}else return!0}}return!1}var hu,Et,mu,qn,pu,gu=pe(()=>{Xr();hu=D(W()),Et=Symbol("own-data");o(ro,"getChanges");o(Tu,"assignTrackedAccessors");o(eg,"trackObject");mu=class{static{o(this,"GenericTrackedObject")}constructor(t){this[ce]=t}};Tu(mu,{});o(Ru,"collapseData");o(so,"deepFreeze");o(Su,"hasChanges");qn=Symbol.for("has-array-changes"),pu=class extends Array{static{o(this,"TrackedArray")}[qn];constructor(t){super(t)}splice(...t){return this[qn]=!0,super.splice(...t)}push(...t){return this[qn]=!0,super.push(...t)}pop(){return this[qn]=!0,super.pop()}unshift(...t){return this[qn]=!0,super.unshift(...t)}shift(){return this[qn]=!0,super.shift()}};pu.prototype.constructor=Array});function Ye(e,t){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let r=e.transaction=new RE;e.timestamp&&(r.timestamp=e.timestamp),r[Oe]=e,e.resourceCache=[];let s;try{if(s=t(r),s?.then)return s.then(n,i)}catch(a){i(a)}return n(s);function n(a){let c=r.commit();return c.then?c.then(()=>(e.transaction=null,a)):(e.transaction=null,a)}function i(a){throw r.abort(),e.transaction=null,a}}var tg,rg,RE,Gn=pe(()=>{tg=D(vt()),rg=require("../index");Xr();o(Ye,"transaction");(0,rg._assignPackageExport)("transaction",Ye);Ye.commit=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ye.abort=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()};RE=class extends Array{static{o(this,"TransactionSet")}commit(t=!0){let r=[],s=this.length;for(let n=0;n<s;n++)this[n].validate?.();this.timestamp||(this.timestamp=(0,tg.getNextMonotonicTime)());for(let n=0;n<s;n++){let a=this[n].commit(this.timestamp,t);a?.then&&r.push(a)}return r.length>0?Promise.all(r).then(()=>(this.splice(0,s),this.commit(t))):this.length>s?(this.splice(0,s),this.commit(t)):(this.length=0,{txnTime:this.timestamp})}abort(){for(let t of this)t.abort?.()}doneReading(){for(let t of this)t.doneReading?.()}}});function OE(e,t,r,s,n){let i=e[0]??e.attribute,a,c,u,l,_=e[1]??e.value;_ instanceof Date&&(_=_.getTime());let d=e.comparator,E;switch(KF[d]||d){case"lt":a=!0,c=_;break;case"le":a=!0,c=_,u=!0;break;case"gt":a=_,l=!0;break;case"ge":a=_;break;case"prefix":a=_,c=_.slice(0),c[c.length-1]=jr.MAXIMUM_KEY;break;case"starts_with":a=_.toString(),c=_+String.fromCharCode(65535);break;case"between":a=_[0],a instanceof Date&&(a=a.getTime()),c=_[1],c instanceof Date&&(c=c.getTime()),u=!0;break;case ut.SEARCH_TYPES.EQUALS:case void 0:a=_,c=_,u=!0;break;case"ne":case"contains":case"ends_with":E=!0;break}if(r){let S=a;a=c,c=S,S=!l,l=!u,u=S}let f=i===s.primaryKey||i==null,h=f?s.primaryStore:s.indices[i];if(!h||h.isIndexing||E){if(!n)throw new gE.ClientError(`"${i}" is not indexed${h?.isIndexing?" yet":""}, can not search for this attribute`,404);let S=NE(e);if(!S)throw new gE.ClientError(`Unknown search operator ${e.comparator}`);return s.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:y,value:O})=>new Promise(H=>setImmediate(()=>H(S(O)?y:ng.SKIP))))}let T={start:a,end:c,inclusiveEnd:u,exclusiveStart:l,values:!f,transaction:t,reverse:r};return f?h.getRange(T):h.getRange(T).map(({value:S})=>S)}function NE(e){let t=e.comparator,r=e[0]??e.attribute,s=e[1]??e.value;switch(s instanceof Date&&(s=s.getTime()),t){case ut.SEARCH_TYPES.EQUALS:case void 0:return Zr(r,n=>n===s);case ut.SEARCH_TYPES.CONTAINS:return Zr(r,n=>n?.toString().includes(s));case ut.SEARCH_TYPES.ENDS_WITH:case ut.SEARCH_TYPES._ENDS_WITH:return Zr(r,n=>n?.toString().endsWith(s));case ut.SEARCH_TYPES.STARTS_WITH:case ut.SEARCH_TYPES._STARTS_WITH:return Zr(r,n=>typeof n=="string"&&n.startsWith(s));case ut.SEARCH_TYPES.BETWEEN:return s[0]instanceof Date&&(s[0]=s[0].getTime()),s[1]instanceof Date&&(s[1]=s[1].getTime()),Zr(r,n=>(0,jr.compareKeys)(n,s[0])>=0&&(0,jr.compareKeys)(n,s[1])<=0);case"gt":case ut.SEARCH_TYPES.GREATER_THAN:case ut.SEARCH_TYPES._GREATER_THAN:return Zr(r,n=>(0,jr.compareKeys)(n,s)>0);case"ge":case ut.SEARCH_TYPES.GREATER_THAN_EQUAL:case ut.SEARCH_TYPES._GREATER_THAN_EQUAL:return Zr(r,n=>(0,jr.compareKeys)(n,s)>=0);case ut.SEARCH_TYPES.LESS_THAN:case"lt":case ut.SEARCH_TYPES._LESS_THAN:return Zr(r,n=>(0,jr.compareKeys)(n,s)<0);case"le":case ut.SEARCH_TYPES.LESS_THAN_EQUAL:case ut.SEARCH_TYPES._LESS_THAN_EQUAL:return Zr(r,n=>(0,jr.compareKeys)(n,s)<=0);case"ne":return Zr(r,n=>(0,jr.compareKeys)(n,s)!==0);default:return}}function Zr(e,t){return r=>{let s=r[e];return typeof s!="object"||!s?t(s):Array.isArray(s)?s.some(t):s instanceof Date?t(s.getTime()):!1}}function Au(e){if(!e)return;let t=new AE,r,s,n,i,a;for(;r=sg.exec(e);){i=sg.lastIndex;let[,c,u]=r;switch(u){case")":switch(a){case"limit":if(c.indexOf(",")>-1){let[l,_]=c.split(",");t.offset=+l,t.limit=_-t.offset}else t.limit=+c;break;case"select":if(c[0]==="["){if(c[c.length-1]!=="]")throw new Error("Unmatched brackets");t.select=c.slice(1,-1).split(","),t.select.asArray=!0}else c.indexOf(",")>-1?t.select=(c.endsWith(",")?c.slice(0,-1):c).split(","):t.select=c;break;case"group-by":throw new Error("Group by is not implemented yet");case"sort":t.sort=c.split(",").map(l=>{switch(l[0]){case"-":return{attribute:l.slice(1),descending:!0};case"+":return{attribute:l.slice(1),descending:!1};default:return{attribute:l,descending:!1}}});break;default:throw new Error(`Unknown query function call ${a}`)}break;case"(":a=c;break;case"=":s?c.length<=2&&(n=c):(n="equals",s=decodeURIComponent(c));break;case"!=":case"<":case"<=":case">":case">=":n=YF[u],s=decodeURIComponent(c);break;case"=*":n="ends_with",s=decodeURIComponent(c);break;case"*":case"*&":t.conditions.push({comparator:n==="ends_with"?"contains":"starts_with",attribute:s,value:decodeURIComponent(c)}),s=null;break;case"":case void 0:case"&":case"|":if(!s)throw new Error(`Unable to parse query, no part before ${u} at ${i} in ${e}`);t.conditions.push({comparator:n,attribute:s,value:decodeURIComponent(c)}),s=void 0;break;default:throw new Error(`Unknown operator ${u} in query ${e}`)}}if(i!==e.length)throw new Error(`Unable to parse query, unexpected end in ${e}`);return t}var gE,ut,jr,ng,sg,YF,KF,AE,Ou=pe(()=>{gE=D(W()),ut=D(xe()),jr=require("ordered-binary"),ng=require("lmdb"),sg=/([^?&|=<>!()*]+)([&|=<>!()*]*)/g,YF={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne"};o(OE,"idsForCondition");KF={greater_than:"gt",greater_than_equal:"ge",less_than:"lt",less_than_equal:"le",not_equal:"ne",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};o(NE,"filterByType");o(Zr,"attributeComparator");o(Au,"parseQuery");AE=class{static{o(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}}});var IE={};Ze(IE,{CONTEXT:()=>Oe,ID_PROPERTY:()=>ie,IS_COLLECTION:()=>ws,RECORD_PROPERTY:()=>ce,Resource:()=>ft,SAVE_UPDATES_PROPERTY:()=>lg,snake_case:()=>QF});function QF(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function ig(e,t){if(e=e.slice(1),e.indexOf("/")===-1)return e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e));let r=e.split("/"),s=new yE(r.length);for(let n=0;n<r.length;n++)s[n]=t.coerceId(decodeURIComponent(r[n]));return s}function Lr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,a){let c,u,l;if(r?a?(l=i,a=a[Oe]||a):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,a=i[Oe]||i):l=i:(l=n,c=l[ie]??l[this.primaryKey]??null):i?a=i[Oe]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(a=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[];for(let d of n){if(typeof d=="object"&&d)break;c.push(d)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null)))}else{if(typeof(c=n.url)=="string"){let d=c.indexOf("?");if(d>-1){let f=this.parseQuery(c.slice(d+1));u?u=Object.assign(f,u):u=f,c=c.slice(0,d)}let E=this.parsePath(c,a,u);E?.query?(u=E.query,c=E.id):c=E}c===void 0&&(c=n.id??null)}else c=n??null;if(a||(a={}),t.allowInvalidated&&(a.allowInvalidated=!0),a.transaction){let d=this.getResource(c,a,t);return d.then?d.then(_):_(d)}else return Ye(a,()=>{let d=this.getResource(c,a,t);return d.then?d.then(_):_(d)});function _(d){if(t.type==="read"&&(d[lg]=!1),a.authorize){a.authorize=!1;let E=t.type==="read"?d.allowRead(a.user,a):t.type==="update"?d.doesExist?.()===!1?d.allowCreate(a.user,a):d.allowUpdate(a.user,a):t.type==="create"?d.allowCreate(a.user,a):d.allowDelete(a.user,a);if(E?.then)return E.then(f=>{if(!f)throw new Nu(a.user);return typeof l?.then=="function"?l.then(h=>e(d,u,a,h)):e(d,u,a,l)});if(!E)throw new Nu(a.user)}return typeof l?.then=="function"?l.then(E=>e(d,u,a,E)):e(d,u,a,l)}o(_,"authorizeActionOnResource")}}function Mr(e,t){let r=new ug.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function bE(e){let t=e[ce];if(t){let r=e[Et];return s=>{let n;return e.hasOwnProperty(s)&&typeof(n=e[s])!="function"?n:r&&s in r?r[s]:t[s]}}else return r=>e[r]}function ag(e){if(typeof e=="string")return t=>bE(t)(e);if(typeof e=="object"){if(e.asArray)return r=>{let s=[],n=bE(r);for(let i of e)s.push(n(i));return s};let t=e.forceNulls;return r=>{let s={},n=bE(r);for(let i of e){let a=n(i);a===void 0&&t&&(a=null),s[i]=a}return s}}else throw new Error("Invalid select argument type "+typeof e)}var og,cg,ug,Oe,ie,ws,lg,ce,WF,ft,Nu,yE,Xr=pe(()=>{og=require("crypto");to();cg=require("../index"),ug=D(W());gu();Gn();Ou();Oe=Symbol.for("context"),ie=Symbol.for("primary-key"),ws=Symbol("is-collection"),lg=Symbol("save-updates"),ce=Symbol("stored-record"),WF={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},ft=class{static{o(this,"Resource")}[Oe];[ie];static transactions;constructor(t,r){this[ie]=t;let s=r?.[Oe];this[Oe]=s!==void 0?s:r||null}updateModificationTime(t=Date.now()){t>this[LAST_MODIFICATION_PROPERTY]&&(this[LAST_MODIFICATION_PROPERTY]=t)}static get=Lr(function(t,r,s,n){let i=t.get?.(r);if(i?.then)return i.then(a);return a(i);function a(c){let u;if((u=r?.select)&&c!=null){let l=ag(u);return typeof c?.map=="function"?c.map(l):l(c)}return c}},{type:"read"});static put=Lr(function(t,r,s,n){if(Array.isArray(n)&&t[ws]){let i=[],a=s.authorize;for(let c of n)a&&(s.authorize=!0),i.push(this.put(t,r,s,c));return i}return t.put?t.put(n,r):Mr(t,"put")},{hasContent:!0,type:"update"});static delete=Lr(function(t,r,s,n){return t.delete?t.delete(r):Mr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,og.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),Ye(s,()=>{let i=new this(n,s),a=i.put?i.put(r):Mr(i,"put");return s.newLocation=n,s.createdResource=!0,a?.then?a.then(()=>n):n})}static post=Lr(function(t,r,s,n){return t[ie]!=null&&t.update(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Lr(function(t,r,s,n){return t.connect?t.connect(r):Mr(t,"connect")},{type:"read"});static subscribe=Lr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Mr(t,"subscribe")},{type:"read"});static publish=Lr(function(t,r,s,n){return t[ie]!=null&&t.update(),t.publish?t.publish(n,r):Mr(t,"publish")},{hasContent:!0,type:"create"});static search=Lr(function(t,r,s,n){let i=t.search?t.search(s):Mr(t,"search"),a=s.select;if(a&&s.hasOwnProperty("select")&&i!=null){let c=ag(a);return i.map(c)}return i},{type:"read"});static query=Lr(function(t,r,s,n){return t.search?t.search(n,r):Mr(t,"search")},{hasContent:!0,type:"read"});static copy=Lr(function(t,r,s,n){return t.copy?t.copy(s.headers?.destination,r):Mr(t,"copy")},{type:"create"});static move=Lr(function(t,r,s,n){return t.move?t.move(s.headers?.destination,r):Mr(t,"move")},{type:"delete"});post(t){if(this[ws])return this.constructor.create(this[ie],t,this[Oe]);Mr(this,"post")}static isCollection(t){return t?.[ws]}static coerceId(t){return t}static parseQuery(t){return Au(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let i=t.slice(n+1);t=t.slice(0,n);let a=r?.headers&&WF[i];if(a)r.headers.accept=a;else if(s)s.property=i;else return{query:{property:i},id:ig(t,this)}}return ig(t,this)}static getResource(t,r,s){let n,i=r[Oe],a;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?a=r.isCollection:a=t==null||Array.isArray(t)&&t[t.length-1]==null;let c=a&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let l=u.asMap.get(t);if(n=l?.find(_=>_.constructor===c),n)return n;l||u.asMap.set(t,l=[]),l.push(n=new c(t,i))}else{if(n=u.find(l=>l[ie]===t&&l.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let l=new Map;for(let _ of u){let d=_[ie],E=l.get(d);E?E.push(_):l.set(d,[_])}i.resourceCache.length=0,i.resourceCache.asMap=l}}}else n=new c(t,i);return a&&(n[ws]=!0),n}connect(t){let r=new Jr;if(t?.subscribe!==!1){let s={listener:i=>{r.send(i)}},n=this.subscribe?.(s);r.on("close",()=>n?.end())}return r}update(t){throw new Error("Not implemented")}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[ie]}getContext(){return this[Oe]}};ft.prototype[Oe]=null;(0,cg._assignPackageExport)("Resource",ft);o(QF,"snake_case");Nu=class extends Error{static{o(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.http_resp_code=403):(super("Must login"),this.http_resp_code=401)}};o(ig,"pathToId");yE=class extends Array{static{o(this,"MulitPartId")}toString(){return this.join("/")}};o(Lr,"transactional");o(Mr,"missingMethod");o(bE,"selectFromObject");o(ag,"transformForSelect")});var wE={};Ze(wE,{server:()=>ht});var _g,ht,on=pe(()=>{_g=require("../index"),ht={};(0,_g._assignPackageExport)("server",ht)});var DE={};Ze(DE,{loadGQLSchema:()=>JF,start:()=>UE,startOnMainThread:()=>zF});function UE({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:a,Source:c,Kind:u,NamedTypeNode:l,StringValueNode:_}=await import("graphql"),d=a(new c(r.toString(),n)),E=new Map,f=[],h;for(let T of d.definitions)switch(T.kind){case u.OBJECT_TYPE_DEFINITION:let Y=function(A){if(A.kind==="NonNullType"){let G=Y(A.type);return G.nullable=!0,G}return A.kind==="ListType"?{type:"array",elements:Y(A.type)}:{type:A.name?.value}};o(Y,"getProperty");let S=T.name.value,y=[],O={table:null,database:null,properties:y};E.set(S,O);for(let A of T.directives){if(A.name.value==="table"){for(let w of A.arguments)O[w.name.value]=w.value.value;O.schema&&(O.database=O.schema),O.table||(O.table=S),O.audit&&(O.audit=O.audit!=="false"),O.attributes=O.properties,f.push(O)}if(A.name.value==="sealed"&&(O.sealed=!0),A.name.value==="export"){O.export=!0;for(let w of A.arguments)w.name.value==="name"&&(O.export={name:w.value.value})}}let H=!1;for(let A of T.fields){let w=Y(A.type);w.name=A.name.value,y.push(w);for(let G of A.directives)if(G.name.value==="primaryKey")H?console.warn("Can not define two attributes as a primary key"):(w.isPrimaryKey=!0,H=!0);else if(G.name.value==="indexed")w.indexed=!0;else if(G.name.value==="createdTime")w.assignCreatedTime=!0;else if(G.name.value==="updatedTime")w.assignUpdatedTime=!0;else if(G.name.value==="expiresAt")w.expiresAt=!0;else if(G.name.value==="allow"){let k=w.authorizedRoles=[];for(let X of G.arguments)X.name.value==="role"&&k.push(X.value.value)}}O.typeName=S,S==="Query"&&(h=O)}for(let[T,S]of E)for(let y of S.properties){let O=E.get(y.type);O&&(y.properties=O.properties)}for(let T of f)T.tableClass=e(T),T.export&&i.set((0,CE.dirname)(s)+"/"+(T.export.name||T.typeName),T.tableClass);if(h)for(let T of h.properties){let S=E.get(T.type);if(!S)throw new Error(`${T.type} was not found as a Query export`);i.set((0,CE.dirname)(s)+"/"+T.name,S.tableClass)}}}var CE,zF,JF,dg=pe(()=>{CE=require("path");de();o(UE,"start");zF=UE,JF=UE({ensureTable:et}).handleFile});async function bu(e){return XF?(no||(no=ZF(eq)),(await(await no).import(e)).namespace):import(e)}async function ZF(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),no=new Compartment({console,Math,Date,fetch:jF,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,fg.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:ft,tables:sr,databases:Pe})}};let s=await(0,Eg.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),no}function jF(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function eq(){return{Resource:ft,tables:sr}}var Eg,fg,XF,no,LE=pe(()=>{Xr();de();Eg=require("fs/promises"),fg=require("path"),XF=!1;o(bu,"secureImport");o(ZF,"getCompartment");o(jF,"secureOnlyFetch");o(eq,"getGlobalVars")});var PE={};Ze(PE,{handleFile:()=>tq});async function tq(e,t,r,s){let n=new Map,i=(0,hg.pathToFileURL)(r).toString(),a=await bu(i);u(a.default)&&s.set((0,ME.dirname)(t),a.default),c(a,(0,ME.dirname)(t));function c(l,_){for(let d in l){let E=l[d];u(E)?s.set(_+"/"+d,E):typeof E=="object"&&c(E,_+"/"+d)}}o(c,"recurseForResources");function u(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return o(u,"isResource"),n}var hg,ME,mg=pe(()=>{hg=require("url");LE();ME=require("path");o(tq,"handleFile")});var BE={};Ze(BE,{start:()=>rq});function rq({resources:e}){e.set("login",vE),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var vE,Sg=pe(()=>{Xr();o(rq,"start");vE=class extends ft{static{o(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:a}=r;return{data:await s.login(n,i)}}}});var FE=m((rre,Rg)=>{"use strict";var{Readable:sq}=require("stream"),nq=1e4;Rg.exports={streamAsJSON(e){return new HE({value:e})}};var HE=class extends sq{static{o(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0)}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator](),a;for(;;)if(a=i.next(),a.then&&(yield a.then(c=>(a=c,""))),a.done){yield"]";return}else n?n=!1:yield",",yield*this.serialize(a.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),pg)}catch(n){yield pg(n)}else yield JSON.stringify(t)}else yield JSON.stringify(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Tg(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>nq?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return Tg(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}};function pg(e){return console.error(e),JSON.stringify(e.toString())}o(pg,"handleError");function Tg(e,t,r){return e&&e.then?r?e.then(t,r):e.then(t):t(e)}o(Tg,"when")});var Mg=m((ire,Lg)=>{"use strict";var qE=require("recursive-iterator"),iq=require("alasql"),GE=require("clone"),gg=x(),{handleHDBError:Ag,hdb_errors:aq}=W(),{HDB_ERROR_MSGS:Og,HTTP_STATUS_CODES:Ng}=aq,{getDatabases:oq}=(de(),re(Ne)),cq=["DISTINCT_ARRAY"],bg=Symbol("validateTables"),xE=Symbol("validateTable"),nre=Symbol("getAllColumns"),yg=Symbol("validateAllColumns"),yu=Symbol("findColumn"),Ig=Symbol("validateOrderBy"),io=Symbol("validateSegment"),kE=Symbol("validateColumn"),wg=Symbol("setColumnsForTable"),Cg=Symbol("checkColumnsForAsterisk"),Ug=Symbol("validateGroupBy"),Dg=Symbol("hasColumns"),VE=class{static{o(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[bg](),this[Cg](),this[yg]()}[bg](){if(this[Dg]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[xE](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[xE](t.table)})}}[Dg](){let t=!1,r=new qE(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[xE](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=oq();if(!r[t.databaseid])throw Ag(new Error,Og.SCHEMA_NOT_FOUND(t.databaseid),Ng.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Ag(new Error,Og.TABLE_NOT_FOUND(t.databaseid,t.tableid),Ng.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=GE(n);i.table=GE(t),this.attributes.push(i)})}[yu](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)}[Cg](){let t=new qE(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[wg](r.tableid)}[wg](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new iq.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[yg](){this[io](this.statement.columns,!1),this[io](this.statement.joins,!1),this[io](this.statement.where,!1),this[Ug](this.statement.group,!1),this[io](this.statement.order,!0)}[io](t,r){if(!t)return;let s=new qE(t),n=[];for(let{node:i,path:a}of s)!gg.isEmpty(i)&&!gg.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Ig](i):n.push(this[kE](i)));return n}[Ug](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&cq.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=GE(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[yu](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,a)=>{if(i.toString()===s.toString()){n=i,r.splice(a,1);return}});else{let i=this[yu](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((a,c)=>{if(a.attribute===i[0].attribute&&a.table.tableid===i[0].table.tableid){n=a,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`}[Ig](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[kE](t)}[kE](t){let r=this[yu](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]}};Lg.exports=VE});var vg=m((ore,Pg)=>{"use strict";var $E=class{static{o(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Pg.exports=$E});var Hg=m((ure,Bg)=>{"use strict";var YE=class{static{o(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Bg.exports=YE});var Iu=m((_re,Fg)=>{"use strict";var WE=Q(),QE=g();WE.initSync();var uq=WE.get(QE.CONFIG_PARAMS.STORAGE_COMPRESSION),lq=WE.get(QE.CONFIG_PARAMS.STORAGE_CACHING)!==!1,_q=QE.UPDATES_PROPERTY,KE=class{static{o(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=uq&&r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=lq&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.alwaysLazyProperty=s=>s===_q)}};Fg.exports=KE});var Cu=m((Ere,Gg)=>{"use strict";var vi=Q(),ao=g();vi.initSync();var dq=vi.get(ao.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||vi.get(ao.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||vi.get(ao.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",qg=vi.get(ao.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),Eq=vi.get(ao.CONFIG_PARAMS.STORAGE_NOREADAHEAD),wu=class{static{o(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=dq,this.noFSAccess=!0,qg!==void 0&&(this.overlappingSync=qg),this.noReadAhead=Eq}};Gg.exports=wu;wu.MAX_DBS=1e4});var ye=m((hre,Jg)=>{"use strict";var JE=require("lmdb"),Pr=require("fs-extra"),nr=require("path"),Uu=vt(),Vg=q(),Bt=rr().LMDB_ERRORS_ENUM,Du=Hg(),XE=Iu(),$g=Cu(),cn=xe(),xg=g(),{table:fq,resetDatabases:hq}=(de(),re(Ne)),kg=Q(),vr=cn.INTERNAL_DBIS_NAME,Yg=cn.DBI_DEFINITION_NAME,mq="data.mdb",Sq="lock.mdb",oo=".mdb",pq="-lock",zE=class{static{o(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=pr(t,r),this.key_type=this.dbi[cn.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[cn.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new JE.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function Lu(e,t){if(e===void 0)throw new Error(Bt.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Bt.ENV_NAME_REQUIRED)}o(Lu,"pathEnvNameValidation");async function ZE(e,t,r=!0){try{await Pr.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Bt.INVALID_BASE_PATH):s}try{let s=nr.join(e,t+oo);return await Pr.access(s,Pr.constants.R_OK|Pr.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Pr.access(nr.join(e,t,mq),Pr.constants.R_OK|Pr.constants.F_OK),nr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Bt.INVALID_ENVIRONMENT)}else throw new Error(Bt.INVALID_ENVIRONMENT);throw s}}o(ZE,"validateEnvironmentPath");function Mu(e,t){if(Uu.validateEnv(e),t===void 0)throw new Error(Bt.DBI_NAME_REQUIRED)}o(Mu,"validateEnvDBIName");async function Tq(e,t,r=!1,s=!1){Lu(e,t);let n=nr.basename(e);t=t.toString();let i=kg.get(xg.CONFIG_PARAMS.SCHEMAS);i||kg.setProperty(xg.CONFIG_PARAMS.SCHEMAS,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await ZE(e,t,s),Kg(e,t,r)}catch(a){if(a.message===Bt.INVALID_ENVIRONMENT){let c=nr.join(e,t);await Pr.mkdirp(s?c:e);let u=new $g(s?c:c+oo,!1),l=JE.open(u);l.dbis=Object.create(null);let _=new XE(!1);l.openDB(vr,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=jE(e,t,r);return l[cn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=l,l}throw a}}o(Tq,"createEnvironment");async function Rq(e,t,r,s=!0){Lu(e,t),t=t.toString();let n=nr.join(e,t);return fq({table:t,database:nr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}o(Rq,"copyEnvironment");async function Kg(e,t,r=!1){Lu(e,t),t=t.toString();let s=jE(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 ZE(e,t),i=nr.join(e,t+oo),a=n!=i,c=new $g(n,a),u=JE.open(c);u.dbis=Object.create(null);let l=Qg(u);for(let _=0;_<l.length;_++)pr(u,l[_]);return u[cn.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}o(Kg,"openEnvironment");async function gq(e,t,r=!1){Lu(e,t),t=t.toString();let s=nr.join(e,t+oo),n=await ZE(e,t);if(global.lmdb_map!==void 0){let i=jE(e,t,r);if(global.lmdb_map[i]){let a=global.lmdb_map[i];await Wg(a),delete global.lmdb_map[i]}}await Pr.remove(n),await Pr.remove(n===s?n+pq:nr.join(nr.dirname(n),Sq))}o(gq,"deleteEnvironment");async function Wg(e){Uu.validateEnv(e);let t=e[cn.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}o(Wg,"closeEnvironment");function jE(e,t,r=!1){let n=`${nr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}o(jE,"getCachedEnvironmentName");function Aq(e){Uu.validateEnv(e);let t=Object.create(null),r=pr(e,vr);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==vr)try{t[s]=Object.assign(new Du,n)}catch{Vg.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}o(Aq,"listDBIDefinitions");function Qg(e){Uu.validateEnv(e);let t=[],r=pr(e,vr);for(let{key:s}of r.getRange({start:!1}))s!==vr&&t.push(s);return t}o(Qg,"listDBIs");function Oq(e,t){let s=pr(e,vr).getEntry(t),n=new Du;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Vg.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}o(Oq,"getDBIDefinition");function zg(e,t,r,s=!r){if(Mu(e,t),t=t.toString(),t===vr)throw new Error(Bt.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return pr(e,t)}catch(n){if(n.message===Bt.DBI_DOES_NOT_EXIST){let i=new XE(r,s===!0),a=e.openDB(t,i),c=new Du(r===!0,s);return a[Yg]=c,pr(e,vr).putSync(t,c),e.dbis[t]=a,a}throw n}}o(zg,"createDBI");function pr(e,t){if(Mu(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==vr?r=Oq(e,t):r=new Du,r===void 0)throw new Error(Bt.DBI_DOES_NOT_EXIST);let s;try{let n=new XE(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(Bt.DBI_DOES_NOT_EXIST):n}return s[Yg]=r,e.dbis[t]=s,s}o(pr,"openDBI");function Nq(e,t){Mu(e,t),t=t.toString();let r=pr(e,t),s=r.getStats();return r[cn.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}o(Nq,"statDBI");async function bq(e,t){try{let r=nr.join(e,t+oo);return(await Pr.stat(r)).size}catch{throw new Error(Bt.INVALID_ENVIRONMENT)}}o(bq,"environmentDataSize");function yq(e,t){if(Mu(e,t),t=t.toString(),t===vr)throw new Error(Bt.CANNOT_DROP_INTERNAL_DBIS_NAME);pr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],pr(e,vr).removeSync(t)}o(yq,"dropDBI");function Iq(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{pr(e,i)}catch(a){if(a.message===Bt.DBI_DOES_NOT_EXIST)zg(e,i,i!==t,i===t),s=!0;else throw a}}s&&hq()}o(Iq,"initializeDBIs");Jg.exports={openDBI:pr,openEnvironment:Kg,createEnvironment:Tq,listDBIs:Qg,listDBIDefinitions:Aq,createDBI:zg,dropDBI:yq,statDBI:Nq,deleteEnvironment:gq,initializeDBIs:Iq,TransactionCursor:zE,environmentDataSize:bq,copyEnvironment:Rq,closeEnvironment:Wg}});var Zg=m((Sre,Xg)=>{"use strict";var ef=class{static{o(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};Xg.exports=ef});var eA=m((Tre,jg)=>{"use strict";var tf=class{static{o(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};jg.exports=tf});var rA=m((gre,tA)=>{"use strict";var rf=class{static{o(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};tA.exports=rf});var Bi=m((yre,iA)=>{"use strict";var wq=ye(),Cq=Zg(),Uq=eA(),Dq=rA(),es=vt(),co=rr().LMDB_ERRORS_ENUM,Lq=xe(),Cs=g(),Mq=x(),Pq=require("uuid"),Ore=require("lmdb"),{handleHDBError:vq,hdb_errors:Bq}=W(),{OVERFLOW_MARKER:Nre,MAX_SEARCH_KEY_LENGTH:bre}=Lq,sA=Q();sA.initSync();var Pu=sA.get(Cs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),sf=Cs.TIME_STAMP_NAMES_ENUM.CREATED_TIME,xn=Cs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function Hq(e,t,r,s,n=es.getNextMonotonicTime()){cf(e,t,r,s),nf(e,t,r);let i=new Cq,a=[],c=[];for(let u=0;u<s.length;u++){let l=s[u];nA(l,!0,n);let _=Fq(e,t,r,l),d=l[t];a.push(_),c.push(d)}return af(a,c,s,i,n)}o(Hq,"insertRecords");function Fq(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let a=r[i];if(a===t||s.hasOwnProperty(a)===!1)continue;let c=s[a];if(typeof c=="function"){let _=c([[{}]]);Array.isArray(_)&&(c=_[0][Cs.FUNC_VAL],s[a]=c)}let u=es.getIndexedValues(c),l=e.dbis[a];if(u){Pu&&l.prefetch(u.map(_=>({key:_,value:n})),vu);for(let _=0,d=u.length;_<d;_++)l.put(u[_],n)}}Pu&&e.dbis[t].prefetch([n],vu),e.dbis[t].put(n,s,s[xn])})}o(Fq,"insertRecord");function qq(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}o(qq,"removeSkippedRecords");function nA(e,t,r){let s=r>0;(s||!Number.isInteger(e[xn]))&&(e[xn]=r||(r=es.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[sf]))&&(e[sf]=r||es.getNextMonotonicTime()):delete e[sf]}o(nA,"setTimestamps");function nf(e,t,r){r.indexOf(Cs.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Cs.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Cs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Cs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),wq.initializeDBIs(e,t,r)}o(nf,"initializeTransaction");async function Gq(e,t,r,s,n=es.getNextMonotonicTime()){cf(e,t,r,s),nf(e,t,r);let i=new Uq,a=[],c=[],u=[];for(let l=0;l<s.length;l++){let _=s[l],d=_[t],E;try{E=of(e,t,_,d,i,!0,n)}catch{i.skipped_hashes.push(d),a.push(l);continue}c.push(E),u.push(d)}return af(c,u,s,i,n,a)}o(Gq,"updateRecords");async function xq(e,t,r,s,n=es.getNextMonotonicTime()){try{cf(e,t,r,s)}catch(u){throw vq(u,u.message,Bq.HTTP_STATUS_CODES.BAD_REQUEST)}nf(e,t,r);let i=new Dq,a=[],c=[];for(let u=0;u<s.length;u++){let l=s[u],_;Mq.isEmpty(l[t])?(_=Pq.v4(),l[t]=_):_=l[t];let d=of(e,t,l,_,i,!1,n);a.push(d),c.push(_)}return af(a,c,s,i,n)}o(xq,"upsertRecords");async function af(e,t,r,s,n,i=[]){let a=await Promise.all(e);for(let c=0,u=a.length;c<u;c++)a[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||es.getNextMonotonicTime(),qq(r,i),s}o(af,"finalizeWrite");function of(e,t,r,s,n,i=!1,a){let c=e.dbis[t],u=c.getEntry(s),l=u?.value,_=l;if(!l){if(i)return!1;l={}}if(nA(r,!_,a),Number.isInteger(r[xn])&&l[xn]>r[xn])return!1;_&&n.original_records.push(l);let d,E=o(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let T=r[h],S=e.dbis[h];if(S===void 0)continue;let y=l[h];if(typeof T=="function"){let H=T([[l]]);Array.isArray(H)&&(T=H[0][Cs.FUNC_VAL],r[h]=T)}if(T===y)continue;let O=es.getIndexedValues(y);if(O){Pu&&S.prefetch(O.map(H=>({key:H,value:s})),vu);for(let H=0,Y=O.length;H<Y;H++)S.remove(O[H],s)}if(O=es.getIndexedValues(T),O){Pu&&S.prefetch(O.map(H=>({key:H,value:s})),vu);for(let H=0,Y=O.length;H<Y;H++)S.put(O[H],s)}}let f=Object.assign({},l,r);c.put(s,f,f[xn])},"do_put");return u?d=c.ifVersion(s,u.version,E):d=c.ifNoExists(s,E),d.then(f=>f?!0:of(e,t,r,s,n,i,a))}o(of,"updateUpsertRecord");function kq(e,t,r){if(es.validateEnv(e),t===void 0)throw new Error(co.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(co.WRITE_ATTRIBUTES_REQUIRED):new Error(co.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}o(kq,"validateBasic");function cf(e,t,r,s){if(kq(e,t,r),!Array.isArray(s))throw s===void 0?new Error(co.RECORDS_REQUIRED):new Error(co.RECORDS_MUST_BE_ARRAY)}o(cf,"validateWrite");function vu(){}o(vu,"noop");iA.exports={insertRecords:Hq,updateRecords:Gq,upsertRecords:xq}});var kn=m((wre,Vq)=>{Vq.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var ts=m((Cre,cA)=>{"use strict";var oA=x(),aA=g(),Hi=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Us=require("joi"),un={schema_format:{pattern:Hi,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},$q=Us.alternatives(Us.string().min(1).max(un.schema_length.maximum).pattern(Hi).messages({"string.pattern.base":"{:#label} "+un.schema_format.message}),Us.number()).required(),Yq=Us.alternatives(Us.string().min(1).max(un.schema_length.maximum).pattern(Hi).messages({"string.pattern.base":"{:#label} "+un.schema_format.message}),Us.number()),Kq=Us.alternatives(Us.string().min(1).max(un.schema_length.maximum).pattern(Hi).messages({"string.pattern.base":"{:#label} "+un.schema_format.message}),Us.number()).required();function Wq(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>un.schema_length.maximum?`'${e}' maximum of 250 characters`:Hi.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}o(Wq,"checkValidTable");function Qq(e,t){return oA.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}o(Qq,"validateSchemaExists");function zq(e,t){let r=t.state.ancestors[0].schema;return oA.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}o(zq,"validateTableExists");function Jq(e,t){return e.toLowerCase()===aA.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${aA.SYSTEM_SCHEMA_NAME}' name is reserved`):e}o(Jq,"validateSchemaName");cA.exports={common_validators:un,schema_regex:Hi,hdb_schema_table:$q,validateSchemaExists:Qq,validateTableExists:zq,validateSchemaName:Jq,checkValidTable:Wq,hdb_database:Yq,hdb_table:Kq}});var ve=m((Dre,uA)=>{"use strict";var Ht=require("validate.js");Ht.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||Ht.validators.type.checks[t](e)?null:` must be a '${t}' value`};Ht.validators.type.checks={Object:function(e){return Ht.isObject(e)&&!Ht.isArray(e)},Array:Ht.isArray,Integer:Ht.isInteger,Number:Ht.isNumber,String:Ht.isString,Date:Ht.isDate,Boolean:function(e){return typeof e=="boolean"}};Ht.validators.hasValidFileExt=function(e,t){return Ht.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};uA.exports={validateObject:Xq,validateObjectAsync:Zq,validateBySchema:jq};function Xq(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=Ht(e,t,{format:"flat"});return r?new Error(r):null}o(Xq,"validateObject");async function Zq(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await Ht.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}o(Zq,"validateObjectAsync");function jq(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}o(jq,"validateBySchema")});var Bu=m((Mre,lA)=>{var{common_validators:rs}=ts(),lo=ve(),uo="is required",Ke={database:{presence:!1,format:rs.schema_format,length:rs.schema_length},schema:{presence:!1,format:rs.schema_format,length:rs.schema_length},table:{presence:!0,format:rs.schema_format,length:rs.schema_length},attribute:{presence:!0,format:rs.schema_format,length:rs.schema_length},hash_attribute:{presence:!0,format:rs.schema_format,length:rs.schema_length}};function _o(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}o(_o,"makeAttributesStrings");function eG(e){return e=_o(e),Ke.table.presence=!1,Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,lo.validateObject(e,Ke)}o(eG,"schema_object");function tG(e){return e=_o(e),Ke.table.presence={message:uo},Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,lo.validateObject(e,Ke)}o(tG,"table_object");function rG(e){return e=_o(e),Ke.table.presence={message:uo},Ke.attribute.presence=!1,lo.validateObject(e,Ke)}o(rG,"create_table_object");function sG(e){return e=_o(e),Ke.table.presence={message:uo},Ke.attribute.presence={message:uo},Ke.hash_attribute.presence=!1,lo.validateObject(e,Ke)}o(sG,"attribute_object");function nG(e){return e=_o(e),Ke.table.presence={message:uo},Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,lo.validateObject(e,Ke)}o(nG,"describe_table");function iG(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`)}}o(iG,"validateTableResidence");lA.exports={schema_object:eG,create_table_object:rG,table_object:tG,attribute_object:sG,describe_table:nG,validateTableResidence:iG}});var dA=m((vre,_A)=>{"use strict";var aG=require("uuid"),uf=class{static{o(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||aG.v4(),this.schema_table=`${this.schema}.${this.table}`}};_A.exports=uf});var Hu=m((Hre,EA)=>{"use strict";var oG=dA(),lf=class extends oG{static{o(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,a=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=a}};EA.exports=lf});var hA=m((qre,fA)=>{"use strict";fA.exports=uG;var cG="inserted";function uG(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===cG?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}o(uG,"returnObject")});var Fu=m((xre,RA)=>{"use strict";var lG=g(),_f=ye(),_G=Bi(),{getSystemSchemaPath:dG,getSchemaPath:EG}=we(),fG=kn(),hG=Bu(),mG=Hu(),SG=hA(),{handleHDBError:mA,hdb_errors:pA}=W(),SA=x(),{HTTP_STATUS_CODES:pG}=pA,df=fG.hdb_attribute,TA=[];for(let e=0;e<df.attributes.length;e++)TA.push(df.attributes[e].attribute);var TG="inserted";RA.exports=RG;async function RG(e){let t=hG.attribute_object(e);if(t)throw mA(new Error,t.message,pA.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&SA.checkGlobalSchemaTable(e.schema,e.table);if(r)throw mA(new Error,r,pG.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=SA.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new mG(e.schema,e.table,e.attribute,e.id);try{let i=await _f.openEnvironment(EG(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);_f.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let a=await _f.openEnvironment(dG(),lG.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await _G.insertRecords(a,df.hash_attribute,TA,[n]);return SG(TG,c,{records:[n]},u)}catch(i){throw i}}o(RG,"lmdbCreateAttribute")});var ff=m((Vre,AA)=>{var{hdb_table:gG,hdb_database:gA}=ts(),AG=ve(),Ef=require("joi"),OG={undefined:"undefined",null:"null"},NG=o((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let a=r[i];(!a||a.length===0||OG[a]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${a}'`:n+=`. Invalid attribute name: '${a}'`)}return n?t.message(n):e},"custom_records_val"),bG=Ef.object({database:gA,schema:gA,table:gG,records:Ef.array().items(Ef.object().custom(NG)).required()});AA.exports=function(e){return AG.validateBySchema(e,bG)}});var Eo=m((Kre,NA)=>{"use strict";var Ds=x(),OA=q(),Yre=ff(),{getDatabases:yG}=(de(),re(Ne)),{ClientError:Vn}=W();NA.exports=IG;function IG(e){if(Ds.isEmpty(e))throw new Vn("invalid update parameters defined.");if(Ds.isEmptyOrZeroLength(e.schema))throw new Vn("invalid schema specified.");if(Ds.isEmptyOrZeroLength(e.table))throw new Vn("invalid table specified.");if(!Array.isArray(e.records))throw new Vn("records must be an array");let t=yG()[e.schema]?.[e.table];if(Ds.isEmpty(t))throw new Vn(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(a=>{if(i&&Ds.isEmptyOrZeroLength(a[r]))throw OA.error("a valid hash attribute must be provided with update record:",a),new Vn("a valid hash attribute must be provided with update record, check log for more info");if(!Ds.isEmptyOrZeroLength(a[r])&&(a[r]==="null"||a[r]==="undefined"))throw OA.error(`a valid hash value must be provided with ${e.operation} record:`,a),new Vn(`Invalid hash value: '${a[r]}' is not a valid hash attribute value, check log for more info`);!Ds.isEmpty(a[r])&&a[r]!==""&&s.has(Ds.autoCast(a[r]))&&(a.skip=!0),s.add(Ds.autoCast(a[r]));for(let c in a)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}o(IG,"insertUpdateValidate")});var fo=m((Qre,bA)=>{"use strict";var wG=g().OPERATIONS_ENUM,hf=class{static{o(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=wG.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};bA.exports=hf});var po=m((Xre,yA)=>{"use strict";var Jre=fo(),qu=g(),Sf=x(),mf=q(),CG=require("uuid"),{handleHDBError:ho,hdb_errors:UG}=W(),{HDB_ERROR_MSGS:mo,HTTP_STATUS_CODES:So}=UG;yA.exports=DG;function DG(e,t,r){for(let n=0;n<t.length;n++)LG(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];MG(i,r,e.operation)}}o(DG,"processRows");function LG(e){if(Buffer.byteLength(String(e))>qu.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw ho(new Error,mo.ATTR_NAME_LENGTH_ERR(e),So.BAD_REQUEST,void 0,void 0,!0);if(Sf.isEmptyOrZeroLength(e)||Sf.isEmpty(e.trim()))throw ho(new Error,mo.ATTR_NAME_NULLISH_ERR,So.BAD_REQUEST,void 0,void 0,!0)}o(LG,"validateAttribute");function MG(e,t,r){if(!e.hasOwnProperty(t)||Sf.isEmptyOrZeroLength(e[t])){if(r===qu.OPERATIONS_ENUM.INSERT||r===qu.OPERATIONS_ENUM.UPSERT){e[t]=CG.v4();return}throw mf.error("Update transaction aborted due to record with no hash value:",e),ho(new Error,mo.RECORD_MISSING_HASH_ERR,So.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>qu.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw mf.error(e),ho(new Error,mo.HASH_VAL_LENGTH_ERR,So.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw mf.error(e),ho(new Error,mo.INVALID_FORWARD_SLASH_IN_HASH_ERR,So.BAD_REQUEST,void 0,void 0,!0)}o(MG,"validateHash")});var wA=m((jre,IA)=>{"use strict";var pf=class{static{o(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};IA.exports=pf});var DA=m((tse,UA)=>{"use strict";var Tf=ye(),PG=q(),CA=rr().LMDB_ERRORS_ENUM;UA.exports=vG;async function vG(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 a=t[i];if(a.startsWith(`${e.schema}.`)||a.startsWith(`txn.${e.schema}.`))try{await Tf.closeEnvironment(global.lmdb_map[a])}catch(c){if(c.message!==CA.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Tf.closeEnvironment(global.lmdb_map[s]),await Tf.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==CA.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){PG.error(t)}}o(vG,"cleanLMDBMap")});var Ls=m((sse,vA)=>{"use strict";var To=require("crypto"),BG=Q(),{CONFIG_PARAMS:HG}=g(),MA="aes-256-cbc",FG=32,qG=16,Rf=64,PA=32,GG=Rf+PA,LA=new Map;vA.exports={encrypt:xG,decrypt:kG,createNatsTableStreamName:VG};function xG(e){let t=To.randomBytes(FG),r=To.randomBytes(qG),s=To.createCipheriv(MA,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),a=r.toString("hex"),c=n.toString("hex");return i+a+c}o(xG,"encrypt");function kG(e){let t=e.substr(0,Rf),r=e.substr(Rf,PA),s=e.substr(GG,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),a=To.createDecipheriv(MA,Buffer.from(t,"hex"),n),c=a.update(i);return c=Buffer.concat([c,a.final()]),c.toString()}o(kG,"decrypt");function VG(e,t){let r=BG.get(HG.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=LA.get(r);return s||(s=To.createHash("md5").update(r).digest("hex"),LA.set(r,s)),s}o(VG,"createNatsTableStreamName")});var $n=m((ase,HA)=>{"use strict";var ise=Tr(),Gu=q(),BA=Bu(),$G=Ls(),xu=x(),{handleHDBError:ku,hdb_errors:YG}=W(),{HDB_ERROR_MSGS:Vu,HTTP_STATUS_CODES:gf}=YG,KG=Q();KG.initSync();var{getDatabases:Af}=(de(),re(Ne));HA.exports={describeAll:WG,describeTable:$u,describeSchema:QG};async function WG(e){try{let t=xu.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=Af(),i={},a={},c=[];for(let l in n){i[l]=!0,!t&&!s&&(a[l]=e.hdb_user.role.permission[l].describe);let _=n[l];for(let d in _)try{let E;if(t||s)E=await $u({schema:l,table:d});else if(r&&r[l].describe&&r[l].tables[d].describe){let f=r[l].tables[d].attribute_permissions;E=await $u({schema:l,table:d},f)}E&&c.push(E)}catch(E){Gu.error(E)}}let u={};for(let l in c)t||s?(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):a[c[l].schema]&&(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?u[l]={}:a[l]&&(u[l]={});return u}catch(t){return Gu.error("Got an error in describeAll"),Gu.error(t),ku(new Error,Vu.DESCRIBE_ALL_ERR)}}o(WG,"describeAll");async function $u(e,t){xu.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=BA.describe_table(e);if(i)throw i;let c=Af()[r];if(!c)throw ku(new Error,Vu.SCHEMA_NOT_FOUND(e.schema),gf.NOT_FOUND);let u=c[s];if(!u)throw ku(new Error,Vu.TABLE_NOT_FOUND(e.schema,e.table),gf.NOT_FOUND);let l=[];if(n){let d={};n.forEach(E=>{E.describe&&(d[E.attribute_name]=!0)}),u.attributes.forEach(E=>{d[E.name]&&l.push(E)})}else l=u.attributes;let _={schema:r,name:u.tableName,attributes:l,hash_attribute:u.attributes.find(d=>d.isPrimaryKey||d.is_hash_attribute)?.name};_.clustering_stream_name=$G.createNatsTableStreamName(_.schema,_.name);try{_.record_count=u.getRecordCount();let d=u.auditStore;if(d)for(let E of d.getKeys({reverse:!0,limit:1}))_.last_updated_record=E[0];if(!_.last_updated_record&&u.indices.__updatedtime__)for(let E of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))_.last_updated_record=E}catch(d){Gu.warn(`unable to stat table dbi due to ${d}`)}return _}o($u,"descTable");async function QG(e){xu.transformReq(e);let t=BA.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=Af()[s];if(!i)throw ku(new Error,Vu.SCHEMA_NOT_FOUND(e.schema),gf.NOT_FOUND);let a={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),xu.isEmpty(u)||u.describe){let l=await $u({schema:e.schema,table:c},u?u.attribute_permissions:null);l&&(a[l.name]=l)}}return a}o(QG,"describeSchema")});var ln=m((lse,kA)=>{var zG=kn(),{callbackify:qA,promisify:JG}=require("util"),{getDatabases:GA}=(de(),re(Ne));kA.exports={setSchemaDataToGlobal:FA,getTableSchema:XG,getSystemSchema:ZG,setSchemaDataToGlobalAsync:JG(FA)};var xA=$n(),cse=qA(xA.describeAll),use=qA(xA.describeTable);function FA(e){global.hdb_schema=GA(),e&&e()}o(FA,"setSchemaDataToGlobal");function XG(e,t,r){let s=GA()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}o(XG,"getTableSchema");function ZG(){return zG}o(ZG,"getSystemSchema")});var Rr=m((dse,KA)=>{"use strict";var Ku=ff(),mt=x(),jG=require("util"),Wu=Br(),ex=ln(),VA=q(),{handleHDBError:Yn,hdb_errors:tx}=W(),{HTTP_STATUS_CODES:Kn}=tx,rx=jG.promisify(ex.getTableSchema),sx="updated",$A="inserted",YA="upserted";KA.exports={insert:ix,update:ax,upsert:ox,validation:nx,flush:cx};async function nx(e){if(mt.isEmpty(e))throw new Error("invalid update parameters defined.");if(mt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(mt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await rx(e.schema,e.table),r=Ku(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={},a=!1;return e.operation==="update"&&(a=!0),e.records.forEach(c=>{if(a&&mt.isEmptyOrZeroLength(c[s]))throw VA.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(!mt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw VA.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!mt.isEmpty(c[s])&&c[s]!==""&&n.has(mt.autoCast(c[s]))&&(c.skip=!0),n.add(mt.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}o(nx,"validation");async function ix(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=Ku(e);if(t)throw Yn(new Error,t.message,Kn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Yn(new Error,r,Kn.BAD_REQUEST);let s=await Wu.createRecords(e);return Yu($A,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}o(ix,"insertData");async function ax(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=Ku(e);if(t)throw Yn(new Error,t.message,Kn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Yn(new Error,r,Kn.BAD_REQUEST);let s=await Wu.updateRecords(e);return mt.isEmpty(s.existing_rows)?Yu(sx,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):Yu(s.update_action,[],e,s.hashes,void 0,s.txn_time)}o(ax,"updateData");async function ox(e){if(e.operation!=="upsert")throw Yn(new Error,"invalid operation, must be upsert",Kn.INTERNAL_SERVER_ERROR);let t=Ku(e);if(t)throw Yn(new Error,t.message,Kn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Yn(new Error,r,Kn.BAD_REQUEST);let s=await Wu.upsertRecords(e);return Yu(YA,s.written_hashes,e,[],s.new_attributes,s.txn_time)}o(ox,"upsertData");function Yu(e,t,r,s,n,i){let a={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===$A?(a.inserted_hashes=t,a.skipped_hashes=s,a):e===YA?(a.upserted_hashes=t,a):(a.update_hashes=t,a.skipped_hashes=s,a)}o(Yu,"returnObject");function cx(e){return mt.transformReq(e),Wu.flush(e.schema,e.table)}o(cx,"flush")});var Nf=m((fse,zA)=>{var ux=ve(),Of=require("joi"),{hdb_table:lx,hdb_database:WA}=ts(),QA={schema:WA,database:WA,table:lx},_x={date:Of.date().iso().required()},dx={timestamp:Of.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};zA.exports=function(e,t){let r=t==="timestamp"?{...QA,...dx}:{...QA,..._x},s=Of.object(r);return ux.validateBySchema(e,s)}});var ZA=m((hse,XA)=>{var Ex=ve(),bf=require("joi"),{hdb_table:fx,hdb_database:JA}=ts(),hx=bf.object({schema:JA,database:JA,table:fx,hash_values:bf.array().required(),ids:bf.array()});XA.exports=function(e){return Ex.validateBySchema(e,hx)}});var eO=m((mse,jA)=>{"use strict";var yf=class{static{o(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},If=class{static{o(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,a){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=a}},wf=class{static{o(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};jA.exports={InsertObject:yf,NoSQLSeachObject:If,DeleteResponseObject:wf}});var zn=m((pse,iO)=>{"use strict";var rO=Nf(),mx=ZA(),Wn=x(),tO=require("moment"),sO=q(),{promisify:Sx,callbackify:px}=require("util"),Qn=g(),Tx=ln(),Cf=Sx(Tx.getTableSchema),Uf=Br(),{DeleteResponseObject:Rx}=eO(),{handleHDBError:_n,hdb_errors:gx}=W(),{HDB_ERROR_MSGS:Qu,HTTP_STATUS_CODES:dn}=gx,Ax="records successfully deleted",Ox=px(nO);iO.exports={delete:Ox,deleteRecord:nO,deleteFilesBefore:Nx,deleteAuditLogsBefore:bx};async function Nx(e){let t=rO(e,"date");if(t)throw _n(t,t.message,dn.BAD_REQUEST,void 0,void 0,!0);if(Wn.transformReq(e),!tO(e.date,tO.ISO_8601).isValid())throw _n(new Error,Qu.INVALID_DATE,dn.BAD_REQUEST,Qn.LOG_LEVELS.ERROR,Qu.INVALID_DATE,!0);let s=Wn.checkSchemaTableExist(e.schema,e.table);if(s)throw _n(new Error,s,dn.NOT_FOUND,Qn.LOG_LEVELS.ERROR,s,!0);let n=await Uf.deleteRecordsBefore(e);if(await Cf(e.schema,e.table),sO.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}o(Nx,"deleteFilesBefore");async function bx(e){let t=rO(e,"timestamp");if(t)throw _n(t,t.message,dn.BAD_REQUEST,void 0,void 0,!0);if(Wn.transformReq(e),isNaN(e.timestamp))throw _n(new Error,Qu.INVALID_VALUE("Timestamp"),dn.BAD_REQUEST,Qn.LOG_LEVELS.ERROR,Qu.INVALID_VALUE("Timestamp"),!0);let r=Wn.checkSchemaTableExist(e.schema,e.table);if(r)throw _n(new Error,r,dn.NOT_FOUND,Qn.LOG_LEVELS.ERROR,r,!0);let s=await Uf.deleteAuditLogsBefore(e);return await Cf(e.schema,e.table),sO.info(`Finished deleting audit logs before ${e.timestamp}`),s}o(bx,"deleteAuditLogsBefore");async function nO(e){e.ids&&(e.hash_values=e.ids);let t=mx(e);if(t)throw _n(t,t.message,dn.BAD_REQUEST,void 0,void 0,!0);Wn.transformReq(e);let r=Wn.checkSchemaTableExist(e.schema,e.table);if(r)throw _n(new Error,r,dn.NOT_FOUND,Qn.LOG_LEVELS.ERROR,r,!0);try{await Cf(e.schema,e.table);let s=await Uf.deleteRecords(e);return Wn.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${Ax}`),s}catch(s){if(s.message===Qn.SEARCH_NOT_FOUND_MESSAGE){let n=new Rx;return n.message=Qn.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}o(nO,"deleteRecord")});var zu=m((Rse,cO)=>{var yx=require("crypto"),aO=9;function Ix(e){let t=Cx(aO),r=oO(e+t);return t+r}o(Ix,"createHash");function wx(e,t){let r=e.substr(0,aO),s=r+oO(t+r);return e===s}o(wx,"validateHash");function Cx(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}o(Cx,"generateSalt");function oO(e){return yx.createHash("md5").update(e).digest("hex")}o(oO,"md5");cO.exports={hash:Ix,validate:wx}});var lO=m((Ase,uO)=>{var Df=ve(),It={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 Ux(e){return It.password.presence=!0,It.username.presence=!0,It.role.presence=!0,It.active.presence=!0,Df.validateObject(e,It)}o(Ux,"addUserValidation");function Dx(e){return It.password.presence=!1,It.username.presence=!0,It.role.presence=!1,It.active.presence=!1,Df.validateObject(e,It)}o(Dx,"alterUserValidation");function Lx(e){return It.password.presence=!1,It.username.presence=!0,It.role.presence=!1,It.active.presence=!1,Df.validateObject(e,It)}o(Lx,"dropUserValidation");uO.exports={addUserValidation:Ux,alterUserValidation:Dx,dropUserValidation:Lx}});var Be=m((bse,dO)=>{"use strict";var{platform:Nse}=require("os"),Mx="nats-server.zip",Lf="nats-server",Px=process.platform==="win32"?`${Lf}.exe`:Lf,Mf="HDB",vx=/^[^\s.,*>]+$/,_O="__request__",Bx=o(e=>`${e}.${_O}`,"REQUEST_SUBJECT"),Hx={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin"},Fx={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},qx={HUB:"hub.pid",LEAF:"leaf.pid"},Gx={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},xx={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Mf,deliver_subject:"__HDB__.WORKQUEUE"},kx={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Mf,deliver_subject:"HDB.SCHEMAQUEUE"},Vx={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Mf,deliver_subject:"HDB.USERQUEUE"},$x={SUCCESS:"success",ERROR:"error"},Yx={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},Kx={TXN:"txn",MSGID:"msgid"},Fi={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},Wx={[Fi.ERR]:1,[Fi.WRN]:2,[Fi.INF]:3,[Fi.DBG]:4,[Fi.TRC]:5},Qx={debug:"-D",trace:"-DVV"};dO.exports={NATS_SERVER_ZIP:Mx,NATS_SERVER_NAME:Lf,NATS_BINARY_NAME:Px,PID_FILES:qx,NATS_CONFIG_FILES:Fx,SERVER_SUFFIX:Gx,WORK_QUEUE_CONSUMER_NAMES:xx,SCHEMA_QUEUE_CONSUMER_NAMES:kx,USER_QUEUE_CONSUMER_NAMES:Vx,NATS_TERM_CONSTRAINTS_RX:vx,REQUEST_SUFFIX:_O,UPDATE_REMOTE_RESPONSE_STATUSES:$x,CLUSTER_STATUS_STATUSES:Yx,REQUEST_SUBJECT:Bx,SUBJECT_PREFIXES:Kx,MSG_HEADERS:Hx,LOG_LEVELS:Fi,LOG_LEVEL_FLAGS:Qx,LOG_LEVEL_HIERARCHY:Wx}});var fO=m((Ise,EO)=>{"use strict";var zx={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))},Jx="certificate.pem",Xx="privateKey.pem",Zx="ca.pem";EO.exports={CERTIFICATE_VALUES:zx,CERTIFICATE_PEM_NAME:Jx,PRIVATEKEY_PEM_NAME:Xx,CA_PEM_NAME:Zx}});var vf=m((Cse,RO)=>{"use strict";var pO=require("fs-extra"),j=require("joi"),jx=require("os"),{boolean:Se,string:Ps,number:ir,array:Pf}=j.types(),{totalmem:hO}=require("os"),qi=require("path"),ek=q(),Xu=x(),wse=fO(),mO=g(),tk=ve(),SO="log",rk="components",sk="Invalid logging.rotation.maxSize unit. Available units are G, M or K",nk="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",ik="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",ak="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",ok="rootPath config parameter is undefined",ck="clustering.enabled config parameter is undefined",Ms=ir.min(0).required(),Zu=Pf.items({host:Ps.required(),port:Ms}).empty(null),vs;RO.exports={configValidator:uk,routesValidator:hk,route_constraints:Zu};function uk(e){if(vs=e.rootPath,Xu.isEmpty(vs))throw ok;let t=Se.required(),r=j.valid("production","development").required(),s=ir.min(0).max(1e3).empty(null).default(fk),n=Ps.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Ju),i=j.custom(lk).messages({"any.custom":"{:#label} {:#error}"}),a=Ps.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=j.string().empty(null).default(Ju),u=j.custom(_k).empty(null).default(Ju),l=e.clustering?.enabled;if(Xu.isEmpty(l))throw ck;let _;return l===!0?_=j.object({enabled:t,hubServer:j.object({cluster:j.object({name:j.required().empty(null),network:j.object({port:Ms,routes:Zu}).required()}).required(),leafNodes:j.object({network:j.object({port:Ms}).required()}).required(),network:j.object({port:Ms}).required()}).required(),leafServer:j.object({network:j.object({port:Ms,routes:Zu}).required(),streams:j.object({maxAge:ir.min(120).allow(null).optional(),maxBytes:ir.min(1).allow(null).optional(),maxMsgs:ir.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:j.valid("error","warn","info","debug","trace"),nodeName:a,republishMessages:Se.optional(),databaseLevel:Se.optional(),tls:j.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:Se.required(),verify:Se.optional()}),user:Ps.optional().empty(null)}).required():_=j.object({enabled:t,tls:j.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:Se.required()})}).required(),j.object({authentication:j.object({authorizeLocal:Se,cacheTTL:ir.required(),enableSessions:Se,operationTokenTimeout:j.required(),refreshTokenTimeout:j.required()}),analytics:j.object({aggregatePeriod:ir}),clustering:_,customFunctions:j.object({enabled:t,network:j.object({cors:Se.required(),corsAccessList:Pf.required(),headersTimeout:ir.min(1).required(),https:Se.required(),keepAliveTimeout:ir.min(1).required(),port:Ms,timeout:ir.min(1).required()}),nodeEnv:r,root:n,tls:j.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),localStudio:j.object({enabled:t}).required(),logging:j.object({auditAuthEvents:j.object({logFailed:Se,logSuccessful:Se}),file:Se.required(),level:j.valid("notify","fatal","error","warn","info","debug","trace"),rotation:j.object({enabled:Se.optional(),compress:Se.optional(),interval:Ps.custom(Ek).optional().empty(null),maxSize:Ps.custom(dk).optional().empty(null),path:Ps.optional().empty(null).default(Ju)}).required(),root:n,stdStreams:Se.required(),auditLog:Se.required()}).required(),operationsApi:j.object({foreground:Se.required(),network:j.object({cors:Se.required(),corsAccessList:Pf.required(),headersTimeout:ir.min(1).required(),https:Se.required(),keepAliveTimeout:ir.min(1).required(),port:Ms,timeout:ir.min(1).required()}).required(),nodeEnv:r,tls:j.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Ps.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:j.object({network:j.object({port:Ms,securePort:Ms}).required(),webSocket:Se.optional(),requireAuthentication:Se.optional()}),http:j.object({threads:s}).required(),storage:j.object({writeAsync:Se.required(),overlappingSync:Se.optional(),caching:Se.optional(),compression:Se.optional(),noReadAhead:Se.optional(),path:u,prefetchWrites:Se.optional()}).required(),ignoreScripts:Se.optional()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}o(uk,"configValidator");function TO(e){return pO.existsSync(e)?null:`Specified path ${e} does not exist.`}o(TO,"doesPathExist");function lk(e,t){if(e===null)return;let r=TO(e);return r?t.message(r):e}o(lk,"validatePemFile");function _k(e,t){j.assert(e,Ps.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=TO(e);if(r)return t.message(r)}o(_k,"validatePath");function dk(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(sk);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(ik):e}o(dk,"validateRotationMaxSize");function Ek(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(nk);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(ak):e}o(Ek,"validateRotationInterval");function fk(e,t){let r=t.state.path.join("."),s=jx.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||hO();return i=Math.round(Math.min(i,hO())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),ek.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}o(fk,"setDefaultThreads");function Ju(e,t){if(!Xu.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(Xu.isEmpty(vs))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return qi.join(vs,rk);case"logging.root":return qi.join(vs,SO);case"clustering.leafServer.streams.path":return qi.join(vs,"clustering","leaf");case"storage.path":let s=qi.join(vs,mO.LEGACY_DATABASES_DIR_NAME);return pO.existsSync(s)?s:qi.join(vs,mO.DATABASES_DIR_NAME);case"logging.rotation.path":return qi.join(vs,SO);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}o(Ju,"setDefaultRoot");function hk(e){let t=j.object({routes:Zu});return tk.validateBySchema({routes:e},t)}o(hk,"routesValidator")});var Ar=m((Lse,UO)=>{"use strict";var gr=g(),lt=x(),tt=q(),{configValidator:mk,routesValidator:gO}=vf(),Ft=require("fs-extra"),Sk=require("yaml"),Hr=require("path"),pk=require("is-number"),OO=require("properties-reader"),Tk=require("lodash"),{handleHDBError:Rk}=W(),{HTTP_STATUS_CODES:gk,HDB_ERROR_MSGS:ju}=rr(),Dse=require("minimist"),{SCHEMAS_PARAM_CONFIG:Ro,CONFIG_PARAMS:En,CONFIG_PARAM_MAP:Bs}=gr,Ak="Unable to get config value because config is uninitialized",Ok="Config successfully initialized",Nk="Error backing up config file",bk="Empty parameter sent to getConfigValue",NO=Hr.join(gr.PACKAGE_ROOT,"config","yaml",gr.HDB_DEFAULT_CONFIG_FILE),yk="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",AO={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"},el,St;UO.exports={createConfigFile:Ik,getDefaultConfig:wk,getConfigValue:yO,initConfig:IO,flattenConfig:Xn,updateConfigValue:wO,updateConfigObject:Uk,getConfiguration:Mk,setConfiguration:Pk,readConfigFile:Ff,getClusteringRoutes:vk,initOldConfig:CO,getConfigFromFile:Bk,getConfigFilePath:Jn,addConfig:Hk,deleteConfigFromFile:Fk};function Ik(e){let t=fn(NO);el=Xn(t.toJSON());let r;for(let a in e){let c=Bs[a.toLowerCase()];if(c===En.SCHEMAS){r=e[a];continue}if(c!==void 0){let u=c.split("_"),l=Bf(c,e[a]);c==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{t.setIn([...u],l)}catch(_){tt.error(_)}}}r&&bO(t,r),Hf(t);let s=t.toJSON();St=Xn(s);let n=t.getIn(["rootPath"]),i=Hr.join(n,gr.HDB_CONFIG_FILE);Ft.createFileSync(i),Ft.writeFileSync(i,String(t)),tt.trace(`Config file written to ${i}`)}o(Ik,"createConfigFile");function bO(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!lt.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(Ro.TABLES))for(let i in s[n][Ro.TABLES])for(let a in s[n][Ro.TABLES][i]){let c=s[n][Ro.TABLES][i][a],u=[En.SCHEMAS,n,Ro.TABLES,i,a];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let a=s[n][i],c=[En.SCHEMAS,n,i];e.hasIn(c)?e.setIn(c,a):e.addIn(c,a)}}}catch(s){tt.error("Error parsing schemas CLI/env config arguments",s)}}o(bO,"setSchemasConfig");function wk(e){if(el===void 0){let r=fn(NO);el=Xn(r.toJSON())}let t=Bs[e.toLowerCase()];if(t!==void 0)return el[t.toLowerCase()]}o(wk,"getDefaultConfig");function yO(e){if(e==null){tt.error(bk);return}if(St===void 0){tt.trace(Ak);return}let t=Bs[e.toLowerCase()];if(t!==void 0)return St[t.toLowerCase()]}o(yO,"getConfigValue");function Jn(e=lt.getPropsFilePath()){let t=lt.getEnvCliRootPath();return t?Hr.join(t,gr.HDB_CONFIG_FILE):OO(e).get(gr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}o(Jn,"getConfigFilePath");function IO(e=!1){if(St===void 0||e){let t;if(!lt.noBootFile()){t=lt.getPropsFilePath();try{Ft.accessSync(t,Ft.constants.F_OK|Ft.constants.R_OK)}catch(i){throw tt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Jn(t),s;if(r.includes("config/settings.js"))try{CO(r);return}catch(i){if(i.code!==gr.NODE_ERROR_CODES.ENOENT)throw i}try{s=fn(r)}catch(i){if(i.code===gr.NODE_ERROR_CODES.ENOENT){tt.trace(`HarperDB config file not found at ${r}.
|
|
5
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw tt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}Ck(s,r),Hf(s);let n=s.toJSON();if(St=Xn(n),St.logging_rotation_rotate)for(let i in AO)St[i]&&tt.error(`Config ${AO[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);tt.trace(Ok)}}o(IO,"initConfig");function Ck(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Hr.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Hr.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Hr.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(tt.trace("Updating config file with missing config params"),Ft.writeFileSync(t,String(e)))}o(Ck,"checkForUpdatedConfig");function Hf(e){let t=e.toJSON(),r=mk(t);if(r.error)throw ju.CONFIG_VALIDATION(r.error.message);e.setIn(["http","threads"],r.value.http.threads),e.setIn(["customFunctions","root"],r.value.customFunctions.root),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path)}o(Hf,"validateConfig");function Uk(e,t){St===void 0&&(St={});let r=Bs[e.toLowerCase()];if(r===void 0){tt.trace(`Unable to update config object because config param '${e}' does not exist`);return}St[r.toLowerCase()]=t}o(Uk,"updateConfigObject");function wO(e,t,r=void 0,s=!1,n=!1,i=!1){St===void 0&&IO();let a=yO(Bs.hdb_root),c=Hr.join(a,gr.HDB_CONFIG_FILE),u=fn(c),l;if(r===void 0&&e.toLowerCase()===En.SCHEMAS)l=t;else if(r===void 0){let E;if(i)E=e;else if(E=Bs[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=Bf(E,t);u.setIn([...f],h)}else for(let E in r){let f=Bs[E.toLowerCase()];if(f===En.SCHEMAS){l=r[E];continue}if(f!==void 0){let h=f.split("_"),T=Bf(f,r[E]);f==="rootPath"&&T?.endsWith("/")&&(T=T.slice(0,-1));try{u.setIn([...h],T)}catch(S){tt.error(S)}}}l&&bO(u,l),Hf(u);let _=u.getIn(["rootPath"]),d=Hr.join(_,gr.HDB_CONFIG_FILE);s===!0&&Dk(c,_),Ft.writeFileSync(d,String(u)),n&&(St=Xn(u.toJSON())),tt.trace(`Config parameter: ${e} updated with value: ${t}`)}o(wO,"updateConfigValue");function Dk(e,t){try{let r=Hr.join(t,"backup",`${gr.HDB_CONFIG_FILE}.bak`);Ft.copySync(e,r),tt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){tt.error(Nk),tt.error(r)}}o(Dk,"backupConfigFile");var Lk=["schemas"];function Xn(e){let t={};for(let r in e)if(e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])&&!Lk.includes(r)){let s=Xn(e[r]);for(let n in s)s.hasOwnProperty(n)&&(t[r.toLowerCase()+"_"+n]=s[n])}else t[r.toLowerCase()]=e[r];return t}o(Xn,"flattenConfig");function Bf(e,t){if(e===En.CLUSTERING_NODENAME||e===En.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(pk(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||lt.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 lt.autoCast(t)}o(Bf,"castConfigValue");function Mk(){let e=lt.getPropsFilePath(),t=Jn(e);return fn(t).toJSON()}o(Mk,"getConfiguration");async function Pk(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return wO(void 0,void 0,n,!0),yk}catch(i){throw typeof i=="string"||i instanceof String?Rk(i,i,gk.BAD_REQUEST,void 0,void 0,!0):i}}o(Pk,"setConfiguration");function Ff(){let e=lt.getPropsFilePath();try{Ft.accessSync(e,Ft.constants.F_OK|Ft.constants.R_OK)}catch(s){if(!lt.noBootFile())throw tt.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Jn(e);return fn(t).toJSON()}o(Ff,"readConfigFile");function fn(e){return Sk.parseDocument(Ft.readFileSync(e,"utf8"),{simpleKeys:!0})}o(fn,"parseYamlDoc");function vk(){let e=Ff(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=lt.isEmptyOrZeroLength(t)?[]:t;let r=gO(t);if(r)throw ju.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=lt.isEmptyOrZeroLength(s)?[]:s;let n=gO(s);if(n)throw ju.CONFIG_VALIDATION(n.message);if(!lt.isEmptyOrZeroLength(s)&&!lt.isEmptyOrZeroLength(t)){let i=t.filter(a=>s.some(c=>c.host===a.host&&c.port===a.port));if(!lt.isEmptyOrZeroLength(i)){let a=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw ju.CONFIG_VALIDATION(a)}}return{hub_routes:t,leaf_routes:s}}o(vk,"getClusteringRoutes");function CO(e){let t=OO(e);St={};for(let r in Bs){let s=t.get(r.toUpperCase());if(lt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=Bs[r].toLowerCase();n===En.LOGGING_ROOT?St[n]=Hr.dirname(s):St[n]=s}return St}o(CO,"initOldConfig");function Bk(e){let t=Ff();return Tk.get(t,e.replaceAll("_","."))}o(Bk,"getConfigFromFile");async function Hk(e,t){let r=fn(Jn());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await Ft.writeFile(Jn(),String(r))}o(Hk,"addConfig");function Fk(e){let t=Jn(lt.getPropsFilePath()),r=fn(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Hr.join(s,gr.HDB_CONFIG_FILE);Ft.writeFileSync(n,String(r))}o(Fk,"deleteConfigFromFile")});var LO=m((Pse,DO)=>{"use strict";var tl=g(),rl=class{static{o(this,"BaseLicense")}constructor(t=0,r=tl.RAM_ALLOCATION_ENUM.DEFAULT,s=tl.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},qf=class extends rl{static{o(this,"ExtendedLicense")}constructor(t=0,r=tl.RAM_ALLOCATION_ENUM.DEFAULT,s=tl.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};DO.exports={BaseLicense:rl,ExtendedLicense:qf}});var go=m((Bse,FO)=>{"use strict";var xi=require("fs-extra"),MO=zu(),PO=require("crypto"),qk=require("moment"),Gk=require("uuid").v4,wt=q(),xf=require("path"),xk=x(),hn=g(),kk=LO().ExtendedLicense,Gi="invalid license key format",Vk="061183",$k="mofi25",Yk="aes-256-cbc",Kk=16,Wk=32,vO=Q();vO.initSync();var Gf;FO.exports={validateLicense:BO,generateFingerPrint:zk,licenseSearch:HO,getLicense:Zk};function kf(){return xf.join(vO.getHdbBasePath(),hn.LICENSE_KEY_DIR_NAME,hn.LICENSE_FILE_NAME)}o(kf,"getLicenseDirPath");function Qk(){let e=kf();return xf.join(e,hn.LICENSE_FILE_NAME)}o(Qk,"getLicenseFilePath");function Vf(){let e=kf();return xf.join(e,hn.REG_KEY_FILE_NAME)}o(Vf,"getFingerPrintFilePath");async function zk(){let e=Vf();try{return await xi.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await Jk();throw wt.error(`Error writing fingerprint file to ${e}`),wt.error(t),new Error("There was an error generating the fingerprint")}}o(zk,"generateFingerPrint");async function Jk(){let e=Gk(),t=MO.hash(e),r=Vf();try{await xi.mkdirp(kf()),await xi.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw wt.error(`Error writing fingerprint file to ${r}`),wt.error(s),new Error("There was an error generating the fingerprint")}return t}o(Jk,"writeFingerprint");function BO(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:hn.RAM_ALLOCATION_ENUM.DEFAULT,version:hn.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return wt.error("empty license key passed to validate."),r;let s=Vf(),n=!1;try{n=xi.statSync(s)}catch(i){wt.error(i)}if(n){let i;try{i=xi.readFileSync(s,"utf8")}catch{wt.error("error validating this machine in the license"),r.valid_machine=!1;return}let a=e.split($k),c=a[1];c=Buffer.concat([Buffer.from(c)],Kk);let u=Buffer.concat([Buffer.from(i)],Wk),l=PO.createDecipheriv(Yk,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let _=null;try{_=l.update(a[0],"hex","utf8"),_.trim(),_+=l.final("utf8")}catch{let f=Xk(a[0],i);if(f)_=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Gi),wt.error(Gi),new Error(Gi)}let d;if(isNaN(_))try{d=JSON.parse(_),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(Gi),wt.error(Gi),new Error(Gi)}else r.exp_date=_;r.exp_date<qk().valueOf()&&(r.valid_date=!1),MO.validate(a[1],`${Vk}${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||wt.error("Invalid licence"),r}o(BO,"validateLicense");function Xk(e,t){try{let r=PO.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{wt.warn("Check old license failed")}}o(Xk,"checkOldLicense");function HO(){let e=new kk,t=[];try{t=xi.readFileSync(Qk(),"utf-8").split(hn.NEW_LINE)}catch(r){r.code==="ENOENT"?wt.info("no license file found"):wt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(xk.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=BO(n.license_key,n.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(n){wt.error("There was an error parsing the license string."),wt.error(n),e.ram_allocation=hn.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Gf=e,e}o(HO,"licenseSearch");async function Zk(){return Gf||await HO(),Gf}o(Zk,"getLicense")});var Or=m((xse,eN)=>{"use strict";var VO="username is required",$O="nothing to update, must supply active, role or password to update",YO="password cannot be an empty string",KO="If role is specified, it cannot be empty.",WO="active must be true or false";eN.exports={addUser:oV,alterUser:cV,dropUser:lV,getSuperUser:fV,userInfo:_V,listUsers:nl,listUsersExternal:dV,setUsersToGlobal:Vi,findAndValidateUser:jO,getClusterUser:hV,USERNAME_REQUIRED:VO,ALTERUSER_NOTHING_TO_UPDATE:$O,EMPTY_PASSWORD:YO,EMPTY_ROLE:KO,ACTIVE_BOOLEAN:WO};var QO=Rr(),jk=zn(),Yf=zu(),zO=lO(),JO=Tr(),Kf=Hs(),ar=x(),XO=require("validate.js"),ue=q(),{promisify:eV}=require("util"),Wf=Ls(),qO=g(),GO=Be(),tV=Ar(),Fse=Q(),qse=go(),rV=kn(),{table:Gse}=(de(),re(Ne)),{handleHDBError:ss,hdb_errors:sV}=W(),{HTTP_STATUS_CODES:ns,AUTHENTICATION_ERROR_MSGS:$f,HDB_ERROR_MSGS:ki}=sV,{UserEventMsg:Qf}=Fr(),xO=require("lodash"),{_assignPackageExport:nV}=require("../index");nV("getUser",jO);var ZO={username:!0,active:!0,role:!0,password:!0},kO=new Map,sl=JO.searchByValue,iV=JO.searchByHash,aV=eV(jk.delete);async function oV(e){let t=XO.cleanAttributes(e,ZO),r=zO.addUserValidation(t);if(r)throw ss(new Error,r.message,ns.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 sl(s),n=n&&Array.from(n)}catch(u){throw ue.error("There was an error searching for a role in add user"),ue.error(u),u}if(!n||n.length<1)throw ss(new Error,ki.ROLE_NAME_NOT_FOUND(t.role),ns.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw ss(new Error,ki.DUP_ROLES_FOUND(t.role),ns.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=Wf.encrypt(t.password)),t.password=Yf.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},a;try{a=await QO.insert(i)}catch(u){throw ue.error("There was an error searching for a user."),ue.error(u),u}ue.debug(a);try{await Vi()}catch(u){throw ue.error("Got an error setting users to global"),ue.error(u),u}if(a.skipped_hashes.length===1)throw ss(new Error,ki.USER_ALREADY_EXISTS(t.username),ns.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],Kf.signalUserChange(new Qf(process.pid)),`${c.username} successfully added`}o(oV,"addUser");async function cV(e){let t=XO.cleanAttributes(e,ZO);if(ar.isEmptyOrZeroLength(t.username))throw new Error(VO);if(ar.isEmptyOrZeroLength(t.password)&&ar.isEmptyOrZeroLength(t.role)&&ar.isEmptyOrZeroLength(t.active))throw new Error($O);if(!ar.isEmpty(t.password)&&ar.isEmptyOrZeroLength(t.password.trim()))throw new Error(YO);if(!ar.isEmpty(t.active)&&!ar.isBoolean(t.active))throw new Error(WO);let r=uV(t.username);if(!ar.isEmpty(t.password)&&!ar.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Wf.encrypt(t.password)),t.password=Yf.hash(t.password)),t.role==="")throw new Error(KO);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},a;try{a=Array.from(await sl(i)||[])}catch(c){throw ue.error("Got an error searching for a role."),ue.error(c),c}if(!a||a.length===0){let c=ki.ALTER_USER_ROLE_NOT_FOUND(t.role);throw ue.error(c),ss(new Error,c,ns.NOT_FOUND,void 0,void 0,!0)}if(a.length>1){let c=ki.ALTER_USER_DUP_ROLES(t.role);throw ue.error(c),ss(new Error,c,ns.CONFLICT,void 0,void 0,!0)}t.role=a[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await QO.update(s)}catch(i){throw ue.error("Error during update."),ue.error(i),i}try{await Vi()}catch(i){throw ue.error("Got an error setting users to global"),ue.error(i),i}return Kf.signalUserChange(new Qf(process.pid)),n}o(cV,"alterUser");function uV(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}o(uV,"isClusterUser");async function lV(e){try{let t=zO.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(ar.isEmpty(global.hdb_users.get(e.username)))throw ss(new Error,ki.USER_NOT_EXIST(e.username),ns.NOT_FOUND,void 0,void 0,!0);let s;try{s=await aV(r)}catch(n){throw ue.error("Got an error deleting a user."),ue.error(n),n}ue.debug(s);try{await Vi()}catch(n){throw ue.error("Got an error setting users to global."),ue.error(n),n}return Kf.signalUserChange(new Qf(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}o(lV,"dropUser");async function _V(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 iV(r)}catch(n){throw ue.error("Got an error searching for a role."),ue.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw ue.error(r),r}return t}o(_V,"userInfo");async function dV(){let e;try{e=await nl()}catch(t){throw ue.error("Got an error listing users."),ue.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()]}o(dV,"listUsersExternal");async function nl(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await sl(e)}catch(a){throw ue.error("Got an error searching for roles."),ue.error(a),a}let r={};for(let a of t)r[a.id]=xO.cloneDeep(a);if(Object.keys(r).length===0)return null;let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await sl(s)}catch(a){throw ue.error("Got an error searching for users."),ue.error(a),a}let i=new Map;for(let a of n)a=xO.cloneDeep(a),a.role=r[a.role],EV(a.role),i.set(a.username,a);return i}catch(e){throw ue.error("got an error listing users"),ue.error(e),ar.errorizeMessage(e)}return null}o(nl,"listUsers");function EV(e){try{if(!e){ue.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(rV)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){ue.error("Got an error trying to set system permissions."),ue.error(t)}}o(EV,"appendSystemTablesToRole");async function Vi(){try{let e=await nl();global.hdb_users=e}catch(e){throw ue.error(e),e}}o(Vi,"setUsersToGlobal");async function jO(e,t,r=!0){global.hdb_users||await Vi();let s=global.hdb_users.get(e);if(!s)throw ss(new Error,$f.GENERIC_AUTH_FAIL,ns.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw ss(new Error,$f.USER_INACTIVE,ns.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(kO.get(t)===s.password)return n;if(Yf.validate(s.password,t))kO.set(t,s.password);else throw ss(new Error,$f.GENERIC_AUTH_FAIL,ns.UNAUTHORIZED,void 0,void 0,!0)}return n}o(jO,"findAndValidateUser");async function fV(){global.hdb_users||await Vi();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}o(fV,"getSuperUser");async function hV(){let e=await nl(),t=tV.getConfigFromFile(qO.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!ar.isEmpty(r)&&r?.role?.role===qO.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Wf.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+GO.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+GO.SERVER_SUFFIX.ADMIN,r}o(hV,"getClusterUser")});var Oo=m((Yse,nN)=>{"use strict";var Zn=q(),or=g(),mV=DA(),Vse=ln(),$se=$n(),SV=Or(),{validateEvent:tN}=Fr(),Ao=Br(),pV=require("process"),{resetDatabases:TV}=(de(),re(Ne)),RV={[or.ITC_EVENT_TYPES.SCHEMA]:gV,[or.ITC_EVENT_TYPES.USER]:sN};async function gV(e){let t=tN(e);if(t){Zn.error(t);return}Zn.trace("ITC schemaHandler received schema event:",e),await mV(e.message),await AV(e.message)}o(gV,"schemaHandler");async function AV(e){try{Ao.resetReadTxn(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Ao.resetReadTxn(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Ao.resetReadTxn(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=TV();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Zn.error(t)}}o(AV,"syncSchemaMetadata");var rN=[];async function sN(e){try{try{Ao.resetReadTxn(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Ao.resetReadTxn(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Zn.warn(r)}let t=tN(e);if(t){Zn.error(t);return}Zn.trace(`ITC userHandler ${or.HDB_ITC_CLIENT_PREFIX}${pV.pid} received user event:`,e),await SV.setUsersToGlobal();for(let r of rN)r()}catch(t){Zn.error(t)}}o(sN,"userHandler");sN.addListener=function(e){rN.push(e)};nN.exports=RV});var Fr=m((Xse,aN)=>{"use strict";var Wse=q(),zf=x(),OV=g(),{ITC_ERRORS:No}=rr(),{parentPort:Qse,threadId:NV,isMainThread:bV,workerData:zse}=require("worker_threads"),{onMessageFromWorkers:yV,broadcast:Jse,broadcastWithAcknowledgement:IV}=_t();aN.exports={sendItcEvent:wV,validateEvent:iN,SchemaEventMsg:CV,UserEventMsg:UV};var il;yV(async(e,t)=>{il=il||Oo(),iN(e),il[e.type]&&await il[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function wV(e){return!bV&&e.message&&(e.message.originator=NV),IV(e)}o(wV,"sendItcEvent");function iN(e){if(typeof e!="object")return No.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||zf.isEmpty(e.type))return No.MISSING_TYPE;if(!e.hasOwnProperty("message")||zf.isEmpty(e.message))return No.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||zf.isEmpty(e.message.originator))return No.MISSING_ORIGIN;if(OV.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return No.INVALID_EVENT(e.type)}o(iN,"validateEvent");function CV(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}o(CV,"SchemaEventMsg");function UV(e){this.originator=e}o(UV,"UserEventMsg")});var Hs=m((ene,lN)=>{"use strict";var oN=g(),jse=x(),al=q(),cN=wA(),$i,{sendItcEvent:uN}=Fr();function DV(e){try{al.trace("signalSchemaChange called with message:",e),$i=$i||Oo();let t=new cN(oN.ITC_EVENT_TYPES.SCHEMA,e);return $i.schema(t),uN(t)}catch(t){al.error(t)}}o(DV,"signalSchemaChange");function LV(e){try{al.trace("signalUserChange called with message:",e),$i=$i||Oo();let t=new cN(oN.ITC_EVENT_TYPES.USER,e);return $i.user(t),uN(t)}catch(t){al.error(t)}}o(LV,"signalUserChange");lN.exports={signalSchemaChange:DV,signalUserChange:LV}});var ol=m((rne,dN)=>{"use strict";var _N=x(),MV=g(),PV=q(),vV=Fu(),BV=Hu(),HV=Hs(),{SchemaEventMsg:FV}=Fr(),qV="already exists in";dN.exports=GV;async function GV(e,t,r){if(_N.isEmptyOrZeroLength(r))return r;let s=[];_N.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 xV(e,t.schema,t.name,i)})),n}o(GV,"lmdbCheckForNewAttributes");async function xV(e,t,r,s){let n=new BV(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await kV(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(qV))PV.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}o(xV,"createNewAttribute");async function kV(e){let t;return t=await vV(e),HV.signalSchemaChange(new FV(process.pid,MV.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}o(kV,"createAttribute")});var Yi=m((nne,EN)=>{"use strict";var Jf=class{static{o(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};EN.exports=Jf});var hN=m((ane,fN)=>{"use strict";var VV=Yi(),$V=g().OPERATIONS_ENUM,Xf=class extends VV{static{o(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super($V.INSERT,r,s,n,i),this.records=t}};fN.exports=Xf});var SN=m((cne,mN)=>{"use strict";var YV=Yi(),KV=g().OPERATIONS_ENUM,Zf=class extends YV{static{o(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,a=void 0){super(KV.UPDATE,s,n,i,a),this.records=t,this.original_records=r}};mN.exports=Zf});var TN=m((lne,pN)=>{"use strict";var WV=Yi(),QV=g().OPERATIONS_ENUM,jf=class extends WV{static{o(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,a=void 0){super(QV.UPSERT,s,n,i,a),this.records=t,this.original_records=r}};pN.exports=jf});var gN=m((dne,RN)=>{"use strict";var zV=Yi(),JV=g().OPERATIONS_ENUM,eh=class extends zV{static{o(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(JV.DELETE,s,n,t,i),this.original_records=r}};RN.exports=eh});var bo=m((hne,bN)=>{"use strict";var fne=require("path"),AN=ye(),XV=hN(),ZV=SN(),jV=TN(),e$=gN(),Ki=xe(),ON=x(),{CONFIG_PARAMS:t$}=g(),NN=Q();NN.initSync();var cl=g().OPERATIONS_ENUM,{getTransactionAuditStorePath:r$}=we();bN.exports=s$;async function s$(e,t){if(NN.get(t$.LOGGING_AUDITLOG)===!1)return;let r=r$(e.schema,e.table),s=await AN.openEnvironment(r,e.table,!0),n=n$(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){AN.initializeDBIs(s,Ki.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Ki.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[Ki.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[Ki.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),ON.isEmpty(n.user_name)||s.dbis[Ki.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let a=0;a<n.hash_values.length;a++)s.dbis[Ki.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[a],i)})}}o(s$,"writeTransaction");function n$(e,t){let r=ON.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===cl.INSERT)return new XV(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===cl.UPDATE)return new ZV(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===cl.UPSERT)return new jV(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===cl.DELETE)return new e$(t.deleted,t.original_records,r,t.txn_time,e.__origin)}o(n$,"createTransactionObject")});var th=m((pne,yN)=>{"use strict";var i$=Eo(),Sne=fo(),yo=g(),a$=po(),o$=Bi().insertRecords,c$=ye(),u$=q(),l$=ol(),{getSchemaPath:_$}=we(),d$=bo();yN.exports=E$;async function E$(e){try{let{schema_table:t,attributes:r}=i$(e);a$(e,r,t.hash_attribute),e.schema!==yo.SYSTEM_SCHEMA_NAME&&(r.includes(yo.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(yo.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(yo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(yo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await l$(e.hdb_auth_header,t,r),n=_$(e.schema,e.table),i=await c$.openEnvironment(n,e.table),a=await o$(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await d$(e,a)}catch(c){u$.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:a.written_hashes,skipped_hashes:a.skipped_hashes,schema_table:t,new_attributes:s,txn_time:a.txn_time}}catch(t){throw t}}o(E$,"lmdbCreateRecords")});var CN=m((Rne,wN)=>{"use strict";var IN=g(),f$=th(),h$=fo(),m$=require("fs-extra"),{getSchemaPath:S$}=we();wN.exports=p$;async function p$(e){let t=[{name:e.schema,createddate:Date.now()}],r=new h$(IN.SYSTEM_SCHEMA_NAME,IN.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await f$(r),await m$.mkdirp(S$(e.schema))}o(p$,"lmdbCreateSchema")});var DN=m((Ane,UN)=>{"use strict";var rh=class{static{o(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};UN.exports=rh});var vN=m((Ine,PN)=>{"use strict";var LN=ye(),sh=vt(),nh=rr().LMDB_ERRORS_ENUM,T$=xe(),MN=q(),Nne=x(),R$=require("lmdb"),g$=DN(),A$=g(),{OVERFLOW_MARKER:bne,MAX_SEARCH_KEY_LENGTH:yne}=T$,O$=A$.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function N$(e,t,r,s){if(sh.validateEnv(e),t===void 0)throw new Error(nh.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(nh.IDS_REQUIRED):new Error(nh.IDS_MUST_BE_ITERABLE);try{let n=LN.listDBIs(e);LN.initializeDBIs(e,t,n);let i=new g$,a,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{a=r[E];let h=e.dbis[t].get(a);if(!h||s&&h[O$]>s){i.skipped.push(a);continue}let T=e.dbis[t].ifVersion(a,R$.IF_EXISTS,()=>{e.dbis[t].remove(a);for(let S=0;S<n.length;S++){let y=n[S];if(!h.hasOwnProperty(y)||y===t)continue;let O=e.dbis[y],H=h[y];if(H!=null)try{let Y=sh.getIndexedValues(H);if(Y)for(let A=0,w=Y.length;A<w;A++)O.remove(Y[A],a)}catch{MN.warn(`cannot delete from attribute: ${y}, ${H}:${a}`)}}});c.push(T),u.push(a),i.original_records.push(h)}catch(h){MN.warn(h),i.skipped.push(a)}let l=[],_=await Promise.all(c);for(let E=0,f=_.length;E<f;E++)_[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),l.push(E));let d=0;for(let E=0;E<l.length;E++){let f=l[E];i.original_records.splice(f-d,1),d++}return i.txn_time=sh.getNextMonotonicTime(),i}catch(n){throw n}}o(N$,"deleteRecords");PN.exports={deleteRecords:N$}});var Io=m((Cne,HN)=>{"use strict";var Wi=x(),b$=vN(),y$=ye(),{getSchemaPath:I$}=we(),w$=bo(),C$=q();HN.exports=U$;async function U$(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Wi.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Wi.isEmptyOrZeroLength(e.hash_values)&&!Wi.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Wi.isEmpty(u)||e.hash_values.push(u)}}if(Wi.isEmptyOrZeroLength(e.hash_values))return BN([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Wi.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=I$(e.schema,e.table),i=await y$.openEnvironment(n,e.table),a=await b$.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await w$(e,a)}catch(c){C$.error(`unable to write transaction due to ${c.message}`)}return BN(a.deleted,a.skipped,a.txn_time)}catch(n){throw n}}o(U$,"lmdbDeleteRecords");function BN(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}}o(BN,"createDeleteResponse")});var ah=m((Lne,FN)=>{"use strict";var D$=g(),Dne=vt();function ih(e,t){let r=Object.create(null);if(t.length===1&&D$.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}o(ih,"parseRow");function L$(e,t,r,s){let n=ih(r,e);s.push(n)}o(L$,"searchAll");function M$(e,t,r,s){let n=ih(r,e);s[t]=n}o(M$,"searchAllToMap");function P$(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}o(P$,"iterateDBI");function jn(e,t,r,s,n){let i=Object.create(null);i[n]=e;let a;s===n?a=e:(a=t,s!==void 0&&(i[s]=a)),r[0].push(a),r[1].push(i)}o(jn,"pushResults");function v$(e,t,r,s,n,i){t.toString().endsWith(e)&&jn(t,r,s,n,i)}o(v$,"endsWith");function B$(e,t,r,s,n,i){t.toString().includes(e)&&jn(t,r,s,n,i)}o(B$,"contains");function H$(e,t,r,s,n,i){t>e&&jn(t,r,s,n,i)}o(H$,"greaterThanCompare");function F$(e,t,r,s,n,i){t>=e&&jn(t,r,s,n,i)}o(F$,"greaterThanEqualCompare");function q$(e,t,r,s,n,i){t<e&&jn(t,r,s,n,i)}o(q$,"lessThanCompare");function G$(e,t,r,s,n,i){t<=e&&jn(t,r,s,n,i)}o(G$,"lessThanEqualCompare");FN.exports={parseRow:ih,searchAll:L$,searchAllToMap:M$,iterateDBI:P$,endsWith:v$,contains:B$,greaterThanCompare:H$,greaterThanEqualCompare:F$,lessThanCompare:q$,lessThanEqualCompare:G$,pushResults:jn}});var Qi=m((Hne,YN)=>{"use strict";var mn=ye(),Pne=q(),cr=vt(),ul=xe(),ke=rr().LMDB_ERRORS_ENUM,vne=x(),x$=g(),ll=ah(),{parseRow:k$}=ll,Bne=require("lmdb"),{OVERFLOW_MARKER:qN,MAX_SEARCH_KEY_LENGTH:V$}=ul;function GN(e,t,r,s=!1,n=void 0,i=void 0){return ei(e,t,r,(a,c)=>c.getRange({transaction:a,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}o(GN,"iterateFullIndex");function wo(e,t,r,s,n,i=!1,a=void 0,c=void 0,u=!1,l=!1){return ei(e,t,r,(_,d,E,f)=>{let O={transaction:_,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:a,offset:c,inclusiveEnd:i===!0?!u:!l,exclusiveStart:i===!0?l:u};return f===r?(O.values=!1,d.getRange(O).map(H=>({value:H}))):d.getRange(O)})}o(wo,"iterateRangeBetween");function ei(e,t,r,s){let n=e.database||e,i=mn.openDBI(n,r);i[ul.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&mn.openDBI(n,t);let a;e.database?a=e:(a=e.useReadTransaction(),a.database=e);let c=s(a,i,n,t);return c.transaction=a,e.database||(c.onDone=()=>{a.done()}),c}o(ei,"setupTransaction");function xN(e,t,r,s){let n;return function(i,a){if(typeof i=="string"&&i.endsWith(qN)){if(!n)if(r)n=mn.openDBI(e,r);else{let u=mn.listDBIs(e);for(let l=0,_=u.length;l<_&&(n=mn.openDBI(e,u[l]),!n[ul.DBI_DEFINITION_NAME].is_hash_attribute);l++);}i=n.get(a,{transaction:t,lazy:!0})[s]}return i}}o(xN,"getOverflowCheck");function $$(e,t,r,s=!1,n=void 0,i=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);return ei(e,t,t,(a,c,u)=>(_l(r),r=Co(u,r),c.getRange({transaction:a,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(l=>k$(l.value,r))))}o($$,"searchAll");function Y$(e,t,r,s=!1,n=void 0,i=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);_l(r),r=Co(e.database||e,r);let a=new Map;for(let{key:c,value:u}of GN(e,t,t,s,n,i))a.set(c,ll.parseRow(u,r));return a}o(Y$,"searchAllToMap");function K$(e,t,r=!1,s=void 0,n=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);let i=Object.create(null),a=GN(e,void 0,t,r,s,n),c=a.transaction,u=xN(c.database,c,void 0,t);for(let{key:l,value:_}of a){let d=u(l,_);i[d]===void 0&&(i[d]=[]),i[d].push(_)}return i}o(K$,"iterateDBI");function W$(e,t){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);return mn.statDBI(e,t).entryCount}o(W$,"countAll");function Q$(e,t,r,s,n=!1,i=void 0,a=void 0){return Sn(e,r,s),ei(e,t,r,(c,u,l,_)=>(s=cr.convertKeyValueToWrite(s),_===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:a}).map(d=>({key:s,value:d}))))}o(Q$,"equals");function z$(e,t,r){return Sn(e,t,r),mn.openDBI(e,t).getValuesCount(r)}o(z$,"count");function J$(e,t,r,s,n=!1,i=void 0,a=void 0){return Sn(e,r,s),ei(e,null,r,(c,u)=>{s=cr.convertKeyValueToWrite(s);let l=!0;typeof s=="number"&&(l=!1);let _;if(n===!0){let d;for(let E of u.getKeys({transaction:c,start:s}))if(!E.startsWith(s)){d=E;break}return d!==void 0&&(Number.isInteger(a)?a++:i++),_=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:a}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(s))return E;if(l===!0)return _.DONE}}),_.filter(E=>E)}else return _=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:a}).map(d=>{if(d.key.toString().startsWith(s))return d;if(l===!0)return _.DONE}),l?_:_.filter(d=>d)})}o(J$,"startsWith");function X$(e,t,r,s,n=!1,i=void 0,a=void 0){return kN(e,t,r,s,n,i,a,!0)}o(X$,"endsWith");function kN(e,t,r,s,n=!1,i=void 0,a=void 0,c=!1){return Sn(e,r,s),ei(e,null,r,(u,l,_,d)=>{let E=xN(_,u,d,r);return a=Number.isInteger(a)?a:0,l.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(f=>{let h=f.toString();return h.endsWith(qN)?l.getValues(f,{transaction:u}).map(T=>{let S=E(f,T);if(c?S.endsWith(s):S.includes(s))return{key:S,value:T}}).filter(T=>T):(c?h.endsWith(s):h.includes(s))?l[ul.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:l.getValues(f,{transaction:u}).map(T=>({key:f,value:T})):[]}).slice(a,i===void 0?void 0:i+(a||0))})}o(kN,"contains");function Z$(e,t,r,s,n=!1,i=void 0,a=void 0){Sn(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),wo(e,t,r,s,u,n,i,a,!0,!1)}o(Z$,"greaterThan");function j$(e,t,r,s,n=!1,i=void 0,a=void 0){Sn(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),wo(e,t,r,s,u,n,i,a,!1,!1)}o(j$,"greaterThanEqual");function eY(e,t,r,s,n=!1,i=void 0,a=void 0){Sn(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),wo(e,t,r,u,s,n,i,a,!1,!0)}o(eY,"lessThan");function tY(e,t,r,s,n=!1,i=void 0,a=void 0){Sn(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),wo(e,t,r,u,s,n,i,a,!1,!1)}o(tY,"lessThanEqual");function rY(e,t,r,s,n,i=!1,a=void 0,c=void 0){if(cr.validateEnv(e),r===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ke.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ke.END_VALUE_REQUIRED);if(s=cr.convertKeyValueToWrite(s),n=cr.convertKeyValueToWrite(n),s>n)throw new Error(ke.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return wo(e,t,r,s,n,i,a,c)}o(rY,"between");function sY(e,t,r,s){cr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(_l(r),r=Co(n,r),s===void 0)throw new Error(ke.ID_REQUIRED);let a=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(a=ll.parseRow(c,r)),a}o(sY,"searchByHash");function nY(e,t,r){cr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ke.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}o(nY,"checkHashExists");function iY(e,t,r,s,n=[]){return $N(e,t,r,s,n),VN(e,t,r,s,n).map(i=>i[1])}o(iY,"batchSearchByHash");function aY(e,t,r,s,n=[]){$N(e,t,r,s,n);let i=new Map;for(let[a,c]of VN(e,t,r,s,n))i.set(a,c);return i}o(aY,"batchSearchByHashToMap");function VN(e,t,r,s,n=[]){return ei(e,t,t,(i,a,c)=>{r=Co(c,r);let u=r.length<3;return s.map(l=>{let _=c.dbis[t].get(l,{transaction:i,lazy:u});if(_)return[l,ll.parseRow(_,r)];n.push(l)}).filter(l=>l)})}o(VN,"batchHashSearch");function $N(e,t,r,s,n){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(_l(r),s==null)throw new Error(ke.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ke.IDS_MUST_BE_ITERABLE)}o($N,"initializeBatchSearchByHash");function _l(e){if(!Array.isArray(e))throw e===void 0?new Error(ke.FETCH_ATTRIBUTES_REQUIRED):new Error(ke.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}o(_l,"validateFetchAttributes");function Sn(e,t,r){if(cr.validateEnv(e),t===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ke.SEARCH_VALUE_REQUIRED);if(r?.length>V$)throw new Error(ke.SEARCH_VALUE_TOO_LARGE)}o(Sn,"validateComparisonFunctions");function Co(e,t){return t.length===1&&x$.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=mn.listDBIs(e)),t}o(Co,"setGetWholeRowAttributes");YN.exports={searchAll:$$,searchAllToMap:Y$,count:z$,countAll:W$,equals:Q$,startsWith:J$,endsWith:X$,contains:kN,searchByHash:sY,setGetWholeRowAttributes:Co,batchSearchByHash:iY,batchSearchByHashToMap:aY,checkHashExists:nY,iterateDBI:K$,greaterThan:Z$,greaterThanEqual:j$,lessThan:eY,lessThanEqual:tY,between:rY}});var zi=m((qne,JN)=>{var KN=require("lodash"),WN=ve(),Ce=require("joi"),oY=x(),{hdb_schema_table:dl,checkValidTable:QN,hdb_table:zN,hdb_database:El}=ts(),{handleHDBError:cY,hdb_errors:uY}=W(),{getDatabases:lY}=(de(),re(Ne)),{HTTP_STATUS_CODES:_Y}=uY,dY=Ce.object({database:El,schema:El,table:zN,search_attribute:dl,search_value:Ce.any().required(),get_attributes:Ce.array().min(1).items(dl).optional(),desc:Ce.bool(),limit:Ce.number().integer().min(1),offset:Ce.number().integer().min(0)}),EY=Ce.object({database:El,schema:El,table:zN,operator:Ce.string().valid("and","or").default("and").lowercase(),offset:Ce.number().integer().min(0),limit:Ce.number().integer().min(1),get_attributes:Ce.array().min(1).items(dl).optional(),conditions:Ce.array().min(1).items(Ce.object({search_attribute:dl,search_type:Ce.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:Ce.when("search_type",{switch:[{is:"equals",then:Ce.any()},{is:"between",then:Ce.array().items(Ce.alternatives([Ce.string(),Ce.number()])).length(2)}],otherwise:Ce.alternatives(Ce.string(),Ce.number())}).required()})).required()});JN.exports=function(e,t){let r=null;switch(t){case"value":r=WN.validateBySchema(e,dY);break;case"hashes":let i=function(a){n?n+=". "+a:n=a};var s=i;o(i,"addError");let n;i(QN("database",e.schema)),i(QN("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(a=>typeof a=="string"||typeof a=="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(a=>typeof a=="string"||typeof a=="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=WN.validateBySchema(e,EY);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=oY.checkGlobalSchemaTable(e.schema,e.table);if(n)return cY(new Error,n,_Y.NOT_FOUND);let a=lY()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let l=0,_=e.conditions.length;l<_;l++){let d=e.conditions[l];c.push(d.search_attribute)}let u=KN.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!KN.some(a,_=>_===l||_.attribute===l||_.attribute===l.attribute));if(u&&u.length>0){let l=u.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var oh=m((xne,XN)=>{"use strict";var fY=ye(),hY=zi(),{getSchemaPath:mY}=we();XN.exports=SY;function SY(e){let t=hY(e,"hashes");if(t)throw t;let r=mY(e.schema,e.table);return fY.openEnvironment(r,e.table)}o(SY,"initialize")});var ch=m((Vne,ZN)=>{"use strict";var pY=Qi(),TY=oh();ZN.exports=RY;async function RY(e){let t=await TY(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return pY.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}o(RY,"lmdbGetDataByHash")});var Ji=m((Yne,jN)=>{"use strict";var uh=class{static{o(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};jN.exports=uh});var tb=m((Qne,eb)=>{"use strict";var Wne=Ji(),gY=Qi(),AY=oh();eb.exports=OY;async function OY(e){let t=await AY(e),r=global.hdb_schema[e.schema][e.table];return gY.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}o(OY,"lmdbSearchByHash")});var is=m((Jne,rb)=>{"use strict";var lh=class{static{o(this,"SearchObject")}constructor(t,r,s,n,i,a,c,u=!1,l=void 0,_=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=a,this.end_value=c,this.reverse=u,this.limit=l,this.offset=_}};rb.exports=lh});var fl=m((Zne,cb)=>{"use strict";var Ct=Qi(),NY=ye(),bY=x(),ae=xe(),ti=g(),yY=kn(),sb=rr().LMDB_ERRORS_ENUM,{getSchemaPath:IY}=we(),Fs=ti.SEARCH_WILDCARDS;async function wY(e,t,r){let s;e.schema===ti.SYSTEM_SCHEMA_NAME?s=yY[e.table]:s=global.hdb_schema[e.schema][e.table];let n=ob(e,s.hash_attribute,r,t);return ib(e,n,s.hash_attribute,r)}o(wY,"prepSearch");async function ib(e,t,r,s){let n=IY(e.schema,e.table),i=await NY.openEnvironment(n,e.table),a=ab(i,e,t,r),c=a.transaction||i;if([ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,ae.SEARCH_TYPES.SEARCH_ALL,ae.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return a;if(CY(e,r)===!1){let _=e.search_attribute;if(_===r)return s?nb(a,()=>!0):a.map(E=>({[r]:E.key}));let d=o(E=>({[r]:E.value,[_]:E.key}),"toObject");return s?nb(a,d):a.map(d)}let l=e.search_attribute===r?a.map(_=>_.key):a.map(_=>_.value);return s===!0?Ct.batchSearchByHashToMap(c,r,e.get_attributes,l):Ct.batchSearchByHash(c,r,e.get_attributes,l)}o(ib,"executeSearch");function ab(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:a,limit:c,offset:u}=t;switch(a=typeof a=="boolean"?a:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case ae.SEARCH_TYPES.EQUALS:n=Ct.equals(e,i,t.search_attribute,t.search_value,a,c,u);break;case ae.SEARCH_TYPES.CONTAINS:n=Ct.contains(e,i,t.search_attribute,t.search_value,a,c,u);break;case ae.SEARCH_TYPES.ENDS_WITH:case ae.SEARCH_TYPES._ENDS_WITH:n=Ct.endsWith(e,i,t.search_attribute,t.search_value,a,c,u);break;case ae.SEARCH_TYPES.STARTS_WITH:case ae.SEARCH_TYPES._STARTS_WITH:n=Ct.startsWith(e,i,t.search_attribute,t.search_value,a,c,u);break;case ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Ct.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Ct.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case ae.SEARCH_TYPES.SEARCH_ALL:return Ct.searchAll(e,s,t.get_attributes,a,c,u);case ae.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Ct.searchAllToMap(e,s,t.get_attributes,a,c,u);case ae.SEARCH_TYPES.BETWEEN:n=Ct.between(e,i,t.search_attribute,t.search_value,t.end_value,a,c,u);break;case ae.SEARCH_TYPES.GREATER_THAN:case ae.SEARCH_TYPES._GREATER_THAN:n=Ct.greaterThan(e,i,t.search_attribute,t.search_value,a,c,u);break;case ae.SEARCH_TYPES.GREATER_THAN_EQUAL:case ae.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Ct.greaterThanEqual(e,i,t.search_attribute,t.search_value,a,c,u);break;case ae.SEARCH_TYPES.LESS_THAN:case ae.SEARCH_TYPES._LESS_THAN:n=Ct.lessThan(e,i,t.search_attribute,t.search_value,a,c,u);break;case ae.SEARCH_TYPES.LESS_THAN_EQUAL:case ae.SEARCH_TYPES._LESS_THAN_EQUAL:n=Ct.lessThanEqual(e,i,t.search_attribute,t.search_value,a,c,u);break;default:return Object.create(null)}return n}o(ab,"searchByType");function nb(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}o(nb,"createMapFromIterable");function CY(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}o(CY,"checkToFetchMore");function ob(e,t,r,s){if(bY.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),a=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Fs.indexOf(n)>-1)return r===!0?ae.SEARCH_TYPES.SEARCH_ALL_TO_MAP:ae.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(Fs[0])<0&&n.indexOf(Fs[1])<0)return c===!0?r===!0?ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:ae.SEARCH_TYPES.EQUALS;if(Fs.indexOf(i)>=0&&Fs.indexOf(a)>=0)return e.search_value=e.search_value.slice(1,-1),ae.SEARCH_TYPES.CONTAINS;if(Fs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),ae.SEARCH_TYPES.ENDS_WITH;if(Fs.indexOf(a)>=0)return e.search_value=e.search_value.slice(0,-1),ae.SEARCH_TYPES.STARTS_WITH;if(n.includes(Fs[0])||n.includes(Fs[1]))return ae.SEARCH_TYPES.EQUALS;throw new Error(sb.UNKNOWN_SEARCH_TYPE)}else switch(s){case ti.VALUE_SEARCH_COMPARATORS.BETWEEN:return ae.SEARCH_TYPES.BETWEEN;case ti.VALUE_SEARCH_COMPARATORS.GREATER:return ae.SEARCH_TYPES.GREATER_THAN;case ti.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return ae.SEARCH_TYPES.GREATER_THAN_EQUAL;case ti.VALUE_SEARCH_COMPARATORS.LESS:return ae.SEARCH_TYPES.LESS_THAN;case ti.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return ae.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(sb.UNKNOWN_SEARCH_TYPE)}}o(ob,"createSearchTypeFromSearchObject");cb.exports={executeSearch:ib,createSearchTypeFromSearchObject:ob,prepSearch:wY,searchByType:ab}});var lb=m((tie,ub)=>{"use strict";var eie=is(),UY=zi(),DY=x(),LY=g(),MY=fl();ub.exports=PY;function PY(e,t){if(!DY.isEmpty(t)&&LY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=UY(e,"value");if(s)throw s;let n=!0;return MY.prepSearch(e,t,n)}o(PY,"lmdbGetDataByValue")});var Uo=m((nie,_b)=>{"use strict";var sie=is(),vY=zi(),BY=x(),HY=g(),FY=fl();_b.exports=qY;async function qY(e,t){if(!BY.isEmpty(t)&&HY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=vY(e,"value");if(s)throw s;return FY.prepSearch(e,t,!1)}o(qY,"lmdbSearchByValue")});var Eb=m((oie,db)=>{"use strict";var aie=xe(),_h=class{static{o(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,a=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=a,this.conditions=n,this.operator=c}},dh=class{static{o(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Eh=class{static{o(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};db.exports={SearchByConditionsObject:_h,SearchCondition:dh,SortAttribute:Eh}});var pb=m((_ie,Sb)=>{"use strict";var uie=Eb().SearchByConditionsObject,GY=is(),xY=zi(),fh=Qi(),hl=xe(),{Resource:lie}=(Xr(),re(IE)),mb=fl(),kY=ah(),VY=require("lodash"),{getSchemaPath:$Y}=we(),fb=ye(),{handleHDBError:YY,hdb_errors:KY}=W(),{HTTP_STATUS_CODES:WY}=KY,QY=1e8;Sb.exports=zY;async function zY(e){let t=xY(e,"conditions");if(t)throw YY(t,t.message,WY.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=$Y(e.schema,e.table),s=await fb.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let l of e.conditions)fb.openDBI(s,l.search_attribute);let i=VY.sortBy(e.conditions,l=>{if(l.estimated_count===void 0){let _=l.search_type;_===hl.SEARCH_TYPES.EQUALS?l.estimated_count=fh.count(s,l.search_attribute,l.search_value):_===hl.SEARCH_TYPES.CONTAINS||_===hl.SEARCH_TYPES.ENDS_WITH?l.estimated_count=1/0:l.estimated_count=QY}return l.estimated_count}),a=s.useReadTransaction();a.database=s;let c=await hb(a,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let l=s.dbis[n.hash_attribute],_=i.slice(1).map(mb.filterByType),d=_.length,E=fh.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(f=>l.get(f,{transaction:a,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!_[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>kY.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await hb(a,e,E,n.hash_attribute);c=c.concat(f)}let l=new Set,_=e.offset||0;c=c.filter(d=>l.has(d)?!1:(l.add(d),!0)).slice(_,e.limit&&e.limit+_),u=fh.batchSearchByHash(a,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{a.done()},u}o(zY,"lmdbSearchByConditions");async function hb(e,t,r,s){let n=new GY(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===hl.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,mb.searchByType(e,n,i,s).map(a=>a.value)}o(hb,"executeConditionSearch")});var Do=m((Eie,Tb)=>{"use strict";var JY=g().OPERATIONS_ENUM,hh=class{static{o(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=JY.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};Tb.exports=hh});var mh=m((hie,Ib)=>{"use strict";var Ob=is(),Nb=Do(),bb=Uo(),yb=Io(),qt=g(),Rb=x(),gb=ye(),{getTransactionAuditStorePath:XY,getSchemaPath:ZY}=we(),Ab=q();Ib.exports=jY;async function jY(e){try{if(Rb.isEmpty(global.hdb_schema[e.schema])||Rb.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await eK(e),await tK(e);let t=ZY(e.schema,e.table);try{await gb.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Ab.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=XY(e.schema,e.table);await gb.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Ab.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}o(jY,"lmdbDropTable");async function eK(e){let t=new Ob(qt.SYSTEM_SCHEMA_NAME,qt.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await bb(t)),s=[];for(let i=0;i<r.length;i++){let a=r[i];s.push(a.id)}if(s.length===0)return;let n=new Nb(qt.SYSTEM_SCHEMA_NAME,qt.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await yb(n)}o(eK,"deleteAttributesFromSystem");async function tK(e){let t=new Ob(qt.SYSTEM_SCHEMA_NAME,qt.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await bb(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let a=r[i];a.name===e.table&&a.schema===e.schema&&(s=a)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new Nb(qt.SYSTEM_SCHEMA_NAME,qt.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await yb(n)}catch(i){throw i}}o(tK,"dropTableFromSystem")});var Cb=m((Sie,wb)=>{"use strict";var rK=require("fs-extra"),sK=is(),nK=Ji(),iK=Do(),aK=mh(),oK=Io(),cK=ch(),uK=Uo(),qs=g(),{getSchemaPath:lK}=we(),{handleHDBError:_K,hdb_errors:dK}=W(),{HDB_ERROR_MSGS:EK,HTTP_STATUS_CODES:fK}=dK;wb.exports=hK;async function hK(e){let t;try{t=await mK(e.schema);let r=new sK(qs.SYSTEM_SCHEMA_NAME,qs.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,qs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[qs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await uK(r));for(let a=0;a<s.length;a++){let c={schema:t,table:s[a].name};try{await aK(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new iK(qs.SYSTEM_SCHEMA_NAME,qs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await oK(n);let i=lK(t);await rK.remove(i)}catch(r){throw r}}o(hK,"lmdbDropSchema");async function mK(e){let t=new nK(qs.SYSTEM_SCHEMA_NAME,qs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[qs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await cK(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw _K(new Error,EK.SCHEMA_NOT_FOUND(e),fK.NOT_FOUND,void 0,void 0,!0);return s}o(mK,"validateDropSchema")});var ph=m((Tie,Ub)=>{"use strict";var Sh=class{static{o(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};Ub.exports=Sh});var Lb=m((Aie,Db)=>{"use strict";var SK=require("fs-extra"),ml=ye(),{getTransactionAuditStorePath:pK}=we(),Th=xe(),gie=ph();Db.exports=TK;async function TK(e){let t;try{let r=pK(e.schema,e.table);await SK.mkdirp(r),t=await ml.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{ml.createDBI(t,Th.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),ml.createDBI(t,Th.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),ml.createDBI(t,Th.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}o(TK,"createTransactionsAuditEnvironment")});var Bb=m((Nie,vb)=>{"use strict";var Rh=g(),Mb=ye(),RK=Bi(),{getSystemSchemaPath:gK,getSchemaPath:AK}=we(),OK=kn(),NK=Fu(),gh=Hu(),bK=q(),yK=Lb(),Oh=OK.hdb_table,Pb=[];for(let e=0;e<Oh.attributes.length;e++)Pb.push(Oh.attributes[e].attribute);vb.exports=IK;async function IK(e,t){let r=AK(t.schema,t.table),s=new gh(t.schema,t.table,Rh.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new gh(t.schema,t.table,Rh.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new gh(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Mb.createEnvironment(r,t.table),e!==void 0){let a=await Mb.openEnvironment(gK(),Rh.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await RK.insertRecords(a,Oh.hash_attribute,Pb,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Ah(s),await Ah(n),await Ah(i)}await yK(t)}catch(a){throw a}}o(IK,"lmdbCreateTable");async function Ah(e){try{await NK(e)}catch(t){bK.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}o(Ah,"createAttribute")});var Fb=m((yie,Hb)=>{"use strict";var wK=Eo(),CK=po(),UK=ol(),Lo=g(),DK=Bi().updateRecords,LK=ye(),{getSchemaPath:MK}=we(),PK=bo(),vK=q();Hb.exports=BK;async function BK(e){try{let{schema_table:t,attributes:r}=wK(e);CK(e,r,t.hash_attribute),e.schema!==Lo.SYSTEM_SCHEMA_NAME&&(r.includes(Lo.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Lo.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Lo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Lo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await UK(e.hdb_auth_header,t,r),n=MK(e.schema,e.table),i=await LK.openEnvironment(n,e.table),a=await DK(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await PK(e,a)}catch(c){vK.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:a.written_hashes,skipped_hashes:a.skipped_hashes,schema_table:t,new_attributes:s,txn_time:a.txn_time}}catch(t){throw t}}o(BK,"lmdbUpdateRecords")});var Gb=m((wie,qb)=>{"use strict";var HK=g().OPERATIONS_ENUM,Nh=class{static{o(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=HK.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};qb.exports=Nh});var kb=m((Die,xb)=>{"use strict";var Uie=Gb(),FK=Eo(),qK=po(),GK=ol(),Mo=g(),xK=Bi().upsertRecords,kK=ye(),{getSchemaPath:VK}=we(),$K=bo(),YK=q(),{handleHDBError:KK,hdb_errors:WK}=W();xb.exports=QK;async function QK(e){let t;try{t=FK(e)}catch(u){throw KK(u,u.message,WK.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;qK(e,s,r.hash_attribute),e.schema!==Mo.SYSTEM_SCHEMA_NAME&&(s.includes(Mo.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(Mo.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(Mo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(Mo.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await GK(e.hdb_auth_header,r,s),i=VK(e.schema,e.table),a=await kK.openEnvironment(i,e.table),c=await xK(a,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await $K(e,c)}catch(u){YK.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}o(QK,"lmdbUpsertRecords")});var $b=m((Mie,Vb)=>{"use strict";var bh=class{static{o(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};Vb.exports=bh});var Kb=m((vie,Yb)=>{"use strict";var yh=class{static{o(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};Yb.exports=yh});var zb=m((Fie,Qb)=>{"use strict";var Ih=ye(),{getTransactionAuditStorePath:zK}=we(),Hie=$b(),Po=xe(),JK=x(),Wb=Kb(),XK=require("util").promisify,ZK=XK(setTimeout),jK=1e4,e1=100;Qb.exports=t1;async function t1(e){let t=zK(e.schema,e.table),r=await Ih.openEnvironment(t,e.table,!0),s=Ih.listDBIs(r);Ih.initializeDBIs(r,Po.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new Wb;do n=await r1(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 ZK(e1);while(n.transactions_deleted>0);return i}o(t1,"deleteAuditLogsBefore");async function r1(e,t){let r=new Wb;try{let s=e.dbis[Po.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:a}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=a[Po.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];JK.isEmpty(c)||(n=e.dbis[Po.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<a.hash_values.length;u++)n=e.dbis[Po.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(a.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>jK)break}return await n,r}catch(s){throw s}}o(r1,"deleteTransactions")});var Xb=m((Gie,Jb)=>{"use strict";var wh=class{static{o(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};Jb.exports=wh});var jb=m((Vie,Zb)=>{"use strict";var s1=is(),n1=Do(),kie=Xb(),as=g(),i1=x(),Ch=ye(),a1=kn(),o1=Uo(),c1=Io(),{getSchemaPath:u1}=we();Zb.exports=l1;async function l1(e,t=!0){let r;e.schema===as.SYSTEM_SCHEMA_NAME?r=a1[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await d1(e),n=u1(e.schema,e.table),i=await Ch.openEnvironment(n,e.table);return t===!0&&await _1(e,i,r.hash_attribute),Ch.dropDBI(i,e.attribute),s}o(l1,"lmdbDropAttribute");async function _1(e,t,r){let s=Ch.openDBI(t,r),n,i=e.attribute;for(let{key:a,value:c,version:u}of s.getRange({start:!1,versions:!0})){let l={};for(let _ in c)_!==i&&(l[_]=c[_]);n=t.dbis[r].put(a,l,u)}await n}o(_1,"removeAttributeFromAllObjects");async function d1(e){let t=new s1(as.SYSTEM_SCHEMA_NAME,as.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await o1(t)).filter(a=>a[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(i1.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(a=>a[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new n1(as.SYSTEM_SCHEMA_NAME,as.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return c1(i)}o(d1,"dropAttributeFromSystem")});var iy=m((Kie,ny)=>{"use strict";var Uh=ye(),Xi=xe(),Yie=vt(),Dh=g(),ey=x(),{getTransactionAuditStorePath:E1}=we(),f1=Qi(),Sl=Yi(),h1=q();ny.exports=m1;async function m1(e){let t=E1(e.schema,e.table),r=await Uh.openEnvironment(t,e.table,!0),s=Uh.listDBIs(r);Uh.initializeDBIs(r,Xi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Dh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return ty(r,e.search_values);case Dh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,p1(r,e.search_values,n);case Dh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return S1(r,e.search_values);default:return ty(r)}}o(m1,"readAuditLog");function ty(e,t=[0,Date.now()]){ey.isEmpty(t[0])&&(t[0]=0),ey.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[Xi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new Sl,n))}o(ty,"searchTransactionsByTimestamp");function S1(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let a of e.dbis[Xi.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(a);r.set(n,sy(e,i))}return Object.fromEntries(r)}o(S1,"searchTransactionsByUsername");function p1(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let l=t[c],_=f1.equals(e,Xi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Xi.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,l);for(let{value:d}of _){let E=Number(d);s.has(E)?s.get(E).push(l.toString()):s.set(E,[l.toString()])}}let n=Array.from(s.keys()),i=sy(e,n),a=new Map;for(let c=0;c<i.length;c++){let u=i[c],l=u.timestamp,_=s.get(l);ry(u,"records",r,_,a),ry(u,"original_records",r,_,a)}return Object.fromEntries(a)}o(p1,"searchTransactionsByHashValues");function ry(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let a=0;a<e[t].length;a++){let c=e[t][a],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let l=n.get(u),_=l[l.length-1];if(_.timestamp===i)_[t]=[c];else{let d=new Sl(e.operation,e.user_name,i,void 0);d[t]=[c],l.push(d)}}else{let l=new Sl(e.operation,e.user_name,i,void 0);l[t]=[c],n.set(u,[l])}}}o(ry,"loopRecords");function sy(e,t){let r=[];try{let s=e.dbis[Xi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let a=Object.assign(new Sl,i);r.push(a)}}catch(i){h1.warn(i)}return r}catch(s){throw s}}o(sy,"batchSearchTransactions")});var oy=m((Jie,ay)=>{"use strict";var{getSchemaPath:Qie}=we(),zie=ye(),{database:T1}=(de(),re(Ne));ay.exports={writeTransaction:R1};async function R1(e,t,r){return T1({database:e,table:t}).transaction(r)}o(R1,"writeTransaction")});var _y=m((Zie,ly)=>{"use strict";var{getSchemaPath:cy}=we(),uy=ye();ly.exports={flush:g1,resetReadTxn:A1};async function g1(e,t){return(await uy.openEnvironment(cy(e,t),t.toString())).flushed}o(g1,"flush");async function A1(e,t){try{(await uy.openEnvironment(cy(e,t),t.toString())).resetReadTxn()}catch{}}o(A1,"resetReadTxn")});var hy=m((eae,fy)=>{"use strict";var{Readable:O1}=require("stream"),{getDatabases:N1}=(de(),re(Ne)),{readSync:b1,openSync:y1,createReadStream:dy}=require("fs"),{open:I1}=require("lmdb"),Ey=Iu(),w1=Cu(),{INTERNAL_DBIS_NAME:C1}=xe();fy.exports=D1;var Lh=32768,U1=100;async function D1(e){let t=e.database||e.schema||"data",r=N1()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let l=r[n[0]];if(!l)throw new Error(`Can not find table ${n[0]}`);let _=l.dbisDB,d=I1({noSync:!0,maxDbs:w1.MAX_DBS}),E,f=d.openDB(C1,new Ey(!1)),h=_.useReadTransaction(),T=0;for(let{key:y,value:O}of _.getRange({transaction:h,start:!1}))if(n.some(H=>y.startsWith?.(H+"/"))){f.put(y,O);let[,H]=y.split("/"),Y=!H,A=new Ey(!Y,Y);A.encoding="binary";let w=d.openDB(y,A),G=_.openDB(y,A);for(let{key:k,version:X,value:ge}of G.getRange({transaction:h,versions:Y}))E=w.put(k,ge,X),T++%U1===0&&await new Promise(ct=>setTimeout(ct,20))}await E;let S=dy(d.path);return S.headers=u(),S.on("close",()=>{h.done(),d.close()}),S}let a=r[Object.keys(r)[0]].primaryStore,c=y1(a.path);return a.transaction(()=>{let l=Buffer.alloc(Lh);b1(c,l,0,Lh);let _=a.useReadTransaction(),d=dy(null,{fd:c,start:Lh}),E=new O1.from(async function*(){yield l;for await(let f of d)yield f;_.done()}());return E.headers=u(),E});function u(){let l=new Map;return l.set("content-type","application/octet-stream"),l.set("content-disposition",`attachment; filename="${t}"`),l.set("date",s),l}}o(D1,"getBackup")});var py=m((rae,Sy)=>{"use strict";var L1=q(),{handleHDBError:M1}=W(),P1=vg(),v1=Fu(),B1=th(),H1=CN(),F1=Io(),q1=ch(),G1=tb(),x1=lb(),k1=Uo(),V1=pb(),$1=Cb(),Y1=Bb(),K1=Fb(),W1=kb(),Q1=zb(),z1=mh(),J1=jb(),X1=iy(),Z1=oy(),my=_y(),j1=hy(),Mh=class extends P1{static{o(this,"LMDBBridge")}async searchByConditions(t){return V1(t)}async getDataByHash(t){return await q1(t)}async searchByHash(t){return await G1(t)}async getDataByValue(t,r){return await x1(t,r)}async searchByValue(t){return await k1(t)}async createSchema(t){return await H1(t)}async dropSchema(t){return await $1(t)}async createTable(t,r){return await Y1(t,r)}async dropTable(t){return await z1(t)}async createAttribute(t){return await v1(t)}async createRecords(t){return await B1(t)}async updateRecords(t){return await K1(t)}async upsertRecords(t){try{return await W1(t)}catch(r){throw M1(r,null,null,L1.ERR,r)}}async deleteRecords(t){return await F1(t)}async dropAttribute(t){return await J1(t)}async deleteAuditLogsBefore(t){return await Q1(t)}async readAuditLog(t){return await X1(t)}writeTransaction(t,r,s){return Z1.writeTransaction(t,r,s)}flush(t,r){return my.flush(t,r)}resetReadTxn(t,r){return my.resetReadTxn(t,r)}getBackup(t){return j1(t)}};Sy.exports=Mh});var Iy={};Ze(Iy,{ResourceBridge:()=>Bh});function Hh({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function Ry(e,t){let r=os(e),s=Hh(e,r);if(!r)throw new qr.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user};return Ye(i,async function*(a){for(let c of e.hash_values){let u=await r.get({id:c,lazy:n,select:s},i);u=u&&Ru(u),t?yield{key:c,value:u}:yield u}})}function os(e){let t=e.database||e.schema||tW,r=Gr()[t];if(!r)throw(0,qr.handleHDBError)(new Error,eW.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function gy(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*Ay(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:a,timestamp:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(a),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[a],records:[u]})}s&&(yield s)}var Oy,pl,qr,Ny,by,xr,Ph,vh,yy,eW,tW,rW,sW,Ty,Bh,wy=pe(()=>{"use strict";Oy=D(py()),pl=D(zi()),qr=D(W());de();Ny=D(Eo()),by=D(po()),xr=D(g()),Ph=D(Hs()),vh=D(Fr()),yy=D(x());Gn();gu();({HDB_ERROR_MSGS:eW}=qr.hdb_errors),tW="data",rW=1e4,sW=10,Bh=class extends Oy.default{static{o(this,"ResourceBridge")}constructor(t){super(t),Ty=this}async searchByConditions(t){let r=(0,pl.default)(t,"conditions");if(r)throw(0,qr.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=os(t);if(!s)throw new qr.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i=>({attribute:i.search_attribute,comparator:i.search_type,value:i.search_value}));return s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Hh(t,s),allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let a of s)a.is_primary_key?(a.isPrimaryKey=!0,delete a.is_primary_key):a.name===i&&i&&(a.isPrimaryKey=!0);else{if(!i)throw new qr.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}et({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await os(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=os(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=o((a,c,u)=>(c=Object.assign({},c),delete c[s],r.primaryStore.ifVersion(a,u,()=>r.primaryStore.put(a,c,u)).then(l=>{if(!l){let{value:_,version:d}=r.primaryStore.getEntry(a);return i(a,_,d)}})),"deleteRecord");for(let{key:a,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))n=i(a,c,u),await new Promise(l=>setImmediate(l));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){os(t).dropTable()}createSchema(t){return vo({database:t.schema,table:null}),Ph.signalSchemaChange(new vh.SchemaEventMsg(process.pid,xr.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Fh(t.schema),Ph.signalSchemaChange(new vh.SchemaEventMsg(process.pid,xr.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,Ty.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,Ny.default)(t);(0,by.default)(t,s,r.primaryKey);let n,i=Gr()[t.schema][t.table],a={user:t.hdb_user};return Ye(a,async c=>{if(!i.schemaDefined){n=[];for(let _ of s)i.attributes.find(E=>E.name==_)||n.push(_);n.length>0&&await i.addAttributes(n.map(_=>({name:_,indexed:!0})))}let u=[],l=[];for(let _ of t.records){let d=await i.get(_[i.primaryKey],a);if(t.requires_existing&&!d||t.requires_no_existing&&d){l.push(_[i.primaryKey]);continue}d&&(d=Ru(d));for(let E in _)if(Object.prototype.hasOwnProperty.call(_,E)){let f=_[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,_[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(_),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(_,E)||(_[E]=d[E]);await i.put(_,a),u.push(_[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:l}})}async deleteRecords(t){let r=Gr()[t.schema][t.table],s={user:t.hdb_user};return Ye(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),a=[],c=[];for(let u of i)await r.delete(u,s)?a.push(u):c.push(u);return gy(a,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Gr()[t.schema][t.table];if(!r.createdTimeProperty)throw new qr.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:xr.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],a=[],c=0,u=[],l=o(async()=>{let _=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(..._.deleted_hashes),a.push(..._.skipped_hashes),await(0,yy.async_set_timeout)(sW),u=[],n=!0},"chunkDelete");for await(let _ of s)u.push(_[r.primaryKey]),c++,c%rW===0&&await l();return u.length>0&&await l(),n?gy(i,a,void 0):{message:"No records found to delete"}}searchByHash(t){let r=(0,pl.default)(t,"hashes");if(r)throw r;return Ry(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of Ry(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&xr.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);let s=(0,pl.default)(t,"value");if(s)throw s;let n=os(t);if(!n)throw new qr.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===xr.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let a=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:a,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Hh(t,n)})}async getDataByValue(t,r){let s=new Map,n=os(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){os({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return os(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=os(t),s={};switch(t.search_type){case xr.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[i]=(await r.getHistoryOfRecord(i)).map(a=>{let c=a.type;return c==="put"&&(c="upsert"),{operation:c,user_name:a.user,hash_values:[i],records:[a.value]}});return s;case xr.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of Ay(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return Ay(r,t.search_values?.[0],t.search_values?.[1])}}};o(Hh,"getSelect");o(Ry,"getRecords");o(os,"getTable");o(gy,"createDeleteResponse");o(Ay,"groupRecordsInHistory")});var Br=m((cae,Cy)=>{"use strict";var{ResourceBridge:nW}=(wy(),re(Iy)),iW=Q();iW.initSync();var Tl;function aW(){return Tl||(Tl=new nW,Tl)}o(aW,"getBridge");Cy.exports=aW()});var My=m((lae,Ly)=>{"use strict";var Uy=require("lodash"),Bo=require("mathjs"),oW=require("jsonata"),Dy=x();Ly.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?Uy.uniqWith(e,Uy.isEqual):e,searchJSON:cW,mad:Ho.bind(null,Bo.mad),mean:Ho.bind(null,Bo.mean),mode:Ho.bind(null,Bo.mode),prod:Ho.bind(null,Bo.prod),median:Ho.bind(null,Bo.median)};function Ho(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}o(Ho,"aggregateFunction");function cW(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(Dy.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),Dy.isEmpty(this.__ala__.res[r])){let s=oW(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}o(cW,"searchJSON")});var vy=m((dae,Py)=>{"use strict";var We=require("moment"),qh="YYYY-MM-DDTHH:mm:ss.SSSZZ";We.suppressDeprecationWarnings=!0;Py.exports={current_date:()=>We().utc().format("YYYY-MM-DD"),current_time:()=>We().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return We(e).utc().format("YYYY");case"month":return We(e).utc().format("MM");case"day":return We(e).utc().format("DD");case"hour":return We(e).utc().format("HH");case"minute":return We(e).utc().format("mm");case"second":return We(e).utc().format("ss");case"millisecond":return We(e).utc().format("SSS");default:break}},date:e=>We(e).utc().format(qh),date_format:(e,t)=>We(e).utc().format(t),date_add:(e,t,r)=>We(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>We(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=We(e).utc(),n=We(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>We().utc().valueOf(),get_server_time:()=>We().format(qh),offset_utc:(e,t)=>We(e).utc().utcOffset(t).format(qh)}});var qy=m((Eae,Fy)=>{"use strict";var uW=require("@turf/area"),lW=require("@turf/length"),_W=require("@turf/circle"),dW=require("@turf/difference"),EW=require("@turf/distance"),fW=require("@turf/boolean-contains"),hW=require("@turf/boolean-equal"),mW=require("@turf/boolean-disjoint"),SW=require("@turf/helpers"),By=g(),le=x();Fy.exports={geoArea:pW,geoLength:TW,geoCircle:RW,geoDifference:gW,geoDistance:Hy,geoNear:AW,geoContains:OW,geoEqual:NW,geoCrosses:bW,geoConvert:yW};var Gh="geo1 is required",xh="geo2 is required";function pW(e){if(le.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),uW.default(e)}o(pW,"geoArea");function TW(e,t){if(le.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),lW.default(e,{units:t||"kilometers"})}o(TW,"geoLength");function RW(e,t,r){if(le.isEmpty(e))throw new Error("point is required");if(le.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),_W.default(e,t,{units:r||"kilometers"})}o(RW,"geoCircle");function gW(e,t){if(le.isEmpty(e))throw new Error("poly1 is required");if(le.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),dW(e,t)}o(gW,"geoDifference");function Hy(e,t,r){if(le.isEmpty(e))throw new Error("point1 is required");if(le.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),EW.default(e,t,{units:r||"kilometers"})}o(Hy,"geoDistance");function AW(e,t,r,s){if(le.isEmpty(e))throw new Error("point1 is required");if(le.isEmpty(t))throw new Error("point2 is required");if(le.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");return Hy(e,t,s)<=r}o(AW,"geoNear");function OW(e,t){if(le.isEmpty(e))throw new Error(Gh);if(le.isEmpty(e))throw new Error(xh);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),fW.default(e,t)}o(OW,"geoContains");function NW(e,t){if(le.isEmpty(e))throw new Error(Gh);if(le.isEmpty(e))throw new Error(xh);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),hW.default(e,t)}o(NW,"geoEqual");function bW(e,t){if(le.isEmpty(e))throw new Error(Gh);if(le.isEmpty(e))throw new Error(xh);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),!mW.default(e,t)}o(bW,"geoCrosses");function yW(e,t,r){if(le.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(le.isEmpty(t))throw new Error("geo_type is required");if(le.isEmpty(By.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(By.GEO_CONVERSION_ENUM).join(",")}`);return SW[t](e,r)}o(yW,"geoConvert")});var Rl=m((hae,Gy)=>{var ri=My(),ur=vy(),cs=qy();Gy.exports=e=>{e.aggr.mad=e.aggr.MAD=ri.mad,e.aggr.mean=e.aggr.MEAN=ri.mean,e.aggr.mode=e.aggr.MODE=ri.mode,e.aggr.prod=e.aggr.PROD=ri.prod,e.aggr.median=e.aggr.MEDIAN=ri.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ri.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ri.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=ur.current_date,e.fn.current_time=e.fn.CURRENT_TIME=ur.current_time,e.fn.extract=e.fn.EXTRACT=ur.extract,e.fn.date=e.fn.DATE=ur.date,e.fn.date_format=e.fn.DATE_FORMAT=ur.date_format,e.fn.date_add=e.fn.DATE_ADD=ur.date_add,e.fn.date_sub=e.fn.DATE_SUB=ur.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=ur.date_diff,e.fn.now=e.fn.NOW=ur.now,e.fn.offset_utc=e.fn.OFFSET_UTC=ur.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=ur.get_server_time,e.fn.getdate=e.fn.GETDATE=ur.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=ur.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=cs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=cs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=cs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=cs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=cs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=cs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=cs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=cs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=cs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=cs.geoNear}});var $y=m((mae,Vy)=>{"use strict";var Fo=require("lodash"),pt=require("alasql");pt.options.cache=!1;var IW=Rl(),xy=require("clone"),gl=require("recursive-iterator"),se=q(),ne=x(),Zi=Br(),wW=g(),{hdb_errors:CW}=W(),{getDatabases:ky}=(de(),re(Ne)),UW="IS NULL",kr="There was a problem performing this search. Please check the logs and try again.";IW(pt);var kh=class{static{o(this,"SQLSearch")}constructor(t,r){if(ne.isEmpty(t))throw se.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(),ne.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!ne.isEmptyOrZeroLength(s))return se.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw se.error("Error thrown from checkEmptySQL in SQLSearch class method search."),se.error(s),new Error(kr)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw se.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),se.error(s),new Error(kr)}if(Object.keys(this.data).length===0)return se.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw se.error("Error thrown from processJoins in SQLSearch class method search."),se.error(s),new Error(kr)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw se.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),se.error(s),new Error(kr)}try{return t=await this._finalSQL(),t}catch(s){throw se.error("Error thrown from finalSQL in SQLSearch class method search."),se.error(s),new Error(kr)}}_getColumns(){let t=new gl(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(xy(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Fo.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=ky()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(ne.isEmpty(this.statement.where)){se.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new gl(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!ne.isEmpty(r)&&r.right)if(ne.isNotEmptyAndHasValue(r.right.value)){let s=ne.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new pt.yy.LogicValue({value:s}):r.right instanceof pt.yy.StringValue&&!ne.isEmpty(s)&&ne.autoCasterIsNumberCheck(s.toString())&&(r.right=new pt.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=ne.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new pt.yy.LogicValue({value:i}):s instanceof pt.yy.StringValue&&ne.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new pt.yy.NumValue({value:i}))});if(t){se.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new gl(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 a=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!ne.isEmpty(wW.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(ne.isEmpty(this.comparator_search_values[a])&&(this.comparator_search_values[a]={ignore:!1,comparators:[]}),!this.comparator_search_values[a].ignore){if(ne.isEmptyOrZeroLength(r.left.columnid)||ne.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[a].ignore=!0,this.comparator_search_values[a].comparators=[];continue}this.comparator_search_values[a].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(ne.isEmpty(this.exact_search_values[a])&&(this.exact_search_values[a]={ignore:!1,values:new Set}),!this.exact_search_values[a].ignore){let c=!1;switch(r.op){case"=":!ne.isEmpty(r.right.value)||!ne.isEmpty(r.left.value)?s.add(ne.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let l=0;l<u.length;l++)if(u[l].value)s.add(u[l].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[a].ignore=c,c?this.exact_search_values[a].values=new Set:this.exact_search_values[a].values=new Set([...this.exact_search_values[a].values,...s])}}}_setAliasesForColumns(){if(ne.isEmptyOrZeroLength(this.all_table_attributes)&&ne.isEmptyOrZeroLength(this.statement.from)&&ne.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&&Fo.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(ne.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);ne.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(ne.isEmptyOrZeroLength(this.all_table_attributes)&&!ne.isEmptyOrZeroLength(this.columns.columns))return t;if(ne.isEmptyOrZeroLength(this.all_table_attributes)&&ne.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await pt.promise(r)}catch(r){throw se.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),se.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(xy(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(ne.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(UW)>-1&&this.tables.forEach(n=>{let i={columnid:ky()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Fo.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 a=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[a].__hash_name;return n[a]||(n[a]=[],n[a].push(null),this._addColumnToMergedAttributes(a,c)),i.attribute!==c&&(n[a].push(null),this._addColumnToMergedAttributes(a,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,a=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,l=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===a&&(u=!0),!ne.isEmpty(this.exact_search_values[l])&&!this.exact_search_values[l].ignore&&!ne.isEmptyOrZeroLength(this.exact_search_values[l].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[l].values);let _=await Zi.getDataByHash(c);for(let d of c.hash_values)_.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(_){throw se.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),se.error(_),new Error(kr)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[l].values).map(async _=>{let d=Object.assign({},c);d.search_value=_;let E=await Zi.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]):(this.data[i].__merged_data[f]=[...s[i]],this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(f)))}))}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),se.error(_),new Error(kr)}else if(!ne.isEmpty(this.comparator_search_values[l])&&!this.comparator_search_values[l].ignore&&!ne.isEmptyOrZeroLength(this.comparator_search_values[l].comparators))try{let _=this.comparator_search_values[l].comparators;for(let d=0,E=_.length;d<E;d++){let f=_[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await Zi.getDataByValue(c,f.operation);if(u)for(let[T]of h)this.data[i].__merged_data[T]||(this.data[i].__merged_data[T]=[...s[i]],this._setMergedHashAttribute(i,ne.autoCast(T)));else for(let[T,S]of h)this.data[i].__merged_data[T]?this._updateMergedAttribute(i,T,n.attribute,S[n.attribute]):(this.data[i].__merged_data[T]=[...s[i]],this._updateMergedAttribute(i,T,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(T)))}}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),se.error(_),new Error(kr)}else try{c.search_attribute=n.attribute,c.search_value="*";let _=await Zi.getDataByValue(c);if(u)for(let[d]of _)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,ne.autoCast(d)));else for(let[d,E]of _)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(d)))}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),se.error(_),new Error(kr)}}}_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 pt.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,a=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===a});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 pt.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new pt.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 pt.yy.FuncValue:new pt.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let a=[],c={};n.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,T=f.as?f.as_orig:f.tableid_orig;a.push({key:`'${T}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${T}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"",l="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(l="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let _="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(_=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${l} ${_} ${d}`,h=this._convertColumnsToIndexes(f,n);E=await pt.promise(h,t),t=null}catch(f){throw se.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),se.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let T=E[f];a.forEach(S=>{T[S.key]!==null&&T[S.key]!==void 0&&S.keys.add(T[S.key])})}a.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),T=Fo.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,y=T.length;S<y;S++){let O=T[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[O]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new gl(this.columns);for(let{node:i}of n)if(i&&i.columnid){let a=this._findColumn(i);if(a){let c=a.table.as?a.table.as:a.table.tableid;(!t[c]||t[c].indexOf(a.attribute)<0)&&s.push(a)}}s=Fo.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw se.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),se.error(i),new Error(kr)}}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,a=[];for(let _ in i)a.push(i[_][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:a,get_attributes:n.columns},u=await Zi.getDataByHash(c),l=n.columns.length;for(let _=0,d=a.length;_<d;_++){let E=a[_],f=u.get(E);for(let h=0;h<l;h++){let T=n.columns[h],S=f[T]===void 0?null:f[T];this.data[s].__merged_data[E].push(S)}}}}catch(r){throw se.error("Error thrown from getDataByHash function in SQLSearch class method getData."),se.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(a=>{let c=a.aggregatorid?a.expression:a,u=a.aggregatorid?a.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(this.statement.limit&&delete this.statement.limit,this.statement.offset&&delete this.statement.offset);let s;try{let n=this._buildSQL();se.trace(`Final SQL: ${n}`),s=await pt.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),se.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw se.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),se.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 se.error(CW.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),se.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((a,c)=>{let u=n[i],l=new RegExp(`${u}.\`${a}\``,"g"),_=`${u}.[${c}]`;s=s.replace(l,_)});for(let i in this.data)this.data[i].__merged_attributes.forEach((a,c)=>{let u=new RegExp(`\`${a}\``,"g"),l=`[${c}]`;s=s.replace(u,l)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let a=await Zi.getDataByValue(i);for(let[c,u]of a)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(a){throw se.error("There was an error when processing this SQL operation. Check your logs"),se.error(a),new Error(kr)}}return Object.values(Object.values(this.data)[0].__merged_data)}};Vy.exports=kh});var Tr=m((pae,Yy)=>{"use strict";var DW=Mg();Yy.exports={searchByConditions:MW,searchByHash:PW,searchByValue:vW,search:BW};var Vh=Br(),{transformReq:$h}=x(),LW=$y();async function MW(e){return $h(e),Vh.searchByConditions(e)}o(MW,"searchByConditions");async function PW(e){$h(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Vh.searchByHash(e))r&&t.push(r);return t}o(PW,"searchByHash");async function vW(e){$h(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Vh.searchByValue(e))t.push(r);return t}o(vW,"searchByValue");function BW(e,t){try{let r=new DW(e);r.validate(),new LW(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}o(BW,"search")});var Al=m((Rae,Ky)=>{"use strict";var HW=Br();Ky.exports={writeTransaction:FW};function FW(e,t,r){return HW.writeTransaction(e,t,r)}o(FW,"writeTransaction")});var Jy=m((Oae,zy)=>{"use strict";var qW=Tr(),GW=ln(),Wy=q(),xW=Rr(),Aae=Al(),kW=require("clone"),Kh=require("alasql"),VW=Rl(),Qy=require("util"),$W=Qy.promisify(GW.getTableSchema),YW=Qy.promisify(qW.search),KW=g(),Yh=x();VW(Kh);zy.exports={update:QW};var WW="There was a problem performing this update. Please check the logs and try again.";async function QW({statement:e,hdb_user:t}){let r=await $W(e.table.databaseid,e.table.tableid),s=zW(e.columns);Yh.backtickASTSchemaItems(e);let{table:n,where:i}=e,a=kW(n),c=Yh.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,l=Kh.parse(u).statements[0],_=await YW(l),d=JW(s,_);return XW(a,d,t)}o(QW,"update");function zW(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=Kh.compile(`SELECT ${r.expression.toString()} AS [${KW.FUNC_VAL}] FROM ?`)}),t}catch(t){throw Wy.error(t),new Error(WW)}}o(zW,"createUpdateRecord");function JW(e,t){return Yh.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}o(JW,"buildUpdateRecords");async function XW(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await xW.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){Wy.error(`Error delete new_attributes from update response: ${i}`)}return n}o(XW,"updateRecords")});var Zy=m((Iae,Xy)=>{var ZW=require("alasql"),jW=Tr(),eQ=q(),tQ=Br(),Qh=require("util"),Wh=x(),rQ=g(),sQ=ln(),bae=Al(),yae=Rr(),nQ="record",iQ="successfully deleted",aQ=Qh.callbackify(lQ),oQ=Qh.promisify(jW.search),cQ=Qh.promisify(sQ.getTableSchema);Xy.exports={convertDelete:aQ};function uQ(e){return`${e.deleted_hashes.length} ${nQ}${e.deleted_hashes.length===1?"":"s"} ${iQ}`}o(uQ,"generateReturnMessage");async function lQ({statement:e,hdb_user:t}){let r=await cQ(e.table.databaseid,e.table.tableid);Wh.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=Wh.isEmpty(n)?"":` WHERE ${n.toString()}`,a=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=ZW.parse(a).statements[0],u={operation:rQ.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await oQ(c);let l=await tQ.deleteRecords(u);return Wh.isEmptyOrZeroLength(l.message)&&(l.message=uQ(l)),delete l.txn_time,l}catch(l){throw eQ.error(l),l.hdb_code?l.message:l}}o(lQ,"convertDelete")});var sI=m((Cae,rI)=>{"use strict";var _Q=$n(),{hdb_errors:jy}=W(),{getDatabases:eI}=(de(),re(Ne));rI.exports={checkSchemaExists:tI,checkSchemaTableExists:dQ,schema_describe:_Q};async function tI(e){if(!eI()[e])return jy.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(tI,"checkSchemaExists");async function dQ(e,t){let r=await tI(e);if(r)return r;if(!eI()[e][t])return jy.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(dQ,"checkSchemaTableExists")});var yl=m((Lae,oI)=>{"use strict";var ji=Bu(),ea=sI(),EQ=q(),fQ=require("uuid").v4,Dae=require("clone"),Nl=Hs(),ta=g(),hQ=require("util"),pn=Br(),{handleHDBError:Gt,hdb_errors:mQ}=W(),{HDB_ERROR_MSGS:Ol,HTTP_STATUS_CODES:xt}=mQ,{SchemaEventMsg:bl}=Fr(),nI=rt(),{getDatabases:SQ}=(de(),re(Ne)),{transformReq:ra}=x();oI.exports={createSchema:pQ,createSchemaStructure:iI,createTable:TQ,createTableStructure:aI,createAttribute:NQ,dropSchema:RQ,dropTable:gQ,dropAttribute:AQ,getBackup:bQ};async function pQ(e){let t=await iI(e);return Nl.signalSchemaChange(new bl(process.pid,e.operation,e.schema)),t}o(pQ,"createSchema");async function iI(e){let t=ji.schema_object(e);if(t)throw Gt(t,t.message,xt.BAD_REQUEST,void 0,void 0,!0);if(ra(e),!await ea.checkSchemaExists(e.schema))throw Gt(new Error,Ol.SCHEMA_EXISTS_ERR(e.schema),xt.BAD_REQUEST,ta.LOG_LEVELS.ERROR,Ol.SCHEMA_EXISTS_ERR(e.schema),!0);return await pn.createSchema(e),`database '${e.schema}' successfully created`}o(iI,"createSchemaStructure");async function TQ(e){return ra(e),await aI(e)}o(TQ,"createTable");async function aI(e){let t=ji.create_table_object(e);if(t)throw Gt(t,t.message,xt.BAD_REQUEST,void 0,void 0,!0);if(ji.validateTableResidence(e.residence),!await ea.checkSchemaTableExists(e.schema,e.table))throw Gt(new Error,Ol.TABLE_EXISTS_ERR(e.schema,e.table),xt.BAD_REQUEST,ta.LOG_LEVELS.ERROR,Ol.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:fQ(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await pn.createTable(s,e);else throw Gt(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",xt.BAD_REQUEST);else await pn.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}o(aI,"createTableStructure");async function RQ(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=ji.schema_object(e),s=t??r;if(s)throw Gt(s,s.message,xt.BAD_REQUEST,void 0,void 0,!0);ra(e);let n=await ea.checkSchemaExists(e.schema);if(n)throw Gt(new Error,n,xt.NOT_FOUND,ta.LOG_LEVELS.ERROR,n,!0);let i=await ea.schema_describe.describeSchema({schema:e.schema}),a=Object.keys(global.hdb_schema[e.schema]);return await pn.dropSchema(e),Nl.signalSchemaChange(new bl(process.pid,e.operation,e.schema)),await nI.purgeSchemaTableStreams(e.schema,a),`successfully deleted '${e.schema}'`}o(RQ,"dropSchema");async function gQ(e){let t=ji.table_object(e);if(t)throw Gt(t,t.message,xt.BAD_REQUEST,void 0,void 0,!0);ra(e);let r=await ea.checkSchemaTableExists(e.schema,e.table);if(r)throw Gt(new Error,r,xt.NOT_FOUND,ta.LOG_LEVELS.ERROR,r,!0);return await pn.dropTable(e),await nI.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}o(gQ,"dropTable");async function AQ(e){let t=ji.attribute_object(e);if(t)throw Gt(t,t.message,xt.BAD_REQUEST,void 0,void 0,!0);ra(e);let r=await ea.checkSchemaTableExists(e.schema,e.table);if(r)throw Gt(new Error,r,xt.NOT_FOUND,ta.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Gt(new Error,"You cannot drop a hash attribute",xt.BAD_REQUEST,void 0,void 0,!0);if(ta.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Gt(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,xt.BAD_REQUEST,void 0,void 0,!0);try{return await pn.dropAttribute(e),OQ(e),Nl.signalSchemaChange(new bl(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw EQ.error(`Got an error deleting attribute ${hQ.inspect(e)}.`),s}}o(AQ,"dropAttribute");function OQ(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}o(OQ,"dropAttributeFromGlobal");async function NQ(e){ra(e);let t=SQ()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw Gt(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,xt.BAD_REQUEST,void 0,void 0,!0);return await pn.createAttribute(e),Nl.signalSchemaChange(new bl(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}o(NQ,"createAttribute");function bQ(e){return pn.getBackup(e)}o(bQ,"getBackup")});var uI=m((Pae,cI)=>{"use strict";var{OPERATIONS_ENUM:yQ}=g(),zh=class{static{o(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=yQ.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};cI.exports=zh});var Jh=m((Hae,fI)=>{"use strict";var IQ=Br(),Bae=uI(),Il=x(),wl=g(),wQ=Q(),{handleHDBError:lI,hdb_errors:CQ}=W(),{HDB_ERROR_MSGS:_I,HTTP_STATUS_CODES:dI}=CQ,UQ=Object.values(wl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),EI="To use this operation audit log must be enabled in harperdb-config.yaml";fI.exports=DQ;async function DQ(e){if(Il.isEmpty(e.schema))throw new Error(_I.SCHEMA_REQUIRED_ERR);if(Il.isEmpty(e.table))throw new Error(_I.TABLE_REQUIRED_ERR);if(!wQ.get(wl.CONFIG_PARAMS.LOGGING_AUDITLOG))throw lI(new Error,EI,dI.BAD_REQUEST,wl.LOG_LEVELS.ERROR,EI,!0);let t=Il.checkSchemaTableExist(e.schema,e.table);if(t)throw lI(new Error,t,dI.NOT_FOUND,wl.LOG_LEVELS.ERROR,t,!0);if(!Il.isEmpty(e.search_type)&&UQ.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await IQ.readAuditLog(e)}o(DQ,"readAuditLog")});var mI=m((qae,hI)=>{"use strict";var{OPERATIONS_ENUM:LQ}=g(),Xh=class{static{o(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=LQ.GET_BACKUP,this.schema=t,this.table=r}};hI.exports=Xh});var TI=m((Vae,pI)=>{"use strict";var MQ=Br(),xae=mI(),Zh=x(),PQ=g(),kae=Q(),{handleHDBError:vQ,hdb_errors:BQ}=W(),{HDB_ERROR_MSGS:SI,HTTP_STATUS_CODES:HQ}=BQ;pI.exports=FQ;async function FQ(e){if(Zh.isEmpty(e.schema))throw new Error(SI.SCHEMA_REQUIRED_ERR);if(Zh.isEmpty(e.table))throw new Error(SI.TABLE_REQUIRED_ERR);let t=Zh.checkSchemaTableExist(e.schema,e.table);if(t)throw vQ(new Error,t,HQ.NOT_FOUND,PQ.LOG_LEVELS.ERROR,t,!0);return await MQ.getBackup(read_audit_log_object)}o(FQ,"getBackup")});var bI=m((Yae,NI)=>{var Tn=require("validate.js"),gI=ve(),sa=g(),{handleHDBError:qQ,hdb_errors:GQ}=W(),{HDB_ERROR_MSGS:Ve,HTTP_STATUS_CODES:xQ}=GQ,jh=o(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),kQ={STRUCTURE_USER:"structure_user"},RI=Object.values(sa.ROLE_TYPES_ENUM),VQ="attribute_permissions",$Q="attribute_name",{PERMS_CRUD_ENUM:na}=sa,YQ=[VQ,...Object.values(na)],AI=[na.READ,na.INSERT,na.UPDATE],KQ=[$Q,...AI];function WQ(e){let t=jh();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,OI(e,t)}o(WQ,"addRoleValidation");function QQ(e){let t=jh();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,OI(e,t)}o(QQ,"alterRoleValidation");function zQ(e){let t=jh();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,gI.validateObject(e,t)}o(zQ,"dropRoleValidation");var JQ=["operation","role","id","permission","hdb_user","hdb_auth_header"];function OI(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let a=0,c=s.length;a<c;a++)JQ.includes(s[a])||n.push(s[a]);n.length>0&&Qe(Ve.INVALID_ROLE_JSON_KEYS(n),r);let i=gI.validateObject(e,t);if(i&&i.message.split(",").forEach(a=>{Qe(a,r)}),e.permission){let a=XQ(e);a&&Qe(a,r),RI.forEach(c=>{e.permission[c]&&!Tn.isBoolean(e.permission[c])&&Qe(Ve.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let a in e.permission)if(RI.indexOf(a)<0){if(a===kQ.STRUCTURE_USER){let u=e.permission[a];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let l=0,_=u.length;l<_;l++){let d=u[l];global.hdb_schema[d]||Qe(Ve.SCHEMA_NOT_FOUND(d),r)}continue}Qe(Ve.STRUCTURE_USER_ROLE_TYPE_ERROR(a),r);continue}let c=e.permission[a];if(!a||!global.hdb_schema[a]){Qe(Ve.SCHEMA_NOT_FOUND(a),r);continue}if(c.tables)for(let u in c.tables){let l=c.tables[u];if(!u||!global.hdb_schema[a][u]){Qe(Ve.TABLE_NOT_FOUND(a,u),r);continue}if(Object.keys(l).forEach(_=>{YQ.includes(_)||Qe(Ve.INVALID_PERM_KEY(_),r,a,u)}),Object.values(na).forEach(_=>{Tn.isDefined(l[_])?Tn.isBoolean(l[_])||Qe(Ve.TABLE_PERM_NOT_BOOLEAN(_),r,a,u):Qe(Ve.TABLE_PERM_MISSING(_),r,a,u)}),Tn.isDefined(l.attribute_permissions)){if(!Tn.isArray(l.attribute_permissions)){Qe(Ve.ATTR_PERMS_NOT_ARRAY,r,a,u);continue}}else{Qe(Ve.ATTR_PERMS_ARRAY_MISSING,r,a,u);continue}if(l.attribute_permissions){let _=global.hdb_schema[a][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in l.attribute_permissions){let f=l.attribute_permissions[E];if(Object.keys(f).forEach(T=>{!KQ.includes(T)&&T!==na.DELETE&&Qe(Ve.INVALID_ATTR_PERM_KEY(T),r,a,u)}),!Tn.isDefined(f.attribute_name)){Qe(Ve.ATTR_PERM_MISSING_NAME,r,a,u);continue}let h=f.attribute_name;if(!_.includes(h)){Qe(Ve.INVALID_ATTRIBUTE_IN_PERMS(h),r,a,u);continue}AI.forEach(T=>{Tn.isDefined(f[T])?Tn.isBoolean(f[T])||Qe(Ve.ATTR_PERM_NOT_BOOLEAN(T,h),r,a,u):Qe(Ve.ATTR_PERM_MISSING(T,h),r,a,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(l.read===!1&&d.read===!0||l.insert===!1&&d.insert===!0||l.update===!1&&d.update===!0){let E=`${a}.${u}`;Qe(Ve.MISMATCHED_TABLE_ATTR_PERMS(E),r,a,u)}}}}return ZQ(r)}o(OI,"customValidate");NI.exports={addRoleValidation:WQ,alterRoleValidation:QQ,dropRoleValidation:zQ};function XQ(e){let{operation:t,permission:r}=e;if(t===sa.OPERATIONS_ENUM.ADD_ROLE||t===sa.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 Ve.SU_CU_ROLE_COMBINED_ERROR;{let a=r.super_user?sa.ROLE_TYPES_ENUM.SUPER_USER:sa.ROLE_TYPES_ENUM.CLUSTER_USER;return Ve.SU_CU_ROLE_NO_PERMS_ALLOWED(a)}}}return null}o(XQ,"validateNoSUPerms");function ZQ(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:Ve.ROLE_PERMS_ERROR,...e};return qQ(new Error,s,xQ.BAD_REQUEST)}else return null}o(ZQ,"generateRolePermResponse");function Qe(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]}}o(Qe,"addPermError")});var im=m((Wae,CI)=>{"use strict";var yI=Rr(),II=Tr(),jQ=zn(),tm=bI(),rm=Hs(),ez=require("uuid").v4,tz=require("util"),Cl=g(),rz=x(),sm=II.searchByValue,sz=II.searchByHash,nz=tz.promisify(jQ.delete),iz=is(),az=Ji(),{hdb_errors:oz,handleHDBError:ia}=W(),{HDB_ERROR_MSGS:wI,HTTP_STATUS_CODES:Ul}=oz,{UserEventMsg:nm}=Fr();CI.exports={addRole:cz,alterRole:uz,dropRole:lz,listRoles:_z};function em(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}o(em,"scrubRoleDetails");async function cz(e){let t=tm.addRoleValidation(e);if(t)throw t;e=em(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},s;try{s=Array.from(await sm(r)||[])}catch(i){throw ia(i)}if(s&&s.length>0)throw ia(new Error,wI.ROLE_ALREADY_EXISTS(e.role),Ul.CONFLICT,void 0,void 0,!0);e.id||(e.id=ez());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await yI.insert(n),rm.signalUserChange(new nm(process.pid)),e=em(e),e}o(cz,"addRole");async function uz(e){let t=tm.alterRoleValidation(e);if(t)throw t;e=em(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await yI.update(r)}catch(n){throw ia(n)}if(s&&s?.message==="updated 0 of 1 records")throw ia(new Error,"Invalid role id",Ul.BAD_REQUEST,void 0,void 0,!0);return await rm.signalUserChange(new nm(process.pid)),e}o(uz,"alterRole");async function lz(e){let t=tm.dropRoleValidation(e);if(t)throw ia(new Error,t,Ul.BAD_REQUEST,void 0,void 0,!0);let r=new az(Cl.SYSTEM_SCHEMA_NAME,Cl.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await sz(r));if(s.length===0)throw ia(new Error,wI.ROLE_NOT_FOUND,Ul.NOT_FOUND,void 0,void 0,!0);let n=new iz(Cl.SYSTEM_SCHEMA_NAME,Cl.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await sm(n)),a=!1;if(rz.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){a=!0;break}}if(a===!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 nz(c),rm.signalUserChange(new nm(process.pid)),`${s[0].role} successfully deleted`}o(lz,"dropRole");async function _z(){return sm({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}o(_z,"listRoles")});var MI=m((zae,LI)=>{"use strict";var dz=Q(),Rn=require("joi"),Ez=ve(),UI=require("moment"),fz=require("fs-extra"),am=require("path"),hz=require("lodash"),qo=g(),{LOG_LEVELS:si}=g(),mz="YYYY-MM-DD hh:mm:ss",Sz=am.resolve(__dirname,"../logs");LI.exports=function(e){return Ez.validateBySchema(e,pz)};var pz=Rn.object({from:Rn.custom(DI),until:Rn.custom(DI),level:Rn.valid(si.NOTIFY,si.FATAL,si.ERROR,si.WARN,si.INFO,si.DEBUG,si.TRACE),order:Rn.valid("asc","desc"),limit:Rn.number().min(1),start:Rn.number().min(0),log_name:Rn.custom(Tz)});function DI(e,t){if(UI(e,UI.ISO_8601).format(mz)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}o(DI,"validateDatetime");function Tz(e,t){if(hz.invert(qo.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=dz.get(qo.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?qo.LOG_NAMES.HDB:e,i=n===qo.LOG_NAMES.INSTALL?am.join(Sz,qo.LOG_NAMES.INSTALL):am.join(s,n);return fz.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}o(Tz,"validateReadLogPath")});var cm=m((Xae,PI)=>{"use strict";var Dl=g(),Rz=q(),gz=Q(),Az=MI(),om=require("path"),Oz=require("fs-extra"),{once:Nz}=require("events"),{handleHDBError:bz,hdb_errors:yz}=W(),{PACKAGE_ROOT:Iz}=g(),wz=om.join(Iz,"logs"),Cz=1e3;PI.exports=Uz;async function Uz(e){let t=Az(e);if(t)throw bz(t,t.message,yz.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=gz.get(Dl.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?Dl.LOG_NAMES.HDB:e.log_name,n=s===Dl.LOG_NAMES.INSTALL?om.join(wz,Dl.LOG_NAMES.INSTALL):om.join(r,s),i=Oz.createReadStream(n);i.on("error",A=>{Rz.error(A)});let a=e.level!==void 0,c=a?e.level:void 0,u=e.from!==void 0,l=u?new Date(e.from):void 0,_=e.until!==void 0,d=_?new Date(e.until):void 0,E=e.limit===void 0?Cz:e.limit,f=e.order===void 0?void 0:e.order,h=e.start===void 0?0:e.start,T=h+E,S=0,y=[],O="",H;i.on("data",A=>{let w=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;A=O+A;let G=0,k;for(;(k=w.exec(A))&&!i.destroyed;){H&&(H.message=A.slice(G,k.index),Y(H));let[X,ge,ct]=k,Di=ct.split("] ["),Ga=Di[0],Hn=Di[1];Di.splice(0,2),H={timestamp:ge,thread:Ga,level:Hn,tags:Di,message:""},G=k.index+X.length}O=A.slice(G)}),i.on("end",A=>{i.destroyed||H&&(H.message=O.trim(),Y(H))}),i.resume();function Y(A){let w,G,k;switch(!0){case(a&&u&&_):w=new Date(A.timestamp),G=new Date(l),k=new Date(d),A.level===c&&w>=G&&w<=k&&S<h?S++:A.level===c&&w>=G&&w<=k&&(gn(A,f,y),S++,S===T&&i.destroy());break;case(a&&u):w=new Date(A.timestamp),G=new Date(l),A.level===c&&w>=G&&S<h?S++:A.level===c&&w>=G&&(gn(A,f,y),S++,S===T&&i.destroy());break;case(a&&_):w=new Date(A.timestamp),k=new Date(d),A.level===c&&w<=k&&S<h?S++:A.level===c&&w<=k&&(gn(A,f,y),S++,S===T&&i.destroy());break;case(u&&_):w=new Date(A.timestamp),G=new Date(l),k=new Date(d),w>=G&&w<=k&&S<h?S++:w>=G&&w<=k&&(gn(A,f,y),S++,S===T&&i.destroy());break;case a:A.level===c&&S<h?S++:A.level===c&&(gn(A,f,y),S++,S===T&&i.destroy());break;case u:w=new Date(A.timestamp),G=new Date(l),w>=G&&S<h?S++:w>=G&&S>=h&&(gn(A,f,y),S++,S===T&&i.destroy());break;case _:w=new Date(A.timestamp),k=new Date(d),w<=k&&S<h?S++:w<=k&&S>=h&&(gn(A,f,y),S++,S===T&&i.destroy());break;default:S<h?S++:(gn(A,f,y),S++,S===T&&i.destroy())}}return o(Y,"onLogMessage"),await Nz(i,"close"),y}o(Uz,"readLog");function gn(e,t,r){t==="desc"?Dz(e,r):t==="asc"?Lz(e,r):r.push(e)}o(gn,"pushLineToResult");function Dz(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)}o(Dz,"insertDescending");function Lz(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)}o(Lz,"insertAscending")});var Ml=m((roe,FI)=>{"use strict";var um=require("joi"),{string:Ll,boolean:vI,date:Mz}=um.types(),Pz=ve(),{validateSchemaExists:jae,validateTableExists:eoe,validateSchemaName:toe}=ts(),vz=g(),Bz=Be(),BI=Q();BI.initSync();var Hz=Ll.invalid(BI.get(vz.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Bz.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(),HI={operation:Ll.valid("add_node","update_node"),node_name:Hz,subscriptions:um.array().items({table:Ll.optional(),schema:Ll.required(),subscribe:vI.required(),publish:vI.required().custom(qz),start_time:Mz.iso()}).min(1).required()};function Fz(e){return Pz.validateBySchema(e,um.object(HI))}o(Fz,"addUpdateNodeValidator");function qz(e,t){if(t.state.ancestors[2].operation==="add_node"&&e===!1&&t.state.ancestors[0].subscribe===!1)return t.message(`'subscriptions[${t.state.path[1]}]' subscribe and/or publish must be set to true when adding a node`)}o(qz,"checkForFalsy");FI.exports={addUpdateNodeValidator:Fz,validation_schema:HI}});var GI=m((noe,qI)=>{var Gz=ve(),xz={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};qI.exports=function(e){return Gz.validateObject(e,xz)}});var _m=m((ioe,xI)=>{"use strict";var kz=g().OPERATIONS_ENUM,lm=class{static{o(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=kz.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};xI.exports=lm});var VI=m((ooe,kI)=>{"use strict";var Vz={OPERATION:"operation",REFRESH:"refresh"},dm=class{static{o(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},Em=class{static{o(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};kI.exports={JWTTokens:dm,TOKEN_TYPE_ENUM:Vz,JWTRSAKeys:Em}});var ko=m((uoe,WI)=>{"use strict";var xo=require("jsonwebtoken"),fm=require("fs-extra"),hm=x(),Nr=g(),{handleHDBError:kt,hdb_errors:$z}=W(),{HTTP_STATUS_CODES:Vt,AUTHENTICATION_ERROR_MSGS:$t}=$z,Go=q(),$I=zu(),pm=Or(),Yz=Rr().update,Kz=_m(),Wz=Hs(),{UserEventMsg:Qz}=Fr(),An=Q();An.initSync();var mm=require("path"),{JWTTokens:zz,JWTRSAKeys:Jz,TOKEN_TYPE_ENUM:Pl}=VI(),Xz=An.get(Nr.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?An.get(Nr.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",Zz=An.get(Nr.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?An.get(Nr.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",vl="RS256",Sm;WI.exports={createTokens:jz,validateOperationToken:tJ,refreshOperationToken:eJ,validateRefreshToken:KI};async function jz(e){if(hm.isEmpty(e)||typeof e!="object")throw kt(new Error,$t.INVALID_AUTH_OBJECT,Vt.BAD_REQUEST,void 0,void 0,!0);if(hm.isEmpty(e.username))throw kt(new Error,$t.USERNAME_REQUIRED,Vt.BAD_REQUEST,void 0,void 0,!0);if(hm.isEmpty(e.password))throw kt(new Error,$t.PASSWORD_REQUIRED,Vt.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await pm.findAndValidateUser(e.username,e.password),!t)throw kt(new Error,$t.INVALID_CREDENTIALS,Vt.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw Go.error(E),kt(new Error,$t.INVALID_CREDENTIALS,Vt.UNAUTHORIZED,void 0,void 0,!0)}let r=await Bl(),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},a=await YI(i,r.private_key,r.passphrase),c=await xo.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:Zz,algorithm:vl,subject:Pl.REFRESH}),u=$I.hash(c),l=new Kz(Nr.SYSTEM_SCHEMA_NAME,Nr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),_,d;try{_=await Yz(l)}catch(E){Go.error(E),d=E}if(d!==void 0||_.skipped_hashes.length>0)throw kt(new Error,$t.REFRESH_TOKEN_SAVE_FAILED,Vt.INTERNAL_SERVER_ERROR);return Wz.signalUserChange(new Qz(process.pid)),new zz(a,c)}o(jz,"createTokens");async function YI(e,t,r){return await xo.sign(e,{key:t,passphrase:r},{expiresIn:Xz,algorithm:vl,subject:Pl.OPERATION})}o(YI,"signOperationToken");async function Bl(){if(Sm===void 0)try{let e=mm.join(An.getHdbBasePath(),Nr.LICENSE_KEY_DIR_NAME,Nr.JWT_ENUM.JWT_PASSPHRASE_NAME),t=mm.join(An.getHdbBasePath(),Nr.LICENSE_KEY_DIR_NAME,Nr.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=mm.join(An.getHdbBasePath(),Nr.LICENSE_KEY_DIR_NAME,Nr.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await fm.readFile(e)).toString(),n=(await fm.readFile(t)).toString(),i=(await fm.readFile(r)).toString();Sm=new Jz(i,n,s)}catch(e){throw Go.error(e),kt(new Error,$t.NO_ENCRYPTION_KEYS,Vt.INTERNAL_SERVER_ERROR)}return Sm}o(Bl,"getJWTRSAKeys");async function eJ(e){if(!e)throw kt(new Error,$t.INVALID_BODY,Vt.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw kt(new Error,$t.REFRESH_TOKEN_REQUIRED,Vt.BAD_REQUEST,void 0,void 0,!0);await KI(e.refresh_token);let t=await Bl(),r=await xo.decode(e.refresh_token);return{operation_token:await YI({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}o(eJ,"refreshOperationToken");async function tJ(e){try{let t=await Bl(),r=await xo.verify(e,t.public_key,{algorithms:vl,subject:Pl.OPERATION});return await pm.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Go.warn(t),t.name&&t.name==="TokenExpiredError"?kt(new Error,$t.TOKEN_EXPIRED,Vt.FORBIDDEN):kt(new Error,$t.INVALID_TOKEN,Vt.UNAUTHORIZED)}}o(tJ,"validateOperationToken");async function KI(e){let t;try{let r=await Bl(),s=await xo.verify(e,r.public_key,{algorithms:vl,subject:Pl.REFRESH});t=await pm.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Go.warn(r),r.name&&r.name==="TokenExpiredError"?kt(new Error,$t.TOKEN_EXPIRED,Vt.FORBIDDEN):kt(new Error,$t.INVALID_TOKEN,Vt.UNAUTHORIZED)}if(!$I.validate(t.refresh_token,e))throw kt(new Error,$t.INVALID_TOKEN,Vt.UNAUTHORIZED);return t}o(KI,"validateRefreshToken")});var Tm=m((doe,JI)=>{"use strict";var rJ=GI(),aa=require("passport"),sJ=require("passport-local").Strategy,nJ=require("passport-http").BasicStrategy,iJ=require("util"),aJ=Or(),zI=iJ.callbackify(aJ.findAndValidateUser),_oe=rr(),oJ=g(),QI=ko();aa.use(new sJ(function(e,t,r){zI(e,t,r)}));aa.use(new nJ(function(e,t,r){zI(e,t,r)}));aa.serializeUser(function(e,t){t(null,e)});aa.deserializeUser(function(e,t){t(null,e)});function cJ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let s,n;if(e.headers?.authorization){let a=e.headers.authorization.split(" ");s=a[0],n=a[1]}function i(a,c){return a?r(a):c?r(null,c):r("Must login")}switch(o(i,"handleResponse"),s){case"Basic":aa.authenticate("basic",{session:!1},(a,c)=>{i(a,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===oJ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?QI.validateRefreshToken(n).then(a=>{e.body.refresh_token=n,r(null,a)}).catch(a=>{r(a)}):QI.validateOperationToken(n).then(a=>{r(null,a)}).catch(a=>{r(a)});break;default:aa.authenticate("local",{session:!1},function(a,c){i(a,c)})(e,t,r);break}}o(cJ,"authorize");function uJ(e,t){let r=rJ(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!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 a=i[e.schema].tables[e.table].attribute_permissions;for(let c in a)e.attributes.indexOf(a[c].attribute_name)>-1&&!a[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${a[c].attribute_name} `))}return t(null,s)}o(uJ,"checkPermissions");JI.exports={authorize:cJ,checkPermissions:uJ}});var oa=m((foe,XI)=>{"use strict";var Rm=class{static{o(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},gm=class{static{o(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};XI.exports={Node:Rm,NodeSubscription:gm}});var jI=m((moe,ZI)=>{"use strict";var lJ=g().OPERATIONS_ENUM,Am=class{static{o(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=lJ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};ZI.exports=Am});var Vo=m((poe,ew)=>{"use strict";var Om=class{static{o(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},Nm=class{static{o(this,"RemotePayloadSubscription")}constructor(t,r,s,n,i,a,c){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=a,this.attributes=c}};ew.exports={RemotePayloadObject:Om,RemotePayloadSubscription:Nm}});var rw=m((Roe,tw)=>{"use strict";var bm=class{static{o(this,"TableSizeObject")}constructor(t,r,s=0,n=0,i=0,a=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=a}};tw.exports=bm});var iw=m((boe,nw)=>{"use strict";var _J=rw(),Aoe=xe(),sw=ye(),dJ=q(),{getSchemaPath:Ooe,getTransactionAuditStorePath:Noe}=we(),{getDatabases:EJ}=(de(),re(Ne));nw.exports=fJ;async function fJ(e){let t=new _J;try{let r=EJ()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await sw.environmentDataSize(schema_path,e.name),a=await sw.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=s.entryCount,t.transaction_log_size=a,t.transaction_log_record_count=n.entryCount}catch(r){dJ.warn(`unable to stat table dbi due to ${r}`)}return t}o(fJ,"lmdbGetTableSize")});var ow=m((Ioe,aw)=>{"use strict";var ym=class{static{o(this,"SystemInformationObject")}constructor(t,r,s,n,i,a,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=a,this.harperdb_processes=c}};aw.exports=ym});var ca=m((Doe,_w)=>{"use strict";var hJ=require("fs-extra"),mJ=require("path"),Ut=require("systeminformation"),On=q(),SJ=rt(),Im=Be(),Fl=g(),pJ=iw(),lw=$n(),{getThreadInfo:cw}=_t(),Hm=Q();Hm.initSync();var TJ=ow(),{openEnvironment:Coe}=ye(),{getSchemaPath:Uoe}=we(),{database:RJ}=(de(),re(Ne)),Hl;_w.exports={getHDBProcessInfo:Dm,getNetworkInfo:Mm,getDiskInfo:Lm,getMemoryInfo:Um,getCPUInfo:Cm,getTimeInfo:wm,getSystemInformation:Pm,systemInformation:gJ,getTableSize:vm,getMetrics:Bm};function wm(){return Ut.time()}o(wm,"getTimeInfo");async function Cm(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:a,governor:c,socket:u,cache:l,..._}=await Ut.cpu();_.cpu_speed=await Ut.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:T,raw_currentload_user:S,cpus:y,...O}=await Ut.currentLoad();return O.cpus=[],y.forEach(H=>{let{raw_load:Y,raw_load_idle:A,raw_load_irq:w,raw_load_nice:G,raw_load_system:k,raw_load_user:X,...ge}=H;O.cpus.push(ge)}),_.current_load=O,_}catch(e){return On.error(`error in getCPUInfo: ${e}`),{}}}o(Cm,"getCPUInfo");async function Um(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Ut.mem();return Object.assign(n,process.memoryUsage())}catch(e){return On.error(`error in getMemoryInfo: ${e}`),{}}}o(Um,"getMemoryInfo");async function Dm(){let e={core:[],clustering:[]};try{let t=await Ut.processes(),r;try{r=Number.parseInt(await hJ.readFile(mJ.join(Hm.get(Fl.CONFIG_PARAMS.ROOTPATH),Fl.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===Fl.NODE_ERROR_CODES.ENOENT)On.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return On.error(`error in getHDBProcessInfo: ${t}`),e}}o(Dm,"getHDBProcessInfo");async function Lm(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Ut.disksIO();e.io=i;let{rx_sec:a,tx_sec:c,wx_sec:u,...l}=await Ut.fsStats();return e.read_write=l,e.size=await Ut.fsSize(),e}catch(t){return On.error(`error in getDiskInfo: ${t}`),e}}o(Lm,"getDiskInfo");async function Mm(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Ut.networkInterfaceDefault(),e.latency=await Ut.inetChecksite("google.com"),(await Ut.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:a,dhcp:c,dnsSuffix:u,ieee8021xAuth:l,ieee8021xState:_,carrier_changes:d,...E}=s;e.interfaces.push(E)}),(await Ut.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:a,...c}=s;e.stats.push(c)}),e}catch(t){return On.error(`error in getNetworkInfo: ${t}`),e}}o(Mm,"getNetworkInfo");async function Pm(){if(Hl!==void 0)return Hl;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:a,...c}=await Ut.osInfo();e=c;let u=await Ut.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Hl=e,Hl}catch(t){return On.error(`error in getSystemInformation: ${t}`),e}}o(Pm,"getSystemInformation");async function vm(){let e=[],t=await lw.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await pJ(s));return e}o(vm,"getTableSize");async function Bm(){let e=await lw.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let a=RJ({database:r,table:n}).getStats();s[n]={puts:a.puts,deletes:a.deletes,txns:a.txns,pageFlushes:a.pageFlushes,writes:a.writes,pagesWritten:a.pagesWritten,timeDuringTxns:a.timeDuringTxns,timeStartTxns:a.timeStartTxns,timePageFlushes:a.timePageFlushes,timeSync:a.timeSync}}catch(i){On.notify(`Error getting stats for table ${n}: ${i}`)}}return t}o(Bm,"getMetrics");async function uw(){if(Hm.get(Fl.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await SJ.getNATSReferences(),r=await t.streams.info(Im.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(Im.WORK_QUEUE_CONSUMER_NAMES.stream_name,Im.WORK_QUEUE_CONSUMER_NAMES.durable_name),n={ingest:{stream:{...r.state},consumer:{num_ack_pending:s._info.num_ack_pending,num_redelivered:s._info.num_redelivered,num_waiting:s._info.num_waiting,num_pending:s._info.num_pending}}};return r.config?.sources&&(n.ingest.stream.sources=r.config.sources),n}}o(uw,"getNatsStreamInfo");async function gJ(e){let t=new TJ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await Pm(),t.time=wm(),t.cpu=await Cm(),t.memory=await Um(),t.disk=await Lm(),t.network=await Mm(),t.harperdb_processes=await Dm(),t.table_size=await vm(),t.metrics=await Bm(),t.threads=await cw(),t.replication=await uw(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await Pm();break;case"time":t.time=wm();break;case"cpu":t.cpu=await Cm();break;case"memory":t.memory=await Um();break;case"disk":t.disk=await Lm();break;case"network":t.network=await Mm();break;case"harperdb_processes":t.harperdb_processes=await Dm();break;case"table_size":t.table_size=await vm();break;case"database_metrics":case"metrics":t.metrics=await Bm();break;case"threads":t.threads=await cw();break;case"replication":t.replication=await uw();break;default:break}return t}o(gJ,"systemInformation")});var $o=m((Moe,AJ)=>{AJ.exports={name:"harperdb",version:"4.2.0-alpha.11",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{node:">=14.0.0","preferred-node":"18.15.0","go-lang":"1.19.12","nats-server":"2.9.21"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.382.0","@aws-sdk/lib-storage":"3.382.0","@aws-sdk/abort-controller":"3.370.0","@endo/static-module-record":"^0.7.16","@fastify/autoload":"~5.7.1","@fastify/compress":"~6.4.0","@fastify/cors":"~8.3.0","@fastify/static":"~6.10.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"1.7.4","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2",esbuild:"^0.18.0","fast-glob":"3.3.1",fastify:"~4.21.0","fastify-plugin":"~4.5.0","fs-extra":"11.1.1",graphql:"^16.6.0","human-readable-ids":"1.0.4",inquirer:"8.2.5","is-number":"7.0.0",joi:"17.9.2",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.1",lmdb:"2.8.4",lodash:"4.17.21",mathjs:"11.9.1",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.0",msgpackr:"1.9.7",nats:"2.16.0",needle:"3.2.0","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.4.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.14.2",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0",ses:"^0.18.1","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.18.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.0","validate.js":"0.13.1",ws:"^8.13.0",yaml:"2.3.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"0.27.2",chai:"4.3.7","chai-integer":"0.1.0",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^4.9.4","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var Fm=m((Boe,dw)=>{"use strict";var Poe=require("fs-extra"),voe=q();dw.exports={version:OJ,printVersion:bJ,nodeVersion:NJ};var Nn=$o();function OJ(){if(Nn)return Nn.version}o(OJ,"version");function NJ(){if(Nn&&Nn.engines&&Nn.engines["preferred-node"])return Nn.engines["preferred-node"]}o(NJ,"nodeVersion");function bJ(){Nn&&console.log(`HarperDB Version ${Nn.version}`)}o(bJ,"printVersion")});var Gs=m((Goe,mw)=>{"use strict";var yJ=Rr(),qm=x(),IJ=require("util"),ni=g(),Ew=Q();Ew.initSync();var wJ=Tm(),fw=Tr(),{Node:Foe,NodeSubscription:qoe}=oa(),CJ=Ji(),UJ=jI(),{RemotePayloadObject:DJ,RemotePayloadSubscription:LJ}=Vo(),{handleHDBError:MJ,hdb_errors:PJ}=W(),{HTTP_STATUS_CODES:vJ,HDB_ERROR_MSGS:BJ}=PJ,HJ=is(),FJ=ca(),qJ=Fm(),{getDatabases:GJ}=(de(),re(Ne)),xJ=IJ.promisify(wJ.authorize),kJ=fw.searchByHash,VJ=fw.searchByValue;mw.exports={authHeaderToUser:$J,isEmpty:YJ,getNodeRecord:KJ,upsertNodeRecord:WJ,buildNodePayloads:QJ,checkClusteringEnabled:zJ,getAllNodeRecords:JJ,getSystemInfo:XJ,reverseSubscription:hw};async function $J(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await xJ(t,null),e}o($J,"authHeaderToUser");function YJ(e){return e==null}o(YJ,"isEmpty");async function KJ(e){let t=new CJ(ni.SYSTEM_SCHEMA_NAME,ni.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return kJ(t)}o(KJ,"getNodeRecord");async function WJ(e){let t=new UJ(ni.SYSTEM_SCHEMA_NAME,ni.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return yJ.upsert(t)}o(WJ,"upsertNodeRecord");function hw(e){if(qm.isEmpty(e.subscribe)||qm.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}o(hw,"reverseSubscription");function QJ(e,t,r,s){let n=[];for(let i=0,a=e.length;i<a;i++){let c=e[i],{schema:u,table:l}=c,_=qm.getTableHashAttribute(u,l),{subscribe:d,publish:E}=hw(c),f=GJ()[u]?.[l],h=new LJ(u,l,_,E,d,c.start_time,f.schemaDefined&&f.attributes);n.push(h)}return new DJ(r,t,n,s)}o(QJ,"buildNodePayloads");function zJ(){if(!Ew.get(ni.CONFIG_PARAMS.CLUSTERING_ENABLED))throw MJ(new Error,BJ.CLUSTERING_NOT_ENABLED,vJ.BAD_REQUEST,void 0,void 0,!0)}o(zJ,"checkClusteringEnabled");async function JJ(){let e=new HJ(ni.SYSTEM_SCHEMA_NAME,ni.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await VJ(e))}o(JJ,"getAllNodeRecords");async function XJ(){let e=await FJ.getSystemInformation();return{hdb_version:qJ.version(),node_version:e.node_version,platform:e.platform}}o(XJ,"getSystemInfo")});var Gm=m((koe,Nw)=>{"use strict";var ql=rt(),Sw=x(),pw=Be(),Tw=g(),Gl=q(),Rw=yl(),ZJ=ph(),{RemotePayloadObject:jJ}=Vo(),{handleHDBError:gw,hdb_errors:e2}=W(),{HTTP_STATUS_CODES:Aw}=e2,{NodeSubscription:Ow}=oa();Nw.exports=t2;async function t2(e,t){let r;try{r=await ql.request(`${t}.${pw.REQUEST_SUFFIX}`,new jJ(Tw.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Gl.trace("Response from remote describe all request:",r)}catch(a){Gl.error(`addNode received error from describe all request to remote node: ${a}`);let c=ql.requestErrorHandler(a,"add_node",t);throw gw(new Error,c,Aw.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===pw.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let a=`Error returned from remote node ${t}: ${r.message}`;throw gw(new Error,a,Aw.INTERNAL_SERVER_ERROR,"error",a)}let s=r.message,n=[],i=[];for(let a of e){let{schema:c,table:u}=a;if(c===Tw.SYSTEM_SCHEMA_NAME){await ql.createLocalTableStream(c,u);let h=new Ow(c,u,a.publish,a.subscribe);h.start_time=a.start_time,i.push(h);continue}let l=Sw.doesSchemaExist(c),_=s[c]!==void 0,d=u?Sw.doesTableExist(c,u):!0,E=u?s?.[c]?.[u]!==void 0:!0;if(!l&&!_||!d&&!E){n.push(a);continue}if(!l&&_&&(Gl.trace(`addNode creating schema: ${c}`),await Rw.createSchema({operation:"create_schema",schema:c})),!d&&E){Gl.trace(`addNode creating table: ${u} in schema: ${c}`);let h=new ZJ(c,u,s[c][u].hash_attribute);h.attributes=s[c][u].attributes,await Rw.createTable(h)}await ql.createLocalTableStream(c,u);let f=new Ow(c,u,a.publish,a.subscribe);f.start_time=a.start_time,i.push(f)}return{added:i,skipped:n}}o(t2,"reviewSubscriptions")});var Vl=m(($oe,Iw)=>{"use strict";var{handleHDBError:xl,hdb_errors:r2}=W(),{HTTP_STATUS_CODES:kl}=r2,{addUpdateNodeValidator:s2}=Ml(),Yo=q(),yw=g(),bw=Be(),n2=x(),xm=rt(),Ko=Gs(),i2=Q(),a2=Gm(),{Node:o2,NodeSubscription:c2}=oa(),{broadcast:u2}=_t(),l2="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",_2="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",d2=i2.get(yw.CONFIG_PARAMS.CLUSTERING_NODENAME);Iw.exports=E2;async function E2(e,t=!1){Yo.trace("addNode called with:",e),Ko.checkClusteringEnabled();let r=s2(e);if(r)throw xl(r,r.message,kl.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await Ko.getNodeRecord(s);if(!n2.isEmptyOrZeroLength(d))throw xl(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,kl.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await a2(e.subscriptions,s),a={message:void 0,added:n,skipped:i};if(n.length===0)return a.message=l2,a;let c=Ko.buildNodePayloads(n,d2,yw.OPERATIONS_ENUM.ADD_NODE,await Ko.getSystemInfo());Yo.trace("addNode sending remote payload:",c);let u;try{u=await xm.request(`${s}.${bw.REQUEST_SUFFIX}`,c)}catch(d){Yo.error(`addNode received error from request: ${d}`);let E=xm.requestErrorHandler(d,"add_node",s);throw xl(new Error,E,kl.INTERNAL_SERVER_ERROR,"error",E)}if(u.status===bw.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw xl(new Error,d,kl.INTERNAL_SERVER_ERROR,"error",d)}Yo.trace(u);let l=[];for(let d=0,E=n.length;d<E;d++){let f=n[d];Yo.trace("Add node updating work stream for node:",s,"subscriptions:",f),await xm.updateWorkStream(f,s),n[d].start_time===void 0&&delete n[d].start_time,l.push(new c2(f.schema,f.table,f.publish,f.subscribe))}let _=new o2(s,l,u.system_info);return await Ko.upsertNodeRecord(_),u2({type:"nats_update"}),i.length>0?a.message=_2:a.message=`Successfully added '${s}' to manifest`,a}o(E2,"addNode")});var Vm=m((Koe,Uw)=>{"use strict";var{handleHDBError:$l,hdb_errors:f2}=W(),{HTTP_STATUS_CODES:Yl}=f2,{addUpdateNodeValidator:h2}=Ml(),Wo=q(),Cw=g(),ww=Be(),m2=x(),km=rt(),Qo=Gs(),S2=Q(),{cloneDeep:p2}=require("lodash"),T2=Gm(),{NodeSubscription:R2}=oa(),{broadcast:g2}=_t(),A2="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",O2="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",N2=S2.get(Cw.CONFIG_PARAMS.CLUSTERING_NODENAME);Uw.exports=b2;async function b2(e){Wo.trace("updateNode called with:",e),Qo.checkClusteringEnabled();let t=h2(e);if(t)throw $l(t,t.message,Yl.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=p2(await Qo.getNodeRecord(r));if(m2.isEmptyOrZeroLength(s))throw $l(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,Yl.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await T2(e.subscriptions,r),a={message:void 0,updated:n,skipped:i};if(n.length===0)return a.message=A2,a;let c=Qo.buildNodePayloads(n,N2,Cw.OPERATIONS_ENUM.UPDATE_NODE,await Qo.getSystemInfo());Wo.trace("updateNode sending remote payload:",c);let u;try{u=await km.request(`${r}.${ww.REQUEST_SUFFIX}`,c)}catch(l){Wo.error(`updateNode received error from request: ${l}`);let _=km.requestErrorHandler(l,"update_node",r);throw $l(new Error,_,Yl.INTERNAL_SERVER_ERROR,"error",_)}if(u.status===ww.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${u.message}`;throw $l(new Error,l,Yl.INTERNAL_SERVER_ERROR,"error",l)}Wo.trace(u);for(let l=0,_=n.length;l<_;l++){let d=n[l];Wo.trace(`updateNode updating work stream for node: ${r} subscription:`,d),await km.updateWorkStream(d,r),n[l].start_time===void 0&&delete n[l].start_time}return await y2(s[0],n,u.system_info),i.length>0?a.message=O2:a.message=`Successfully updated '${r}'`,a}o(b2,"updateNode");async function y2(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let a=t[n],c=!1;for(let u=0,l=e.subscriptions.length;u<l;u++){let _=s.subscriptions[u];if(_.schema===a.schema&&_.table===a.table){_.publish=a.publish,_.subscribe=a.subscribe,c=!0;break}}c||s.subscriptions.push(new R2(a.schema,a.table,a.publish,a.subscribe))}s.system_info=r,await Qo.upsertNodeRecord(s),g2({type:"nats_update"})}o(y2,"updateNodeTable")});var vw=m((Qoe,Pw)=>{"use strict";var Mw=require("joi"),{string:Dw}=Mw.types(),I2=ve(),Lw=g(),w2=Q(),C2=Be();Pw.exports=U2;function U2(e){let t=Dw.invalid(w2.get(Lw.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(C2.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=Mw.object({operation:Dw.valid(Lw.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return I2.validateBySchema(e,r)}o(U2,"removeNodeValidator")});var Wl=m((Joe,xw)=>{"use strict";var{handleHDBError:Bw,hdb_errors:D2}=W(),{HTTP_STATUS_CODES:Hw}=D2,L2=vw(),zo=q(),Fw=Gs(),M2=x(),Kl=g(),qw=Be(),Gw=rt(),P2=Q(),{RemotePayloadObject:v2}=Vo(),{NodeSubscription:B2}=oa(),H2=Do(),F2=zn(),{broadcast:q2}=_t(),G2=P2.get(Kl.CONFIG_PARAMS.CLUSTERING_NODENAME);xw.exports=x2;async function x2(e){zo.trace("removeNode called with:",e),Fw.checkClusteringEnabled();let t=L2(e);if(t)throw Bw(t,t.message,Hw.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await Fw.getNodeRecord(r);if(M2.isEmptyOrZeroLength(s))throw Bw(new Error,`Node '${r}' was not found.`,Hw.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new v2(Kl.OPERATIONS_ENUM.REMOVE_NODE,G2,[]),i,a=!1;try{i=await Gw.request(`${r}.${qw.REQUEST_SUFFIX}`,n),zo.trace("Remove node reply from remote node:",r,i)}catch(u){zo.error("removeNode received error from request:",u),a=!0}for(let u=0,l=s.subscriptions.length;u<l;u++){let _=s.subscriptions[u];zo.trace(`Remove node removing subscription: ${_.schema}.${_.table} for node: ${r}`);let d=new B2(_.schema,_.table,!1,!1);await Gw.updateWorkStream(d,r)}let c=new H2(Kl.SYSTEM_SCHEMA_NAME,Kl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await F2.deleteRecord(c),q2({type:"nats_update"}),i?.status===qw.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||a?(zo.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}o(x2,"removeNode")});var $w=m((Zoe,Vw)=>{"use strict";var kw=require("joi"),{string:k2,array:V2}=kw.types(),$2=ve(),Y2=Ml();Vw.exports=K2;function K2(e){let t=kw.object({operation:k2.valid("configure_cluster").required(),connections:V2.items(Y2.validation_schema).required()});return $2.validateBySchema(e,t)}o(K2,"configureClusterValidator")});var $m=m((ece,zw)=>{"use strict";var W2=g(),Ql=q(),Q2=x(),z2=Wl(),J2=Vl(),Yw=Gs(),X2=$w(),{handleHDBError:Kw,hdb_errors:Z2}=W(),{HTTP_STATUS_CODES:Ww}=Z2,j2="Configure cluster complete.",e3="Failed to configure the cluster. Check the logs for more details.",t3="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";zw.exports=r3;async function r3(e){Ql.trace("configure cluster called with:",e),Yw.checkClusteringEnabled();let t=X2(e);if(t)throw Kw(t,t.message,Ww.BAD_REQUEST,void 0,void 0,!0);let r=await Yw.getAllNodeRecords(),s=[];for(let E=0,f=r.length;E<f;E++)s.push(Qw(z2,{operation:W2.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[E].name},r[E].name));let n=await Promise.allSettled(s);Ql.trace("All results from configure_cluster remove node:",n);let i=[],a=e.connections.length;for(let E=0;E<a;E++){let f=e.connections[E];i.push(Qw(J2,f,f.node_name))}let c=await Promise.allSettled(i);Ql.trace("All results from configure_cluster add node:",c);let u=[],l=[],_=!1,d=n.concat(c);for(let E=0,f=d.length;E<f;E++){let h=d[E];h.status==="rejected"&&(Ql.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(_=!0);let T=h?.value?.result;typeof T=="string"&&T.includes("Successfully removed")||h.status==="rejected"||l.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(Q2.isEmptyOrZeroLength(u))return{message:j2,connections:l};if(_)return{message:t3,failed_nodes:u,connections:l};throw Kw(new Error,e3,Ww.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}o(r3,"configureCluster");async function Qw(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}o(Qw,"functionWrapper")});var Xw=m((rce,Jw)=>{"use strict";var zl=require("joi"),s3=ve(),{validateSchemaExists:n3,validateTableExists:i3,validateSchemaName:a3}=ts(),o3=zl.object({operation:zl.string().valid("purge_stream"),schema:zl.string().custom(n3).custom(a3).required(),table:zl.string().custom(i3).required()});function c3(e){return s3.validateBySchema(e,o3)}o(c3,"purgeStreamValidator");Jw.exports=c3});var Ym=m((nce,Zw)=>{"use strict";var{handleHDBError:u3,hdb_errors:l3}=W(),{HTTP_STATUS_CODES:_3}=l3,d3=Xw(),E3=rt(),f3=Gs();Zw.exports=h3;async function h3(e){let t=d3(e);if(t)throw u3(t,t.message,_3.BAD_REQUEST,void 0,void 0,!0);f3.checkClusteringEnabled();let{schema:r,table:s}=e;return await E3.purgeTableStream(r,s),`Successfully purged table '${r}.${s}'`}o(h3,"purgeStream")});var Qm=m((ace,nC)=>{"use strict";var Wm=Gs(),m3=rt(),tC=Q(),Jl=g(),ii=Be(),S3=x(),Km=q(),{RemotePayloadObject:p3}=Vo(),{ErrorCode:jw}=require("nats"),eC=tC.get(Jl.CONFIG_PARAMS.CLUSTERING_ENABLED),rC=tC.get(Jl.CONFIG_PARAMS.CLUSTERING_NODENAME);nC.exports={clusterStatus:T3,buildNodeStatus:sC};async function T3(){let e={node_name:rC,is_enabled:eC,connections:[]};if(!eC)return e;let t=await Wm.getAllNodeRecords();if(S3.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(sC(t[s],e.connections));return await Promise.allSettled(r),e}o(T3,"clusterStatus");async function sC(e,t){let r=e.name,s=new p3(Jl.OPERATIONS_ENUM.CLUSTER_STATUS,rC,void 0,await Wm.getSystemInfo()),n,i,a=ii.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await m3.request(ii.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===ii.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(a=ii.CLUSTER_STATUS_STATUSES.CLOSED,Km.error(`Error getting node status from ${r} `,n))}catch(u){Km.warn(`Error getting node status from ${r}`,u),u.code===jw.NoResponders?a=ii.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===jw.Timeout?a=ii.CLUSTER_STATUS_STATUSES.TIMEOUT:a=ii.CLUSTER_STATUS_STATUSES.CLOSED}let c=new R3(r,a,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let u={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==Jl.PRE_4_0_0_VERSION&&await Wm.upsertNodeRecord(u)}catch(u){Km.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}o(sC,"buildNodeStatus");function R3(e,t,r,s,n,i,a,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=a,this.system_info=c}o(R3,"NodeStatusObject")});var Jm=m((cce,iC)=>{"use strict";var{handleHDBError:g3,hdb_errors:A3}=W(),{HTTP_STATUS_CODES:O3}=A3,N3=rt(),b3=Gs(),zm=x(),Xl=require("joi"),y3=ve(),I3=2e3,w3=Xl.object({timeout:Xl.number().min(1),connected_nodes:Xl.boolean(),routes:Xl.boolean()});iC.exports=C3;async function C3(e){b3.checkClusteringEnabled();let t=y3.validateBySchema(e,w3);if(t)throw g3(t,t.message,O3.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||zm.autoCastBoolean(s),a=n===void 0||zm.autoCastBoolean(n),c={nodes:[]},u=await N3.getServerList(r??I3),l={};if(i)for(let _=0,d=u.length;_<d;_++){let E=u[_].statsz;E&&(l[u[_].server.name]=E.routes)}for(let _=0,d=u.length;_<d;_++){if(u[_].statsz)continue;let E=u[_].server,f=u[_].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[_].response_time};i&&(h.connected_nodes=l[E.name]?l[E.name].map(T=>T.name.slice(0,-4)):[]),a&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(T=>({host:T.split(":")[0],port:zm.autoCast(T.split(":")[1])})):[]),c.nodes.push(h)}}return c}o(C3,"clusterNetwork")});var uC=m((lce,cC)=>{"use strict";var Xm=require("joi"),aC=ve(),{route_constraints:oC}=vf();cC.exports={setRoutesValidator:U3,deleteRoutesValidator:D3};function U3(e){let t=Xm.object({server:Xm.valid("hub","leaf").required(),routes:oC.required()});return aC.validateBySchema(e,t)}o(U3,"setRoutesValidator");function D3(e){let t=Xm.object({routes:oC.required()});return aC.validateBySchema(e,t)}o(D3,"deleteRoutesValidator")});var jm=m((dce,EC)=>{"use strict";var ai=Ar(),Zm=x(),Zl=g(),lC=uC(),{handleHDBError:_C,hdb_errors:L3}=W(),{HTTP_STATUS_CODES:dC}=L3,M3="cluster routes successfully set",P3="cluster routes successfully deleted";EC.exports={setRoutes:v3,getRoutes:B3,deleteRoutes:H3};function v3(e){let t=lC.setRoutesValidator(e);if(t)throw _C(t,t.message,dC.BAD_REQUEST,void 0,void 0,!0);let r=ai.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],a=[];for(let c=0,u=e.routes.length;c<u;c++){let l=e.routes[c];l.port=Zm.autoCast(l.port);let _=s.some(E=>E.host===l.host&&E.port===l.port),d=n.some(E=>E.host===l.host&&E.port===l.port);_||d?i.push(l):(s.push(l),a.push(l))}return e.server==="hub"?ai.updateConfigValue(Zl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):ai.updateConfigValue(Zl.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:M3,set:a,skipped:i}}o(v3,"setRoutes");function B3(){let e=ai.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}o(B3,"getRoutes");function H3(e){let t=lC.deleteRoutesValidator(e);if(t)throw _C(t,t.message,dC.BAD_REQUEST,void 0,void 0,!0);let r=ai.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],a=[],c=!1,u=!1;for(let l=0,_=e.routes.length;l<_;l++){let d=e.routes[l],E=!1;for(let f=0,h=s.length;f<h;f++){let T=s[f];if(d.host===T.host&&d.port===T.port){s.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,T=n.length;h<T;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&a.push(d)}}return c&&(s=Zm.isEmptyOrZeroLength(s)?null:s,ai.updateConfigValue(Zl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=Zm.isEmptyOrZeroLength(n)?null:n,ai.updateConfigValue(Zl.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:P3,deleted:i,skipped:a}}o(H3,"deleteRoutes")});var hC=m((fce,fC)=>{"use strict";var Jo=require("alasql"),oi=require("recursive-iterator"),Vr=q(),F3=x(),Xo=g(),eS=class{static{o(this,"sql_statement_bucket")}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,G3(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=>Xo.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=>!Xo.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,a=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[a]&&t[i].tables[a][Xo.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[a].attribute_permissions.length>0?c=q3(t[i].tables[a].attribute_permissions):c=global.hdb_schema[i][a].attributes.map(l=>({attribute_name:l.attribute}));let u=this.affected_attributes.get(i).get(a).filter(l=>!Xo.SEARCH_WILDCARDS.includes(l));c.forEach(({attribute_name:l})=>{let _=new Jo.yy.Column({columnid:l});n.tableid&&(_.tableid=n.tableid),this.ast.columns.push(_),u.includes(l)||u.push(l)}),this.affected_attributes.get(i).set(a,u)}}),this.ast}};function q3(e){return e.filter(t=>t[Xo.PERMS_CRUD_ENUM.READ])}o(q3,"filterReadRestrictedAttrs");function G3(e,t,r,s,n){x3(e,t,r,s,n)}o(G3,"interpretAST");function Zo(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,a=e.tableid;e.as&&(a=e.as),n.set(a,i)}}o(Zo,"addSchemaTableToMap");function x3(e,t,r,s,n){if(!e){Vr.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Jo.yy.Insert?Y3(e,t,r):e instanceof Jo.yy.Select?k3(e,t,r,s,n):e instanceof Jo.yy.Update?V3(e,t,r):e instanceof Jo.yy.Delete?$3(e,t,r):Vr.error("AST in getRecordAttributesAST() is not a valid SQL type.")}o(x3,"getRecordAttributesAST");function k3(e,t,r,s,n){if(!e){Vr.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(F3.isEmptyOrZeroLength(i)){Vr.error("No schema specified");return}e.from.forEach(c=>{Zo(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Zo(c.table,t,r,s,n)});let a=new oi(e.columns);for(let{node:c}of a)if(c&&c.columnid){let u=c.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{Vr.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(c.columnid)<0&&t.get(l).get(u).push(c.columnid)}if(e.where){let c=new oi(e.where),u=e.from[0].tableid;for(let{node:l}of c)if(l&&l.columnid){let _=l.tableid?l.tableid:u;if(!t.get(i).has(_))if(r.has(_))_=r.get(_);else{Vr.info(`table specified as ${_} not found.`);continue}t.get(i).get(_).indexOf(l.columnid)<0&&t.get(i).get(_).push(l.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new oi(c.on);for(let{node:l}of u)if(l&&l.columnid){let _=l.tableid,d=n.get(_);if(!t.get(d).has(_))if(r.has(_))_=r.get(_);else{Vr.info(`table specified as ${_} not found.`);continue}t.get(d).get(_).indexOf(l.columnid)<0&&t.get(d).get(_).push(l.columnid)}}),e.order){let c=new oi(e.order);for(let{node:u}of c)if(u&&u.columnid){let l=u.tableid,_=s.has(l)?s.get(l):i;if(l||(l=e.from[0].tableid),!t.get(_).has(l))if(r.has(l))l=r.get(l);else{Vr.info(`table specified as ${l} not found.`);return}t.get(_).get(l).indexOf(u.columnid)<0&&t.get(_).get(l).push(u.columnid)}}}o(k3,"getSelectAttributes");function V3(e,t,r){if(!e){Vr.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new oi(e.columns),n=e.table.databaseid;Zo(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&tS(e.table.tableid,n,i.columnid,t,r)}o(V3,"getUpdateAttributes");function $3(e,t,r){if(!e){Vr.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new oi(e.where),n=e.table.databaseid;Zo(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&tS(e.table.tableid,n,i.columnid,t,r)}o($3,"getDeleteAttributes");function Y3(e,t,r){if(!e){Vr.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new oi(e.columns),n=e.into.databaseid;Zo(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&tS(e.into.tableid,n,i.columnid,t,r)}o(Y3,"getInsertAttributes");function tS(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)}o(tS,"pushAttribute");fC.exports=eS});var nS=m((mce,TC)=>{var jl=go(),mC=require("chalk"),lr=q(),SC=require("prompt"),{promisify:K3}=require("util"),rS=g(),W3=require("fs-extra"),Q3=require("path"),z3=x(),J3=Fm(),pC=Q();pC.initSync();var X3=require("moment"),Z3=K3(SC.get),j3=Q3.join(pC.getHdbBasePath(),rS.LICENSE_KEY_DIR_NAME,rS.LICENSE_FILE_NAME,rS.LICENSE_FILE_NAME);TC.exports={getFingerprint:tX,setLicense:eX,parseLicense:sS,register:rX,getRegistrationInfo:nX};async function eX(e){if(e&&e.key&&e.company){try{lr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await sS(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw lr.error(r),lr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}o(eX,"setLicense");async function tX(){let e={};try{e=await jl.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw lr.error(r),lr.error(t),new Error(r)}return e}o(tX,"getFingerprint");async function sS(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");lr.info("Validating license input...");let r=jl.validateLicense(e,t);if(lr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(lr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(lr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{lr.info("writing license to disk"),await W3.writeFile(j3,JSON.stringify({license_key:e,company:t}))}catch(s){throw lr.error("Failed to write License"),s}return"Registration successful."}o(sS,"parseLicense");async function rX(){let e=await sX();return sS(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}o(rX,"register");async function sX(){let e=await jl.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:mC.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:mC.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{SC.start()}catch(s){lr.error(s)}let r;try{r=await Z3(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}o(sX,"promptForRegistration");async function nX(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await jl.getLicense()}catch(r){throw lr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(z3.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=J3.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=X3.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}o(nX,"getRegistrationInfo")});var gC=m((pce,RC)=>{"use strict";var iX=Be(),iS=class{static{o(this,"HubConfigObject")}constructor(t,r,s,n,i,a,c,u,l,_,d,E,f,h){this.port=t,a===null&&(a=void 0),this.server_name=r+iX.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:a,insecure:c,verify:u},this.leafnodes={port:l,tls:{cert_file:n,key_file:i,ca_file:a,insecure:c}},this.cluster={name:_,port:d,routes:E,tls:{cert_file:n,key_file:i,ca_file:a,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};RC.exports=iS});var NC=m((Rce,OC)=>{"use strict";var AC=Be(),aS=class{static{o(this,"LeafConfigObject")}constructor(t,r,s,n,i,a,c,u,l,_,d){this.port=t,d===null&&(d=void 0),this.server_name=r+AC.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+AC.SERVER_SUFFIX.LEAF},this.tls={cert_file:l,key_file:_,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:a,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};OC.exports=aS});var yC=m((Ace,bC)=>{"use strict";var oS=class{static{o(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};bC.exports=oS});var wC=m((Nce,IC)=>{"use strict";var aX=Be(),cS=class{static{o(this,"SysUserObject")}constructor(t,r){this.user=t+aX.SERVER_SUFFIX.ADMIN,this.password=r}};IC.exports=cS});var _S=m((yce,DC)=>{"use strict";var jo=require("path"),s_=require("fs-extra"),oX=gC(),cX=NC(),uX=yC(),lX=wC(),uS=Or(),ua=x(),Yt=Ar(),r_=g(),e_=Be(),{CONFIG_PARAMS:ze}=r_,tc=q(),n_=Q(),CC=Ls(),lS=rt(),ec="clustering",_X=1e4,UC=5;DC.exports={generateNatsConfig:dX,removeNatsConfig:EX};async function dX(e=!1,t=void 0){n_.initSync();let r=n_.get(ze.ROOTPATH),s=jo.join(r,ec,e_.PID_FILES.HUB),n=jo.join(r,ec,e_.PID_FILES.LEAF),i=Yt.getConfigFromFile(ze.CLUSTERING_LEAFSERVER_STREAMS_PATH),a=jo.join(r,ec,e_.NATS_CONFIG_FILES.HUB_SERVER),c=jo.join(r,ec,e_.NATS_CONFIG_FILES.LEAF_SERVER),u=Yt.getConfigFromFile(ze.CLUSTERING_TLS_CERTIFICATE),l=Yt.getConfigFromFile(ze.CLUSTERING_TLS_PRIVATEKEY),_=Yt.getConfigFromFile(ze.CLUSTERING_TLS_CERT_AUTH),d=Yt.getConfigFromFile(ze.CLUSTERING_TLS_INSECURE),E=Yt.getConfigFromFile(ze.CLUSTERING_TLS_VERIFY),f=Yt.getConfigFromFile(ze.CLUSTERING_NODENAME),h=Yt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await lS.checkNATSServerInstalled()||i_("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let T=await uS.listUsers(),S=Yt.getConfigFromFile(ze.CLUSTERING_USER),y=await uS.getClusterUser();(ua.isEmpty(y)||y.active!==!0)&&i_(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await t_(ze.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await t_(ze.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await t_(ze.CLUSTERING_HUBSERVER_NETWORK_PORT),await t_(ze.CLUSTERING_LEAFSERVER_NETWORK_PORT));let O=[],H=[];for(let[ge,ct]of T.entries())ct.role.role===r_.ROLE_TYPES_ENUM.CLUSTER_USER&&ct.active&&(O.push(new lX(ct.username,CC.decrypt(ct.hash))),H.push(new uX(ct.username,CC.decrypt(ct.hash))));let Y=[],{hub_routes:A}=Yt.getClusteringRoutes();if(!ua.isEmptyOrZeroLength(A))for(let ge of A)Y.push(`tls://${y.sys_name_encoded}:${y.uri_encoded_d_hash}@${ge.host}:${ge.port}`);let w=new oX(Yt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_NETWORK_PORT),f,s,u,l,_,d,E,h,Yt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_CLUSTER_NAME),Yt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),Y,O,H);_==null&&(delete w.tls.ca_file,delete w.leafnodes.tls.ca_file),t=ua.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===r_.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await s_.writeJson(a,w),tc.trace(`Hub server config written to ${a}`));let G=`tls://${y.sys_name_encoded}:${y.uri_encoded_d_hash}@0.0.0.0:${h}`,k=`tls://${y.uri_encoded_name}:${y.uri_encoded_d_hash}@0.0.0.0:${h}`,X=new cX(Yt.getConfigFromFile(ze.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,n,i,[G],[k],O,H,u,l,_,d);_==null&&delete X.tls.ca_file,(t===void 0||t===r_.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await s_.writeJson(c,X),tc.trace(`Leaf server config written to ${c}`))}o(dX,"generateNatsConfig");async function t_(e){let t=n_.get(e);return ua.isEmpty(t)&&i_(`port undefined for '${e}'`),await ua.isPortTaken(t)&&i_(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}o(t_,"isPortAvailable");function i_(e){let t=`Error generating clustering config: ${e}`;tc.error(t),console.error(t),process.exit(1)}o(i_,"generateNatsConfigError");async function EX(e){let{port:t,config_file:r}=lS.getServerConfig(e),{username:s,decrypt_hash:n}=await uS.getClusterUser(),i=0,a=500;for(;i<UC;){try{let l=await lS.createConnection(t,s,n,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){tc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=UC)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 ua.async_set_timeout(a*i)}let c="0".repeat(_X),u=jo.join(n_.get(ze.ROOTPATH),ec,r);await s_.writeFile(u,c),await s_.remove(u),tc.notify(e,"started.")}o(EX,"removeNatsConfig")});var HC=m((wce,BC)=>{"use strict";var _r=Q(),fX=go(),oe=g(),rc=Be(),xs=require("path"),{PACKAGE_ROOT:o_}=g(),LC=Q(),a_=x(),la="/dev/null",hX=xs.join(o_,"launchServiceScripts"),MC=xs.join(o_,"utility/scripts"),mX=xs.join(MC,oe.HDB_RESTART_SCRIPT),PC=xs.resolve(o_,"dependencies",`${process.platform}-${process.arch}`,rc.NATS_BINARY_NAME);function vC(){let t=fX.licenseSearch().ram_allocation||oe.RAM_ALLOCATION_ENUM.DEFAULT,r=oe.MEM_SETTING_KEY+t,s={[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return a_.noBootFile()&&(s[oe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=a_.getEnvCliRootPath()),{name:oe.PROCESS_DESCRIPTORS.HDB,script:oe.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:o_}}o(vC,"generateMainServerConfig");var SX=9930;function pX(){_r.initSync(!0);let e=_r.get(oe.CONFIG_PARAMS.ROOTPATH),t=xs.join(e,"clustering",rc.NATS_CONFIG_FILES.HUB_SERVER),r=xs.join(_r.get(oe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),oe.LOG_NAMES.HDB),s=LC.get(oe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=rc.LOG_LEVEL_FLAGS[_r.get(oe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==SX?"-"+s:""),script:PC,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=la,i.error_file=la),i}o(pX,"generateNatsHubServerConfig");var TX=9940;function RX(){_r.initSync(!0);let e=_r.get(oe.CONFIG_PARAMS.ROOTPATH),t=xs.join(e,"clustering",rc.NATS_CONFIG_FILES.LEAF_SERVER),r=xs.join(_r.get(oe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),oe.LOG_NAMES.HDB),s=LC.get(oe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=rc.LOG_LEVEL_FLAGS[_r.get(oe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==TX?"-"+s:""),script:PC,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=la,i.error_file=la),i}o(RX,"generateNatsLeafServerConfig");function gX(){_r.initSync();let e=xs.join(_r.get(oe.CONFIG_PARAMS.LOGGING_ROOT),oe.LOG_NAMES.HDB),t={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:oe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:hX,autorestart:!1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=la,t.error_file=la),t}o(gX,"generateClusteringUpgradeV4ServiceConfig");function AX(){let e={[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.RESTART_HDB};return a_.noBootFile()&&(e[oe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=a_.getEnvCliRootPath()),{...{name:oe.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:MC},script:mX}}o(AX,"generateRestart");function OX(){return{apps:[vC()]}}o(OX,"generateAllServiceConfigs");BC.exports={generateAllServiceConfigs:OX,generateMainServerConfig:vC,generateRestart:AX,generateNatsHubServerConfig:pX,generateNatsLeafServerConfig:RX,generateClusteringUpgradeV4ServiceConfig:gX}});var ZC=m((vce,XC)=>{"use strict";var Te=g(),NX=x(),sc=_S(),nc=rt(),us=Be(),bn=HC(),c_=Q(),ks=q(),bX=Gs(),{startWorker:FC,onMessageFromWorkers:yX}=_t(),IX=ca(),wX=require("util"),GC=require("child_process"),{execFile:CX}=GC,Uce=wX.promisify(GC.exec),Dce=require("systeminformation"),fe;XC.exports={enterPM2Mode:UX,start:ci,stop:dS,reload:xC,restart:kC,list:ES,describe:$C,connect:Vs,kill:vX,startAllServices:BX,startService:fS,getUniqueServicesList:YC,restartAllServices:HX,isServiceRegistered:KC,reloadStopStart:WC,restartHdb:VC,deleteProcess:MX,startClusteringProcesses:zC,startClusteringThreads:JC,isHdbRestartRunning:PX,isClusteringRunning:qX,stopClustering:FX,reloadClustering:GX};var{PACKAGE_ROOT:Lce}=g(),Mce=g(),{loggerWithTag:Pce}=ks,ic=!1;yX(e=>{e.type==="restart"&&c_.initSync(!0)});function UX(){ic=!0}o(UX,"enterPM2Mode");function Vs(){return fe||(fe=require("pm2")),new Promise((e,t)=>{fe.connect((r,s)=>{ks.setupConsoleLogging(),r&&t(r),e(s)})})}o(Vs,"connect");var Kt,DX=10,qC;function ci(e){if(ic)return LX(e);let t=CX(e.script,e.args.split(" "),e);t.name=e.name,t.on("exit",n=>{let i=Kt.indexOf(t);i>-1&&Kt.splice(i,1),!qC&&n>0&&(e.restarts=(e.restarts||0)+1,e.restarts<DX&&ci(e))});let r={serviceName:e.name.replace(/ /g,"-")};function s(n){let i=c_.get(Te.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),a=/\[\d+][^\[]+\[(\w+)]/g,c,u=0,l;for(;c=a.exec(n);){if(c.index&&us.LOG_LEVEL_HIERARCHY[i]>=us.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===us.LOG_LEVELS.ERR||l===us.LOG_LEVELS.WRN?ks.OUTPUTS.STDERR:ks.OUTPUTS.STDOUT;ks.logCustomLevel(l||"info",E,r,n.slice(u,c.index).trim())}let[_,d]=c;u=c.index+_.length,l=us.LOG_LEVELS[d]}if(us.LOG_LEVEL_HIERARCHY[i]>=us.LOG_LEVEL_HIERARCHY[l||"info"]){let _=l===us.LOG_LEVELS.ERR||l===us.LOG_LEVELS.WRN?ks.OUTPUTS.STDERR:ks.OUTPUTS.STDOUT;ks.logCustomLevel(l||"info",_,r,n.slice(u).trim())}}if(o(s,"extractMessages"),t.stdout.on("data",s),t.stderr.on("data",s),t.unref(),!Kt){Kt=[];let n=o(()=>{qC=!0,Kt&&(Kt.map(i=>i.kill()),process.exit(0))},"kill_children");process.on("exit",n),process.on("SIGINT",n),process.on("SIGQUIT",n),process.on("SIGTERM",n)}Kt.push(t)}o(ci,"start");function LX(e){return new Promise(async(t,r)=>{try{await Vs()}catch(s){r(s)}fe.start(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}o(LX,"startWithPM2");function dS(e){if(!ic){for(let t of Kt||[])t.name===e&&(Kt.splice(Kt.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Vs()}catch(s){r(s)}fe.stop(e,async(s,n)=>{s&&(fe.disconnect(),r(s)),fe.delete(e,(i,a)=>{i&&(fe.disconnect(),r(s)),fe.disconnect(),t(a)})})})}o(dS,"stop");function xC(e){return new Promise(async(t,r)=>{try{await Vs()}catch(s){r(s)}fe.reload(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}o(xC,"reload");function kC(e){if(!ic)for(let t of Kt||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Vs()}catch(s){r(s)}fe.restart(e,(s,n)=>{fe.disconnect(),t(n)})})}o(kC,"restart");function MX(e){return new Promise(async(t,r)=>{try{await Vs()}catch(s){r(s)}fe.delete(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}o(MX,"deleteProcess");async function VC(){await ci(bn.generateRestart())}o(VC,"restartHdb");async function PX(){let e=await ES();for(let t in e)if(e[t].name===Te.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}o(PX,"isHdbRestartRunning");function ES(){return new Promise(async(e,t)=>{try{await Vs()}catch(r){t(r)}fe.list((r,s)=>{r&&(fe.disconnect(),t(r)),fe.disconnect(),e(s)})})}o(ES,"list");function $C(e){return new Promise(async(t,r)=>{try{await Vs()}catch(s){r(s)}fe.describe(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}o($C,"describe");function vX(){if(!ic){for(let e of Kt||[])e.kill();Kt=[];return}return new Promise(async(e,t)=>{try{await Vs()}catch(r){t(r)}fe.killDaemon((r,s)=>{r&&(fe.disconnect(),t(r)),fe.disconnect(),e(s)})})}o(vX,"kill");async function BX(){try{await zC(),await JC(),await ci(bn.generateAllServiceConfigs())}catch(e){throw fe.disconnect(),e}}o(BX,"startAllServices");async function fS(e){try{let t;switch(e=e.toLowerCase(),e){case Te.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=bn.generateMainServerConfig();break;case Te.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=bn.generateNatsIngestServiceConfig();break;case Te.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=bn.generateNatsReplyServiceConfig();break;case Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=bn.generateNatsHubServerConfig(),await ci(t),await sc.removeNatsConfig(e);return;case Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=bn.generateNatsLeafServerConfig(),await ci(t),await sc.removeNatsConfig(e);return;case Te.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=bn.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await ci(t)}catch(t){throw fe.disconnect(),t}}o(fS,"startService");async function YC(){try{let e=await ES(),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 fe.disconnect(),e}}o(YC,"getUniqueServicesList");async function HX(e=[]){try{let t=!1,r=await YC();for(let s=0,n=Object.values(r).length;s<n;s++){let a=Object.values(r)[s].name;e.includes(a)||(a===Te.PROCESS_DESCRIPTORS.HDB?t=!0:await kC(a))}t&&await WC(Te.PROCESS_DESCRIPTORS.HDB)}catch(t){throw fe.disconnect(),t}}o(HX,"restartAllServices");async function KC(e){if(Kt?.find(r=>r.name===e))return!0;let t=await IX.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}o(KC,"isServiceRegistered");async function WC(e){let t=e===Te.PROCESS_DESCRIPTORS.HDB?c_.get(Te.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):c_.get(Te.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await $C(e),s=NX.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await dS(e),await fS(e)):e===Te.PROCESS_DESCRIPTORS.HDB?await VC():await xC(e)}o(WC,"reloadStopStart");var QC;async function zC(){for(let e in Te.CLUSTERING_PROCESSES){let t=Te.CLUSTERING_PROCESSES[e];await fS(t)}}o(zC,"startClusteringProcesses");async function JC(){QC=FC(Te.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Te.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await nc.createWorkQueueStream(us.WORK_QUEUE_CONSUMER_NAMES),await nc.updateIngestStreamConsumer(),await nc.updateLocalStreams();let e=await bX.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Te.PRE_4_0_0_VERSION){ks.info("Starting clustering upgrade 4.0.0 process"),FC(Te.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}o(JC,"startClusteringThreads");async function FX(){for(let e in Te.CLUSTERING_PROCESSES)if(e!==Te.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Te.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await QC.terminate();else{let t=Te.CLUSTERING_PROCESSES[e];await dS(t)}}o(FX,"stopClustering");async function qX(){for(let e in Te.CLUSTERING_PROCESSES){let t=Te.CLUSTERING_PROCESSES[e];if(await KC(t)===!1)return!1}return!0}o(qX,"isClusteringRunning");async function GX(){await sc.generateNatsConfig(!0),await nc.reloadNATSHub(),await nc.reloadNATSLeaf(),await sc.removeNatsConfig(Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await sc.removeNatsConfig(Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}o(GX,"reloadClustering")});var gS=m((Hce,nU)=>{"use strict";var xX=require("minimist"),{isMainThread:SS,parentPort:tU}=require("worker_threads"),He=g(),{PROCESS_DESCRIPTORS_VALIDATE:ac}=He,ls=q(),pS=x(),u_=_S(),_a=rt(),hS=Be(),rU=Ar(),_s=ZC(),jC=ca(),kX=uE(),{restartWorkers:l_,onMessageByType:VX}=_t(),{handleHDBError:$X,hdb_errors:YX}=W(),{HTTP_STATUS_CODES:KX}=YX,__=Q();__.initSync();var oc=`Restarting HarperDB. This may take up to ${He.RESTART_TIMEOUT_MS/1e3} seconds.`,WX="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",eU="Clustering is not enabled so cannot be restarted",QX="Invalid service",ui,$r;nU.exports={restart:sU,restartService:TS};SS&&VX(He.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?TS({service:e.workerType}):sU({operation:"restart"})});async function sU(e){$r=Object.keys(e).length===0,ui=await _s.isServiceRegistered(He.HDB_PROC_DESCRIPTOR);let t=xX(process.argv);if(t.service){await TS(t);return}if($r&&!ui){console.error(WX);return}if($r&&console.log(oc),ui){_s.enterPM2Mode(),ls.notify(oc);let r=kX(Object.keys(He.CONFIG_PARAM_MAP),!0);return pS.isEmptyOrZeroLength(Object.keys(r))||rU.updateConfigValue(void 0,void 0,r,!0,!0),JX(),oc}return SS?(ls.notify(oc),await RS(),setTimeout(()=>{l_()},50)):tU.postMessage({type:He.ITC_EVENT_TYPES.RESTART}),oc}o(sU,"restart");async function TS(e){let{service:t}=e;if(He.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw $X(new Error,QX,KX.BAD_REQUEST,void 0,void 0,!0);if(ui=await _s.isServiceRegistered(He.HDB_PROC_DESCRIPTOR),!SS)return tU.postMessage({type:He.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case ac.clustering:if(!__.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=eU;break}$r&&console.log("Restarting clustering"),ls.notify("Restarting clustering"),await RS();break;case ac.clustering_config:case ac["clustering config"]:if(!__.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=eU;break}$r&&console.log("Restarting clustering_config"),ls.notify("Restarting clustering_config"),await _s.reloadClustering();break;case"custom_functions":case"custom functions":case ac.harperdb:case ac.http_workers:if($r&&!ui){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}$r&&console.log("Restarting http_workers"),ls.notify("Restarting http_workers"),ui?await _s.restart(He.HDB_PROC_DESCRIPTOR):setTimeout(()=>{l_("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(ls.error(r),$r&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}o(TS,"restartService");async function zX(){await _a.publishToStream(`${hS.SUBJECT_PREFIXES.TXN}.${hS.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,hS.WORK_QUEUE_CONSUMER_NAMES.stream_name,_a.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}o(zX,"postDummyNatsMsg");async function JX(){await RS(),await _s.restart(He.HDB_PROC_DESCRIPTOR),await pS.async_set_timeout(2e3),__.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await mS(),$r&&(await _a.closeConnection(),process.exit(0))}o(JX,"restartPM2Mode");async function RS(){if(!rU.getConfigFromFile(He.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await jC.getHDBProcessInfo()).clustering.length===0)ls.trace("Clustering not running, restart will start clustering services"),await u_.generateNatsConfig(!0),await _s.startClusteringProcesses(),await _s.startClusteringThreads(),await mS(),$r&&await _a.closeConnection();else{await zX(),await u_.generateNatsConfig(!0),ui?(ls.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await _s.restart(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await _s.restart(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await jC.getHDBProcessInfo()).clustering.forEach(n=>{ls.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await pS.async_set_timeout(3e3),await mS(),await _a.updateLocalStreams(),$r&&await _a.closeConnection(),ls.trace("Restart clustering restarting ingest and reply service threads");let t=l_(He.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=l_(He.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}o(RS,"restartClustering");async function mS(){await u_.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await u_.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}o(mS,"removeNatsConfig")});var hU=m((Gce,fU)=>{"use strict";var qce=require("lodash"),Wt=g(),{handleHDBError:iU,hdb_errors:XX}=W(),{HDB_ERROR_MSGS:ZX,HTTP_STATUS_CODES:jX}=XX,AS=q();fU.exports={getRolePermissions:t4};var li=Object.create(null),e4=o(e=>({key:e,perms:{}}),"perms_template_obj"),uU=o((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),lU=o((e=!1,t=!1,r=!1,s=!1)=>({[Wt.PERMS_CRUD_ENUM.READ]:e,[Wt.PERMS_CRUD_ENUM.INSERT]:t,[Wt.PERMS_CRUD_ENUM.UPDATE]:r,[Wt.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),OS=o((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...lU(t,r,s,n)}),"table_perms_template"),aU=o((e,t=lU())=>({attribute_name:e,describe:EU(t),[cc]:t[cc],[NS]:t[NS],[bS]:t[bS]}),"attr_perms_template"),oU=o((e,t=!1)=>({attribute_name:e,describe:t,[cc]:t}),"timestamp_attr_perms_template"),{READ:cc,INSERT:NS,UPDATE:bS}=Wt.PERMS_CRUD_ENUM,_U=Object.values(Wt.PERMS_CRUD_ENUM),dU=[cc,NS,bS];function t4(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[Wt.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(li[t]&&li[t].key===s)return li[t].perms;let n=r4(e,r);return li[t]?li[t].key=s:li[t]=e4(s),li[t].perms=n,n}catch(r){if(!e[Wt.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Wt.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Wt.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 AS.error(s),AS.debug(r),iU(new Error,ZX.OUTDATED_PERMS_TRANSLATION_ERROR,jX.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
6
|
-
${r.stack}`;throw AS.error(s),iU(new Error)}}}o(t4,"getRolePermissions");function r4(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[Wt.SYSTEM_SCHEMA_NAME]=s[Wt.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]=s4(t[i]);return}r[i]=uU(),s[i]?(s[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(a=>{if(s[i].tables[a]){let c=s[i].tables[a],u=t[i][a],l=n4(c,u);r[i].describe||_U.forEach(_=>{l[_]&&(r[i].describe=!0)}),r[i].tables[a]=l}else r[i].tables[a]=OS()})):Object.keys(t[i]).forEach(a=>{r[i].tables[a]=OS()})}),r}o(r4,"translateRolePermissions");function s4(e){let t=uU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=OS(!0,!0,!0,!0,!0)}),t}o(s4,"createStructureUserPermissions");function n4(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((l,_)=>{let{attribute_name:d}=_,E=_;return Wt.TIME_STAMP_NAMES.includes(d)&&(E=oU(d,_[cc])),l[d]=E,l},{}),a=t.primaryKey||t.hash_attribute,c=!!i[a],u=aU(a);return t.attributes.forEach(({attribute:l})=>{if(i[l]){let _=i[l];_.describe=EU(_),n.attribute_permissions.push(_),c||i4(_,u)}else if(l!==a){let _;Wt.TIME_STAMP_NAMES.includes(l)?_=oU(l):_=aU(l),n.attribute_permissions.push(_)}}),c||n.attribute_permissions.push(u),n.describe=cU(n),n}else return e.describe=cU(e),e}o(n4,"getTableAttrPerms");function cU(e){return _U.filter(t=>e[t]).length>0}o(cU,"getSchemaTableDescribePerm");function EU(e){return dU.filter(t=>e[t]).length>0}o(EU,"getAttributeDescribePerm");function i4(e,t){dU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}o(i4,"checkForHashPerms")});var mU={};Ze(mU,{Resources:()=>d_,keyArrayToString:()=>da,resetResources:()=>a4,resources:()=>yn});function a4(){return yn=new d_}function da(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var d_,yn,uc=pe(()=>{Gn();d_=class extends Map{static{o(this,"Resources")}isWorker=!0;loginPath;set(t,r,s,n){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:s,hasSubPaths:!1,relativeURL:""},a=super.get(t);if(a&&(a.Resource.databaseName!==r.databaseName||a.Resource.tableName!==r.tableName)&&!n)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let l=2;for(;(l=c.indexOf("/",l))>-1;){let _=this.get(c.slice(0,l));_&&(_.hasSubPaths=!0),l+=2}}}getMatch(t,r){let s=2,n;for(;(s=t.indexOf("/",s))>-1;){let c=t.slice(0,s),u=this.get(c);if(u){if(u.relativeURL=t.slice(s),!u.hasSubPaths)return u;n=u}s+=2}if(n)return n;let i=t.indexOf("?"),a=i>-1?t.slice(0,i):t;return n=this.get(a),n?n.relativeURL=i>-1?t.slice(i):"":n||(n=this.get(""),n&&(n.relativeURL="")),n}getResource(t,r){let s=this.getMatch(t);if(s)return t=s.relativeURL,s.Resource.getResource(this.pathToId(t,s.Resource),r)}call(t,r,s){return Ye(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};o(a4,"resetResources");o(da,"keyArrayToString")});var lc={};Ze(lc,{authentication:()=>AU,login:()=>h4,logout:()=>m4,start:()=>f4});async function AU(e,t){let r=e.headers,s=r.authorization,n=r.cookie,i=r.origin,a=[];if(i){let f=e.isOperationsServer?l4?u4:[]:c4?o4:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h={"Access-Control-Allow-Methods":"POST, GET, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Accept, Content-Type, Authorization","Access-Control-Allow-Origin":i};return E_&&(h["Access-Control-Allow-Credentials"]="true"),{status:200,headers:h}}a.push("Access-Control-Allow-Origin",i),E_&&a.push("Access-Control-Allow-Credentials","true")}}let c,u;if(E_){let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(f);if(h>=0){let T=n.indexOf(";",h),S=n.indexOf("=",h);c=n.slice(S+1,T===-1?n.length:T),u=await pU.get(c)}e.session=u||(u={})}e.user=null;let l=o((f,h,T)=>{let S=new m_.AuthAuditLog(f,h,Tt.AUTH_AUDIT_TYPES.AUTHENTICATION,e.headers["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=T,c&&(S.session_id=c),e.headers.referer&&(S.referer=e.headers.referer),e.headers.origin&&(S.origin=e.headers.origin),h===Tt.AUTH_AUDIT_STATUS.SUCCESS?SU.notify(S):SU.error(S)},"authAuditLog"),_;if(s){if(_=Ea.get(s),!_){let[f,h]=s.split(" "),T,S;try{switch(f){case"Basic":[T,S]=atob(h).split(":"),_=T||S?await ht.auth(T,S):null;break;case"Bearer":try{_=await(0,h_.validateOperationToken)(h)}catch(y){if(y.message==="invalid token")try{return await(0,h_.validateRefreshToken)(h),{status:-1}}catch{throw y}}break}}catch(y){return E4&&(Ea.get(h)||(Ea.set(h,h),l(T,Tt.AUTH_AUDIT_STATUS.FAILURE,f))),{status:401,body:$s({error:y.message},e)}}Ea.set(s,_),d4&&l(_.username,Tt.AUTH_AUDIT_STATUS.SUCCESS,f)}e.user=_}else u?.user?e.user=await ht.auth(u.user,null,!1):_4&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")&&(e.user=_=await(0,f_.getSuperUser)());E_&&(e.session.update=function(f){if(!c){c=(0,RU.v4)();let T=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${c}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;a?a.push("set-cookie",T):d?.headers?.set&&d.headers.set("set-cookie",T)}return f.id=c,pU.put(f)},e.login=async function(f,h){e.user=await ht.auth(f,h),e.session.update({user:e.user.username})},(_&&!u||u?.user?.username!==_?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let d=await t(e);if(!d)return d;d.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&yn.loginPath?(d.status=302,d.headers.Location=yn.loginPath(e)):d.headers["WWW-Authenticate"]="Basic");let E=a.length;if(E>0){let f=d.headers;f||(d.headers=f={});for(let h=0;h<E;){let T=a[h++];f[T]=a[h++]}}return a=null,d}function f4({server:e,port:t}){e.request(AU,{port:t||"all"}),TU||(TU=!0,setInterval(()=>{Ea=new Map},br.get(Tt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),gU.user.addListener(()=>{Ea=new Map}))}async function h4(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function m4(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var f_,h_,RU,br,Tt,m_,gU,SU,o4,c4,u4,l4,pU,E_,_4,d4,E4,Ea,TU,S_=pe(()=>{f_=D(Or());on();uc();h_=D(ko());de();RU=require("uuid"),br=D(Q()),Tt=D(g()),m_=D(q());fa();gU=D(Oo()),SU=(0,m_.loggerWithTag)("auth-event");br.initSync();o4=br.get(Tt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),c4=br.get(Tt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS),u4=br.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),l4=br.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS);ht.auth=f_.findAndValidateUser;pU=et({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),E_=br.get(Tt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,_4=br.get(Tt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??!0,d4=br.get(Tt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,E4=br.get(Tt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,Ea=new Map;o(AU,"authentication");o(f4,"start");o(h4,"login");o(m4,"logout")});var CU=m((zce,wU)=>{"use strict";var he=require("joi"),OU=require("fs-extra"),NU=require("path"),Ks=ve(),bU=Q(),yU=g(),IU=q(),{hdb_errors:S4}=W(),{HDB_ERROR_MSGS:Dt}=S4,Ys=/^[a-zA-Z0-9-_]+$/;wU.exports={getDropCustomFunctionValidator:T4,setCustomFunctionValidator:R4,addComponentValidator:N4,dropCustomFunctionProjectValidator:b4,packageComponentValidator:y4,deployComponentValidator:I4,setComponentFileValidator:g4,getComponentFileValidator:O4,dropComponentFileValidator:A4};function p_(e,t,r){try{let s=bU.get(yU.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=NU.join(s,t);return OU.existsSync(n)?e?t:r.message(Dt.PROJECT_EXISTS):e?r.message(Dt.NO_PROJECT):t}catch(s){return IU.error(s),r.message(Dt.VALIDATION_ERR)}}o(p_,"checkProjectExists");function _c(e,t){return e.includes("..")?t.message("Invalid file path"):e}o(_c,"checkFilePath");function p4(e,t,r,s){try{let n=bU.get(yU.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=NU.join(n,e,t,r+".js");return OU.existsSync(i)?r:s.message(Dt.NO_FILE)}catch(n){return IU.error(n),s.message(Dt.VALIDATION_ERR)}}o(p4,"checkFileExists");function T4(e){let t=he.object({project:he.string().pattern(Ys).custom(p_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),type:he.string().valid("helpers","routes").required(),file:he.string().pattern(Ys).custom(p4.bind(null,e.project,e.type)).custom(_c).required().messages({"string.pattern.base":Dt.BAD_FILE_NAME})});return Ks.validateBySchema(e,t)}o(T4,"getDropCustomFunctionValidator");function R4(e){let t=he.object({project:he.string().pattern(Ys).custom(p_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),type:he.string().valid("helpers","routes").required(),file:he.string().custom(_c).required(),function_content:he.string().required()});return Ks.validateBySchema(e,t)}o(R4,"setCustomFunctionValidator");function g4(e){let t=he.object({project:he.string().pattern(Ys).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),file:he.string().custom(_c).required(),payload:he.string().optional(),encoding:he.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ks.validateBySchema(e,t)}o(g4,"setComponentFileValidator");function A4(e){let t=he.object({project:he.string().pattern(Ys).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),file:he.string().custom(_c).optional()});return Ks.validateBySchema(e,t)}o(A4,"dropComponentFileValidator");function O4(e){let t=he.object({project:he.string().required(),file:he.string().custom(_c).required(),encoding:he.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ks.validateBySchema(e,t)}o(O4,"getComponentFileValidator");function N4(e){let t=he.object({project:he.string().pattern(Ys).custom(p_.bind(null,!1)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME})});return Ks.validateBySchema(e,t)}o(N4,"addComponentValidator");function b4(e){let t=he.object({project:he.string().pattern(Ys).custom(p_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME})});return Ks.validateBySchema(e,t)}o(b4,"dropCustomFunctionProjectValidator");function y4(e){let t=he.object({project:he.string().pattern(Ys).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),skip_node_modules:he.boolean()});return Ks.validateBySchema(e,t)}o(y4,"packageComponentValidator");function I4(e){let t=he.object({project:he.string().pattern(Ys).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),payload:he.string().optional().messages({"string.pattern.base":Dt.BAD_PACKAGE}),package:he.string().optional()});return Ks.validateBySchema(e,t)}o(I4,"deployComponentValidator")});var CS=m((Xce,LU)=>{"use strict";var be=require("fs-extra"),yS=require("fast-glob"),me=require("path"),UU=require("tar-fs"),w4=require("uuid").v4,IS=require("normalize-path"),ds=CU(),Rt=q(),Ie=g(),$e=Q(),T_=Ar(),C4=x(),{PACKAGE_ROOT:U4}=g(),{handleHDBError:st,hdb_errors:D4}=W(),{HDB_ERROR_MSGS:In,HTTP_STATUS_CODES:nt}=D4,L4=me.join(U4,"application-template"),wS=me.join($e.get(Ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function DU(){let e=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw st(new Error,In.NOT_ENABLED,nt.BAD_REQUEST,void 0,void 0,!0)}o(DU,"isCFEnabled");function M4(){Rt.trace("getting custom api status");let e={};try{e={is_enabled:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw st(new Error,In.FUNCTION_STATUS,nt.INTERNAL_SERVER_ERROR,Rt.ERR,t)}return e}o(M4,"customFunctionsStatus");function P4(){Rt.trace("getting custom api endpoints");let e={},t=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{yS.sync(IS(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:yS.sync(IS(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:yS.sync(IS(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw st(new Error,In.GET_FUNCTIONS,nt.INTERNAL_SERVER_ERROR,Rt.ERR,r)}return e}o(P4,"getCustomFunctions");function v4(e){e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=ds.getDropCustomFunctionValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);Rt.trace("getting custom api endpoint file content");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,a=me.join(r,s,n,i+".js");try{return be.readFileSync(a,{encoding:"utf8"})}catch(c){throw st(new Error,In.GET_FUNCTION,nt.INTERNAL_SERVER_ERROR,Rt.ERR,c)}}o(v4,"getCustomFunction");function B4(e){DU(),e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=ds.setCustomFunctionValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);Rt.trace("setting custom function file content");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:a}=e;try{return be.outputFileSync(me.join(r,s,n,i+".js"),a),`Successfully updated custom function: ${i}.js`}catch(c){throw st(new Error,In.SET_FUNCTION,nt.INTERNAL_SERVER_ERROR,Rt.ERR,c)}}o(B4,"setCustomFunction");function H4(e){e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=ds.getDropCustomFunctionValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);Rt.trace("dropping custom function file");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return be.unlinkSync(me.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(a){throw st(new Error,In.DROP_FUNCTION,nt.INTERNAL_SERVER_ERROR,Rt.ERR,a)}}o(H4,"dropCustomFunction");function F4(e){DU(),e.project&&(e.project=me.parse(e.project).name);let t=ds.addComponentValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);Rt.trace("adding component");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=me.join(r,s);return be.mkdirSync(n,{recursive:!0}),be.copySync(L4,n),`Successfully added project: ${s}`}catch(n){throw st(new Error,In.ADD_FUNCTION,nt.INTERNAL_SERVER_ERROR,Rt.ERR,n)}}o(F4,"addComponent");function q4(e){e.project&&(e.project=me.parse(e.project).name);let t=ds.dropCustomFunctionProjectValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);Rt.trace("dropping custom function project");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=$e.get(Ie.CONFIG_PARAMS.APPS);if(!C4.isEmptyOrZeroLength(n)){let i=!1;for(let[a,c]of n.entries())if(c.name===s){n.splice(a,1),i=!0;break}if(i)return T_.updateConfigValue(Ie.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=me.join(r,s);return be.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw st(new Error,In.DROP_FUNCTION_PROJECT,nt.INTERNAL_SERVER_ERROR,Rt.ERR,i)}}o(q4,"dropCustomFunctionProject");async function G4(e){e.project&&(e.project=me.parse(e.project).name);let t=ds.packageComponentValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;Rt.trace("packaging component",s);let n;try{n=await be.realpath(me.join(r,s))}catch(u){if(u.code!==Ie.NODE_ERROR_CODES.ENOENT)throw u;try{n=await be.realpath(me.join($e.get(Ie.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(l){if(l.code===Ie.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await be.ensureDir(wS);let i=me.join(wS,`${s}.tar`),a={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(a={ignore:u=>u.includes(me.join(n,"node_modules"))}),UU.pack(n,a).pipe(be.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=be.readFileSync(i,{encoding:"base64"});return await be.remove(i),{project:s,payload:c}}o(G4,"packageComponent");async function x4(e){e.project&&(e.project=me.parse(e.project).name);let t=ds.deployComponentValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,package:i}=e;if(Rt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");if(n){let a=me.join(r,s);i="file:"+a,await be.ensureDir(a);let c,u;do c=me.join(wS,w4()+".tar"),u=await be.pathExists(c);while(u);await be.outputFile(c,n,{encoding:"base64"});let l=be.createReadStream(c);l.pipe(UU.extract(a)),await new Promise(_=>l.on("end",_)),await be.unlink(c)}return T_.updateConfigValue(`${s}_package`,i,void 0,!1,!1,!0),`Successfully deployed: ${s}`}o(x4,"deployComponent");async function k4(){let e=T_.getConfiguration(),t=[];for(let s in e)if(e[s]?.package){if(e[s].package.startsWith("file:"))continue;t.push(Object.assign(e[s],{name:s}))}let r=o(async(s,n)=>{let i=await be.readdir(s,{withFileTypes:!0});for(let a of i){let c=a.name;if(c.startsWith(".")||c==="node_modules")continue;let u=me.join(s,c);if(await a.isDirectory()){let l={name:c,entries:[]};n.entries.push(l),await r(u,l)}else{let l=await be.stat(u),_={name:me.basename(c),mtime:l.mtime,size:l.size};n.entries.push(_)}}return n},"walk_dir");return r($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),{name:$e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT).split(me.sep).slice(-1).pop(),entries:t})}o(k4,"getComponents");async function V4(e){let t=ds.getComponentFileValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{return await be.readFile(me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),e.project,e.file),r)}catch(s){throw s.code===Ie.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${me.join(e.project,e.file)}'`):s}}o(V4,"getComponentFile");async function $4(e){let t=ds.setComponentFileValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),e.project,e.file);return e.payload!==void 0?(await be.ensureFile(s),await be.outputFile(s,e.payload,r)):await be.ensureDir(s),"Successfully set component: "+e.file}o($4,"setComponentFile");async function Y4(e){let t=ds.dropComponentFileValidator(e);if(t)throw st(t,t.message,nt.BAD_REQUEST);let r=e.file?me.join(e.project,e.file):e.project,s=me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),r);return await be.pathExists(s)&&await be.remove(s),T_.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}o(Y4,"dropComponent");LU.exports={customFunctionsStatus:M4,getCustomFunctions:P4,getCustomFunction:v4,setCustomFunction:B4,dropCustomFunction:H4,addComponent:F4,dropCustomFunctionProject:q4,packageComponent:G4,deployComponent:x4,getComponents:k4,getComponentFile:V4,setComponentFile:$4,dropComponent:Y4}});var US=m((jce,PU)=>{"use strict";var Es=require("joi"),MU=ve();PU.exports={readTransactionLogValidator:K4,deleteTransactionLogsBeforeValidator:W4};function K4(e){let t=Es.object({schema:Es.string().required(),table:Es.string().required(),from:Es.date().timestamp(),to:Es.date().timestamp(),limit:Es.number().min(1)});return MU.validateBySchema(e,t)}o(K4,"readTransactionLogValidator");function W4(e){let t=Es.object({schema:Es.string().required(),table:Es.string().required(),timestamp:Es.date().timestamp().required()});return MU.validateBySchema(e,t)}o(W4,"deleteTransactionLogsBeforeValidator")});var g_=m((tue,qU)=>{"use strict";var DS=g(),R_=rt(),vU=x(),BU=Q(),HU=Ls(),{handleHDBError:ha,hdb_errors:Q4}=W(),{HTTP_STATUS_CODES:ma}=Q4,{readTransactionLogValidator:z4,deleteTransactionLogsBeforeValidator:J4}=US(),FU="This operation relies on clustering and cannot run with it disable.",X4="Logs successfully deleted from transaction log.",Z4="All logs successfully deleted from transaction log.";qU.exports={readTransactionLog:j4,deleteTransactionLogsBefore:eZ};async function*j4(e){let t=z4(e);if(t)throw ha(t,t.message,ma.BAD_REQUEST,void 0,void 0,!0);if(!BU.get(DS.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ha(new Error,FU,ma.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=vU.checkSchemaTableExist(r,s);if(n)throw ha(new Error,n,ma.NOT_FOUND,void 0,void 0,!0);let i=HU.createNatsTableStreamName(r,s),a=await R_.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of a){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let l={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===DS.OPERATIONS_ENUM.DELETE&&(l.hash_values=c?.entry?.hash_values),yield l}}o(j4,"readTransactionLog");async function eZ(e){let t=J4(e);if(t)throw ha(t,t.message,ma.BAD_REQUEST,void 0,void 0,!0);if(!BU.get(DS.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ha(new Error,FU,ma.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=vU.checkSchemaTableExist(r,s);if(i)throw ha(new Error,i,ma.NOT_FOUND,void 0,void 0,!0);let a=HU.createNatsTableStreamName(r,s),{jsm:c}=await R_.getNATSReferences(),u=await R_.getStreamInfo(a),l=new Date(u.state.first_ts).getTime();if(n<=l)return`No transactions exist before: ${n}`;let _=X4,d,E=new Date(u.state.last_ts).getTime();return n>E?(d=u.state.last_seq+1,_=Z4):d=(await R_.viewStream(a,parseInt(n),1))[0].nats_sequence,await c.streams.purge(a,{seq:d}),_}o(eZ,"deleteTransactionLogsBefore")});var b_=m((sue,KU)=>{"use strict";var A_=require("joi"),O_=require("path"),GU=require("fs-extra"),{exec:tZ}=require("child_process"),rZ=require("util"),xU=rZ.promisify(tZ),dc=g(),{handleHDBError:Sa,hdb_errors:sZ}=W(),{HTTP_STATUS_CODES:pa}=sZ,fc=Q(),nZ=ve(),Ec=q();fc.initSync();var LS=fc.get(dc.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),kU="npm install --omit=dev --json",iZ=`${kU} --dry-run`;KU.exports={installModules:uZ,auditModules:lZ,installAllRootModules:aZ,uninstallRootModule:oZ,linkHarperdb:cZ};async function aZ(e=!1){await N_(),await hc(e?"npm install --ignore-scripts":"npm install",fc.get(dc.CONFIG_PARAMS.ROOTPATH))}o(aZ,"installAllRootModules");async function oZ(e){await hc(`npm uninstall ${e}`,fc.get(dc.CONFIG_PARAMS.ROOTPATH))}o(oZ,"uninstallRootModule");async function cZ(){await N_(),await hc(`npm link ${dc.PACKAGE_ROOT}`,fc.get(dc.CONFIG_PARAMS.ROOTPATH))}o(cZ,"linkHarperdb");async function hc(e,t=void 0){let{stdout:r,stderr:s}=await xU(e,{cwd:t});if(s&&!s.includes("Debugger listening"))throw new Error(s.replace(`
|
|
7
|
-
`,""));return
|
|
8
|
-
`,"")}
|
|
1
|
+
"use strict";var CB=Object.create;var $o=Object.defineProperty;var UB=Object.getOwnPropertyDescriptor;var DB=Object.getOwnPropertyNames;var LB=Object.getPrototypeOf,MB=Object.prototype.hasOwnProperty;var a=(e,t)=>$o(e,"name",{value:t,configurable:!0});var Se=(e,t)=>()=>(e&&(t=e(e=0)),t);var m=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),je=(e,t)=>{for(var r in t)$o(e,r,{get:t[r],enumerable:!0})},XT=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of DB(t))!MB.call(e,n)&&n!==r&&$o(e,n,{get:()=>t[n],enumerable:!(s=UB(t,n))||s.enumerable});return e};var C=(e,t,r)=>(r=e!=null?CB(LB(e)):{},XT(t||!e||!e.__esModule?$o(r,"default",{value:e,enumerable:!0}):r,e)),re=e=>XT($o({},"__esModule",{value:!0}),e);var eR=m((Ete,jT)=>{var PB=require("fast-glob"),{statSync:cE,existsSync:uE,readFileSync:vB,writeFileSync:BB}=require("fs"),{spawnSync:HB,spawn:FB}=require("child_process"),{isMainThread:qB}=require("worker_threads"),{join:bs,relative:ZT}=require("path"),{PACKAGE_ROOT:mr}=A(),{tmpdir:GB}=require("os");require("source-map-support").install();var xB=["resources","server","dataLayer"],Yo="ts-build",lE,kB=__filename.endsWith("tsBuild.js");if(kB){if(qB){let r;try{cE(bs(mr,Yo)),r=!0}catch{}if(r)for(let s of PB.sync(xB.map(n=>n+"/**/*.ts"),{cwd:mr})){let n=0,i=0;try{n=cE(bs(mr,s)).mtimeMs-5e3,i=cE(bs(mr,Yo,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),lE=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),lE=!0;if(lE){let s=HB(process.argv[0],[bs(mr,"node_modules/.bin/tsc")],{cwd:mr});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let n=bs(GB(),"harperdb-tsc.pid"),i;if(uE(n))try{process.kill(+vB(n,{encoding:"utf8"}),0),i=!0}catch{}if(!i){console.log("starting tsc background process");let o=FB(process.argv[0],[bs(mr,"node_modules/.bin/tsc"),"--watch"],{cwd:mr,detached:!0,stdio:"ignore"});BB(n,o.pid.toString()),o.unref()}}}}let e=jT.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(mr)&&!s[0].includes("node_modules")){let i=ZT(mr,s[0]),o;i.startsWith(Yo)?o=bs(mr,ZT(Yo,i)):o=bs(mr,Yo,i);let c=bs(o,r),u=c+".js";if(uE(u))return u;if(c.includes(".")&&uE(c))return c}return t(r,s,n)}}});var A=m((mte,fR)=>{"use strict";var Sr=require("path"),VB=require("fs"),{relative:fte,join:hte}=Sr,{existsSync:$B}=VB;function YB(){let e=__dirname;for(;!$B(Sr.join(e,"package.json"));){let t=Sr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(YB,"getHDBPackageRoot");var an=YB(),tR="js",au=tR,KB="harperdb-config.yaml",WB="defaultConfig.yaml",QB="hdb",rR=`harperdb.${au}`,sR=`customFunctionsServer.${au}`,zB=`restartHdb.${au}`,dE="HarperDB",ou="Custom Functions",cu="Clustering Hub",uu="Clustering Leaf",JB="Clustering Ingest Service",XB="Clustering Reply Service",ZB="foreground.pid",jB="hdb.pid",eH="data",tH={HDB:dE,CLUSTERING_HUB:cu,CLUSTERING_LEAF:uu,CLUSTERING_INGEST_SERVICE:JB,CLUSTERING_REPLY_SERVICE:XB,CUSTOM_FUNCTIONS:ou,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},rH={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},sH={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},nH={harperdb:dE,"clustering hub":cu,"clustering leaf":uu,"custom functions":ou,custom_functions:ou,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},iH={CLUSTERING_HUB_PROC_DESCRIPTOR:cu,CLUSTERING_LEAF_PROC_DESCRIPTOR:uu},_E={HDB:Sr.join(an,"server/harperdb"),CUSTOM_FUNCTIONS:Sr.join(an,"server/customFunctions"),CLUSTERING_HUB:Sr.join(an,"server/nats"),CLUSTERING_LEAF:Sr.join(an,"server/nats")},oH={HDB:Sr.join(_E.HDB,rR),CUSTOM_FUNCTIONS:Sr.join(_E.CUSTOM_FUNCTIONS,sR)},aH={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Sr.join(an,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Sr.join(an,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Sr.join(an,"launchServiceScripts/launchUpdateNodes4-0-0.js")},cH={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},nR="support@harperdb.io",uH="customer-success@harperdb.io",iR=1,lH=4141,oR="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",_H="https://www.harperdb.io/product",dH=`For support, please submit a request at ${oR} or contact ${nR}`,aR=`For license support, please contact ${uH}`,EH="None of the specified records were found.",fH="hash attribute not found",hH=`Your current license only supports ${iR} role. ${aR}`,mH="Your current license only supports 3 connections to a node.",SH="127.0.0.1",pH=1,TH=/^\.$/,RH=/^\.\.$/,gH="U+002E",AH=/\//g,OH="U+002F",NH=/U\+002F/g,bH=/^U\+002E$/,yH=/^U\+002EU\+002E$/,IH="d",wH=999999,CH="*",UH="--max-old-space-size=",DH="system",LH="__hdb_hash",MH=".harperdb",PH=".hdb",vH="keys",BH="hdb_boot_properties.file",HH=".updateConfig.json",FH="SIGTSTP",qH=24,GH=6e4,xH=448,kH="blob",VH="trash",$H="database",YH="schema",KH="transactions",WH=".count",QH="id",zH="PROCESS_NAME",cR={SETTINGS_PATH_KEY:"settings_path"},uR=require("lodash"),JH={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"},XH={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},ZH={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},jH={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"},e0={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},tr="hdb_internal:",t0={CREATE_SCHEMA:tr+"create_schema",CREATE_TABLE:tr+"create_table",CREATE_ATTRIBUTE:tr+"create_attribute",ADD_USER:tr+"add_user",ALTER_USER:tr+"alter_user",DROP_USER:tr+"drop_user",HDB_NODES:tr+"hdb_nodes",HDB_USERS:tr+"hdb_users",HDB_WORKERS:tr+"hdb_workers",CATCHUP:tr+"catchup",SCHEMA_CATCHUP:tr+"schema_catchup",WORKER_ROOM:tr+"cluster_workers"},r0={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"},s0="060493.ks",n0=".license",i0={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},K={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},o0={CSV:".csv",JSON:".json"},a0={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},c0={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Ko={};Ko[K.INSERT]=K.INSERT;Ko[K.UPDATE]=K.UPDATE;Ko[K.UPSERT]=K.UPSERT;Ko[K.DELETE]=K.DELETE;var ge=Object.create(null);ge[K.DESCRIBE_ALL]=K.DESCRIBE_ALL;ge[K.DESCRIBE_TABLE]=K.DESCRIBE_TABLE;ge[K.DESCRIBE_SCHEMA]=K.DESCRIBE_SCHEMA;ge[K.READ_LOG]=K.READ_LOG;ge[K.ADD_NODE]=K.ADD_NODE;ge[K.LIST_USERS]=K.LIST_USERS;ge[K.LIST_ROLES]=K.LIST_ROLES;ge[K.USER_INFO]=K.USER_INFO;ge[K.SQL]=K.SQL;ge[K.GET_JOB]=K.GET_JOB;ge[K.SEARCH_JOBS_BY_START_DATE]=K.SEARCH_JOBS_BY_START_DATE;ge[K.DELETE_FILES_BEFORE]=K.DELETE_FILES_BEFORE;ge[K.EXPORT_LOCAL]=K.EXPORT_LOCAL;ge[K.EXPORT_TO_S3]=K.EXPORT_TO_S3;ge[K.CLUSTER_STATUS]=K.CLUSTER_STATUS;ge[K.REMOVE_NODE]=K.REMOVE_NODE;ge[K.RESTART]=K.RESTART;ge[K.CUSTOM_FUNCTIONS_STATUS]=K.CUSTOM_FUNCTIONS_STATUS;ge[K.GET_CUSTOM_FUNCTIONS]=K.GET_CUSTOM_FUNCTIONS;ge[K.GET_CUSTOM_FUNCTION]=K.GET_CUSTOM_FUNCTION;ge[K.SET_CUSTOM_FUNCTION]=K.SET_CUSTOM_FUNCTION;ge[K.DROP_CUSTOM_FUNCTION]=K.DROP_CUSTOM_FUNCTION;ge[K.ADD_CUSTOM_FUNCTION_PROJECT]=K.ADD_CUSTOM_FUNCTION_PROJECT;ge[K.DROP_CUSTOM_FUNCTION_PROJECT]=K.DROP_CUSTOM_FUNCTION_PROJECT;ge[K.PACKAGE_CUSTOM_FUNCTION_PROJECT]=K.PACKAGE_CUSTOM_FUNCTION_PROJECT;ge[K.DEPLOY_CUSTOM_FUNCTION_PROJECT]=K.DEPLOY_CUSTOM_FUNCTION_PROJECT;var u0={DEBUG:"debug",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status"},l0={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},lR={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},_0=uR.invert(lR),g={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root",HTTP_THREADS:"http_threads",HTTP_SESSION_AFFINITY:"http_sessionAffinity",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT:"operationsApi_authentication_operationTokenTimeout",OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT:"operationsApi_authentication_refreshTokenTimeout",OPERATIONSAPI_FOREGROUND:"operationsApi_foreground",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERT_AUTH:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",OPERATIONSAPI_NODEENV:"operationsApi_nodeEnv",ROOTPATH:"rootPath",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",SCHEMAS:"schemas",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication"},_R={settings_path:cR.SETTINGS_PATH_KEY,hdb_root_key:g.ROOTPATH,hdb_root:g.ROOTPATH,server_port_key:g.OPERATIONSAPI_NETWORK_PORT,server_port:g.OPERATIONSAPI_NETWORK_PORT,cert_key:g.OPERATIONSAPI_TLS_CERTIFICATE,certificate:g.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:g.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:g.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:g.OPERATIONSAPI_NETWORK_HTTPS,https_on:g.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:g.OPERATIONSAPI_NETWORK_CORS,cors_on:g.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:g.LOGGING_LEVEL,log_level:g.LOGGING_LEVEL,log_path_key:g.LOGGING_ROOT,log_path:g.LOGGING_ROOT,props_env_key:g.OPERATIONSAPI_NODEENV,node_env:g.OPERATIONSAPI_NODEENV,clustering_node_name_key:g.CLUSTERING_NODENAME,node_name:g.CLUSTERING_NODENAME,clustering_enabled_key:g.CLUSTERING_ENABLED,clustering:g.CLUSTERING_ENABLED,max_http_threads:g.HTTP_THREADS,max_hdb_processes:g.HTTP_THREADS,server_timeout_key:g.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:g.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:g.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:g.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:g.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:g.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:g.LOGGING_AUDITLOG,disable_transaction_log:g.LOGGING_AUDITLOG,operation_token_timeout_key:g.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:g.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:g.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:g.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_enabled_key:g.CUSTOMFUNCTIONS_ENABLED,custom_functions:g.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:g.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:g.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:g.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:g.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:g.HTTP_THREADS,log_to_file:g.LOGGING_FILE,log_to_stdstreams:g.LOGGING_STDSTREAMS,run_in_foreground:g.OPERATIONSAPI_FOREGROUND,local_studio_on:g.LOCALSTUDIO_ENABLED,clustering_port:g.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:g.CLUSTERING_USER,clustering_enabled:g.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:g.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:g.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:g.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:g.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:g.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:g.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:g.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:g.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:g.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:g.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:g.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:g.CLUSTERING_NODENAME,clustering_tls_certificate:g.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:g.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:g.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:g.CLUSTERING_TLS_INSECURE,clustering_tls_verify:g.CLUSTERING_TLS_VERIFY,clustering_loglevel:g.CLUSTERING_LOGLEVEL,clustering_republishmessages:g.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:g.CLUSTERING_DATABASELEVEL,customfunctions_enabled:g.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:g.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:g.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:g.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:g.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:g.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:g.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:g.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:g.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:g.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:g.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:g.CUSTOMFUNCTIONS_NODEENV,http_threads:g.HTTP_THREADS,http_session_affinity:g.HTTP_SESSION_AFFINITY,customfunctions_processes:g.HTTP_THREADS,customfunctions_root:g.CUSTOMFUNCTIONS_ROOT,localstudio_enabled:g.LOCALSTUDIO_ENABLED,logging_file:g.LOGGING_FILE,logging_level:g.LOGGING_LEVEL,logging_root:g.LOGGING_ROOT,logging_rotation_enabled:g.LOGGING_ROTATION_ENABLED,logging_rotation_compress:g.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:g.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:g.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:g.LOGGING_ROTATION_PATH,logging_stdstreams:g.LOGGING_STDSTREAMS,logging_auditlog:g.LOGGING_AUDITLOG,logging_auditretention:g.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:g.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:g.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:g.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:g.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:g.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:g.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:g.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:g.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:g.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:g.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:g.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:g.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:g.OPERATIONSAPI_TLS_CERT_AUTH,operationsapi_network_timeout:g.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:g.OPERATIONSAPI_NODEENV,operationsapi_root:g.ROOTPATH,schemas:g.SCHEMAS,storage_path:g.STORAGE_PATH,ignorescripts:g.IGNORE_SCRIPTS,mqtt_network_port:g.MQTT_NETWORK_PORT,mqtt_websocket:g.MQTT_WEBSOCKET,mqtt_network_secureport:g.MQTT_NETWORK_SECUREPORT,mqtt_requireauthentication:g.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:g.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:g.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:g.AUTHENTICATION_CACHETTL,authentication_enablesessions:g.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:g.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:g.AUTHENTICATION_REFRESHTOKENTIMEOUT};for(let e in g){let t=g[e];_R[t.toLowerCase()]=t}var d0={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},E0={csv_file_load:"csv_file_load",csv_data_load:K.CSV_DATA_LOAD,csv_url_load:K.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"},f0={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"},h0={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},m0={VERSION_DEFAULT:"2.2.0"},S0={DEVELOPMENT:8192,DEFAULT:512},p0={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"},T0={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"},R0={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},dR={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},g0=Symbol("metadata"),A0="__clustering__",O0=Object.values(dR),N0=15984864e5,ER={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},b0=uR.invert(ER),y0={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"},I0=111,w0=`\r
|
|
2
|
+
`,C0={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},U0=["*","%"],D0="unauthorized_access",L0="func_val",M0={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},P0={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},v0={SHUTDOWN:"shutdown",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request",METRICS:"metrics",GET_METRICS:"get_metrics",RESTART:"restart"},B0={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},H0={HTTP:"http"},F0={STOPPED:"stopped",ONLINE:"online"},q0="3.x.x",G0={SUCCESS:"success",FAILURE:"failure"},x0={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};fR.exports={LOCAL_HARPERDB_OPERATIONS:ge,HDB_SUPPORT_ADDRESS:nR,HDB_SUPPORT_URL:oR,HDB_PRICING_URL:_H,SUPPORT_HELP_MSG:dH,LICENSE_HELP_MSG:aR,HDB_PROC_NAME:rR,HDB_PROC_DESCRIPTOR:dE,CLUSTERING_LEAF_PROC_DESCRIPTOR:uu,CLUSTERING_HUB_PROC_DESCRIPTOR:cu,SYSTEM_SCHEMA_NAME:DH,HASH_FOLDER_NAME:LH,HDB_HOME_DIR_NAME:MH,UPDATE_FILE_NAME:HH,LICENSE_KEY_DIR_NAME:vH,BOOT_PROPS_FILE_NAME:BH,JOB_TYPE_ENUM:E0,JOB_STATUS_ENUM:i0,SYSTEM_TABLE_NAMES:jH,SYSTEM_TABLE_HASH_ATTRIBUTES:e0,OPERATIONS_ENUM:K,VALID_S3_FILE_TYPES:o0,S3_BUCKET_AUTH_KEYS:a0,VALID_SQL_OPS_ENUM:c0,GEO_CONVERSION_ENUM:l0,HDB_SETTINGS_NAMES:lR,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:_0,SERVICE_ACTIONS_ENUM:u0,CLUSTER_MESSAGE_TYPE_ENUM:f0,CLUSTER_CONNECTION_DIRECTION_ENUM:h0,CLUSTER_EVENTS_DEFS_ENUM:p0,PERIOD_REGEX:TH,DOUBLE_PERIOD_REGEX:RH,UNICODE_PERIOD:gH,FORWARD_SLASH_REGEX:AH,UNICODE_FORWARD_SLASH:OH,ESCAPED_FORWARD_SLASH_REGEX:NH,ESCAPED_PERIOD_REGEX:bH,ESCAPED_DOUBLE_PERIOD_REGEX:yH,REG_KEY_FILE_NAME:s0,RESTART_TIMEOUT_MS:GH,HDB_FILE_PERMISSIONS:xH,DATABASES_DIR_NAME:$H,LEGACY_DATABASES_DIR_NAME:YH,TRANSACTIONS_DIR_NAME:KH,LIMIT_COUNT_NAME:WH,ID_ATTRIBUTE_STRING:QH,INSERT_MODULE_ENUM:XH,UPGRADE_JSON_FIELD_NAMES_ENUM:ZH,RESTART_CODE:FH,RESTART_CODE_NUM:qH,CLUSTER_OPERATIONS:Ko,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:r0,HDB_INTERNAL_SC_CHANNEL_PREFIX:tr,INTERNAL_SC_CHANNELS:t0,CLUSTERING_MESSAGE_TYPES:y0,HDB_FILE_SUFFIX:PH,BLOB_FOLDER_NAME:kH,HDB_TRASH_DIR:VH,ORIGINATOR_SET_VALUE:I0,LICENSE_VALUES:m0,RAM_ALLOCATION_ENUM:S0,TIME_STAMP_NAMES_ENUM:dR,TIME_STAMP_NAMES:O0,PERMS_UPDATE_RELEASE_TIMESTAMP:N0,SEARCH_NOT_FOUND_MESSAGE:EH,SEARCH_ATTRIBUTE_NOT_FOUND:fH,LICENSE_ROLE_DENIED_RESPONSE:hH,LICENSE_MAX_CONNS_REACHED:mH,BASIC_LICENSE_MAX_NON_CU_ROLES:iR,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:lH,VALUE_SEARCH_COMPARATORS:ER,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:b0,LICENSE_FILE_NAME:n0,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:T0,NEW_LINE:w0,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:pH,MOMENT_DAYS_TAG:IH,API_TURNOVER_SEC:wH,LOOPBACK:SH,CODE_EXTENSION:au,WILDCARD_SEARCH_VALUE:CH,NODE_ERROR_CODES:R0,JAVASCRIPT_EXTENSION:tR,PERMS_CRUD_ENUM:C0,UNAUTHORIZED_PERMISSION_NAME:D0,SEARCH_WILDCARDS:U0,FUNC_VAL:L0,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:M0,JWT_ENUM:P0,CLUSTERING_FLAG:A0,ITC_EVENT_TYPES:v0,CUSTOM_FUNCTION_PROC_NAME:sR,CUSTOM_FUNCTION_PROC_DESCRIPTOR:ou,SERVICES:B0,THREAD_TYPES:H0,MEM_SETTING_KEY:UH,HDB_RESTART_SCRIPT:zB,PROCESS_DESCRIPTORS:tH,SERVICE_SERVERS:oH,SERVICE_SERVERS_CWD:_E,PROCESS_DESCRIPTORS_VALIDATE:nH,LAUNCH_SERVICE_SCRIPTS:aH,LOG_LEVELS:sH,PROCESS_NAME_ENV_PROP:zH,LOG_NAMES:rH,PM2_PROCESS_STATUSES:F0,CONFIG_PARAM_MAP:_R,CONFIG_PARAMS:g,HDB_CONFIG_FILE:KB,HDB_DEFAULT_CONFIG_FILE:WB,ROLE_TYPES_ENUM:cH,BOOT_PROP_PARAMS:cR,INSTALL_PROMPTS:JH,HDB_ROOT_DIR_NAME:QB,CLUSTERING_PROCESSES:iH,FOREGROUND_PID_FILE:ZB,PACKAGE_ROOT:an,PRE_4_0_0_VERSION:q0,SCHEMAS_PARAM_CONFIG:d0,METADATA_PROPERTY:g0,AUTH_AUDIT_STATUS:G0,AUTH_AUDIT_TYPES:x0,HDB_PID_FILE:jB,DEFAULT_DATABASE_NAME:eH};eR()});var EE=m((pte,SR)=>{"use strict";var hR=require("minimist");SR.exports=k0;function k0(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=mR(process.env),s=mR(hR(process.argv))):(r=process.env,s=hR(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(k0,"assignCMDENVVariables");function mR(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(mR,"objKeysToLowerCase")});var x=m((Rte,RE)=>{"use strict";var qn=require("fs-extra"),{workerData:V0,threadId:$0}=require("worker_threads"),ws=require("path"),RR=require("yaml"),gR=require("properties-reader"),et=A(),pR=EE(),Y0=require("os"),{PACKAGE_ROOT:hE}=A(),{_assignPackageExport:K0}=require("../index"),Qo={};for(let e in console)Qo[e]||(Qo[e]=console[e]);var Mt={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},AR={STDOUT:"stdOut",STDERR:"stdErr"},W0=ws.join(hE,"logs"),Q0=ws.join(hE,"config/yaml/",et.HDB_DEFAULT_CONFIG_FILE),z0=1e4,ys,Is,Lt,lu,_u,zo,Pi,Wo;Wo===void 0&&OR();RE.exports={notify:yR,fatal:IR,error:Jo,warn:TE,info:du,debug:pE,trace:SE,setLogLevel:rF,log_level:Lt,loggerWithTag:J0,suppressLogging:X0,initLogSettings:OR,setupConsoleLogging:NR,logCustomLevel:eF,closeLogFile:mE,getLogFilePath:()=>zo,OUTPUTS:AR,AuthAuditLog:iF};K0("logger",RE.exports);function OR(e=!1){try{if(Wo===void 0||e){mE();let t=tF(),r=pR(["ROOTPATH"]);try{Wo=gR(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!qn.pathExistsSync(ws.join(r.ROOTPATH,et.HDB_CONFIG_FILE)))throw s}({level:Lt,config_log_path:_u,to_file:ys,to_stream:Is}=sF(r.ROOTPATH?ws.join(r.ROOTPATH,et.HDB_CONFIG_FILE):Wo.get("settings_path"))),lu=et.LOG_NAMES.HDB,zo=ws.join(_u,lu)}}catch(t){if(Wo=void 0,t.code===et.NODE_ERROR_CODES.ENOENT){let r=pR(Object.keys(et.CONFIG_PARAM_MAP),!0);for(let o in r){let c=et.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===et.CONFIG_PARAMS.LOGGING_LEVEL){Lt=u;continue}if(c===et.CONFIG_PARAMS.LOGGING_STDSTREAMS){Is=u;continue}c===et.CONFIG_PARAMS.LOGGING_FILE&&(ys=c)}let{default_level:s,default_to_file:n,default_to_stream:i}=nF();ys=ys===void 0?n:ys,ys=TR(ys),Is=Is===void 0?i:Is,Is=TR(Is),Lt=Lt===void 0?s:Lt,_u=W0,lu=et.LOG_NAMES.INSTALL,zo=ws.join(_u,lu);return}throw Jo("Error initializing log settings"),Jo(t),t}NR()}a(OR,"initLogSettings");var fE=!0;function NR(){Mi("error",Jo),Mi("warn",TE),Mi("log",du),Mi("info",du),Mi("debug",pE),Mi("trace",SE)}a(NR,"setupConsoleLogging");function Mi(e,t){console[e]=function(...r){if(fE&&t(...r),!/PM2 log:|App \[/.test(r[0]))return Qo[e](...r)}}a(Mi,"logConsole");function J0(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(yR),fatal:r(IR),error:r(Jo),warn:r(TE),info:r(du),debug:r(pE),trace:r(SE)};function r(s){return function(...n){return s(t,...n)}}}a(J0,"loggerWithTag");function X0(e){try{fE=!1,e()}finally{fE=!0}}a(X0,"suppressLogging");var Z0=V0?.name?.replace(/ /g,"-")||"main";function Cs(e,t){let r=new Date(Date.now()).toISOString(),s="",n=t.length,i=n-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||Z0+"/"+$0);c<n;c++){let l=t[c];l instanceof Error&&l.stack?s+=l.stack:typeof l=="object"?s+=JSON.stringify(l):s+=l,c<i&&(s+=" ")}return`${r} [${o.join("] [")}]: ${s}
|
|
3
|
+
`}a(Cs,"createLogRecord");function Xo(e){ys&&bR(e),Is&&process.stdout.write(e)}a(Xo,"logStdOut");function Eu(e){ys&&bR(e),Is&&process.stderr.write(e)}a(Eu,"logStdErr");function bR(e){j0(),Pi?qn.appendFileSync(Pi,e):Qo.log(e)}a(bR,"logToFile");function mE(){try{qn.closeSync(Pi)}catch{}Pi=null}a(mE,"closeLogFile");function j0(){if(!Pi){try{if(!zo)debugger;Pi=qn.openSync(zo,"a")}catch(e){Qo.error(e)}setTimeout(()=>{mE()},z0).unref()}}a(j0,"openLogFile");function du(...e){Mt[Lt]<=Mt.info&&Xo(Cs("info",e))}a(du,"info");function SE(...e){Mt[Lt]<=Mt.trace&&Xo(Cs("trace",e))}a(SE,"trace");function Jo(...e){Mt[Lt]<=Mt.error&&Eu(Cs("error",e))}a(Jo,"error");function pE(...e){Mt[Lt]<=Mt.debug&&Xo(Cs("debug",e))}a(pE,"debug");function yR(...e){Mt[Lt]<=Mt.notify&&Xo(Cs("notify",e))}a(yR,"notify");function IR(...e){Mt[Lt]<=Mt.fatal&&Eu(Cs("fatal",e))}a(IR,"fatal");function TE(...e){Mt[Lt]<=Mt.warn&&Eu(Cs("warn",e))}a(TE,"warn");function eF(e,t,...r){t===AR.STDERR?Eu(Cs(e,r)):Xo(Cs(e,r))}a(eF,"logCustomLevel");function tF(){let e;try{e=Y0.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ws.join(e,et.HDB_HOME_DIR_NAME,et.BOOT_PROPS_FILE_NAME);return qn.existsSync(t)||(t=ws.join(hE,"utility/hdb_boot_properties.file")),t}a(tF,"getPropsFilePath");function rF(e){Lt=e}a(rF,"setLogLevel");function TR(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(TR,"autoCastBoolean");function sF(e){try{if(e.includes("config/settings.js")){let o=gR(e);return{level:o.get(et.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ws.dirname(o.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(et.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=RR.parseDocument(qn.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===et.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(sF,"getLogConfig");function nF(){try{let e=RR.parseDocument(qn.readFileSync(Q0,"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(nF,"getDefaultConfig");function iF(e,t,r,s,n,i){this.username=e,this.status=t,this.type=r,this.originating_ip=s,this.request_method=n,this.path=i}a(iF,"AuthAuditLog")});var CR=m((Ate,wR)=>{"use strict";var oF=require("util"),aF=require("path"),cF=require("child_process"),uF=oF.promisify(cF.execFile),lF=1e3*1e3*10;wR.exports={findPs:_F};async function _F(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await uF("ps",["wwxo",`pid,${r}`],{maxBuffer:lF});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:aF.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(_F,"findPs")});var xe=m((Nte,DR)=>{"use strict";var dF="__dbis__",EF="__txns__",fF="__environment_name__",hF="__dbi_defintion__",mF={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"},SF=["__createdtime__","__updatedtime__"],pF="\uFFFF",UR={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},TF=Object.values(UR);DR.exports={AUDIT_STORE_NAME:EF,INTERNAL_DBIS_NAME:dF,DBI_DEFINITION_NAME:hF,SEARCH_TYPES:mF,TIMESTAMP_NAMES:SF,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:fF,TRANSACTIONS_DBI_NAMES_ENUM:UR,TRANSACTIONS_DBIS:TF,OVERFLOW_MARKER:pF}});var rr=m((bte,GR)=>{"use strict";var LR=A(),MR=xe(),PR={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},vR=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),BR={500:vR("There was an error processing your request."),400:"Invalid request"},RF=BR[PR.INTERNAL_SERVER_ERROR],gF={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.`},AF={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},OF={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"},NF={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${MR.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${MR.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"},bF={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${LR.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 ${LR.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"},HR={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"},yF={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' not found`,SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},IF={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},wF={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},CF={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},UF={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`},FR={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.`},qR={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},DF={FUNCTION_STATUS:"Error getting custom function status, check the log for more details",GET_FUNCTIONS:"Error getting custom functions, check the log for more details",GET_FUNCTION:"Error getting custom function, check the log for more details",SET_FUNCTION:"Error setting custom function, check the log for more details",NO_PROJECT:"Project does not exist. Create one using 'add_custom_function_project'",PROJECT_EXISTS:"Project already exists",VALIDATION_ERR:"Error validating request, check the log for more details",NO_FILE:"File does not exist",BAD_FILE_NAME:"File name can only contain alphanumeric, dash and underscore characters",BAD_PROJECT_NAME:"Project name can only contain alphanumeric, dash and underscores characters",BAD_PACKAGE:"Packaged project must be base64-encoded tar file of project directory",DROP_FUNCTION:"Error dropping custom function, check the log for more details",ADD_FUNCTION:"Error adding custom function project, check the log for more details",DROP_FUNCTION_PROJECT:"Error dropping custom function project, check the log for more details",BAD_FILE_PATH:"Filepath must be valid, and contain the name of the tarball you wish to write",NOT_ENABLED:"Custom functions is not enabled, to enable set fastifyRoutes enabled to true in hdb/harperdb-config.yaml file."},LF={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},MF={...HR,...OF,...gF,...yF,...IF,...wF,...CF,...UF,...bF,...FR,...qR,...DF,...LF,...AF};GR.exports={CHECK_LOGS_WRAPPER:vR,HDB_ERROR_MSGS:MF,DEFAULT_ERROR_MSGS:BR,DEFAULT_ERROR_RESP:RF,HTTP_STATUS_CODES:PR,LMDB_ERRORS_ENUM:NF,AUTHENTICATION_ERROR_MSGS:HR,VALIDATION_ERROR_MSGS:FR,ITC_ERRORS:qR}});var W=m((Ite,VR)=>{"use strict";var vi=rr(),PF=x(),vF=A(),fu=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,xR),this.statusCode=s||vi.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(vi.DEFAULT_ERROR_MSGS[s]?vi.DEFAULT_ERROR_MSGS[s]:vi.DEFAULT_ERROR_MSGS[vi.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&PF[n](i)}},gE=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},AE=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function xR(e,t,r,s=vF.LOG_LEVELS.ERROR,n=null,i=!1){if(kR(e))return e;let o=new fu(e,t,r,s,n);return i&&delete o.stack,o}a(xR,"handleHDBError");function kR(e){return e.__proto__.constructor.name===fu.name}a(kR,"isHDBError");VR.exports={isHDBError:kR,handleHDBError:xR,ClientError:gE,ServerError:AE,hdb_errors:vi}});var we=m((Cte,JR)=>{"use strict";var ra=A(),BF=V(),Pt=Q(),sa=require("path"),HF=require("minimist"),$R=require("fs-extra"),YR=require("lodash");Pt.initSync();var{CONFIG_PARAMS:cn,SCHEMAS_PARAM_CONFIG:Zo,SYSTEM_SCHEMA_NAME:hu}=ra,jo,ea,ta;function KR(){if(jo!==void 0)return jo;if(Pt.getHdbBasePath()!==void 0)return jo=Pt.get(cn.STORAGE_PATH)||sa.join(Pt.getHdbBasePath(),ra.DATABASES_DIR_NAME),jo}a(KR,"getBaseSchemaPath");function WR(){if(ea!==void 0)return ea;if(Pt.getHdbBasePath()!==void 0)return ea=zR(hu),ea}a(WR,"getSystemSchemaPath");function QR(){if(ta!==void 0)return ta;if(Pt.getHdbBasePath()!==void 0)return ta=Pt.get(ra.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||sa.join(Pt.getHdbBasePath(),ra.TRANSACTIONS_DIR_NAME),ta}a(QR,"getTransactionAuditStoreBasePath");function FF(e,t){let r=Pt.get(cn.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||sa.join(QR(),e.toString())}a(FF,"getTransactionAuditStorePath");function zR(e,t){e=e.toString(),t=t&&t.toString();let r=Pt.get(ra.CONFIG_PARAMS.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.path||r?.path||sa.join(KR(),e)}a(zR,"getSchemaPath");function qF(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,HF(process.argv));let s=r[cn.SCHEMAS.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!BF.isObject(s))throw o;i=s}for(let o of i){let c=o[hu];if(!c)continue;let u=Pt.get(cn.SCHEMAS);u=u??{};let l=c?.tables?.[t]?.[Zo.PATH];if(l)return YR.set(u,[hu,Zo.TABLES,t,Zo.PATH],l),Pt.setProperty(cn.SCHEMAS,u),l;let _=c?.[Zo.PATH];if(_)return YR.set(u,[hu,Zo.PATH],_),Pt.setProperty(cn.SCHEMAS,u),_}}let n=r[cn.STORAGE_PATH.toUpperCase()];if(n){if(!$R.pathExistsSync(n))throw new Error(n+" does not exist");let i=sa.join(n,e);return $R.mkdirsSync(i),Pt.setProperty(cn.STORAGE_PATH,n),i}return WR()}a(qF,"initSystemSchemaPaths");function GF(){jo=void 0,ea=void 0,ta=void 0}a(GF,"resetPaths");JR.exports={getBaseSchemaPath:KR,getSystemSchemaPath:WR,getTransactionAuditStorePath:FF,getTransactionAuditStoreBasePath:QR,getSchemaPath:zR,initSystemSchemaPaths:qF,resetPaths:GF}});var vt=m((Mte,tg)=>{"use strict";var xF=rr().LMDB_ERRORS_ENUM,Dte=require("lmdb"),kF=xe(),Lte=require("buffer").Buffer,{OVERFLOW_MARKER:XR,MAX_SEARCH_KEY_LENGTH:mu}=kF,ZR=["number","string","symbol","boolean","bigint"];function VF(e){if(e=e?.primaryStore||e,!e)throw new Error(xF.ENV_REQUIRED)}a(VF,"validateEnv");function $F(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($F,"stringifyData");function YF(e){return e instanceof Date?e.valueOf():e}a(YF,"convertKeyValueToWrite");function KF(e){if(e==null)return;if(ZR.includes(typeof e))return e.length>mu?[e.slice(0,mu)+XR]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];if(ZR.includes(typeof n))n.length>mu?t.push(n.slice(0,mu)+XR):t.push(n);else if(n instanceof Date)return t.push(n.getTime())}}else if(e instanceof Date)return[e.getTime()];return t}a(KF,"getIndexedValues");var Su=0,jR=0;function eg(){jR=Date.now()-performance.now()}a(eg,"adjustStartTime");eg();var WF=6e4;setInterval(eg,WF).unref();function QF(){let e=performance.now()+jR;return e>Su?(Su=e,e):(Su+=488e-6,Su)}a(QF,"getNextMonotonicTime");tg.exports={validateEnv:VF,stringifyData:$F,convertKeyValueToWrite:YF,getNextMonotonicTime:QF,getIndexedValues:KF}});var rg,Jr,OE,na=Se(()=>{rg=require("events"),Jr=class extends rg.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new OE;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},OE=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function ia(e){return e[ft]||(e[ft]=Object.create(null))}function Au(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u={get(){let l=this[ft];if(l&&c in l)return l[c];let _=this[ce]?.[c];if(_&&typeof _=="object"){let d=sg(_,o);if(d)return l||(l=this[ft]=Object.create(null)),l[c]=d}return _},set(l){ia(this)[c]=l},enumerable:!0,configurable:!0};switch(u.get.isAttribute=!0,o.type){case"String":u.set=function(l){if(typeof l!="string")throw(0,pu.ClientError)(`${c} must be a string, attempt to assign ${l}`);ia(this)[c]=l};break;case"Int":u.set=function(l){if(typeof l!="number")throw(0,pu.ClientError)(`${c} must be a string, attempt to assign ${l}`);ia(this)[c]=l};break}s[c]=u,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,u)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[ft];return u?.[o]!==void 0?u[o]:this[ce]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new pu.ClientError("Can not add a property to a sealed table schema");ia(this)[o]=c}),i("deleteProperty",function(o){ia(this)[o]=void 0}),i("toJSON",function(){let o=this[ft],c;for(let l in o)c||(c=Object.assign({},this[ce])),c[l]=o[l];return Object.keys(this).length>0&&(c||(c=Object.assign({},this[ce])),Object.assign(c,this)),c||this[ce]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function sg(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){this[ce]=n}},Au(r,t)),new r(e)):new Tu(e);case Array:let s=new gu(e.length);s[ce]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=sg(o,t?.elements)),s[n]=o}return s}}function Ou(e){let t=e[ft],r;for(let n in t){r||(r=Object.assign({},e[ce]));let i=t[n];i&&typeof i=="object"&&(i=Ou(i)),r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[ce])),Object.assign(r,e)),r||e[ce]}function oa(e){let t;if(e[ce]&&e.constructor===Array&&!Object.isFrozen(e)){t=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=oa(i);o!==i&&t===e&&(t=e.slice(0)),i=o}t[s]=i}return Object.freeze(t)}let r=e[ft];for(let s in r){t||(t=Object.assign({},e[ce]));let n=r[s];n&&typeof n=="object"&&(n=oa(n)),t[s]=n}return t?Object.freeze(t):e[ce]||Object.freeze(e)}function Ru(e){let t=e[ce];if(!t)return!0;if(e.constructor===Array){if(e[Gn]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[ce]===n){if(Ru(i))return!0}else return!0}}else{let r=e[ft];for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[ce]===i){if(Ru(n))return!0}else return!0}else return!0}}return!1}var pu,ft,Tu,Gn,gu,Nu=Se(()=>{Xr();pu=C(W()),ft=Symbol("own-data");a(ia,"getChanges");a(Au,"assignTrackedAccessors");a(sg,"trackObject");Tu=class{static{a(this,"GenericTrackedObject")}constructor(t){this[ce]=t}};Au(Tu,{});a(Ou,"collapseData");a(oa,"deepFreeze");a(Ru,"hasChanges");Gn=Symbol.for("has-array-changes"),gu=class extends Array{static{a(this,"TrackedArray")}[Gn];constructor(t){super(t)}splice(...t){return this[Gn]=!0,super.splice(...t)}push(...t){return this[Gn]=!0,super.push(...t)}pop(){return this[Gn]=!0,super.pop()}unshift(...t){return this[Gn]=!0,super.unshift(...t)}shift(){return this[Gn]=!0,super.shift()}};gu.prototype.constructor=Array});function Ye(e,t){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let r=e.transaction=new NE;e.timestamp&&(r.timestamp=e.timestamp),r[Ae]=e,e.resourceCache=[];let s;try{if(s=t(r),s?.then)return s.then(n,i)}catch(o){i(o)}return n(s);function n(o){let c=r.commit();return c.then?c.then(()=>(e.transaction=null,o)):(e.transaction=null,o)}function i(o){throw r.abort(),e.transaction=null,o}}var ng,ig,NE,xn=Se(()=>{ng=C(vt()),ig=require("../index");Xr();a(Ye,"transaction");(0,ig._assignPackageExport)("transaction",Ye);Ye.commit=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ye.abort=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()};NE=class extends Array{static{a(this,"TransactionSet")}commit(t=!0){let r=[],s=this.length;for(let n=0;n<s;n++)this[n].validate?.();this.timestamp||(this.timestamp=(0,ng.getNextMonotonicTime)());for(let n=0;n<s;n++){let o=this[n].commit(this.timestamp,t);o?.then&&r.push(o)}return r.length>0?Promise.all(r).then(()=>(this.splice(0,s),this.commit(t))):this.length>s?(this.splice(0,s),this.commit(t)):(this.length=0,{txnTime:this.timestamp})}abort(){for(let t of this)t.abort?.()}doneReading(){for(let t of this)t.doneReading?.()}}});function IE(e,t,r,s,n){let i=e[0]??e.attribute,o,c,u,l,_=e[1]??e.value;_ instanceof Date&&(_=_.getTime());let d=e.comparator,E;switch(JF[d]||d){case"lt":o=!0,c=_;break;case"le":o=!0,c=_,u=!0;break;case"gt":o=_,l=!0;break;case"ge":o=_;break;case"prefix":o=_,c=_.slice(0),c[c.length-1]=jr.MAXIMUM_KEY;break;case"starts_with":o=_.toString(),c=_+String.fromCharCode(65535);break;case"between":o=_[0],o instanceof Date&&(o=o.getTime()),c=_[1],c instanceof Date&&(c=c.getTime()),u=!0;break;case lt.SEARCH_TYPES.EQUALS:case void 0:o=_,c=_,u=!0;break;case"ne":case"contains":case"ends_with":E=!0;break}if(r){let p=o;o=c,c=p,p=!l,l=!u,u=p}let f=i===s.primaryKey||i==null,h=f?s.primaryStore:s.indices[i];if(!h||h.isIndexing||E){if(!n)throw new bE.ClientError(`"${i}" is not indexed${h?.isIndexing?" yet":""}, can not search for this attribute`,404);let p=wE(e);if(!p)throw new bE.ClientError(`Unknown search operator ${e.comparator}`);return s.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:R,value:O})=>new Promise(k=>setImmediate(()=>k(p(O)?R:ag.SKIP))))}let T={start:o,end:c,inclusiveEnd:u,exclusiveStart:l,values:!f,transaction:t,reverse:r};return f?h.getRange(T):h.getRange(T).map(({value:p})=>p)}function wE(e){let t=e.comparator,r=e[0]??e.attribute,s=e[1]??e.value;switch(s instanceof Date&&(s=s.getTime()),t){case lt.SEARCH_TYPES.EQUALS:case void 0:return Zr(r,n=>n===s);case lt.SEARCH_TYPES.CONTAINS:return Zr(r,n=>n?.toString().includes(s));case lt.SEARCH_TYPES.ENDS_WITH:case lt.SEARCH_TYPES._ENDS_WITH:return Zr(r,n=>n?.toString().endsWith(s));case lt.SEARCH_TYPES.STARTS_WITH:case lt.SEARCH_TYPES._STARTS_WITH:return Zr(r,n=>typeof n=="string"&&n.startsWith(s));case lt.SEARCH_TYPES.BETWEEN:return s[0]instanceof Date&&(s[0]=s[0].getTime()),s[1]instanceof Date&&(s[1]=s[1].getTime()),Zr(r,n=>(0,jr.compareKeys)(n,s[0])>=0&&(0,jr.compareKeys)(n,s[1])<=0);case"gt":case lt.SEARCH_TYPES.GREATER_THAN:case lt.SEARCH_TYPES._GREATER_THAN:return Zr(r,n=>(0,jr.compareKeys)(n,s)>0);case"ge":case lt.SEARCH_TYPES.GREATER_THAN_EQUAL:case lt.SEARCH_TYPES._GREATER_THAN_EQUAL:return Zr(r,n=>(0,jr.compareKeys)(n,s)>=0);case lt.SEARCH_TYPES.LESS_THAN:case"lt":case lt.SEARCH_TYPES._LESS_THAN:return Zr(r,n=>(0,jr.compareKeys)(n,s)<0);case"le":case lt.SEARCH_TYPES.LESS_THAN_EQUAL:case lt.SEARCH_TYPES._LESS_THAN_EQUAL:return Zr(r,n=>(0,jr.compareKeys)(n,s)<=0);case"ne":return Zr(r,n=>(0,jr.compareKeys)(n,s)!==0);default:return}}function Zr(e,t){return r=>{let s=r[e];return typeof s!="object"||!s?t(s):Array.isArray(s)?s.some(t):s instanceof Date?t(s.getTime()):!1}}function bu(e){if(!e)return;let t=new yE,r,s,n,i,o;for(;r=og.exec(e);){i=og.lastIndex;let[,c,u]=r;switch(u){case")":switch(o){case"limit":if(c.indexOf(",")>-1){let[l,_]=c.split(",");t.offset=+l,t.limit=_-t.offset}else t.limit=+c;break;case"select":if(c[0]==="["){if(c[c.length-1]!=="]")throw new Error("Unmatched brackets");t.select=c.slice(1,-1).split(","),t.select.asArray=!0}else c.indexOf(",")>-1?t.select=(c.endsWith(",")?c.slice(0,-1):c).split(","):t.select=c;break;case"group-by":throw new Error("Group by is not implemented yet");case"sort":t.sort=c.split(",").map(l=>{switch(l[0]){case"-":return{attribute:l.slice(1),descending:!0};case"+":return{attribute:l.slice(1),descending:!1};default:return{attribute:l,descending:!1}}});break;default:throw new Error(`Unknown query function call ${o}`)}break;case"(":o=c;break;case"=":s?c.length<=2&&(n=c):(n="equals",s=decodeURIComponent(c));break;case"!=":case"<":case"<=":case">":case">=":n=zF[u],s=decodeURIComponent(c);break;case"=*":n="ends_with",s=decodeURIComponent(c);break;case"*":case"*&":t.conditions.push({comparator:n==="ends_with"?"contains":"starts_with",attribute:s,value:decodeURIComponent(c)}),s=null;break;case"":case void 0:case"&":case"|":if(!s)throw new Error(`Unable to parse query, no part before ${u} at ${i} in ${e}`);t.conditions.push({comparator:n,attribute:s,value:decodeURIComponent(c)}),s=void 0;break;default:throw new Error(`Unknown operator ${u} in query ${e}`)}}if(i!==e.length)throw new Error(`Unable to parse query, unexpected end in ${e}`);return t}var bE,lt,jr,ag,og,zF,JF,yE,yu=Se(()=>{bE=C(W()),lt=C(xe()),jr=require("ordered-binary"),ag=require("lmdb"),og=/([^?&|=<>!()*]+)([&|=<>!()*]*)/g,zF={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne"};a(IE,"idsForCondition");JF={greater_than:"gt",greater_than_equal:"ge",less_than:"lt",less_than_equal:"le",not_equal:"ne",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(wE,"filterByType");a(Zr,"attributeComparator");a(bu,"parseQuery");yE=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}}});var DE={};je(DE,{CONTEXT:()=>Ae,ID_PROPERTY:()=>ae,IS_COLLECTION:()=>Us,RECORD_PROPERTY:()=>ce,Resource:()=>ht,SAVE_UPDATES_PROPERTY:()=>Eg,snake_case:()=>ZF});function ZF(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function cg(e,t){if(e=e.slice(1),e.indexOf("/")===-1)return e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e));let r=e.split("/"),s=new UE(r.length);for(let n=0;n<r.length;n++)s[n]=t.coerceId(decodeURIComponent(r[n]));return s}function pr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,o){let c,u,l;if(r?o?(l=i,o=o[Ae]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Ae]||i):l=i:(l=n,c=l[ae]??l[this.primaryKey]??null):i?o=i[Ae]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(o=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[];for(let E of n){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let h=this.parseQuery(c.slice(E+1));u?u=Object.assign(h,u):u=h,c=c.slice(0,E)}let f=this.parsePath(c,o,u);f?.query?(u=f.query,c=f.id):c=f}c===void 0&&(c=n.id??null)}else c=n??null;o||(o={});let _;if(u?.allowInvalidated?(_=Object.assign({},t),_.allowInvalidated=!0):_=t,o.transaction){let E=this.getResource(c,o,_);return E.then?E.then(d):d(E)}else return Ye(o,()=>{let E=this.getResource(c,o,_);return E.then?E.then(d):d(E)});function d(E){if(t.type==="read"&&(E[Eg]=!1),o.authorize){o.authorize=!1;let f=t.type==="read"?E.allowRead(o.user,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,o):E.allowUpdate(o.user,o):t.type==="create"?E.allowCreate(o.user,o):E.allowDelete(o.user,o);if(f?.then)return f.then(h=>{if(!h)throw new Iu(o.user);return typeof l?.then=="function"?l.then(T=>e(E,u,o,T)):e(E,u,o,l)});if(!f)throw new Iu(o.user)}return typeof l?.then=="function"?l.then(f=>e(E,u,o,f)):e(E,u,o,l)}a(d,"authorizeActionOnResource")}}function Tr(e,t){let r=new dg.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function CE(e){let t=e[ce];if(t){let r=e[ft];return s=>{let n;return e.hasOwnProperty(s)&&typeof(n=e[s])!="function"?n:r&&s in r?r[s]:t[s]}}else return r=>e[r]}function ug(e){if(typeof e=="string")return t=>CE(t)(e);if(typeof e=="object"){if(e.asArray)return r=>{let s=[],n=CE(r);for(let i of e)s.push(n(i));return s};let t=e.forceNulls;return r=>{let s={},n=CE(r);for(let i of e){let o=n(i);o===void 0&&t&&(o=null),s[i]=o}return s}}else throw new Error("Invalid select argument type "+typeof e)}var lg,_g,dg,Ae,ae,Us,Eg,ce,XF,ht,Iu,UE,Xr=Se(()=>{lg=require("crypto");na();_g=require("../index"),dg=C(W());Nu();xn();yu();Ae=Symbol.for("context"),ae=Symbol.for("primary-key"),Us=Symbol("is-collection"),Eg=Symbol("save-updates"),ce=Symbol("stored-record"),XF={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},ht=class{static{a(this,"Resource")}[Ae];[ae];static transactions;constructor(t,r){this[ae]=t;let s=r?.[Ae];this[Ae]=s!==void 0?s:r||null}updateModificationTime(t=Date.now()){t>this[LAST_MODIFICATION_PROPERTY]&&(this[LAST_MODIFICATION_PROPERTY]=t)}static get=pr(function(t,r,s,n){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null){let l=ug(u);return typeof c?.map=="function"?c.map(l):l(c)}return c}},{type:"read"});static put=pr(function(t,r,s,n){if(Array.isArray(n)&&t[Us]){let i=[],o=s.authorize;for(let c of n)o&&(s.authorize=!0),i.push(this.put(t,r,s,c));return i}return t.put?t.put(n,r):Tr(t,"put")},{hasContent:!0,type:"update"});static delete=pr(function(t,r,s,n){return t.delete?t.delete(r):Tr(t,"delete")},{hasContent:!1,type:"delete",allowInvalidated:!0});static getNewId(){return(0,lg.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),Ye(s,()=>{let i=new this(n,s),o=i.put?i.put(r):Tr(i,"put");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=pr(function(t,r,s,n){return t.invalidate?t.invalidate(r):Tr(t,"delete")},{hasContent:!1,type:"update",allowInvalidated:!0});static post=pr(function(t,r,s,n){return t[ae]!=null&&t.update(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=pr(function(t,r,s,n){return t.connect?t.connect(r):Tr(t,"connect")},{type:"read"});static subscribe=pr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Tr(t,"subscribe")},{type:"read"});static publish=pr(function(t,r,s,n){return t[ae]!=null&&t.update(),t.publish?t.publish(n,r):Tr(t,"publish")},{hasContent:!0,type:"create"});static search=pr(function(t,r,s,n){let i=t.search?t.search(s):Tr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null){let c=ug(o);return i.map(c)}return i},{type:"read"});static query=pr(function(t,r,s,n){return t.search?t.search(n,r):Tr(t,"search")},{hasContent:!0,type:"read"});static copy=pr(function(t,r,s,n){return t.copy?t.copy(s.headers?.destination,r):Tr(t,"copy")},{type:"create"});static move=pr(function(t,r,s,n){return t.move?t.move(s.headers?.destination,r):Tr(t,"move")},{type:"delete"});post(t){if(this[Us])return this.constructor.create(this[ae],t,this[Ae]);Tr(this,"post")}static isCollection(t){return t?.[Us]}static coerceId(t){return t}static parseQuery(t){return bu(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let i=t.slice(n+1);t=t.slice(0,n);let o=r?.headers&&XF[i];if(o)r.headers.accept=o;else if(s)s.property=i;else return{query:{property:i},id:cg(t,this)}}return cg(t,this)}static getResource(t,r,s){let n,i=r[Ae],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=t==null||Array.isArray(t)&&t[t.length-1]==null;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let l=u.asMap.get(t);if(n=l?.find(_=>_.constructor===c),n)return n;l||u.asMap.set(t,l=[]),l.push(n=new c(t,i))}else{if(n=u.find(l=>l[ae]===t&&l.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let l=new Map;for(let _ of u){let d=_[ae],E=l.get(d);E?E.push(_):l.set(d,[_])}i.resourceCache.length=0,i.resourceCache.asMap=l}}}else n=new c(t,i);return o&&(n[Us]=!0),n}connect(t){let r=new Jr;if(t?.subscribe!==!1){let s={listener:i=>{r.send(i)}},n=this.subscribe?.(s);r.on("close",()=>n?.end())}return r}update(t){throw new Error("Not implemented")}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[ae]}getContext(){return this[Ae]}};ht.prototype[Ae]=null;(0,_g._assignPackageExport)("Resource",ht);a(ZF,"snake_case");Iu=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(cg,"pathToId");UE=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(pr,"transactional");a(Tr,"missingMethod");a(CE,"selectFromObject");a(ug,"transformForSelect")});var wu={};je(wu,{server:()=>tt});var fg,tt,es=Se(()=>{fg=require("../index"),tt={};(0,fg._assignPackageExport)("server",tt)});var PE={};je(PE,{loadGQLSchema:()=>eq,start:()=>ME,startOnMainThread:()=>jF});function ME({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:l,StringValueNode:_}=await import("graphql"),d=o(new c(r.toString(),n)),E=new Map,f=[],h;for(let T of d.definitions)switch(T.kind){case u.OBJECT_TYPE_DEFINITION:let $=function(U){if(U.kind==="NonNullType"){let P=$(U.type);return P.nullable=!0,P}return U.kind==="ListType"?{type:"array",elements:$(U.type)}:{type:U.name?.value}};a($,"getProperty");let p=T.name.value,R=[],O={table:null,database:null,properties:R};E.set(p,O);for(let U of T.directives){if(U.name.value==="table"){for(let b of U.arguments)O[b.name.value]=b.value.value;O.schema&&(O.database=O.schema),O.table||(O.table=p),O.audit&&(O.audit=O.audit!=="false"),O.attributes=O.properties,f.push(O)}if(U.name.value==="sealed"&&(O.sealed=!0),U.name.value==="export"){O.export=!0;for(let b of U.arguments)b.name.value==="name"&&(O.export={name:b.value.value})}}let k=!1;for(let U of T.fields){let b=$(U.type);b.name=U.name.value,R.push(b);for(let P of U.directives)if(P.name.value==="primaryKey")k?console.warn("Can not define two attributes as a primary key"):(b.isPrimaryKey=!0,k=!0);else if(P.name.value==="indexed")b.indexed=!0;else if(P.name.value==="createdTime")b.assignCreatedTime=!0;else if(P.name.value==="updatedTime")b.assignUpdatedTime=!0;else if(P.name.value==="expiresAt")b.expiresAt=!0;else if(P.name.value==="allow"){let z=b.authorizedRoles=[];for(let F of P.arguments)F.name.value==="role"&&z.push(F.value.value)}}O.typeName=p,p==="Query"&&(h=O)}for(let[T,p]of E)for(let R of p.properties){let O=E.get(R.type);O&&(R.properties=O.properties)}for(let T of f)T.tableClass=e(T),T.export&&i.set((0,LE.dirname)(s)+"/"+(T.export.name||T.typeName),T.tableClass);if(h)for(let T of h.properties){let p=E.get(T.type);if(!p)throw new Error(`${T.type} was not found as a Query export`);i.set((0,LE.dirname)(s)+"/"+T.name,p.tableClass)}}}var LE,jF,eq,hg=Se(()=>{LE=require("path");de();a(ME,"start");jF=ME,eq=ME({ensureTable:rt}).handleFile});async function Cu(e){return tq?(aa||(aa=rq(nq)),(await(await aa).import(e)).namespace):import(e)}async function rq(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),aa=new Compartment({console,Math,Date,fetch:sq,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,Sg.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:ht,tables:sr,databases:Pe})}};let s=await(0,mg.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),aa}function sq(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function nq(){return{Resource:ht,tables:sr}}var mg,Sg,tq,aa,vE=Se(()=>{Xr();de();mg=require("fs/promises"),Sg=require("path"),tq=!1;a(Cu,"secureImport");a(rq,"getCompartment");a(sq,"secureOnlyFetch");a(nq,"getGlobalVars")});var HE={};je(HE,{handleFile:()=>iq});async function iq(e,t,r,s){let n=new Map,i=(0,pg.pathToFileURL)(r).toString(),o=await Cu(i);u(o.default)&&s.set((0,BE.dirname)(t),o.default),c(o,(0,BE.dirname)(t));function c(l,_){for(let d in l){let E=l[d];u(E)?s.set(_+"/"+d,E):typeof E=="object"&&c(E,_+"/"+d)}}a(c,"recurseForResources");function u(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return a(u,"isResource"),n}var pg,BE,Tg=Se(()=>{pg=require("url");vE();BE=require("path");a(iq,"handleFile")});var qE={};je(qE,{start:()=>oq});function oq({resources:e}){e.set("login",FE),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var FE,Rg=Se(()=>{Xr();a(oq,"start");FE=class extends ht{static{a(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:o}=r;return{data:await s.login(n,i)}}}});var xE=m((are,Og)=>{"use strict";var{Readable:aq}=require("stream"),cq=1e4;Og.exports={streamAsJSON(e){return new GE({value:e})}};var GE=class extends aq{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0)}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator](),o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){yield"]";return}else n?n=!1:yield",",yield*this.serialize(o.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),gg)}catch(n){yield gg(n)}else yield JSON.stringify(t)}else yield JSON.stringify(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Ag(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>cq?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return Ag(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}};function gg(e){return console.error(e),JSON.stringify(e.toString())}a(gg,"handleError");function Ag(e,t,r){return e&&e.then?r?e.then(t,r):e.then(t):t(e)}a(Ag,"when")});var Bg=m((lre,vg)=>{"use strict";var kE=require("recursive-iterator"),uq=require("alasql"),VE=require("clone"),Ng=V(),{handleHDBError:bg,hdb_errors:lq}=W(),{HDB_ERROR_MSGS:yg,HTTP_STATUS_CODES:Ig}=lq,{getDatabases:_q}=(de(),re(Ne)),dq=["DISTINCT_ARRAY"],wg=Symbol("validateTables"),$E=Symbol("validateTable"),ure=Symbol("getAllColumns"),Cg=Symbol("validateAllColumns"),Uu=Symbol("findColumn"),Ug=Symbol("validateOrderBy"),ca=Symbol("validateSegment"),YE=Symbol("validateColumn"),Dg=Symbol("setColumnsForTable"),Lg=Symbol("checkColumnsForAsterisk"),Mg=Symbol("validateGroupBy"),Pg=Symbol("hasColumns"),KE=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[wg](),this[Lg](),this[Cg]()}[wg](){if(this[Pg]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[$E](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[$E](t.table)})}}[Pg](){let t=!1,r=new kE(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[$E](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=_q();if(!r[t.databaseid])throw bg(new Error,yg.SCHEMA_NOT_FOUND(t.databaseid),Ig.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw bg(new Error,yg.TABLE_NOT_FOUND(t.databaseid,t.tableid),Ig.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=VE(n);i.table=VE(t),this.attributes.push(i)})}[Uu](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)}[Lg](){let t=new kE(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[Dg](r.tableid)}[Dg](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new uq.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Cg](){this[ca](this.statement.columns,!1),this[ca](this.statement.joins,!1),this[ca](this.statement.where,!1),this[Mg](this.statement.group,!1),this[ca](this.statement.order,!0)}[ca](t,r){if(!t)return;let s=new kE(t),n=[];for(let{node:i,path:o}of s)!Ng.isEmpty(i)&&!Ng.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Ug](i):n.push(this[YE](i)));return n}[Mg](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&dq.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=VE(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Uu](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[Uu](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`}[Ug](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[YE](t)}[YE](t){let r=this[Uu](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]}};vg.exports=KE});var Fg=m((dre,Hg)=>{"use strict";var WE=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Hg.exports=WE});var Gg=m((fre,qg)=>{"use strict";var QE=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};qg.exports=QE});var Du=m((mre,xg)=>{"use strict";var JE=Q(),XE=A();JE.initSync();var Eq=JE.get(XE.CONFIG_PARAMS.STORAGE_COMPRESSION),fq=JE.get(XE.CONFIG_PARAMS.STORAGE_CACHING)!==!1,hq=XE.UPDATES_PROPERTY,zE=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=Eq&&r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=fq&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.alwaysLazyProperty=s=>s===hq)}};xg.exports=zE});var Mu=m((pre,Vg)=>{"use strict";var Bi=Q(),ua=A();Bi.initSync();var mq=Bi.get(ua.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Bi.get(ua.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Bi.get(ua.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",kg=Bi.get(ua.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),Sq=Bi.get(ua.CONFIG_PARAMS.STORAGE_NOREADAHEAD),Lu=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=mq,this.noFSAccess=!0,kg!==void 0&&(this.overlappingSync=kg),this.noReadAhead=Sq}};Vg.exports=Lu;Lu.MAX_DBS=1e4});var ye=m((Rre,jg)=>{"use strict";var jE=require("lmdb"),Pr=require("fs-extra"),nr=require("path"),Pu=vt(),Kg=x(),Bt=rr().LMDB_ERRORS_ENUM,vu=Gg(),ef=Du(),Wg=Mu(),un=xe(),$g=A(),{table:pq,resetDatabases:Tq}=(de(),re(Ne)),Yg=Q(),vr=un.INTERNAL_DBIS_NAME,Qg=un.DBI_DEFINITION_NAME,Rq="data.mdb",gq="lock.mdb",la=".mdb",Aq="-lock",ZE=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=Rr(t,r),this.key_type=this.dbi[un.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[un.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new jE.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function Bu(e,t){if(e===void 0)throw new Error(Bt.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Bt.ENV_NAME_REQUIRED)}a(Bu,"pathEnvNameValidation");async function tf(e,t,r=!0){try{await Pr.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Bt.INVALID_BASE_PATH):s}try{let s=nr.join(e,t+la);return await Pr.access(s,Pr.constants.R_OK|Pr.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Pr.access(nr.join(e,t,Rq),Pr.constants.R_OK|Pr.constants.F_OK),nr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Bt.INVALID_ENVIRONMENT)}else throw new Error(Bt.INVALID_ENVIRONMENT);throw s}}a(tf,"validateEnvironmentPath");function Hu(e,t){if(Pu.validateEnv(e),t===void 0)throw new Error(Bt.DBI_NAME_REQUIRED)}a(Hu,"validateEnvDBIName");async function Oq(e,t,r=!1,s=!1){Bu(e,t);let n=nr.basename(e);t=t.toString();let i=Yg.get($g.CONFIG_PARAMS.SCHEMAS);i||Yg.setProperty($g.CONFIG_PARAMS.SCHEMAS,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await tf(e,t,s),zg(e,t,r)}catch(o){if(o.message===Bt.INVALID_ENVIRONMENT){let c=nr.join(e,t);await Pr.mkdirp(s?c:e);let u=new Wg(s?c:c+la,!1),l=jE.open(u);l.dbis=Object.create(null);let _=new ef(!1);l.openDB(vr,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=rf(e,t,r);return l[un.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=l,l}throw o}}a(Oq,"createEnvironment");async function Nq(e,t,r,s=!0){Bu(e,t),t=t.toString();let n=nr.join(e,t);return pq({table:t,database:nr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(Nq,"copyEnvironment");async function zg(e,t,r=!1){Bu(e,t),t=t.toString();let s=rf(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 tf(e,t),i=nr.join(e,t+la),o=n!=i,c=new Wg(n,o),u=jE.open(c);u.dbis=Object.create(null);let l=Xg(u);for(let _=0;_<l.length;_++)Rr(u,l[_]);return u[un.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(zg,"openEnvironment");async function bq(e,t,r=!1){Bu(e,t),t=t.toString();let s=nr.join(e,t+la),n=await tf(e,t);if(global.lmdb_map!==void 0){let i=rf(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Jg(o),delete global.lmdb_map[i]}}await Pr.remove(n),await Pr.remove(n===s?n+Aq:nr.join(nr.dirname(n),gq))}a(bq,"deleteEnvironment");async function Jg(e){Pu.validateEnv(e);let t=e[un.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Jg,"closeEnvironment");function rf(e,t,r=!1){let n=`${nr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(rf,"getCachedEnvironmentName");function yq(e){Pu.validateEnv(e);let t=Object.create(null),r=Rr(e,vr);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==vr)try{t[s]=Object.assign(new vu,n)}catch{Kg.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(yq,"listDBIDefinitions");function Xg(e){Pu.validateEnv(e);let t=[],r=Rr(e,vr);for(let{key:s}of r.getRange({start:!1}))s!==vr&&t.push(s);return t}a(Xg,"listDBIs");function Iq(e,t){let s=Rr(e,vr).getEntry(t),n=new vu;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Kg.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(Iq,"getDBIDefinition");function Zg(e,t,r,s=!r){if(Hu(e,t),t=t.toString(),t===vr)throw new Error(Bt.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Rr(e,t)}catch(n){if(n.message===Bt.DBI_DOES_NOT_EXIST){let i=new ef(r,s===!0),o=e.openDB(t,i),c=new vu(r===!0,s);return o[Qg]=c,Rr(e,vr).putSync(t,c),e.dbis[t]=o,o}throw n}}a(Zg,"createDBI");function Rr(e,t){if(Hu(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==vr?r=Iq(e,t):r=new vu,r===void 0)throw new Error(Bt.DBI_DOES_NOT_EXIST);let s;try{let n=new ef(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(Bt.DBI_DOES_NOT_EXIST):n}return s[Qg]=r,e.dbis[t]=s,s}a(Rr,"openDBI");function wq(e,t){Hu(e,t),t=t.toString();let r=Rr(e,t),s=r.getStats();return r[un.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(wq,"statDBI");async function Cq(e,t){try{let r=nr.join(e,t+la);return(await Pr.stat(r)).size}catch{throw new Error(Bt.INVALID_ENVIRONMENT)}}a(Cq,"environmentDataSize");function Uq(e,t){if(Hu(e,t),t=t.toString(),t===vr)throw new Error(Bt.CANNOT_DROP_INTERNAL_DBIS_NAME);Rr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Rr(e,vr).removeSync(t)}a(Uq,"dropDBI");function Dq(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{Rr(e,i)}catch(o){if(o.message===Bt.DBI_DOES_NOT_EXIST)Zg(e,i,i!==t,i===t),s=!0;else throw o}}s&&Tq()}a(Dq,"initializeDBIs");jg.exports={openDBI:Rr,openEnvironment:zg,createEnvironment:Oq,listDBIs:Xg,listDBIDefinitions:yq,createDBI:Zg,dropDBI:Uq,statDBI:wq,deleteEnvironment:bq,initializeDBIs:Dq,TransactionCursor:ZE,environmentDataSize:Cq,copyEnvironment:Nq,closeEnvironment:Jg}});var tA=m((Are,eA)=>{"use strict";var sf=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};eA.exports=sf});var sA=m((Nre,rA)=>{"use strict";var nf=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};rA.exports=nf});var iA=m((yre,nA)=>{"use strict";var of=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};nA.exports=of});var Hi=m((Dre,cA)=>{"use strict";var Lq=ye(),Mq=tA(),Pq=sA(),vq=iA(),ts=vt(),_a=rr().LMDB_ERRORS_ENUM,Bq=xe(),Ds=A(),Hq=V(),Fq=require("uuid"),wre=require("lmdb"),{handleHDBError:qq,hdb_errors:Gq}=W(),{OVERFLOW_MARKER:Cre,MAX_SEARCH_KEY_LENGTH:Ure}=Bq,oA=Q();oA.initSync();var Fu=oA.get(Ds.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),af=Ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME,kn=Ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function xq(e,t,r,s,n=ts.getNextMonotonicTime()){_f(e,t,r,s),cf(e,t,r);let i=new Mq,o=[],c=[];for(let u=0;u<s.length;u++){let l=s[u];aA(l,!0,n);let _=kq(e,t,r,l),d=l[t];o.push(_),c.push(d)}return uf(o,c,s,i,n)}a(xq,"insertRecords");function kq(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let _=c([[{}]]);Array.isArray(_)&&(c=_[0][Ds.FUNC_VAL],s[o]=c)}let u=ts.getIndexedValues(c),l=e.dbis[o];if(u){Fu&&l.prefetch(u.map(_=>({key:_,value:n})),qu);for(let _=0,d=u.length;_<d;_++)l.put(u[_],n)}}Fu&&e.dbis[t].prefetch([n],qu),e.dbis[t].put(n,s,s[kn])})}a(kq,"insertRecord");function Vq(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(Vq,"removeSkippedRecords");function aA(e,t,r){let s=r>0;(s||!Number.isInteger(e[kn]))&&(e[kn]=r||(r=ts.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[af]))&&(e[af]=r||ts.getNextMonotonicTime()):delete e[af]}a(aA,"setTimestamps");function cf(e,t,r){r.indexOf(Ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),Lq.initializeDBIs(e,t,r)}a(cf,"initializeTransaction");async function $q(e,t,r,s,n=ts.getNextMonotonicTime()){_f(e,t,r,s),cf(e,t,r);let i=new Pq,o=[],c=[],u=[];for(let l=0;l<s.length;l++){let _=s[l],d=_[t],E;try{E=lf(e,t,_,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(l);continue}c.push(E),u.push(d)}return uf(c,u,s,i,n,o)}a($q,"updateRecords");async function Yq(e,t,r,s,n=ts.getNextMonotonicTime()){try{_f(e,t,r,s)}catch(u){throw qq(u,u.message,Gq.HTTP_STATUS_CODES.BAD_REQUEST)}cf(e,t,r);let i=new vq,o=[],c=[];for(let u=0;u<s.length;u++){let l=s[u],_;Hq.isEmpty(l[t])?(_=Fq.v4(),l[t]=_):_=l[t];let d=lf(e,t,l,_,i,!1,n);o.push(d),c.push(_)}return uf(o,c,s,i,n)}a(Yq,"upsertRecords");async function uf(e,t,r,s,n,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||ts.getNextMonotonicTime(),Vq(r,i),s}a(uf,"finalizeWrite");function lf(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),l=u?.value,_=l;if(!l){if(i)return!1;l={}}if(aA(r,!_,o),Number.isInteger(r[kn])&&l[kn]>r[kn])return!1;_&&n.original_records.push(l);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let T=r[h],p=e.dbis[h];if(p===void 0)continue;let R=l[h];if(typeof T=="function"){let k=T([[l]]);Array.isArray(k)&&(T=k[0][Ds.FUNC_VAL],r[h]=T)}if(T===R)continue;let O=ts.getIndexedValues(R);if(O){Fu&&p.prefetch(O.map(k=>({key:k,value:s})),qu);for(let k=0,$=O.length;k<$;k++)p.remove(O[k],s)}if(O=ts.getIndexedValues(T),O){Fu&&p.prefetch(O.map(k=>({key:k,value:s})),qu);for(let k=0,$=O.length;k<$;k++)p.put(O[k],s)}}let f=Object.assign({},l,r);c.put(s,f,f[kn])},"do_put");return u?d=c.ifVersion(s,u.version,E):d=c.ifNoExists(s,E),d.then(f=>f?!0:lf(e,t,r,s,n,i,o))}a(lf,"updateUpsertRecord");function Kq(e,t,r){if(ts.validateEnv(e),t===void 0)throw new Error(_a.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(_a.WRITE_ATTRIBUTES_REQUIRED):new Error(_a.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(Kq,"validateBasic");function _f(e,t,r,s){if(Kq(e,t,r),!Array.isArray(s))throw s===void 0?new Error(_a.RECORDS_REQUIRED):new Error(_a.RECORDS_MUST_BE_ARRAY)}a(_f,"validateWrite");function qu(){}a(qu,"noop");cA.exports={insertRecords:xq,updateRecords:$q,upsertRecords:Yq}});var Vn=m((Mre,Wq)=>{Wq.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var rs=m((Pre,_A)=>{"use strict";var lA=V(),uA=A(),Fi=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Ls=require("joi"),ln={schema_format:{pattern:Fi,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},Qq=Ls.alternatives(Ls.string().min(1).max(ln.schema_length.maximum).pattern(Fi).messages({"string.pattern.base":"{:#label} "+ln.schema_format.message}),Ls.number()).required(),zq=Ls.alternatives(Ls.string().min(1).max(ln.schema_length.maximum).pattern(Fi).messages({"string.pattern.base":"{:#label} "+ln.schema_format.message}),Ls.number()),Jq=Ls.alternatives(Ls.string().min(1).max(ln.schema_length.maximum).pattern(Fi).messages({"string.pattern.base":"{:#label} "+ln.schema_format.message}),Ls.number()).required();function Xq(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ln.schema_length.maximum?`'${e}' maximum of 250 characters`:Fi.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(Xq,"checkValidTable");function Zq(e,t){return lA.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(Zq,"validateSchemaExists");function jq(e,t){let r=t.state.ancestors[0].schema;return lA.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(jq,"validateTableExists");function eG(e,t){return e.toLowerCase()===uA.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${uA.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(eG,"validateSchemaName");_A.exports={common_validators:ln,schema_regex:Fi,hdb_schema_table:Qq,validateSchemaExists:Zq,validateTableExists:jq,validateSchemaName:eG,checkValidTable:Xq,hdb_database:zq,hdb_table:Jq}});var ve=m((Bre,dA)=>{"use strict";var Ht=require("validate.js");Ht.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||Ht.validators.type.checks[t](e)?null:` must be a '${t}' value`};Ht.validators.type.checks={Object:function(e){return Ht.isObject(e)&&!Ht.isArray(e)},Array:Ht.isArray,Integer:Ht.isInteger,Number:Ht.isNumber,String:Ht.isString,Date:Ht.isDate,Boolean:function(e){return typeof e=="boolean"}};Ht.validators.hasValidFileExt=function(e,t){return Ht.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};dA.exports={validateObject:tG,validateObjectAsync:rG,validateBySchema:sG};function tG(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=Ht(e,t,{format:"flat"});return r?new Error(r):null}a(tG,"validateObject");async function rG(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await Ht.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(rG,"validateObjectAsync");function sG(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(sG,"validateBySchema")});var Gu=m((Fre,EA)=>{var{common_validators:ss}=rs(),Ea=ve(),da="is required",Ke={database:{presence:!1,format:ss.schema_format,length:ss.schema_length},schema:{presence:!1,format:ss.schema_format,length:ss.schema_length},table:{presence:!0,format:ss.schema_format,length:ss.schema_length},attribute:{presence:!0,format:ss.schema_format,length:ss.schema_length},hash_attribute:{presence:!0,format:ss.schema_format,length:ss.schema_length}};function fa(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(fa,"makeAttributesStrings");function nG(e){return e=fa(e),Ke.table.presence=!1,Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,Ea.validateObject(e,Ke)}a(nG,"schema_object");function iG(e){return e=fa(e),Ke.table.presence={message:da},Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,Ea.validateObject(e,Ke)}a(iG,"table_object");function oG(e){return e=fa(e),Ke.table.presence={message:da},Ke.attribute.presence=!1,Ea.validateObject(e,Ke)}a(oG,"create_table_object");function aG(e){return e=fa(e),Ke.table.presence={message:da},Ke.attribute.presence={message:da},Ke.hash_attribute.presence=!1,Ea.validateObject(e,Ke)}a(aG,"attribute_object");function cG(e){return e=fa(e),Ke.table.presence={message:da},Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,Ea.validateObject(e,Ke)}a(cG,"describe_table");function uG(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(uG,"validateTableResidence");EA.exports={schema_object:nG,create_table_object:oG,table_object:iG,attribute_object:aG,describe_table:cG,validateTableResidence:uG}});var hA=m((Gre,fA)=>{"use strict";var lG=require("uuid"),df=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||lG.v4(),this.schema_table=`${this.schema}.${this.table}`}};fA.exports=df});var xu=m((kre,mA)=>{"use strict";var _G=hA(),Ef=class extends _G{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};mA.exports=Ef});var pA=m(($re,SA)=>{"use strict";SA.exports=EG;var dG="inserted";function EG(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===dG?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(EG,"returnObject")});var ku=m((Kre,OA)=>{"use strict";var fG=A(),ff=ye(),hG=Hi(),{getSystemSchemaPath:mG,getSchemaPath:SG}=we(),pG=Vn(),TG=Gu(),RG=xu(),gG=pA(),{handleHDBError:TA,hdb_errors:gA}=W(),RA=V(),{HTTP_STATUS_CODES:AG}=gA,hf=pG.hdb_attribute,AA=[];for(let e=0;e<hf.attributes.length;e++)AA.push(hf.attributes[e].attribute);var OG="inserted";OA.exports=NG;async function NG(e){let t=TG.attribute_object(e);if(t)throw TA(new Error,t.message,gA.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&RA.checkGlobalSchemaTable(e.schema,e.table);if(r)throw TA(new Error,r,AG.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=RA.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new RG(e.schema,e.table,e.attribute,e.id);try{let i=await ff.openEnvironment(SG(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);ff.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await ff.openEnvironment(mG(),fG.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await hG.insertRecords(o,hf.hash_attribute,AA,[n]);return gG(OG,c,{records:[n]},u)}catch(i){throw i}}a(NG,"lmdbCreateAttribute")});var Sf=m((Qre,bA)=>{var{hdb_table:bG,hdb_database:NA}=rs(),yG=ve(),mf=require("joi"),IG={undefined:"undefined",null:"null"},wG=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||IG[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"),CG=mf.object({database:NA,schema:NA,table:bG,records:mf.array().items(mf.object().custom(wG)).required()});bA.exports=function(e){return yG.validateBySchema(e,CG)}});var ha=m((Xre,IA)=>{"use strict";var Ms=V(),yA=x(),Jre=Sf(),{getDatabases:UG}=(de(),re(Ne)),{ClientError:$n}=W();IA.exports=DG;function DG(e){if(Ms.isEmpty(e))throw new $n("invalid update parameters defined.");if(Ms.isEmptyOrZeroLength(e.schema))throw new $n("invalid schema specified.");if(Ms.isEmptyOrZeroLength(e.table))throw new $n("invalid table specified.");if(!Array.isArray(e.records))throw new $n("records must be an array");let t=UG()[e.schema]?.[e.table];if(Ms.isEmpty(t))throw new $n(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Ms.isEmptyOrZeroLength(o[r]))throw yA.error("a valid hash attribute must be provided with update record:",o),new $n("a valid hash attribute must be provided with update record, check log for more info");if(!Ms.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw yA.error(`a valid hash value must be provided with ${e.operation} record:`,o),new $n(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Ms.isEmpty(o[r])&&o[r]!==""&&s.has(Ms.autoCast(o[r]))&&(o.skip=!0),s.add(Ms.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(DG,"insertUpdateValidate")});var ma=m((jre,wA)=>{"use strict";var LG=A().OPERATIONS_ENUM,pf=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=LG.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};wA.exports=pf});var Ra=m((rse,CA)=>{"use strict";var tse=ma(),Vu=A(),Rf=V(),Tf=x(),MG=require("uuid"),{handleHDBError:Sa,hdb_errors:PG}=W(),{HDB_ERROR_MSGS:pa,HTTP_STATUS_CODES:Ta}=PG;CA.exports=vG;function vG(e,t,r){for(let n=0;n<t.length;n++)BG(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];HG(i,r,e.operation)}}a(vG,"processRows");function BG(e){if(Buffer.byteLength(String(e))>Vu.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Sa(new Error,pa.ATTR_NAME_LENGTH_ERR(e),Ta.BAD_REQUEST,void 0,void 0,!0);if(Rf.isEmptyOrZeroLength(e)||Rf.isEmpty(e.trim()))throw Sa(new Error,pa.ATTR_NAME_NULLISH_ERR,Ta.BAD_REQUEST,void 0,void 0,!0)}a(BG,"validateAttribute");function HG(e,t,r){if(!e.hasOwnProperty(t)||Rf.isEmptyOrZeroLength(e[t])){if(r===Vu.OPERATIONS_ENUM.INSERT||r===Vu.OPERATIONS_ENUM.UPSERT){e[t]=MG.v4();return}throw Tf.error("Update transaction aborted due to record with no hash value:",e),Sa(new Error,pa.RECORD_MISSING_HASH_ERR,Ta.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>Vu.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Tf.error(e),Sa(new Error,pa.HASH_VAL_LENGTH_ERR,Ta.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Tf.error(e),Sa(new Error,pa.INVALID_FORWARD_SLASH_IN_HASH_ERR,Ta.BAD_REQUEST,void 0,void 0,!0)}a(HG,"validateHash")});var DA=m((nse,UA)=>{"use strict";var gf=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};UA.exports=gf});var PA=m((ose,MA)=>{"use strict";var Af=ye(),FG=x(),LA=rr().LMDB_ERRORS_ENUM;MA.exports=qG;async function qG(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 Af.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 Af.closeEnvironment(global.lmdb_map[s]),await Af.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){FG.error(t)}}a(qG,"cleanLMDBMap")});var Ps=m((cse,FA)=>{"use strict";var ga=require("crypto"),GG=Q(),{CONFIG_PARAMS:xG}=A(),BA="aes-256-cbc",kG=32,VG=16,Of=64,HA=32,$G=Of+HA,vA=new Map;FA.exports={encrypt:YG,decrypt:KG,createNatsTableStreamName:WG};function YG(e){let t=ga.randomBytes(kG),r=ga.randomBytes(VG),s=ga.createCipheriv(BA,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(YG,"encrypt");function KG(e){let t=e.substr(0,Of),r=e.substr(Of,HA),s=e.substr($G,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=ga.createDecipheriv(BA,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(KG,"decrypt");function WG(e,t){let r=GG.get(xG.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=vA.get(r);return s||(s=ga.createHash("md5").update(r).digest("hex"),vA.set(r,s)),s}a(WG,"createNatsTableStreamName")});var Yn=m((_se,GA)=>{"use strict";var lse=gr(),$u=x(),qA=Gu(),QG=Ps(),Yu=V(),{handleHDBError:Ku,hdb_errors:zG}=W(),{HDB_ERROR_MSGS:Wu,HTTP_STATUS_CODES:Nf}=zG,JG=Q();JG.initSync();var{getDatabases:bf}=(de(),re(Ne));GA.exports={describeAll:XG,describeTable:Qu,describeSchema:ZG};async function XG(e){try{let t=Yu.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=bf(),i={},o={},c=[];for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let _=n[l];for(let d in _)try{let E;if(t||s)E=await Qu({schema:l,table:d});else if(r&&r[l].describe&&r[l].tables[d].describe){let f=r[l].tables[d].attribute_permissions;E=await Qu({schema:l,table:d},f)}E&&c.push(E)}catch(E){$u.error(E)}}let u={};for(let l in c)t||s?(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?u[l]={}:o[l]&&(u[l]={});return u}catch(t){return $u.error("Got an error in describeAll"),$u.error(t),Ku(new Error,Wu.DESCRIBE_ALL_ERR)}}a(XG,"describeAll");async function Qu(e,t){Yu.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=qA.describe_table(e);if(i)throw i;let c=bf()[r];if(!c)throw Ku(new Error,Wu.SCHEMA_NOT_FOUND(e.schema),Nf.NOT_FOUND);let u=c[s];if(!u)throw Ku(new Error,Wu.TABLE_NOT_FOUND(e.schema,e.table),Nf.NOT_FOUND);let l=[];if(n){let d={};n.forEach(E=>{E.describe&&(d[E.attribute_name]=!0)}),u.attributes.forEach(E=>{d[E.name]&&l.push(E)})}else l=u.attributes;let _={schema:r,name:u.tableName,attributes:l,hash_attribute:u.attributes.find(d=>d.isPrimaryKey||d.is_hash_attribute)?.name};_.clustering_stream_name=QG.createNatsTableStreamName(_.schema,_.name);try{_.record_count=u.getRecordCount();let d=u.auditStore;if(d)for(let E of d.getKeys({reverse:!0,limit:1}))_.last_updated_record=E[0];if(!_.last_updated_record&&u.indices.__updatedtime__)for(let E of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))_.last_updated_record=E}catch(d){$u.warn(`unable to stat table dbi due to ${d}`)}return _}a(Qu,"descTable");async function ZG(e){Yu.transformReq(e);let t=qA.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=bf()[s];if(!i)throw Ku(new Error,Wu.SCHEMA_NOT_FOUND(e.schema),Nf.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),Yu.isEmpty(u)||u.describe){let l=await Qu({schema:e.schema,table:c},u?u.attribute_permissions:null);l&&(o[l.name]=l)}}return o}a(ZG,"describeSchema")});var _n=m((hse,YA)=>{var jG=Vn(),{callbackify:kA,promisify:ex}=require("util"),{getDatabases:VA}=(de(),re(Ne));YA.exports={setSchemaDataToGlobal:xA,getTableSchema:tx,getSystemSchema:rx,setSchemaDataToGlobalAsync:ex(xA)};var $A=Yn(),Ese=kA($A.describeAll),fse=kA($A.describeTable);function xA(e){global.hdb_schema=VA(),e&&e()}a(xA,"setSchemaDataToGlobal");function tx(e,t,r){let s=VA()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}a(tx,"getTableSchema");function rx(){return jG}a(rx,"getSystemSchema")});var Ar=m((Sse,zA)=>{"use strict";var Ju=Sf(),mt=V(),sx=require("util"),Xu=Br(),nx=_n(),KA=x(),{handleHDBError:Kn,hdb_errors:ix}=W(),{HTTP_STATUS_CODES:Wn}=ix,ox=sx.promisify(nx.getTableSchema),ax="updated",WA="inserted",QA="upserted";zA.exports={insert:ux,update:lx,upsert:_x,validation:cx,flush:dx};async function cx(e){if(mt.isEmpty(e))throw new Error("invalid update parameters defined.");if(mt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(mt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await ox(e.schema,e.table),r=Ju(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&&mt.isEmptyOrZeroLength(c[s]))throw KA.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(!mt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw KA.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!mt.isEmpty(c[s])&&c[s]!==""&&n.has(mt.autoCast(c[s]))&&(c.skip=!0),n.add(mt.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(cx,"validation");async function ux(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=Ju(e);if(t)throw Kn(new Error,t.message,Wn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Kn(new Error,r,Wn.BAD_REQUEST);let s=await Xu.createRecords(e);return zu(WA,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(ux,"insertData");async function lx(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=Ju(e);if(t)throw Kn(new Error,t.message,Wn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Kn(new Error,r,Wn.BAD_REQUEST);let s=await Xu.updateRecords(e);return mt.isEmpty(s.existing_rows)?zu(ax,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):zu(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(lx,"updateData");async function _x(e){if(e.operation!=="upsert")throw Kn(new Error,"invalid operation, must be upsert",Wn.INTERNAL_SERVER_ERROR);let t=Ju(e);if(t)throw Kn(new Error,t.message,Wn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Kn(new Error,r,Wn.BAD_REQUEST);let s=await Xu.upsertRecords(e);return zu(QA,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(_x,"upsertData");function zu(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===WA?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===QA?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(zu,"returnObject");function dx(e){return mt.transformReq(e),Xu.flush(e.schema,e.table)}a(dx,"flush")});var If=m((Tse,ZA)=>{var Ex=ve(),yf=require("joi"),{hdb_table:fx,hdb_database:JA}=rs(),XA={schema:JA,database:JA,table:fx},hx={date:yf.date().iso().required()},mx={timestamp:yf.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};ZA.exports=function(e,t){let r=t==="timestamp"?{...XA,...mx}:{...XA,...hx},s=yf.object(r);return Ex.validateBySchema(e,s)}});var tO=m((Rse,eO)=>{var Sx=ve(),wf=require("joi"),{hdb_table:px,hdb_database:jA}=rs(),Tx=wf.object({schema:jA,database:jA,table:px,hash_values:wf.array().required(),ids:wf.array()});eO.exports=function(e){return Sx.validateBySchema(e,Tx)}});var sO=m((gse,rO)=>{"use strict";var Cf=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},Uf=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}},Df=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};rO.exports={InsertObject:Cf,NoSQLSeachObject:Uf,DeleteResponseObject:Df}});var Jn=m((Ose,cO)=>{"use strict";var iO=If(),Rx=tO(),Qn=V(),nO=require("moment"),oO=x(),{promisify:gx,callbackify:Ax}=require("util"),zn=A(),Ox=_n(),Lf=gx(Ox.getTableSchema),Mf=Br(),{DeleteResponseObject:Nx}=sO(),{handleHDBError:dn,hdb_errors:bx}=W(),{HDB_ERROR_MSGS:Zu,HTTP_STATUS_CODES:En}=bx,yx="records successfully deleted",Ix=Ax(aO);cO.exports={delete:Ix,deleteRecord:aO,deleteFilesBefore:wx,deleteAuditLogsBefore:Cx};async function wx(e){let t=iO(e,"date");if(t)throw dn(t,t.message,En.BAD_REQUEST,void 0,void 0,!0);if(Qn.transformReq(e),!nO(e.date,nO.ISO_8601).isValid())throw dn(new Error,Zu.INVALID_DATE,En.BAD_REQUEST,zn.LOG_LEVELS.ERROR,Zu.INVALID_DATE,!0);let s=Qn.checkSchemaTableExist(e.schema,e.table);if(s)throw dn(new Error,s,En.NOT_FOUND,zn.LOG_LEVELS.ERROR,s,!0);let n=await Mf.deleteRecordsBefore(e);if(await Lf(e.schema,e.table),oO.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(wx,"deleteFilesBefore");async function Cx(e){let t=iO(e,"timestamp");if(t)throw dn(t,t.message,En.BAD_REQUEST,void 0,void 0,!0);if(Qn.transformReq(e),isNaN(e.timestamp))throw dn(new Error,Zu.INVALID_VALUE("Timestamp"),En.BAD_REQUEST,zn.LOG_LEVELS.ERROR,Zu.INVALID_VALUE("Timestamp"),!0);let r=Qn.checkSchemaTableExist(e.schema,e.table);if(r)throw dn(new Error,r,En.NOT_FOUND,zn.LOG_LEVELS.ERROR,r,!0);let s=await Mf.deleteAuditLogsBefore(e);return await Lf(e.schema,e.table),oO.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(Cx,"deleteAuditLogsBefore");async function aO(e){e.ids&&(e.hash_values=e.ids);let t=Rx(e);if(t)throw dn(t,t.message,En.BAD_REQUEST,void 0,void 0,!0);Qn.transformReq(e);let r=Qn.checkSchemaTableExist(e.schema,e.table);if(r)throw dn(new Error,r,En.NOT_FOUND,zn.LOG_LEVELS.ERROR,r,!0);try{await Lf(e.schema,e.table);let s=await Mf.deleteRecords(e);return Qn.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${yx}`),s}catch(s){if(s.message===zn.SEARCH_NOT_FOUND_MESSAGE){let n=new Nx;return n.message=zn.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(aO,"deleteRecord")});var ju=m((bse,_O)=>{var Ux=require("crypto"),uO=9;function Dx(e){let t=Mx(uO),r=lO(e+t);return t+r}a(Dx,"createHash");function Lx(e,t){let r=e.substr(0,uO),s=r+lO(t+r);return e===s}a(Lx,"validateHash");function Mx(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(Mx,"generateSalt");function lO(e){return Ux.createHash("md5").update(e).digest("hex")}a(lO,"md5");_O.exports={hash:Dx,validate:Lx}});var EO=m((Ise,dO)=>{var Pf=ve(),It={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 Px(e){return It.password.presence=!0,It.username.presence=!0,It.role.presence=!0,It.active.presence=!0,Pf.validateObject(e,It)}a(Px,"addUserValidation");function vx(e){return It.password.presence=!1,It.username.presence=!0,It.role.presence=!1,It.active.presence=!1,Pf.validateObject(e,It)}a(vx,"alterUserValidation");function Bx(e){return It.password.presence=!1,It.username.presence=!0,It.role.presence=!1,It.active.presence=!1,Pf.validateObject(e,It)}a(Bx,"dropUserValidation");dO.exports={addUserValidation:Px,alterUserValidation:vx,dropUserValidation:Bx}});var Be=m((Use,hO)=>{"use strict";var{platform:Cse}=require("os"),Hx="nats-server.zip",vf="nats-server",Fx=process.platform==="win32"?`${vf}.exe`:vf,Bf="HDB",qx=/^[^\s.,*>]+$/,fO="__request__",Gx=a(e=>`${e}.${fO}`,"REQUEST_SUBJECT"),xx={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin"},kx={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},Vx={HUB:"hub.pid",LEAF:"leaf.pid"},$x={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},Yx={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Bf,deliver_subject:"__HDB__.WORKQUEUE"},Kx={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Bf,deliver_subject:"HDB.SCHEMAQUEUE"},Wx={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Bf,deliver_subject:"HDB.USERQUEUE"},Qx={SUCCESS:"success",ERROR:"error"},zx={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},Jx={TXN:"txn",MSGID:"msgid"},qi={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},Xx={[qi.ERR]:1,[qi.WRN]:2,[qi.INF]:3,[qi.DBG]:4,[qi.TRC]:5},Zx={debug:"-D",trace:"-DVV"};hO.exports={NATS_SERVER_ZIP:Hx,NATS_SERVER_NAME:vf,NATS_BINARY_NAME:Fx,PID_FILES:Vx,NATS_CONFIG_FILES:kx,SERVER_SUFFIX:$x,WORK_QUEUE_CONSUMER_NAMES:Yx,SCHEMA_QUEUE_CONSUMER_NAMES:Kx,USER_QUEUE_CONSUMER_NAMES:Wx,NATS_TERM_CONSTRAINTS_RX:qx,REQUEST_SUFFIX:fO,UPDATE_REMOTE_RESPONSE_STATUSES:Qx,CLUSTER_STATUS_STATUSES:zx,REQUEST_SUBJECT:Gx,SUBJECT_PREFIXES:Jx,MSG_HEADERS:xx,LOG_LEVELS:qi,LOG_LEVEL_FLAGS:Zx,LOG_LEVEL_HIERARCHY:Xx}});var SO=m((Lse,mO)=>{"use strict";var jx={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))},ek="certificate.pem",tk="privateKey.pem",rk="ca.pem";mO.exports={CERTIFICATE_VALUES:jx,CERTIFICATE_PEM_NAME:ek,PRIVATEKEY_PEM_NAME:tk,CA_PEM_NAME:rk}});var Ff=m((Pse,OO)=>{"use strict";var gO=require("fs-extra"),ee=require("joi"),sk=require("os"),{boolean:pe,string:Bs,number:ir,array:Hf}=ee.types(),{totalmem:pO}=require("os"),Gi=require("path"),nk=x(),tl=V(),Mse=SO(),TO=A(),ik=ve(),RO="log",ok="components",ak="Invalid logging.rotation.maxSize unit. Available units are G, M or K",ck="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",uk="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",lk="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",_k="rootPath config parameter is undefined",dk="clustering.enabled config parameter is undefined",vs=ir.min(0).required(),rl=Hf.items({host:Bs.required(),port:vs}).empty(null),Hs;OO.exports={configValidator:Ek,routesValidator:Tk,route_constraints:rl};function Ek(e){if(Hs=e.rootPath,tl.isEmpty(Hs))throw _k;let t=pe.required(),r=ee.valid("production","development").required(),s=ir.min(0).max(1e3).empty(null).default(pk),n=Bs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(el),i=ee.custom(fk).messages({"any.custom":"{:#label} {:#error}"}),o=Bs.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=ee.string().empty(null).default(el),u=ee.custom(hk).empty(null).default(el),l=e.clustering?.enabled;if(tl.isEmpty(l))throw dk;let _;return l===!0?_=ee.object({enabled:t,hubServer:ee.object({cluster:ee.object({name:ee.required().empty(null),network:ee.object({port:vs,routes:rl}).required()}).required(),leafNodes:ee.object({network:ee.object({port:vs}).required()}).required(),network:ee.object({port:vs}).required()}).required(),leafServer:ee.object({network:ee.object({port:vs,routes:rl}).required(),streams:ee.object({maxAge:ir.min(120).allow(null).optional(),maxBytes:ir.min(1).allow(null).optional(),maxMsgs:ir.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:ee.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:pe.optional(),databaseLevel:pe.optional(),tls:ee.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:pe.required(),verify:pe.optional()}),user:Bs.optional().empty(null)}).required():_=ee.object({enabled:t,tls:ee.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:pe.required()})}).required(),ee.object({authentication:ee.object({authorizeLocal:pe,cacheTTL:ir.required(),enableSessions:pe,operationTokenTimeout:ee.required(),refreshTokenTimeout:ee.required()}),analytics:ee.object({aggregatePeriod:ir}),clustering:_,customFunctions:ee.object({enabled:t,network:ee.object({cors:pe.required(),corsAccessList:Hf.required(),headersTimeout:ir.min(1).required(),https:pe.required(),keepAliveTimeout:ir.min(1).required(),port:vs,timeout:ir.min(1).required()}),nodeEnv:r,root:n,tls:ee.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),localStudio:ee.object({enabled:t}).required(),logging:ee.object({auditAuthEvents:ee.object({logFailed:pe,logSuccessful:pe}),file:pe.required(),level:ee.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ee.object({enabled:pe.optional(),compress:pe.optional(),interval:Bs.custom(Sk).optional().empty(null),maxSize:Bs.custom(mk).optional().empty(null),path:Bs.optional().empty(null).default(el)}).required(),root:n,stdStreams:pe.required(),auditLog:pe.required()}).required(),operationsApi:ee.object({foreground:pe.required(),network:ee.object({cors:pe.required(),corsAccessList:Hf.required(),headersTimeout:ir.min(1).required(),https:pe.required(),keepAliveTimeout:ir.min(1).required(),port:vs,timeout:ir.min(1).required()}).required(),nodeEnv:r,tls:ee.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Bs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ee.object({network:ee.object({port:vs,securePort:vs}).required(),webSocket:pe.optional(),requireAuthentication:pe.optional()}),http:ee.object({threads:s}).required(),storage:ee.object({writeAsync:pe.required(),overlappingSync:pe.optional(),caching:pe.optional(),compression:pe.optional(),noReadAhead:pe.optional(),path:u,prefetchWrites:pe.optional()}).required(),ignoreScripts:pe.optional()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Ek,"configValidator");function AO(e){return gO.existsSync(e)?null:`Specified path ${e} does not exist.`}a(AO,"doesPathExist");function fk(e,t){if(e===null)return;let r=AO(e);return r?t.message(r):e}a(fk,"validatePemFile");function hk(e,t){ee.assert(e,Bs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=AO(e);if(r)return t.message(r)}a(hk,"validatePath");function mk(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(ak);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(uk):e}a(mk,"validateRotationMaxSize");function Sk(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(ck);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(lk):e}a(Sk,"validateRotationInterval");function pk(e,t){let r=t.state.path.join("."),s=sk.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||pO();return i=Math.round(Math.min(i,pO())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),nk.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(pk,"setDefaultThreads");function el(e,t){if(!tl.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(tl.isEmpty(Hs))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return Gi.join(Hs,ok);case"logging.root":return Gi.join(Hs,RO);case"clustering.leafServer.streams.path":return Gi.join(Hs,"clustering","leaf");case"storage.path":let s=Gi.join(Hs,TO.LEGACY_DATABASES_DIR_NAME);return gO.existsSync(s)?s:Gi.join(Hs,TO.DATABASES_DIR_NAME);case"logging.rotation.path":return Gi.join(Hs,RO);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(el,"setDefaultRoot");function Tk(e){let t=ee.object({routes:rl});return ik.validateBySchema({routes:e},t)}a(Tk,"routesValidator")});var Nr=m((Hse,MO)=>{"use strict";var Or=A(),_t=V(),st=x(),{configValidator:Rk,routesValidator:NO}=Ff(),Ft=require("fs-extra"),gk=require("yaml"),Hr=require("path"),Ak=require("is-number"),yO=require("properties-reader"),Ok=require("lodash"),{handleHDBError:Nk}=W(),{HTTP_STATUS_CODES:bk,HDB_ERROR_MSGS:sl}=rr(),Bse=require("minimist"),{server:yk}=(es(),re(wu)),{SCHEMAS_PARAM_CONFIG:Aa,CONFIG_PARAMS:fn,CONFIG_PARAM_MAP:Fs}=Or,Ik="Unable to get config value because config is uninitialized",wk="Config successfully initialized",Ck="Error backing up config file",Uk="Empty parameter sent to getConfigValue",IO=Hr.join(Or.PACKAGE_ROOT,"config","yaml",Or.HDB_DEFAULT_CONFIG_FILE),Dk="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",bO={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"},nl,St;MO.exports={createConfigFile:Lk,getDefaultConfig:Mk,getConfigValue:CO,initConfig:UO,flattenConfig:Zn,updateConfigValue:DO,updateConfigObject:vk,getConfiguration:Fk,setConfiguration:qk,readConfigFile:xf,getClusteringRoutes:Gk,initOldConfig:LO,getConfigFromFile:xk,getConfigFilePath:Xn,addConfig:kk,deleteConfigFromFile:Vk};function Lk(e){let t=hn(IO);nl=Zn(t.toJSON());let r;for(let o in e){let c=Fs[o.toLowerCase()];if(c===fn.SCHEMAS){r=e[o];continue}if(c!==void 0){let u=c.split("_"),l=qf(c,e[o]);c==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{t.setIn([...u],l)}catch(_){st.error(_)}}}r&&wO(t,r),Gf(t);let s=t.toJSON();St=Zn(s);let n=t.getIn(["rootPath"]),i=Hr.join(n,Or.HDB_CONFIG_FILE);Ft.createFileSync(i),Ft.writeFileSync(i,String(t)),st.trace(`Config file written to ${i}`)}a(Lk,"createConfigFile");function wO(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!_t.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(Aa.TABLES))for(let i in s[n][Aa.TABLES])for(let o in s[n][Aa.TABLES][i]){let c=s[n][Aa.TABLES][i][o],u=[fn.SCHEMAS,n,Aa.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[fn.SCHEMAS,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){st.error("Error parsing schemas CLI/env config arguments",s)}}a(wO,"setSchemasConfig");function Mk(e){if(nl===void 0){let r=hn(IO);nl=Zn(r.toJSON())}let t=Fs[e.toLowerCase()];if(t!==void 0)return nl[t.toLowerCase()]}a(Mk,"getDefaultConfig");function CO(e){if(e==null){st.error(Uk);return}if(St===void 0){st.trace(Ik);return}let t=Fs[e.toLowerCase()];if(t!==void 0)return St[t.toLowerCase()]}a(CO,"getConfigValue");function Xn(e=_t.getPropsFilePath()){let t=_t.getEnvCliRootPath();return t?Hr.join(t,Or.HDB_CONFIG_FILE):yO(e).get(Or.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Xn,"getConfigFilePath");function UO(e=!1){if(St===void 0||e){let t;if(!_t.noBootFile()){t=_t.getPropsFilePath();try{Ft.accessSync(t,Ft.constants.F_OK|Ft.constants.R_OK)}catch(i){throw st.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Xn(t),s;if(r.includes("config/settings.js"))try{LO(r);return}catch(i){if(i.code!==Or.NODE_ERROR_CODES.ENOENT)throw i}try{s=hn(r)}catch(i){if(i.code===Or.NODE_ERROR_CODES.ENOENT){st.trace(`HarperDB config file not found at ${r}.
|
|
5
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw st.error(i),new Error(`Error reading HarperDB config file at ${r}`)}Pk(s,r),Gf(s);let n=s.toJSON();if(yk.config=n,St=Zn(n),St.logging_rotation_rotate)for(let i in bO)St[i]&&st.error(`Config ${bO[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);st.trace(wk)}}a(UO,"initConfig");function Pk(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Hr.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Hr.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Hr.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(st.trace("Updating config file with missing config params"),Ft.writeFileSync(t,String(e)))}a(Pk,"checkForUpdatedConfig");function Gf(e){let t=e.toJSON(),r=Rk(t);if(r.error)throw sl.CONFIG_VALIDATION(r.error.message);e.setIn(["http","threads"],r.value.http.threads),e.setIn(["customFunctions","root"],r.value.customFunctions.root),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path)}a(Gf,"validateConfig");function vk(e,t){St===void 0&&(St={});let r=Fs[e.toLowerCase()];if(r===void 0){st.trace(`Unable to update config object because config param '${e}' does not exist`);return}St[r.toLowerCase()]=t}a(vk,"updateConfigObject");function DO(e,t,r=void 0,s=!1,n=!1,i=!1){St===void 0&&UO();let o=CO(Fs.hdb_root),c=Hr.join(o,Or.HDB_CONFIG_FILE),u=hn(c),l;if(r===void 0&&e.toLowerCase()===fn.SCHEMAS)l=t;else if(r===void 0){let E;if(i)E=e;else if(E=Fs[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=qf(E,t);u.setIn([...f],h)}else for(let E in r){let f=Fs[E.toLowerCase()];if(f===fn.SCHEMAS){l=r[E];continue}if(f!==void 0){let h=f.split("_"),T=qf(f,r[E]);f==="rootPath"&&T?.endsWith("/")&&(T=T.slice(0,-1));try{u.setIn([...h],T)}catch(p){st.error(p)}}}l&&wO(u,l),Gf(u);let _=u.getIn(["rootPath"]),d=Hr.join(_,Or.HDB_CONFIG_FILE);s===!0&&Bk(c,_),Ft.writeFileSync(d,String(u)),n&&(St=Zn(u.toJSON())),st.trace(`Config parameter: ${e} updated with value: ${t}`)}a(DO,"updateConfigValue");function Bk(e,t){try{let r=Hr.join(t,"backup",`${Or.HDB_CONFIG_FILE}.bak`);Ft.copySync(e,r),st.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){st.error(Ck),st.error(r)}}a(Bk,"backupConfigFile");var Hk=["schemas"];function Zn(e){let t={};for(let r in e)if(e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])&&!Hk.includes(r)){let s=Zn(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(Zn,"flattenConfig");function qf(e,t){if(e===fn.CLUSTERING_NODENAME||e===fn.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(Ak(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||_t.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 _t.autoCast(t)}a(qf,"castConfigValue");function Fk(){let e=_t.getPropsFilePath(),t=Xn(e);return hn(t).toJSON()}a(Fk,"getConfiguration");async function qk(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return DO(void 0,void 0,n,!0),Dk}catch(i){throw typeof i=="string"||i instanceof String?Nk(i,i,bk.BAD_REQUEST,void 0,void 0,!0):i}}a(qk,"setConfiguration");function xf(){let e=_t.getPropsFilePath();try{Ft.accessSync(e,Ft.constants.F_OK|Ft.constants.R_OK)}catch(s){if(!_t.noBootFile())throw st.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Xn(e);return hn(t).toJSON()}a(xf,"readConfigFile");function hn(e){return gk.parseDocument(Ft.readFileSync(e,"utf8"),{simpleKeys:!0})}a(hn,"parseYamlDoc");function Gk(){let e=xf(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=_t.isEmptyOrZeroLength(t)?[]:t;let r=NO(t);if(r)throw sl.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=_t.isEmptyOrZeroLength(s)?[]:s;let n=NO(s);if(n)throw sl.CONFIG_VALIDATION(n.message);if(!_t.isEmptyOrZeroLength(s)&&!_t.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!_t.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw sl.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(Gk,"getClusteringRoutes");function LO(e){let t=yO(e);St={};for(let r in Fs){let s=t.get(r.toUpperCase());if(_t.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=Fs[r].toLowerCase();n===fn.LOGGING_ROOT?St[n]=Hr.dirname(s):St[n]=s}return St}a(LO,"initOldConfig");function xk(e){let t=xf();return Ok.get(t,e.replaceAll("_","."))}a(xk,"getConfigFromFile");async function kk(e,t){let r=hn(Xn());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await Ft.writeFile(Xn(),String(r))}a(kk,"addConfig");function Vk(e){let t=Xn(_t.getPropsFilePath()),r=hn(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Hr.join(s,Or.HDB_CONFIG_FILE);Ft.writeFileSync(n,String(r))}a(Vk,"deleteConfigFromFile")});var vO=m((qse,PO)=>{"use strict";var il=A(),ol=class{static{a(this,"BaseLicense")}constructor(t=0,r=il.RAM_ALLOCATION_ENUM.DEFAULT,s=il.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},kf=class extends ol{static{a(this,"ExtendedLicense")}constructor(t=0,r=il.RAM_ALLOCATION_ENUM.DEFAULT,s=il.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};PO.exports={BaseLicense:ol,ExtendedLicense:kf}});var Oa=m((xse,xO)=>{"use strict";var ki=require("fs-extra"),BO=ju(),HO=require("crypto"),$k=require("moment"),Yk=require("uuid").v4,wt=x(),$f=require("path"),Kk=V(),mn=A(),Wk=vO().ExtendedLicense,xi="invalid license key format",Qk="061183",zk="mofi25",Jk="aes-256-cbc",Xk=16,Zk=32,FO=Q();FO.initSync();var Vf;xO.exports={validateLicense:qO,generateFingerPrint:eV,licenseSearch:GO,getLicense:sV};function Yf(){return $f.join(FO.getHdbBasePath(),mn.LICENSE_KEY_DIR_NAME,mn.LICENSE_FILE_NAME)}a(Yf,"getLicenseDirPath");function jk(){let e=Yf();return $f.join(e,mn.LICENSE_FILE_NAME)}a(jk,"getLicenseFilePath");function Kf(){let e=Yf();return $f.join(e,mn.REG_KEY_FILE_NAME)}a(Kf,"getFingerPrintFilePath");async function eV(){let e=Kf();try{return await ki.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await tV();throw wt.error(`Error writing fingerprint file to ${e}`),wt.error(t),new Error("There was an error generating the fingerprint")}}a(eV,"generateFingerPrint");async function tV(){let e=Yk(),t=BO.hash(e),r=Kf();try{await ki.mkdirp(Yf()),await ki.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw wt.error(`Error writing fingerprint file to ${r}`),wt.error(s),new Error("There was an error generating the fingerprint")}return t}a(tV,"writeFingerprint");function qO(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:mn.RAM_ALLOCATION_ENUM.DEFAULT,version:mn.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return wt.error("empty license key passed to validate."),r;let s=Kf(),n=!1;try{n=ki.statSync(s)}catch(i){wt.error(i)}if(n){let i;try{i=ki.readFileSync(s,"utf8")}catch{wt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(zk),c=o[1];c=Buffer.concat([Buffer.from(c)],Xk);let u=Buffer.concat([Buffer.from(i)],Zk),l=HO.createDecipheriv(Jk,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let _=null;try{_=l.update(o[0],"hex","utf8"),_.trim(),_+=l.final("utf8")}catch{let f=rV(o[0],i);if(f)_=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(xi),wt.error(xi),new Error(xi)}let d;if(isNaN(_))try{d=JSON.parse(_),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(xi),wt.error(xi),new Error(xi)}else r.exp_date=_;r.exp_date<$k().valueOf()&&(r.valid_date=!1),BO.validate(o[1],`${Qk}${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||wt.error("Invalid licence"),r}a(qO,"validateLicense");function rV(e,t){try{let r=HO.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{wt.warn("Check old license failed")}}a(rV,"checkOldLicense");function GO(){let e=new Wk,t=[];try{t=ki.readFileSync(jk(),"utf-8").split(mn.NEW_LINE)}catch(r){r.code==="ENOENT"?wt.info("no license file found"):wt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(Kk.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=qO(n.license_key,n.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(n){wt.error("There was an error parsing the license string."),wt.error(n),e.ram_allocation=mn.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Vf=e,e}a(GO,"licenseSearch");async function sV(){return Vf||await GO(),Vf}a(sV,"getLicense")});var br=m((Kse,sN)=>{"use strict";var KO="username is required",WO="nothing to update, must supply active, role or password to update",QO="password cannot be an empty string",zO="If role is specified, it cannot be empty.",JO="active must be true or false";sN.exports={addUser:dV,alterUser:EV,dropUser:hV,getSuperUser:TV,userInfo:mV,listUsers:cl,listUsersExternal:SV,setUsersToGlobal:$i,findAndValidateUser:rN,getClusterUser:RV,USERNAME_REQUIRED:KO,ALTERUSER_NOTHING_TO_UPDATE:WO,EMPTY_PASSWORD:QO,EMPTY_ROLE:zO,ACTIVE_BOOLEAN:JO};var XO=Ar(),nV=Jn(),Qf=ju(),ZO=EO(),jO=gr(),zf=qs(),or=V(),eN=require("validate.js"),ue=x(),{promisify:iV}=require("util"),Jf=Ps(),kO=A(),VO=Be(),oV=Nr(),Vse=Q(),$se=Oa(),aV=Vn(),{table:Yse}=(de(),re(Ne)),{handleHDBError:ns,hdb_errors:cV}=W(),{HTTP_STATUS_CODES:is,AUTHENTICATION_ERROR_MSGS:Wf,HDB_ERROR_MSGS:Vi}=cV,{UserEventMsg:Xf}=Fr(),$O=require("lodash"),{_assignPackageExport:uV}=require("../index");uV("getUser",rN);var tN={username:!0,active:!0,role:!0,password:!0},YO=new Map,al=jO.searchByValue,lV=jO.searchByHash,_V=iV(nV.delete);async function dV(e){let t=eN.cleanAttributes(e,tN),r=ZO.addUserValidation(t);if(r)throw ns(new Error,r.message,is.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 al(s),n=n&&Array.from(n)}catch(u){throw ue.error("There was an error searching for a role in add user"),ue.error(u),u}if(!n||n.length<1)throw ns(new Error,Vi.ROLE_NAME_NOT_FOUND(t.role),is.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw ns(new Error,Vi.DUP_ROLES_FOUND(t.role),is.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=Jf.encrypt(t.password)),t.password=Qf.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await XO.insert(i)}catch(u){throw ue.error("There was an error searching for a user."),ue.error(u),u}ue.debug(o);try{await $i()}catch(u){throw ue.error("Got an error setting users to global"),ue.error(u),u}if(o.skipped_hashes.length===1)throw ns(new Error,Vi.USER_ALREADY_EXISTS(t.username),is.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],zf.signalUserChange(new Xf(process.pid)),`${c.username} successfully added`}a(dV,"addUser");async function EV(e){let t=eN.cleanAttributes(e,tN);if(or.isEmptyOrZeroLength(t.username))throw new Error(KO);if(or.isEmptyOrZeroLength(t.password)&&or.isEmptyOrZeroLength(t.role)&&or.isEmptyOrZeroLength(t.active))throw new Error(WO);if(!or.isEmpty(t.password)&&or.isEmptyOrZeroLength(t.password.trim()))throw new Error(QO);if(!or.isEmpty(t.active)&&!or.isBoolean(t.active))throw new Error(JO);let r=fV(t.username);if(!or.isEmpty(t.password)&&!or.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Jf.encrypt(t.password)),t.password=Qf.hash(t.password)),t.role==="")throw new Error(zO);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await al(i)||[])}catch(c){throw ue.error("Got an error searching for a role."),ue.error(c),c}if(!o||o.length===0){let c=Vi.ALTER_USER_ROLE_NOT_FOUND(t.role);throw ue.error(c),ns(new Error,c,is.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Vi.ALTER_USER_DUP_ROLES(t.role);throw ue.error(c),ns(new Error,c,is.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await XO.update(s)}catch(i){throw ue.error("Error during update."),ue.error(i),i}try{await $i()}catch(i){throw ue.error("Got an error setting users to global"),ue.error(i),i}return zf.signalUserChange(new Xf(process.pid)),n}a(EV,"alterUser");function fV(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(fV,"isClusterUser");async function hV(e){try{let t=ZO.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(or.isEmpty(global.hdb_users.get(e.username)))throw ns(new Error,Vi.USER_NOT_EXIST(e.username),is.NOT_FOUND,void 0,void 0,!0);let s;try{s=await _V(r)}catch(n){throw ue.error("Got an error deleting a user."),ue.error(n),n}ue.debug(s);try{await $i()}catch(n){throw ue.error("Got an error setting users to global."),ue.error(n),n}return zf.signalUserChange(new Xf(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(hV,"dropUser");async function mV(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 lV(r)}catch(n){throw ue.error("Got an error searching for a role."),ue.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw ue.error(r),r}return t}a(mV,"userInfo");async function SV(){let e;try{e=await cl()}catch(t){throw ue.error("Got an error listing users."),ue.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(SV,"listUsersExternal");async function cl(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await al(e)}catch(o){throw ue.error("Got an error searching for roles."),ue.error(o),o}let r={};for(let o of t)r[o.id]=$O.cloneDeep(o);if(Object.keys(r).length===0)return null;let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await al(s)}catch(o){throw ue.error("Got an error searching for users."),ue.error(o),o}let i=new Map;for(let o of n)o=$O.cloneDeep(o),o.role=r[o.role],pV(o.role),i.set(o.username,o);return i}catch(e){throw ue.error("got an error listing users"),ue.error(e),or.errorizeMessage(e)}return null}a(cl,"listUsers");function pV(e){try{if(!e){ue.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(aV)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){ue.error("Got an error trying to set system permissions."),ue.error(t)}}a(pV,"appendSystemTablesToRole");async function $i(){try{let e=await cl();global.hdb_users=e}catch(e){throw ue.error(e),e}}a($i,"setUsersToGlobal");async function rN(e,t,r=!0){global.hdb_users||await $i();let s=global.hdb_users.get(e);if(!s)throw ns(new Error,Wf.GENERIC_AUTH_FAIL,is.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw ns(new Error,Wf.USER_INACTIVE,is.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(YO.get(t)===s.password)return n;if(Qf.validate(s.password,t))YO.set(t,s.password);else throw ns(new Error,Wf.GENERIC_AUTH_FAIL,is.UNAUTHORIZED,void 0,void 0,!0)}return n}a(rN,"findAndValidateUser");async function TV(){global.hdb_users||await $i();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(TV,"getSuperUser");async function RV(){let e=await cl(),t=oV.getConfigFromFile(kO.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!or.isEmpty(r)&&r?.role?.role===kO.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Jf.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+VO.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+VO.SERVER_SUFFIX.ADMIN,r}a(RV,"getClusterUser")});var ba=m((Jse,aN)=>{"use strict";var jn=x(),ar=A(),gV=PA(),Qse=_n(),zse=Yn(),AV=br(),{validateEvent:nN}=Fr(),Na=Br(),OV=require("process"),{resetDatabases:NV}=(de(),re(Ne)),bV={[ar.ITC_EVENT_TYPES.SCHEMA]:yV,[ar.ITC_EVENT_TYPES.USER]:oN};async function yV(e){let t=nN(e);if(t){jn.error(t);return}jn.trace("ITC schemaHandler received schema event:",e),await gV(e.message),await IV(e.message)}a(yV,"schemaHandler");async function IV(e){try{Na.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Na.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Na.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=NV();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){jn.error(t)}}a(IV,"syncSchemaMetadata");var iN=[];async function oN(e){try{try{Na.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Na.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){jn.warn(r)}let t=nN(e);if(t){jn.error(t);return}jn.trace(`ITC userHandler ${ar.HDB_ITC_CLIENT_PREFIX}${OV.pid} received user event:`,e),await AV.setUsersToGlobal();for(let r of iN)r()}catch(t){jn.error(t)}}a(oN,"userHandler");oN.addListener=function(e){iN.push(e)};aN.exports=bV});var Fr=m((rne,uN)=>{"use strict";var Zse=x(),Zf=V(),wV=A(),{ITC_ERRORS:ya}=rr(),{parentPort:jse,threadId:CV,isMainThread:UV,workerData:ene}=require("worker_threads"),{onMessageFromWorkers:DV,broadcast:tne,broadcastWithAcknowledgement:LV}=dt();uN.exports={sendItcEvent:MV,validateEvent:cN,SchemaEventMsg:PV,UserEventMsg:vV};var ul;DV(async(e,t)=>{ul=ul||ba(),cN(e),ul[e.type]&&await ul[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function MV(e){return!UV&&e.message&&(e.message.originator=CV),LV(e)}a(MV,"sendItcEvent");function cN(e){if(typeof e!="object")return ya.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Zf.isEmpty(e.type))return ya.MISSING_TYPE;if(!e.hasOwnProperty("message")||Zf.isEmpty(e.message))return ya.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Zf.isEmpty(e.message.originator))return ya.MISSING_ORIGIN;if(wV.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return ya.INVALID_EVENT(e.type)}a(cN,"validateEvent");function PV(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(PV,"SchemaEventMsg");function vV(e){this.originator=e}a(vV,"UserEventMsg")});var qs=m((ine,EN)=>{"use strict";var lN=A(),nne=V(),ll=x(),_N=DA(),Yi,{sendItcEvent:dN}=Fr();function BV(e){try{ll.trace("signalSchemaChange called with message:",e),Yi=Yi||ba();let t=new _N(lN.ITC_EVENT_TYPES.SCHEMA,e);return Yi.schema(t),dN(t)}catch(t){ll.error(t)}}a(BV,"signalSchemaChange");function HV(e){try{ll.trace("signalUserChange called with message:",e),Yi=Yi||ba();let t=new _N(lN.ITC_EVENT_TYPES.USER,e);return Yi.user(t),dN(t)}catch(t){ll.error(t)}}a(HV,"signalUserChange");EN.exports={signalSchemaChange:BV,signalUserChange:HV}});var _l=m((ane,hN)=>{"use strict";var fN=V(),FV=A(),qV=x(),GV=ku(),xV=xu(),kV=qs(),{SchemaEventMsg:VV}=Fr(),$V="already exists in";hN.exports=YV;async function YV(e,t,r){if(fN.isEmptyOrZeroLength(r))return r;let s=[];fN.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 KV(e,t.schema,t.name,i)})),n}a(YV,"lmdbCheckForNewAttributes");async function KV(e,t,r,s){let n=new xV(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await WV(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes($V))qV.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(KV,"createNewAttribute");async function WV(e){let t;return t=await GV(e),kV.signalSchemaChange(new VV(process.pid,FV.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(WV,"createAttribute")});var Ki=m((une,mN)=>{"use strict";var jf=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};mN.exports=jf});var pN=m((_ne,SN)=>{"use strict";var QV=Ki(),zV=A().OPERATIONS_ENUM,eh=class extends QV{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(zV.INSERT,r,s,n,i),this.records=t}};SN.exports=eh});var RN=m((Ene,TN)=>{"use strict";var JV=Ki(),XV=A().OPERATIONS_ENUM,th=class extends JV{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(XV.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};TN.exports=th});var AN=m((hne,gN)=>{"use strict";var ZV=Ki(),jV=A().OPERATIONS_ENUM,rh=class extends ZV{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(jV.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};gN.exports=rh});var NN=m((Sne,ON)=>{"use strict";var e$=Ki(),t$=A().OPERATIONS_ENUM,sh=class extends e${static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(t$.DELETE,s,n,t,i),this.original_records=r}};ON.exports=sh});var Ia=m((Rne,wN)=>{"use strict";var Tne=require("path"),bN=ye(),r$=pN(),s$=RN(),n$=AN(),i$=NN(),Wi=xe(),yN=V(),{CONFIG_PARAMS:o$}=A(),IN=Q();IN.initSync();var dl=A().OPERATIONS_ENUM,{getTransactionAuditStorePath:a$}=we();wN.exports=c$;async function c$(e,t){if(IN.get(o$.LOGGING_AUDITLOG)===!1)return;let r=a$(e.schema,e.table),s=await bN.openEnvironment(r,e.table,!0),n=u$(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){bN.initializeDBIs(s,Wi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Wi.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[Wi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[Wi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),yN.isEmpty(n.user_name)||s.dbis[Wi.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[Wi.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(c$,"writeTransaction");function u$(e,t){let r=yN.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===dl.INSERT)return new r$(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===dl.UPDATE)return new s$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===dl.UPSERT)return new n$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===dl.DELETE)return new i$(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(u$,"createTransactionObject")});var nh=m((One,CN)=>{"use strict";var l$=ha(),Ane=ma(),wa=A(),_$=Ra(),d$=Hi().insertRecords,E$=ye(),f$=x(),h$=_l(),{getSchemaPath:m$}=we(),S$=Ia();CN.exports=p$;async function p$(e){try{let{schema_table:t,attributes:r}=l$(e);_$(e,r,t.hash_attribute),e.schema!==wa.SYSTEM_SCHEMA_NAME&&(r.includes(wa.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(wa.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(wa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(wa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await h$(e.hdb_auth_header,t,r),n=m$(e.schema,e.table),i=await E$.openEnvironment(n,e.table),o=await d$(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await S$(e,o)}catch(c){f$.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(p$,"lmdbCreateRecords")});var LN=m((bne,DN)=>{"use strict";var UN=A(),T$=nh(),R$=ma(),g$=require("fs-extra"),{getSchemaPath:A$}=we();DN.exports=O$;async function O$(e){let t=[{name:e.schema,createddate:Date.now()}],r=new R$(UN.SYSTEM_SCHEMA_NAME,UN.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await T$(r),await g$.mkdirp(A$(e.schema))}a(O$,"lmdbCreateSchema")});var PN=m((Ine,MN)=>{"use strict";var ih=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};MN.exports=ih});var FN=m((Lne,HN)=>{"use strict";var vN=ye(),oh=vt(),ah=rr().LMDB_ERRORS_ENUM,N$=xe(),BN=x(),Cne=V(),b$=require("lmdb"),y$=PN(),I$=A(),{OVERFLOW_MARKER:Une,MAX_SEARCH_KEY_LENGTH:Dne}=N$,w$=I$.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function C$(e,t,r,s){if(oh.validateEnv(e),t===void 0)throw new Error(ah.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(ah.IDS_REQUIRED):new Error(ah.IDS_MUST_BE_ITERABLE);try{let n=vN.listDBIs(e);vN.initializeDBIs(e,t,n);let i=new y$,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||s&&h[w$]>s){i.skipped.push(o);continue}let T=e.dbis[t].ifVersion(o,b$.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let p=0;p<n.length;p++){let R=n[p];if(!h.hasOwnProperty(R)||R===t)continue;let O=e.dbis[R],k=h[R];if(k!=null)try{let $=oh.getIndexedValues(k);if($)for(let U=0,b=$.length;U<b;U++)O.remove($[U],o)}catch{BN.warn(`cannot delete from attribute: ${R}, ${k}:${o}`)}}});c.push(T),u.push(o),i.original_records.push(h)}catch(h){BN.warn(h),i.skipped.push(o)}let l=[],_=await Promise.all(c);for(let E=0,f=_.length;E<f;E++)_[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),l.push(E));let d=0;for(let E=0;E<l.length;E++){let f=l[E];i.original_records.splice(f-d,1),d++}return i.txn_time=oh.getNextMonotonicTime(),i}catch(n){throw n}}a(C$,"deleteRecords");HN.exports={deleteRecords:C$}});var Ca=m((Pne,GN)=>{"use strict";var Qi=V(),U$=FN(),D$=ye(),{getSchemaPath:L$}=we(),M$=Ia(),P$=x();GN.exports=v$;async function v$(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Qi.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Qi.isEmptyOrZeroLength(e.hash_values)&&!Qi.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Qi.isEmpty(u)||e.hash_values.push(u)}}if(Qi.isEmptyOrZeroLength(e.hash_values))return qN([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Qi.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=L$(e.schema,e.table),i=await D$.openEnvironment(n,e.table),o=await U$.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await M$(e,o)}catch(c){P$.error(`unable to write transaction due to ${c.message}`)}return qN(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(v$,"lmdbDeleteRecords");function qN(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(qN,"createDeleteResponse")});var uh=m((Hne,xN)=>{"use strict";var B$=A(),Bne=vt();function ch(e,t){let r=Object.create(null);if(t.length===1&&B$.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(ch,"parseRow");function H$(e,t,r,s){let n=ch(r,e);s.push(n)}a(H$,"searchAll");function F$(e,t,r,s){let n=ch(r,e);s[t]=n}a(F$,"searchAllToMap");function q$(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(q$,"iterateDBI");function ei(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(ei,"pushResults");function G$(e,t,r,s,n,i){t.toString().endsWith(e)&&ei(t,r,s,n,i)}a(G$,"endsWith");function x$(e,t,r,s,n,i){t.toString().includes(e)&&ei(t,r,s,n,i)}a(x$,"contains");function k$(e,t,r,s,n,i){t>e&&ei(t,r,s,n,i)}a(k$,"greaterThanCompare");function V$(e,t,r,s,n,i){t>=e&&ei(t,r,s,n,i)}a(V$,"greaterThanEqualCompare");function $$(e,t,r,s,n,i){t<e&&ei(t,r,s,n,i)}a($$,"lessThanCompare");function Y$(e,t,r,s,n,i){t<=e&&ei(t,r,s,n,i)}a(Y$,"lessThanEqualCompare");xN.exports={parseRow:ch,searchAll:H$,searchAllToMap:F$,iterateDBI:q$,endsWith:G$,contains:x$,greaterThanCompare:k$,greaterThanEqualCompare:V$,lessThanCompare:$$,lessThanEqualCompare:Y$,pushResults:ei}});var zi=m((kne,QN)=>{"use strict";var Sn=ye(),qne=x(),cr=vt(),El=xe(),ke=rr().LMDB_ERRORS_ENUM,Gne=V(),K$=A(),fl=uh(),{parseRow:W$}=fl,xne=require("lmdb"),{OVERFLOW_MARKER:kN,MAX_SEARCH_KEY_LENGTH:Q$}=El;function VN(e,t,r,s=!1,n=void 0,i=void 0){return ti(e,t,r,(o,c)=>c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}a(VN,"iterateFullIndex");function Ua(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,l=!1){return ti(e,t,r,(_,d,E,f)=>{let O={transaction:_,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!l,exclusiveStart:i===!0?l:u};return f===r?(O.values=!1,d.getRange(O).map(k=>({value:k}))):d.getRange(O)})}a(Ua,"iterateRangeBetween");function ti(e,t,r,s){let n=e.database||e,i=Sn.openDBI(n,r);i[El.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&Sn.openDBI(n,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=s(o,i,n,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(ti,"setupTransaction");function $N(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(kN)){if(!n)if(r)n=Sn.openDBI(e,r);else{let u=Sn.listDBIs(e);for(let l=0,_=u.length;l<_&&(n=Sn.openDBI(e,u[l]),!n[El.DBI_DEFINITION_NAME].is_hash_attribute);l++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a($N,"getOverflowCheck");function z$(e,t,r,s=!1,n=void 0,i=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);return ti(e,t,t,(o,c,u)=>(hl(r),r=Da(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(l=>W$(l.value,r))))}a(z$,"searchAll");function J$(e,t,r,s=!1,n=void 0,i=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);hl(r),r=Da(e.database||e,r);let o=new Map;for(let{key:c,value:u}of VN(e,t,t,s,n,i))o.set(c,fl.parseRow(u,r));return o}a(J$,"searchAllToMap");function X$(e,t,r=!1,s=void 0,n=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=VN(e,void 0,t,r,s,n),c=o.transaction,u=$N(c.database,c,void 0,t);for(let{key:l,value:_}of o){let d=u(l,_);i[d]===void 0&&(i[d]=[]),i[d].push(_)}return i}a(X$,"iterateDBI");function Z$(e,t){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);return Sn.statDBI(e,t).entryCount}a(Z$,"countAll");function j$(e,t,r,s,n=!1,i=void 0,o=void 0){return pn(e,r,s),ti(e,t,r,(c,u,l,_)=>(s=cr.convertKeyValueToWrite(s),_===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(j$,"equals");function eY(e,t,r){return pn(e,t,r),Sn.openDBI(e,t).getValuesCount(r)}a(eY,"count");function tY(e,t,r,s,n=!1,i=void 0,o=void 0){return pn(e,r,s),ti(e,null,r,(c,u)=>{s=cr.convertKeyValueToWrite(s);let l=!0;typeof s=="number"&&(l=!1);let _;if(n===!0){let d;for(let E of u.getKeys({transaction:c,start:s}))if(!E.startsWith(s)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),_=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(s))return E;if(l===!0)return _.DONE}}),_.filter(E=>E)}else return _=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(l===!0)return _.DONE}),l?_:_.filter(d=>d)})}a(tY,"startsWith");function rY(e,t,r,s,n=!1,i=void 0,o=void 0){return YN(e,t,r,s,n,i,o,!0)}a(rY,"endsWith");function YN(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return pn(e,r,s),ti(e,null,r,(u,l,_,d)=>{let E=$N(_,u,d,r);return o=Number.isInteger(o)?o:0,l.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(f=>{let h=f.toString();return h.endsWith(kN)?l.getValues(f,{transaction:u}).map(T=>{let p=E(f,T);if(c?p.endsWith(s):p.includes(s))return{key:p,value:T}}).filter(T=>T):(c?h.endsWith(s):h.includes(s))?l[El.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:l.getValues(f,{transaction:u}).map(T=>({key:f,value:T})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(YN,"contains");function sY(e,t,r,s,n=!1,i=void 0,o=void 0){pn(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Ua(e,t,r,s,u,n,i,o,!0,!1)}a(sY,"greaterThan");function nY(e,t,r,s,n=!1,i=void 0,o=void 0){pn(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Ua(e,t,r,s,u,n,i,o,!1,!1)}a(nY,"greaterThanEqual");function iY(e,t,r,s,n=!1,i=void 0,o=void 0){pn(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Ua(e,t,r,u,s,n,i,o,!1,!0)}a(iY,"lessThan");function oY(e,t,r,s,n=!1,i=void 0,o=void 0){pn(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Ua(e,t,r,u,s,n,i,o,!1,!1)}a(oY,"lessThanEqual");function aY(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(cr.validateEnv(e),r===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ke.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ke.END_VALUE_REQUIRED);if(s=cr.convertKeyValueToWrite(s),n=cr.convertKeyValueToWrite(n),s>n)throw new Error(ke.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Ua(e,t,r,s,n,i,o,c)}a(aY,"between");function cY(e,t,r,s){cr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(hl(r),r=Da(n,r),s===void 0)throw new Error(ke.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=fl.parseRow(c,r)),o}a(cY,"searchByHash");function uY(e,t,r){cr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ke.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(uY,"checkHashExists");function lY(e,t,r,s,n=[]){return WN(e,t,r,s,n),KN(e,t,r,s,n).map(i=>i[1])}a(lY,"batchSearchByHash");function _Y(e,t,r,s,n=[]){WN(e,t,r,s,n);let i=new Map;for(let[o,c]of KN(e,t,r,s,n))i.set(o,c);return i}a(_Y,"batchSearchByHashToMap");function KN(e,t,r,s,n=[]){return ti(e,t,t,(i,o,c)=>{r=Da(c,r);let u=r.length<3;return s.map(l=>{let _=c.dbis[t].get(l,{transaction:i,lazy:u});if(_)return[l,fl.parseRow(_,r)];n.push(l)}).filter(l=>l)})}a(KN,"batchHashSearch");function WN(e,t,r,s,n){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(hl(r),s==null)throw new Error(ke.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ke.IDS_MUST_BE_ITERABLE)}a(WN,"initializeBatchSearchByHash");function hl(e){if(!Array.isArray(e))throw e===void 0?new Error(ke.FETCH_ATTRIBUTES_REQUIRED):new Error(ke.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(hl,"validateFetchAttributes");function pn(e,t,r){if(cr.validateEnv(e),t===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ke.SEARCH_VALUE_REQUIRED);if(r?.length>Q$)throw new Error(ke.SEARCH_VALUE_TOO_LARGE)}a(pn,"validateComparisonFunctions");function Da(e,t){return t.length===1&&K$.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Sn.listDBIs(e)),t}a(Da,"setGetWholeRowAttributes");QN.exports={searchAll:z$,searchAllToMap:J$,count:eY,countAll:Z$,equals:j$,startsWith:tY,endsWith:rY,contains:YN,searchByHash:cY,setGetWholeRowAttributes:Da,batchSearchByHash:lY,batchSearchByHashToMap:_Y,checkHashExists:uY,iterateDBI:X$,greaterThan:sY,greaterThanEqual:nY,lessThan:iY,lessThanEqual:oY,between:aY}});var Ji=m(($ne,jN)=>{var zN=require("lodash"),JN=ve(),Ce=require("joi"),dY=V(),{hdb_schema_table:ml,checkValidTable:XN,hdb_table:ZN,hdb_database:Sl}=rs(),{handleHDBError:EY,hdb_errors:fY}=W(),{getDatabases:hY}=(de(),re(Ne)),{HTTP_STATUS_CODES:mY}=fY,SY=Ce.object({database:Sl,schema:Sl,table:ZN,search_attribute:ml,search_value:Ce.any().required(),get_attributes:Ce.array().min(1).items(ml).optional(),desc:Ce.bool(),limit:Ce.number().integer().min(1),offset:Ce.number().integer().min(0)}),pY=Ce.object({database:Sl,schema:Sl,table:ZN,operator:Ce.string().valid("and","or").default("and").lowercase(),offset:Ce.number().integer().min(0),limit:Ce.number().integer().min(1),get_attributes:Ce.array().min(1).items(ml).optional(),conditions:Ce.array().min(1).items(Ce.object({search_attribute:ml,search_type:Ce.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:Ce.when("search_type",{switch:[{is:"equals",then:Ce.any()},{is:"between",then:Ce.array().items(Ce.alternatives([Ce.string(),Ce.number()])).length(2)}],otherwise:Ce.alternatives(Ce.string(),Ce.number())}).required()})).required()});jN.exports=function(e,t){let r=null;switch(t){case"value":r=JN.validateBySchema(e,SY);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(XN("database",e.schema)),i(XN("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=JN.validateBySchema(e,pY);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=dY.checkGlobalSchemaTable(e.schema,e.table);if(n)return EY(new Error,n,mY.NOT_FOUND);let o=hY()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let l=0,_=e.conditions.length;l<_;l++){let d=e.conditions[l];c.push(d.search_attribute)}let u=zN.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!zN.some(o,_=>_===l||_.attribute===l||_.attribute===l.attribute));if(u&&u.length>0){let l=u.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var lh=m((Kne,eb)=>{"use strict";var TY=ye(),RY=Ji(),{getSchemaPath:gY}=we();eb.exports=AY;function AY(e){let t=RY(e,"hashes");if(t)throw t;let r=gY(e.schema,e.table);return TY.openEnvironment(r,e.table)}a(AY,"initialize")});var _h=m((Qne,tb)=>{"use strict";var OY=zi(),NY=lh();tb.exports=bY;async function bY(e){let t=await NY(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return OY.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(bY,"lmdbGetDataByHash")});var Xi=m((Jne,rb)=>{"use strict";var dh=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};rb.exports=dh});var nb=m((jne,sb)=>{"use strict";var Zne=Xi(),yY=zi(),IY=lh();sb.exports=wY;async function wY(e){let t=await IY(e),r=global.hdb_schema[e.schema][e.table];return yY.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(wY,"lmdbSearchByHash")});var os=m((tie,ib)=>{"use strict";var Eh=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,l=void 0,_=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=l,this.offset=_}};ib.exports=Eh});var pl=m((sie,_b)=>{"use strict";var Ct=zi(),CY=ye(),UY=V(),ie=xe(),ri=A(),DY=Vn(),ob=rr().LMDB_ERRORS_ENUM,{getSchemaPath:LY}=we(),Gs=ri.SEARCH_WILDCARDS;async function MY(e,t,r){let s;e.schema===ri.SYSTEM_SCHEMA_NAME?s=DY[e.table]:s=global.hdb_schema[e.schema][e.table];let n=lb(e,s.hash_attribute,r,t);return cb(e,n,s.hash_attribute,r)}a(MY,"prepSearch");async function cb(e,t,r,s){let n=LY(e.schema,e.table),i=await CY.openEnvironment(n,e.table),o=ub(i,e,t,r),c=o.transaction||i;if([ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,ie.SEARCH_TYPES.SEARCH_ALL,ie.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(PY(e,r)===!1){let _=e.search_attribute;if(_===r)return s?ab(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[_]:E.key}),"toObject");return s?ab(o,d):o.map(d)}let l=e.search_attribute===r?o.map(_=>_.key):o.map(_=>_.value);return s===!0?Ct.batchSearchByHashToMap(c,r,e.get_attributes,l):Ct.batchSearchByHash(c,r,e.get_attributes,l)}a(cb,"executeSearch");function ub(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case ie.SEARCH_TYPES.EQUALS:n=Ct.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.CONTAINS:n=Ct.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.ENDS_WITH:case ie.SEARCH_TYPES._ENDS_WITH:n=Ct.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.STARTS_WITH:case ie.SEARCH_TYPES._STARTS_WITH:n=Ct.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Ct.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Ct.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case ie.SEARCH_TYPES.SEARCH_ALL:return Ct.searchAll(e,s,t.get_attributes,o,c,u);case ie.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Ct.searchAllToMap(e,s,t.get_attributes,o,c,u);case ie.SEARCH_TYPES.BETWEEN:n=Ct.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case ie.SEARCH_TYPES.GREATER_THAN:case ie.SEARCH_TYPES._GREATER_THAN:n=Ct.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.GREATER_THAN_EQUAL:case ie.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Ct.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.LESS_THAN:case ie.SEARCH_TYPES._LESS_THAN:n=Ct.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.LESS_THAN_EQUAL:case ie.SEARCH_TYPES._LESS_THAN_EQUAL:n=Ct.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(ub,"searchByType");function ab(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(ab,"createMapFromIterable");function PY(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(PY,"checkToFetchMore");function lb(e,t,r,s){if(UY.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),Gs.indexOf(n)>-1)return r===!0?ie.SEARCH_TYPES.SEARCH_ALL_TO_MAP:ie.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(Gs[0])<0&&n.indexOf(Gs[1])<0)return c===!0?r===!0?ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:ie.SEARCH_TYPES.EQUALS;if(Gs.indexOf(i)>=0&&Gs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),ie.SEARCH_TYPES.CONTAINS;if(Gs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),ie.SEARCH_TYPES.ENDS_WITH;if(Gs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),ie.SEARCH_TYPES.STARTS_WITH;if(n.includes(Gs[0])||n.includes(Gs[1]))return ie.SEARCH_TYPES.EQUALS;throw new Error(ob.UNKNOWN_SEARCH_TYPE)}else switch(s){case ri.VALUE_SEARCH_COMPARATORS.BETWEEN:return ie.SEARCH_TYPES.BETWEEN;case ri.VALUE_SEARCH_COMPARATORS.GREATER:return ie.SEARCH_TYPES.GREATER_THAN;case ri.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return ie.SEARCH_TYPES.GREATER_THAN_EQUAL;case ri.VALUE_SEARCH_COMPARATORS.LESS:return ie.SEARCH_TYPES.LESS_THAN;case ri.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return ie.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(ob.UNKNOWN_SEARCH_TYPE)}}a(lb,"createSearchTypeFromSearchObject");_b.exports={executeSearch:cb,createSearchTypeFromSearchObject:lb,prepSearch:MY,searchByType:ub}});var Eb=m((oie,db)=>{"use strict";var iie=os(),vY=Ji(),BY=V(),HY=A(),FY=pl();db.exports=qY;function qY(e,t){if(!BY.isEmpty(t)&&HY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=vY(e,"value");if(s)throw s;let n=!0;return FY.prepSearch(e,t,n)}a(qY,"lmdbGetDataByValue")});var La=m((uie,fb)=>{"use strict";var cie=os(),GY=Ji(),xY=V(),kY=A(),VY=pl();fb.exports=$Y;async function $Y(e,t){if(!xY.isEmpty(t)&&kY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=GY(e,"value");if(s)throw s;return VY.prepSearch(e,t,!1)}a($Y,"lmdbSearchByValue")});var mb=m((die,hb)=>{"use strict";var _ie=xe(),fh=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}},hh=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},mh=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};hb.exports={SearchByConditionsObject:fh,SearchCondition:hh,SortAttribute:mh}});var gb=m((mie,Rb)=>{"use strict";var fie=mb().SearchByConditionsObject,YY=os(),KY=Ji(),Sh=zi(),Tl=xe(),{Resource:hie}=(Xr(),re(DE)),Tb=pl(),WY=uh(),QY=require("lodash"),{getSchemaPath:zY}=we(),Sb=ye(),{handleHDBError:JY,hdb_errors:XY}=W(),{HTTP_STATUS_CODES:ZY}=XY,jY=1e8;Rb.exports=eK;async function eK(e){let t=KY(e,"conditions");if(t)throw JY(t,t.message,ZY.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=zY(e.schema,e.table),s=await Sb.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let l of e.conditions)Sb.openDBI(s,l.search_attribute);let i=QY.sortBy(e.conditions,l=>{if(l.estimated_count===void 0){let _=l.search_type;_===Tl.SEARCH_TYPES.EQUALS?l.estimated_count=Sh.count(s,l.search_attribute,l.search_value):_===Tl.SEARCH_TYPES.CONTAINS||_===Tl.SEARCH_TYPES.ENDS_WITH?l.estimated_count=1/0:l.estimated_count=jY}return l.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await pb(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let l=s.dbis[n.hash_attribute],_=i.slice(1).map(Tb.filterByType),d=_.length,E=Sh.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(f=>l.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!_[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>WY.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await pb(o,e,E,n.hash_attribute);c=c.concat(f)}let l=new Set,_=e.offset||0;c=c.filter(d=>l.has(d)?!1:(l.add(d),!0)).slice(_,e.limit&&e.limit+_),u=Sh.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(eK,"lmdbSearchByConditions");async function pb(e,t,r,s){let n=new YY(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===Tl.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,Tb.searchByType(e,n,i,s).map(o=>o.value)}a(pb,"executeConditionSearch")});var Ma=m((pie,Ab)=>{"use strict";var tK=A().OPERATIONS_ENUM,ph=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=tK.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};Ab.exports=ph});var Th=m((Rie,Ub)=>{"use strict";var yb=os(),Ib=Ma(),wb=La(),Cb=Ca(),qt=A(),Ob=V(),Nb=ye(),{getTransactionAuditStorePath:rK,getSchemaPath:sK}=we(),bb=x();Ub.exports=nK;async function nK(e){try{if(Ob.isEmpty(global.hdb_schema[e.schema])||Ob.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await iK(e),await oK(e);let t=sK(e.schema,e.table);try{await Nb.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")bb.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=rK(e.schema,e.table);await Nb.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")bb.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(nK,"lmdbDropTable");async function iK(e){let t=new yb(qt.SYSTEM_SCHEMA_NAME,qt.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await wb(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 Ib(qt.SYSTEM_SCHEMA_NAME,qt.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await Cb(n)}a(iK,"deleteAttributesFromSystem");async function oK(e){let t=new yb(qt.SYSTEM_SCHEMA_NAME,qt.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,qt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await wb(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 Ib(qt.SYSTEM_SCHEMA_NAME,qt.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await Cb(n)}catch(i){throw i}}a(oK,"dropTableFromSystem")});var Lb=m((Aie,Db)=>{"use strict";var aK=require("fs-extra"),cK=os(),uK=Xi(),lK=Ma(),_K=Th(),dK=Ca(),EK=_h(),fK=La(),xs=A(),{getSchemaPath:hK}=we(),{handleHDBError:mK,hdb_errors:SK}=W(),{HDB_ERROR_MSGS:pK,HTTP_STATUS_CODES:TK}=SK;Db.exports=RK;async function RK(e){let t;try{t=await gK(e.schema);let r=new cK(xs.SYSTEM_SCHEMA_NAME,xs.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,xs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[xs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await fK(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await _K(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new lK(xs.SYSTEM_SCHEMA_NAME,xs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await dK(n);let i=hK(t);await aK.remove(i)}catch(r){throw r}}a(RK,"lmdbDropSchema");async function gK(e){let t=new uK(xs.SYSTEM_SCHEMA_NAME,xs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[xs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await EK(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw mK(new Error,pK.SCHEMA_NOT_FOUND(e),TK.NOT_FOUND,void 0,void 0,!0);return s}a(gK,"validateDropSchema")});var gh=m((Nie,Mb)=>{"use strict";var Rh=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};Mb.exports=Rh});var vb=m((Iie,Pb)=>{"use strict";var AK=require("fs-extra"),Rl=ye(),{getTransactionAuditStorePath:OK}=we(),Ah=xe(),yie=gh();Pb.exports=NK;async function NK(e){let t;try{let r=OK(e.schema,e.table);await AK.mkdirp(r),t=await Rl.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{Rl.createDBI(t,Ah.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Rl.createDBI(t,Ah.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Rl.createDBI(t,Ah.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(NK,"createTransactionsAuditEnvironment")});var qb=m((Cie,Fb)=>{"use strict";var Oh=A(),Bb=ye(),bK=Hi(),{getSystemSchemaPath:yK,getSchemaPath:IK}=we(),wK=Vn(),CK=ku(),Nh=xu(),UK=x(),DK=vb(),yh=wK.hdb_table,Hb=[];for(let e=0;e<yh.attributes.length;e++)Hb.push(yh.attributes[e].attribute);Fb.exports=LK;async function LK(e,t){let r=IK(t.schema,t.table),s=new Nh(t.schema,t.table,Oh.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Nh(t.schema,t.table,Oh.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Nh(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Bb.createEnvironment(r,t.table),e!==void 0){let o=await Bb.openEnvironment(yK(),Oh.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await bK.insertRecords(o,yh.hash_attribute,Hb,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await bh(s),await bh(n),await bh(i)}await DK(t)}catch(o){throw o}}a(LK,"lmdbCreateTable");async function bh(e){try{await CK(e)}catch(t){UK.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(bh,"createAttribute")});var xb=m((Die,Gb)=>{"use strict";var MK=ha(),PK=Ra(),vK=_l(),Pa=A(),BK=Hi().updateRecords,HK=ye(),{getSchemaPath:FK}=we(),qK=Ia(),GK=x();Gb.exports=xK;async function xK(e){try{let{schema_table:t,attributes:r}=MK(e);PK(e,r,t.hash_attribute),e.schema!==Pa.SYSTEM_SCHEMA_NAME&&(r.includes(Pa.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Pa.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Pa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Pa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await vK(e.hdb_auth_header,t,r),n=FK(e.schema,e.table),i=await HK.openEnvironment(n,e.table),o=await BK(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await qK(e,o)}catch(c){GK.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(xK,"lmdbUpdateRecords")});var Vb=m((Mie,kb)=>{"use strict";var kK=A().OPERATIONS_ENUM,Ih=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=kK.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};kb.exports=Ih});var Yb=m((Bie,$b)=>{"use strict";var vie=Vb(),VK=ha(),$K=Ra(),YK=_l(),va=A(),KK=Hi().upsertRecords,WK=ye(),{getSchemaPath:QK}=we(),zK=Ia(),JK=x(),{handleHDBError:XK,hdb_errors:ZK}=W();$b.exports=jK;async function jK(e){let t;try{t=VK(e)}catch(u){throw XK(u,u.message,ZK.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;$K(e,s,r.hash_attribute),e.schema!==va.SYSTEM_SCHEMA_NAME&&(s.includes(va.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(va.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(va.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(va.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await YK(e.hdb_auth_header,r,s),i=QK(e.schema,e.table),o=await WK.openEnvironment(i,e.table),c=await KK(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await zK(e,c)}catch(u){JK.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(jK,"lmdbUpsertRecords")});var Wb=m((Fie,Kb)=>{"use strict";var wh=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};Kb.exports=wh});var zb=m((Gie,Qb)=>{"use strict";var Ch=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};Qb.exports=Ch});var Zb=m((Vie,Xb)=>{"use strict";var Uh=ye(),{getTransactionAuditStorePath:e1}=we(),kie=Wb(),Ba=xe(),t1=V(),Jb=zb(),r1=require("util").promisify,s1=r1(setTimeout),n1=1e4,i1=100;Xb.exports=o1;async function o1(e){let t=e1(e.schema,e.table),r=await Uh.openEnvironment(t,e.table,!0),s=Uh.listDBIs(r);Uh.initializeDBIs(r,Ba.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new Jb;do n=await a1(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 s1(i1);while(n.transactions_deleted>0);return i}a(o1,"deleteAuditLogsBefore");async function a1(e,t){let r=new Jb;try{let s=e.dbis[Ba.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[Ba.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];t1.isEmpty(c)||(n=e.dbis[Ba.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Ba.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>n1)break}return await n,r}catch(s){throw s}}a(a1,"deleteTransactions")});var ey=m((Yie,jb)=>{"use strict";var Dh=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};jb.exports=Dh});var ry=m((Qie,ty)=>{"use strict";var c1=os(),u1=Ma(),Wie=ey(),as=A(),l1=V(),Lh=ye(),_1=Vn(),d1=La(),E1=Ca(),{getSchemaPath:f1}=we();ty.exports=h1;async function h1(e,t=!0){let r;e.schema===as.SYSTEM_SCHEMA_NAME?r=_1[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await S1(e),n=f1(e.schema,e.table),i=await Lh.openEnvironment(n,e.table);return t===!0&&await m1(e,i,r.hash_attribute),Lh.dropDBI(i,e.attribute),s}a(h1,"lmdbDropAttribute");async function m1(e,t,r){let s=Lh.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let l={};for(let _ in c)_!==i&&(l[_]=c[_]);n=t.dbis[r].put(o,l,u)}await n}a(m1,"removeAttributeFromAllObjects");async function S1(e){let t=new c1(as.SYSTEM_SCHEMA_NAME,as.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await d1(t)).filter(o=>o[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(l1.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new u1(as.SYSTEM_SCHEMA_NAME,as.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return E1(i)}a(S1,"dropAttributeFromSystem")});var cy=m((Xie,ay)=>{"use strict";var Mh=ye(),Zi=xe(),Jie=vt(),Ph=A(),sy=V(),{getTransactionAuditStorePath:p1}=we(),T1=zi(),gl=Ki(),R1=x();ay.exports=g1;async function g1(e){let t=p1(e.schema,e.table),r=await Mh.openEnvironment(t,e.table,!0),s=Mh.listDBIs(r);Mh.initializeDBIs(r,Zi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Ph.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return ny(r,e.search_values);case Ph.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,O1(r,e.search_values,n);case Ph.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return A1(r,e.search_values);default:return ny(r)}}a(g1,"readAuditLog");function ny(e,t=[0,Date.now()]){sy.isEmpty(t[0])&&(t[0]=0),sy.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[Zi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new gl,n))}a(ny,"searchTransactionsByTimestamp");function A1(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[Zi.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,oy(e,i))}return Object.fromEntries(r)}a(A1,"searchTransactionsByUsername");function O1(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let l=t[c],_=T1.equals(e,Zi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Zi.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,l);for(let{value:d}of _){let E=Number(d);s.has(E)?s.get(E).push(l.toString()):s.set(E,[l.toString()])}}let n=Array.from(s.keys()),i=oy(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],l=u.timestamp,_=s.get(l);iy(u,"records",r,_,o),iy(u,"original_records",r,_,o)}return Object.fromEntries(o)}a(O1,"searchTransactionsByHashValues");function iy(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let l=n.get(u),_=l[l.length-1];if(_.timestamp===i)_[t]=[c];else{let d=new gl(e.operation,e.user_name,i,void 0);d[t]=[c],l.push(d)}}else{let l=new gl(e.operation,e.user_name,i,void 0);l[t]=[c],n.set(u,[l])}}}a(iy,"loopRecords");function oy(e,t){let r=[];try{let s=e.dbis[Zi.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 gl,i);r.push(o)}}catch(i){R1.warn(i)}return r}catch(s){throw s}}a(oy,"batchSearchTransactions")});var ly=m((toe,uy)=>{"use strict";var{getSchemaPath:jie}=we(),eoe=ye(),{database:N1}=(de(),re(Ne));uy.exports={writeTransaction:b1};async function b1(e,t,r){return N1({database:e,table:t}).transaction(r)}a(b1,"writeTransaction")});var fy=m((soe,Ey)=>{"use strict";var{getSchemaPath:_y}=we(),dy=ye();Ey.exports={flush:y1,resetReadTxn:I1};async function y1(e,t){return(await dy.openEnvironment(_y(e,t),t.toString())).flushed}a(y1,"flush");async function I1(e,t){try{(await dy.openEnvironment(_y(e,t),t.toString())).resetReadTxn()}catch{}}a(I1,"resetReadTxn")});var py=m((ioe,Sy)=>{"use strict";var{Readable:w1}=require("stream"),{getDatabases:C1}=(de(),re(Ne)),{readSync:U1,openSync:D1,createReadStream:hy}=require("fs"),{open:L1}=require("lmdb"),my=Du(),M1=Mu(),{INTERNAL_DBIS_NAME:P1}=xe();Sy.exports=B1;var vh=32768,v1=100;async function B1(e){let t=e.database||e.schema||"data",r=C1()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let l=r[n[0]];if(!l)throw new Error(`Can not find table ${n[0]}`);let _=l.dbisDB,d=L1({noSync:!0,maxDbs:M1.MAX_DBS}),E,f=d.openDB(P1,new my(!1)),h=_.useReadTransaction(),T=0;for(let{key:R,value:O}of _.getRange({transaction:h,start:!1}))if(n.some(k=>R.startsWith?.(k+"/"))){f.put(R,O);let[,k]=R.split("/"),$=!k,U=new my(!$,$);U.encoding="binary";let b=d.openDB(R,U),P=_.openDB(R,U);for(let{key:z,version:F,value:Oe}of P.getRange({transaction:h,versions:$}))E=b.put(z,Oe,F),T++%v1===0&&await new Promise(Ze=>setTimeout(Ze,20))}await E;let p=hy(d.path);return p.headers=u(),p.on("close",()=>{h.done(),d.close()}),p}let o=r[Object.keys(r)[0]].primaryStore,c=D1(o.path);return o.transaction(()=>{let l=Buffer.alloc(vh);U1(c,l,0,vh);let _=o.useReadTransaction(),d=hy(null,{fd:c,start:vh}),E=new w1.from(async function*(){yield l;for await(let f of d)yield f;_.done()}());return E.headers=u(),E});function u(){let l=new Map;return l.set("content-type","application/octet-stream"),l.set("content-disposition",`attachment; filename="${t}"`),l.set("date",s),l}}a(B1,"getBackup")});var gy=m((aoe,Ry)=>{"use strict";var H1=x(),{handleHDBError:F1}=W(),q1=Fg(),G1=ku(),x1=nh(),k1=LN(),V1=Ca(),$1=_h(),Y1=nb(),K1=Eb(),W1=La(),Q1=gb(),z1=Lb(),J1=qb(),X1=xb(),Z1=Yb(),j1=Zb(),eW=Th(),tW=ry(),rW=cy(),sW=ly(),Ty=fy(),nW=py(),Bh=class extends q1{static{a(this,"LMDBBridge")}async searchByConditions(t){return Q1(t)}async getDataByHash(t){return await $1(t)}async searchByHash(t){return await Y1(t)}async getDataByValue(t,r){return await K1(t,r)}async searchByValue(t){return await W1(t)}async createSchema(t){return await k1(t)}async dropSchema(t){return await z1(t)}async createTable(t,r){return await J1(t,r)}async dropTable(t){return await eW(t)}async createAttribute(t){return await G1(t)}async createRecords(t){return await x1(t)}async updateRecords(t){return await X1(t)}async upsertRecords(t){try{return await Z1(t)}catch(r){throw F1(r,null,null,H1.ERR,r)}}async deleteRecords(t){return await V1(t)}async dropAttribute(t){return await tW(t)}async deleteAuditLogsBefore(t){return await j1(t)}async readAuditLog(t){return await rW(t)}writeTransaction(t,r,s){return sW.writeTransaction(t,r,s)}flush(t,r){return Ty.flush(t,r)}resetReadTxn(t,r){return Ty.resetReadTxn(t,r)}getBackup(t){return nW(t)}};Ry.exports=Bh});var Uy={};je(Uy,{ResourceBridge:()=>qh});function Gh({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function Oy(e,t){let r=cs(e),s=Gh(e,r);if(!r)throw new qr.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user};return Ye(i,async function*(o){for(let c of e.hash_values){let u=await r.get({id:c,lazy:n,select:s},i);u=u&&Ou(u),t?yield{key:c,value:u}:yield u}})}function cs(e){let t=e.database||e.schema||oW,r=Gr()[t];if(!r)throw(0,qr.handleHDBError)(new Error,iW.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function Ny(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*by(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:o,timestamp:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(o),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[o],records:[u]})}s&&(yield s)}var yy,Al,qr,Iy,wy,xr,Hh,Fh,Cy,iW,oW,aW,cW,Ay,qh,Dy=Se(()=>{"use strict";yy=C(gy()),Al=C(Ji()),qr=C(W());de();Iy=C(ha()),wy=C(Ra()),xr=C(A()),Hh=C(qs()),Fh=C(Fr()),Cy=C(V());xn();Nu();({HDB_ERROR_MSGS:iW}=qr.hdb_errors),oW="data",aW=1e4,cW=10,qh=class extends yy.default{static{a(this,"ResourceBridge")}constructor(t){super(t),Ay=this}async searchByConditions(t){let r=(0,Al.default)(t,"conditions");if(r)throw(0,qr.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=cs(t);if(!s)throw new qr.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i=>({attribute:i.search_attribute,comparator:i.search_type,value:i.search_value}));return s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Gh(t,s),allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let o of s)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new qr.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}rt({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await cs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=cs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=a((o,c,u)=>(c=Object.assign({},c),delete c[s],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(l=>{if(!l){let{value:_,version:d}=r.primaryStore.getEntry(o);return i(o,_,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))n=i(o,c,u),await new Promise(l=>setImmediate(l));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){cs(t).dropTable()}createSchema(t){return Ha({database:t.schema,table:null}),Hh.signalSchemaChange(new Fh.SchemaEventMsg(process.pid,xr.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await xh(t.schema),Hh.signalSchemaChange(new Fh.SchemaEventMsg(process.pid,xr.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,Ay.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,Iy.default)(t);(0,wy.default)(t,s,r.primaryKey);let n,i=Gr()[t.schema][t.table],o={user:t.hdb_user};return Ye(o,async c=>{if(!i.schemaDefined){n=[];for(let _ of s)i.attributes.find(E=>E.name==_)||n.push(_);n.length>0&&await i.addAttributes(n.map(_=>({name:_,indexed:!0})))}let u=[],l=[];for(let _ of t.records){let d=await i.get(_[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){l.push(_[i.primaryKey]);continue}d&&(d=Ou(d));for(let E in _)if(Object.prototype.hasOwnProperty.call(_,E)){let f=_[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,_[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(_),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(_,E)||(_[E]=d[E]);await i.put(_,o),u.push(_[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:l}})}async deleteRecords(t){let r=Gr()[t.schema][t.table],s={user:t.hdb_user};return Ye(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,s)?o.push(u):c.push(u);return Ny(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Gr()[t.schema][t.table];if(!r.createdTimeProperty)throw new qr.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:xr.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],l=a(async()=>{let _=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(..._.deleted_hashes),o.push(..._.skipped_hashes),await(0,Cy.async_set_timeout)(cW),u=[],n=!0},"chunkDelete");for await(let _ of s)u.push(_[r.primaryKey]),c++,c%aW===0&&await l();return u.length>0&&await l(),n?Ny(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){let r=(0,Al.default)(t,"hashes");if(r)throw r;return Oy(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of Oy(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&xr.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);let s=(0,Al.default)(t,"value");if(s)throw s;let n=cs(t);if(!n)throw new qr.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===xr.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Gh(t,n)})}async getDataByValue(t,r){let s=new Map,n=cs(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){cs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return cs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=cs(t),s={};switch(t.search_type){case xr.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case xr.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of by(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return by(r,t.search_values?.[0],t.search_values?.[1])}}};a(Gh,"getSelect");a(Oy,"getRecords");a(cs,"getTable");a(Ny,"createDeleteResponse");a(by,"groupRecordsInHistory")});var Br=m((Eoe,Ly)=>{"use strict";var{ResourceBridge:uW}=(Dy(),re(Uy)),lW=Q();lW.initSync();var Ol;function _W(){return Ol||(Ol=new uW,Ol)}a(_W,"getBridge");Ly.exports=_W()});var By=m((hoe,vy)=>{"use strict";var My=require("lodash"),Fa=require("mathjs"),dW=require("jsonata"),Py=V();vy.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?My.uniqWith(e,My.isEqual):e,searchJSON:EW,mad:qa.bind(null,Fa.mad),mean:qa.bind(null,Fa.mean),mode:qa.bind(null,Fa.mode),prod:qa.bind(null,Fa.prod),median:qa.bind(null,Fa.median)};function qa(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(qa,"aggregateFunction");function EW(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(Py.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),Py.isEmpty(this.__ala__.res[r])){let s=dW(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(EW,"searchJSON")});var Fy=m((Soe,Hy)=>{"use strict";var We=require("moment"),kh="YYYY-MM-DDTHH:mm:ss.SSSZZ";We.suppressDeprecationWarnings=!0;Hy.exports={current_date:()=>We().utc().format("YYYY-MM-DD"),current_time:()=>We().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return We(e).utc().format("YYYY");case"month":return We(e).utc().format("MM");case"day":return We(e).utc().format("DD");case"hour":return We(e).utc().format("HH");case"minute":return We(e).utc().format("mm");case"second":return We(e).utc().format("ss");case"millisecond":return We(e).utc().format("SSS");default:break}},date:e=>We(e).utc().format(kh),date_format:(e,t)=>We(e).utc().format(t),date_add:(e,t,r)=>We(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>We(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=We(e).utc(),n=We(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>We().utc().valueOf(),get_server_time:()=>We().format(kh),offset_utc:(e,t)=>We(e).utc().utcOffset(t).format(kh)}});var ky=m((poe,xy)=>{"use strict";var fW=require("@turf/area"),hW=require("@turf/length"),mW=require("@turf/circle"),SW=require("@turf/difference"),pW=require("@turf/distance"),TW=require("@turf/boolean-contains"),RW=require("@turf/boolean-equal"),gW=require("@turf/boolean-disjoint"),AW=require("@turf/helpers"),qy=A(),le=V();xy.exports={geoArea:OW,geoLength:NW,geoCircle:bW,geoDifference:yW,geoDistance:Gy,geoNear:IW,geoContains:wW,geoEqual:CW,geoCrosses:UW,geoConvert:DW};var Vh="geo1 is required",$h="geo2 is required";function OW(e){if(le.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),fW.default(e)}a(OW,"geoArea");function NW(e,t){if(le.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),hW.default(e,{units:t||"kilometers"})}a(NW,"geoLength");function bW(e,t,r){if(le.isEmpty(e))throw new Error("point is required");if(le.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),mW.default(e,t,{units:r||"kilometers"})}a(bW,"geoCircle");function yW(e,t){if(le.isEmpty(e))throw new Error("poly1 is required");if(le.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),SW(e,t)}a(yW,"geoDifference");function Gy(e,t,r){if(le.isEmpty(e))throw new Error("point1 is required");if(le.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),pW.default(e,t,{units:r||"kilometers"})}a(Gy,"geoDistance");function IW(e,t,r,s){if(le.isEmpty(e))throw new Error("point1 is required");if(le.isEmpty(t))throw new Error("point2 is required");if(le.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");return Gy(e,t,s)<=r}a(IW,"geoNear");function wW(e,t){if(le.isEmpty(e))throw new Error(Vh);if(le.isEmpty(e))throw new Error($h);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),TW.default(e,t)}a(wW,"geoContains");function CW(e,t){if(le.isEmpty(e))throw new Error(Vh);if(le.isEmpty(e))throw new Error($h);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),RW.default(e,t)}a(CW,"geoEqual");function UW(e,t){if(le.isEmpty(e))throw new Error(Vh);if(le.isEmpty(e))throw new Error($h);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),!gW.default(e,t)}a(UW,"geoCrosses");function DW(e,t,r){if(le.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(le.isEmpty(t))throw new Error("geo_type is required");if(le.isEmpty(qy.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(qy.GEO_CONVERSION_ENUM).join(",")}`);return AW[t](e,r)}a(DW,"geoConvert")});var Nl=m((Roe,Vy)=>{var si=By(),ur=Fy(),us=ky();Vy.exports=e=>{e.aggr.mad=e.aggr.MAD=si.mad,e.aggr.mean=e.aggr.MEAN=si.mean,e.aggr.mode=e.aggr.MODE=si.mode,e.aggr.prod=e.aggr.PROD=si.prod,e.aggr.median=e.aggr.MEDIAN=si.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=si.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=si.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=ur.current_date,e.fn.current_time=e.fn.CURRENT_TIME=ur.current_time,e.fn.extract=e.fn.EXTRACT=ur.extract,e.fn.date=e.fn.DATE=ur.date,e.fn.date_format=e.fn.DATE_FORMAT=ur.date_format,e.fn.date_add=e.fn.DATE_ADD=ur.date_add,e.fn.date_sub=e.fn.DATE_SUB=ur.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=ur.date_diff,e.fn.now=e.fn.NOW=ur.now,e.fn.offset_utc=e.fn.OFFSET_UTC=ur.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=ur.get_server_time,e.fn.getdate=e.fn.GETDATE=ur.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=ur.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=us.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=us.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=us.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=us.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=us.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=us.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=us.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=us.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=us.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=us.geoNear}});var Wy=m((goe,Ky)=>{"use strict";var Ga=require("lodash"),pt=require("alasql");pt.options.cache=!1;var LW=Nl(),$y=require("clone"),bl=require("recursive-iterator"),se=x(),ne=V(),ji=Br(),MW=A(),{hdb_errors:PW}=W(),{getDatabases:Yy}=(de(),re(Ne)),vW="IS NULL",kr="There was a problem performing this search. Please check the logs and try again.";LW(pt);var Yh=class{static{a(this,"SQLSearch")}constructor(t,r){if(ne.isEmpty(t))throw se.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(),ne.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!ne.isEmptyOrZeroLength(s))return se.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw se.error("Error thrown from checkEmptySQL in SQLSearch class method search."),se.error(s),new Error(kr)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw se.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),se.error(s),new Error(kr)}if(Object.keys(this.data).length===0)return se.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw se.error("Error thrown from processJoins in SQLSearch class method search."),se.error(s),new Error(kr)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw se.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),se.error(s),new Error(kr)}try{return t=await this._finalSQL(),t}catch(s){throw se.error("Error thrown from finalSQL in SQLSearch class method search."),se.error(s),new Error(kr)}}_getColumns(){let t=new bl(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($y(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Ga.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=Yy()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(ne.isEmpty(this.statement.where)){se.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new bl(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!ne.isEmpty(r)&&r.right)if(ne.isNotEmptyAndHasValue(r.right.value)){let s=ne.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new pt.yy.LogicValue({value:s}):r.right instanceof pt.yy.StringValue&&!ne.isEmpty(s)&&ne.autoCasterIsNumberCheck(s.toString())&&(r.right=new pt.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=ne.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new pt.yy.LogicValue({value:i}):s instanceof pt.yy.StringValue&&ne.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new pt.yy.NumValue({value:i}))});if(t){se.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new bl(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(!ne.isEmpty(MW.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(ne.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(ne.isEmptyOrZeroLength(r.left.columnid)||ne.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(ne.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"=":!ne.isEmpty(r.right.value)||!ne.isEmpty(r.left.value)?s.add(ne.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let l=0;l<u.length;l++)if(u[l].value)s.add(u[l].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(ne.isEmptyOrZeroLength(this.all_table_attributes)&&ne.isEmptyOrZeroLength(this.statement.from)&&ne.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&&Ga.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(ne.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);ne.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(ne.isEmptyOrZeroLength(this.all_table_attributes)&&!ne.isEmptyOrZeroLength(this.columns.columns))return t;if(ne.isEmptyOrZeroLength(this.all_table_attributes)&&ne.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await pt.promise(r)}catch(r){throw se.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),se.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($y(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(ne.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(vW)>-1&&this.tables.forEach(n=>{let i={columnid:Yy()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Ga.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,l=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!ne.isEmpty(this.exact_search_values[l])&&!this.exact_search_values[l].ignore&&!ne.isEmptyOrZeroLength(this.exact_search_values[l].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[l].values);let _=await ji.getDataByHash(c);for(let d of c.hash_values)_.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(_){throw se.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),se.error(_),new Error(kr)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[l].values).map(async _=>{let d=Object.assign({},c);d.search_value=_;let E=await ji.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]):(this.data[i].__merged_data[f]=[...s[i]],this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(f)))}))}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),se.error(_),new Error(kr)}else if(!ne.isEmpty(this.comparator_search_values[l])&&!this.comparator_search_values[l].ignore&&!ne.isEmptyOrZeroLength(this.comparator_search_values[l].comparators))try{let _=this.comparator_search_values[l].comparators;for(let d=0,E=_.length;d<E;d++){let f=_[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ji.getDataByValue(c,f.operation);if(u)for(let[T]of h)this.data[i].__merged_data[T]||(this.data[i].__merged_data[T]=[...s[i]],this._setMergedHashAttribute(i,ne.autoCast(T)));else for(let[T,p]of h)this.data[i].__merged_data[T]?this._updateMergedAttribute(i,T,n.attribute,p[n.attribute]):(this.data[i].__merged_data[T]=[...s[i]],this._updateMergedAttribute(i,T,n.attribute,p[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(T)))}}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),se.error(_),new Error(kr)}else try{c.search_attribute=n.attribute,c.search_value="*";let _=await ji.getDataByValue(c);if(u)for(let[d]of _)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,ne.autoCast(d)));else for(let[d,E]of _)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(d)))}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),se.error(_),new Error(kr)}}}_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 pt.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 pt.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new pt.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 pt.yy.FuncValue:new pt.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,T=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${T}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${T}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"",l="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(l="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let _="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(_=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${l} ${_} ${d}`,h=this._convertColumnsToIndexes(f,n);E=await pt.promise(h,t),t=null}catch(f){throw se.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),se.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let T=E[f];o.forEach(p=>{T[p.key]!==null&&T[p.key]!==void 0&&p.keys.add(T[p.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),T=Ga.difference(h,[...f.keys].map(p=>p.toString()));for(let p=0,R=T.length;p<R;p++){let O=T[p];delete this.data[`${f.schema}_${f.table}`].__merged_data[O]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new bl(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=Ga.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw se.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),se.error(i),new Error(kr)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let _ in i)o.push(i[_][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await ji.getDataByHash(c),l=n.columns.length;for(let _=0,d=o.length;_<d;_++){let E=o[_],f=u.get(E);for(let h=0;h<l;h++){let T=n.columns[h],p=f[T]===void 0?null:f[T];this.data[s].__merged_data[E].push(p)}}}}catch(r){throw se.error("Error thrown from getDataByHash function in SQLSearch class method getData."),se.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(this.statement.limit&&delete this.statement.limit,this.statement.offset&&delete this.statement.offset);let s;try{let n=this._buildSQL();se.trace(`Final SQL: ${n}`),s=await pt.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),se.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw se.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),se.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 se.error(PW.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),se.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return this.statement.columns.forEach(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=n[i],l=new RegExp(`${u}.\`${o}\``,"g"),_=`${u}.[${c}]`;s=s.replace(l,_)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),l=`[${c}]`;s=s.replace(u,l)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await ji.getDataByValue(i);for(let[c,u]of o)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(o){throw se.error("There was an error when processing this SQL operation. Check your logs"),se.error(o),new Error(kr)}}return Object.values(Object.values(this.data)[0].__merged_data)}};Ky.exports=Yh});var gr=m((Ooe,Qy)=>{"use strict";var BW=Bg();Qy.exports={searchByConditions:FW,searchByHash:qW,searchByValue:GW,search:xW};var Kh=Br(),{transformReq:Wh}=V(),HW=Wy();async function FW(e){return Wh(e),Kh.searchByConditions(e)}a(FW,"searchByConditions");async function qW(e){Wh(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Kh.searchByHash(e))r&&t.push(r);return t}a(qW,"searchByHash");async function GW(e){Wh(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Kh.searchByValue(e))t.push(r);return t}a(GW,"searchByValue");function xW(e,t){try{let r=new BW(e);r.validate(),new HW(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(xW,"search")});var yl=m((boe,zy)=>{"use strict";var kW=Br();zy.exports={writeTransaction:VW};function VW(e,t,r){return kW.writeTransaction(e,t,r)}a(VW,"writeTransaction")});var jy=m((woe,Zy)=>{"use strict";var $W=gr(),YW=_n(),Jy=x(),KW=Ar(),Ioe=yl(),WW=require("clone"),zh=require("alasql"),QW=Nl(),Xy=require("util"),zW=Xy.promisify(YW.getTableSchema),JW=Xy.promisify($W.search),XW=A(),Qh=V();QW(zh);Zy.exports={update:jW};var ZW="There was a problem performing this update. Please check the logs and try again.";async function jW({statement:e,hdb_user:t}){let r=await zW(e.table.databaseid,e.table.tableid),s=eQ(e.columns);Qh.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=WW(n),c=Qh.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,l=zh.parse(u).statements[0],_=await JW(l),d=tQ(s,_);return rQ(o,d,t)}a(jW,"update");function eQ(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=zh.compile(`SELECT ${r.expression.toString()} AS [${XW.FUNC_VAL}] FROM ?`)}),t}catch(t){throw Jy.error(t),new Error(ZW)}}a(eQ,"createUpdateRecord");function tQ(e,t){return Qh.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(tQ,"buildUpdateRecords");async function rQ(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await KW.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){Jy.error(`Error delete new_attributes from update response: ${i}`)}return n}a(rQ,"updateRecords")});var tI=m((Loe,eI)=>{var sQ=require("alasql"),nQ=gr(),iQ=x(),oQ=Br(),Xh=require("util"),Jh=V(),aQ=A(),cQ=_n(),Uoe=yl(),Doe=Ar(),uQ="record",lQ="successfully deleted",_Q=Xh.callbackify(hQ),dQ=Xh.promisify(nQ.search),EQ=Xh.promisify(cQ.getTableSchema);eI.exports={convertDelete:_Q};function fQ(e){return`${e.deleted_hashes.length} ${uQ}${e.deleted_hashes.length===1?"":"s"} ${lQ}`}a(fQ,"generateReturnMessage");async function hQ({statement:e,hdb_user:t}){let r=await EQ(e.table.databaseid,e.table.tableid);Jh.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=Jh.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=sQ.parse(o).statements[0],u={operation:aQ.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await dQ(c);let l=await oQ.deleteRecords(u);return Jh.isEmptyOrZeroLength(l.message)&&(l.message=fQ(l)),delete l.txn_time,l}catch(l){throw iQ.error(l),l.hdb_code?l.message:l}}a(hQ,"convertDelete")});var oI=m((Poe,iI)=>{"use strict";var mQ=Yn(),{hdb_errors:rI}=W(),{getDatabases:sI}=(de(),re(Ne));iI.exports={checkSchemaExists:nI,checkSchemaTableExists:SQ,schema_describe:mQ};async function nI(e){if(!sI()[e])return rI.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(nI,"checkSchemaExists");async function SQ(e,t){let r=await nI(e);if(r)return r;if(!sI()[e][t])return rI.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(SQ,"checkSchemaTableExists")});var Ul=m((Hoe,lI)=>{"use strict";var eo=Gu(),to=oI(),pQ=x(),TQ=require("uuid").v4,Boe=require("clone"),wl=qs(),ro=A(),RQ=require("util"),Tn=Br(),{handleHDBError:Gt,hdb_errors:gQ}=W(),{HDB_ERROR_MSGS:Il,HTTP_STATUS_CODES:xt}=gQ,{SchemaEventMsg:Cl}=Fr(),aI=nt(),{getDatabases:AQ}=(de(),re(Ne)),{transformReq:so}=V();lI.exports={createSchema:OQ,createSchemaStructure:cI,createTable:NQ,createTableStructure:uI,createAttribute:CQ,dropSchema:bQ,dropTable:yQ,dropAttribute:IQ,getBackup:UQ};async function OQ(e){let t=await cI(e);return wl.signalSchemaChange(new Cl(process.pid,e.operation,e.schema)),t}a(OQ,"createSchema");async function cI(e){let t=eo.schema_object(e);if(t)throw Gt(t,t.message,xt.BAD_REQUEST,void 0,void 0,!0);if(so(e),!await to.checkSchemaExists(e.schema))throw Gt(new Error,Il.SCHEMA_EXISTS_ERR(e.schema),xt.BAD_REQUEST,ro.LOG_LEVELS.ERROR,Il.SCHEMA_EXISTS_ERR(e.schema),!0);return await Tn.createSchema(e),`database '${e.schema}' successfully created`}a(cI,"createSchemaStructure");async function NQ(e){return so(e),await uI(e)}a(NQ,"createTable");async function uI(e){let t=eo.create_table_object(e);if(t)throw Gt(t,t.message,xt.BAD_REQUEST,void 0,void 0,!0);if(eo.validateTableResidence(e.residence),!await to.checkSchemaTableExists(e.schema,e.table))throw Gt(new Error,Il.TABLE_EXISTS_ERR(e.schema,e.table),xt.BAD_REQUEST,ro.LOG_LEVELS.ERROR,Il.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:TQ(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await Tn.createTable(s,e);else throw Gt(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",xt.BAD_REQUEST);else await Tn.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(uI,"createTableStructure");async function bQ(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=eo.schema_object(e),s=t??r;if(s)throw Gt(s,s.message,xt.BAD_REQUEST,void 0,void 0,!0);so(e);let n=await to.checkSchemaExists(e.schema);if(n)throw Gt(new Error,n,xt.NOT_FOUND,ro.LOG_LEVELS.ERROR,n,!0);let i=await to.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await Tn.dropSchema(e),wl.signalSchemaChange(new Cl(process.pid,e.operation,e.schema)),await aI.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(bQ,"dropSchema");async function yQ(e){let t=eo.table_object(e);if(t)throw Gt(t,t.message,xt.BAD_REQUEST,void 0,void 0,!0);so(e);let r=await to.checkSchemaTableExists(e.schema,e.table);if(r)throw Gt(new Error,r,xt.NOT_FOUND,ro.LOG_LEVELS.ERROR,r,!0);return await Tn.dropTable(e),await aI.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(yQ,"dropTable");async function IQ(e){let t=eo.attribute_object(e);if(t)throw Gt(t,t.message,xt.BAD_REQUEST,void 0,void 0,!0);so(e);let r=await to.checkSchemaTableExists(e.schema,e.table);if(r)throw Gt(new Error,r,xt.NOT_FOUND,ro.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Gt(new Error,"You cannot drop a hash attribute",xt.BAD_REQUEST,void 0,void 0,!0);if(ro.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Gt(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,xt.BAD_REQUEST,void 0,void 0,!0);try{return await Tn.dropAttribute(e),wQ(e),wl.signalSchemaChange(new Cl(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw pQ.error(`Got an error deleting attribute ${RQ.inspect(e)}.`),s}}a(IQ,"dropAttribute");function wQ(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(wQ,"dropAttributeFromGlobal");async function CQ(e){so(e);let t=AQ()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw Gt(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,xt.BAD_REQUEST,void 0,void 0,!0);return await Tn.createAttribute(e),wl.signalSchemaChange(new Cl(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(CQ,"createAttribute");function UQ(e){return Tn.getBackup(e)}a(UQ,"getBackup")});var dI=m((qoe,_I)=>{"use strict";var{OPERATIONS_ENUM:DQ}=A(),Zh=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=DQ.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};_I.exports=Zh});var jh=m((koe,SI)=>{"use strict";var LQ=Br(),xoe=dI(),Dl=V(),Ll=A(),MQ=Q(),{handleHDBError:EI,hdb_errors:PQ}=W(),{HDB_ERROR_MSGS:fI,HTTP_STATUS_CODES:hI}=PQ,vQ=Object.values(Ll.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),mI="To use this operation audit log must be enabled in harperdb-config.yaml";SI.exports=BQ;async function BQ(e){if(Dl.isEmpty(e.schema))throw new Error(fI.SCHEMA_REQUIRED_ERR);if(Dl.isEmpty(e.table))throw new Error(fI.TABLE_REQUIRED_ERR);if(!MQ.get(Ll.CONFIG_PARAMS.LOGGING_AUDITLOG))throw EI(new Error,mI,hI.BAD_REQUEST,Ll.LOG_LEVELS.ERROR,mI,!0);let t=Dl.checkSchemaTableExist(e.schema,e.table);if(t)throw EI(new Error,t,hI.NOT_FOUND,Ll.LOG_LEVELS.ERROR,t,!0);if(!Dl.isEmpty(e.search_type)&&vQ.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await LQ.readAuditLog(e)}a(BQ,"readAuditLog")});var TI=m(($oe,pI)=>{"use strict";var{OPERATIONS_ENUM:HQ}=A(),em=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=HQ.GET_BACKUP,this.schema=t,this.table=r}};pI.exports=em});var AI=m((Qoe,gI)=>{"use strict";var FQ=Br(),Koe=TI(),tm=V(),qQ=A(),Woe=Q(),{handleHDBError:GQ,hdb_errors:xQ}=W(),{HDB_ERROR_MSGS:RI,HTTP_STATUS_CODES:kQ}=xQ;gI.exports=VQ;async function VQ(e){if(tm.isEmpty(e.schema))throw new Error(RI.SCHEMA_REQUIRED_ERR);if(tm.isEmpty(e.table))throw new Error(RI.TABLE_REQUIRED_ERR);let t=tm.checkSchemaTableExist(e.schema,e.table);if(t)throw GQ(new Error,t,kQ.NOT_FOUND,qQ.LOG_LEVELS.ERROR,t,!0);return await FQ.getBackup(read_audit_log_object)}a(VQ,"getBackup")});var wI=m((Joe,II)=>{var Rn=require("validate.js"),NI=ve(),no=A(),{handleHDBError:$Q,hdb_errors:YQ}=W(),{HDB_ERROR_MSGS:Ve,HTTP_STATUS_CODES:KQ}=YQ,rm=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),WQ={STRUCTURE_USER:"structure_user"},OI=Object.values(no.ROLE_TYPES_ENUM),QQ="attribute_permissions",zQ="attribute_name",{PERMS_CRUD_ENUM:io}=no,JQ=[QQ,...Object.values(io)],bI=[io.READ,io.INSERT,io.UPDATE],XQ=[zQ,...bI];function ZQ(e){let t=rm();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,yI(e,t)}a(ZQ,"addRoleValidation");function jQ(e){let t=rm();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,yI(e,t)}a(jQ,"alterRoleValidation");function ez(e){let t=rm();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,NI.validateObject(e,t)}a(ez,"dropRoleValidation");var tz=["operation","role","id","permission","hdb_user","hdb_auth_header"];function yI(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)tz.includes(s[o])||n.push(s[o]);n.length>0&&Qe(Ve.INVALID_ROLE_JSON_KEYS(n),r);let i=NI.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Qe(o,r)}),e.permission){let o=rz(e);o&&Qe(o,r),OI.forEach(c=>{e.permission[c]&&!Rn.isBoolean(e.permission[c])&&Qe(Ve.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(OI.indexOf(o)<0){if(o===WQ.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let l=0,_=u.length;l<_;l++){let d=u[l];global.hdb_schema[d]||Qe(Ve.SCHEMA_NOT_FOUND(d),r)}continue}Qe(Ve.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Qe(Ve.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let l=c.tables[u];if(!u||!global.hdb_schema[o][u]){Qe(Ve.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(l).forEach(_=>{JQ.includes(_)||Qe(Ve.INVALID_PERM_KEY(_),r,o,u)}),Object.values(io).forEach(_=>{Rn.isDefined(l[_])?Rn.isBoolean(l[_])||Qe(Ve.TABLE_PERM_NOT_BOOLEAN(_),r,o,u):Qe(Ve.TABLE_PERM_MISSING(_),r,o,u)}),Rn.isDefined(l.attribute_permissions)){if(!Rn.isArray(l.attribute_permissions)){Qe(Ve.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Qe(Ve.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(l.attribute_permissions){let _=global.hdb_schema[o][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in l.attribute_permissions){let f=l.attribute_permissions[E];if(Object.keys(f).forEach(T=>{!XQ.includes(T)&&T!==io.DELETE&&Qe(Ve.INVALID_ATTR_PERM_KEY(T),r,o,u)}),!Rn.isDefined(f.attribute_name)){Qe(Ve.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!_.includes(h)){Qe(Ve.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}bI.forEach(T=>{Rn.isDefined(f[T])?Rn.isBoolean(f[T])||Qe(Ve.ATTR_PERM_NOT_BOOLEAN(T,h),r,o,u):Qe(Ve.ATTR_PERM_MISSING(T,h),r,o,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(l.read===!1&&d.read===!0||l.insert===!1&&d.insert===!0||l.update===!1&&d.update===!0){let E=`${o}.${u}`;Qe(Ve.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return sz(r)}a(yI,"customValidate");II.exports={addRoleValidation:ZQ,alterRoleValidation:jQ,dropRoleValidation:ez};function rz(e){let{operation:t,permission:r}=e;if(t===no.OPERATIONS_ENUM.ADD_ROLE||t===no.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 Ve.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?no.ROLE_TYPES_ENUM.SUPER_USER:no.ROLE_TYPES_ENUM.CLUSTER_USER;return Ve.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(rz,"validateNoSUPerms");function sz(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:Ve.ROLE_PERMS_ERROR,...e};return $Q(new Error,s,KQ.BAD_REQUEST)}else return null}a(sz,"generateRolePermResponse");function Qe(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(Qe,"addPermError")});var cm=m((Zoe,LI)=>{"use strict";var CI=Ar(),UI=gr(),nz=Jn(),nm=wI(),im=qs(),iz=require("uuid").v4,oz=require("util"),Ml=A(),az=V(),om=UI.searchByValue,cz=UI.searchByHash,uz=oz.promisify(nz.delete),lz=os(),_z=Xi(),{hdb_errors:dz,handleHDBError:oo}=W(),{HDB_ERROR_MSGS:DI,HTTP_STATUS_CODES:Pl}=dz,{UserEventMsg:am}=Fr();LI.exports={addRole:Ez,alterRole:fz,dropRole:hz,listRoles:mz};function sm(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(sm,"scrubRoleDetails");async function Ez(e){let t=nm.addRoleValidation(e);if(t)throw t;e=sm(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},s;try{s=Array.from(await om(r)||[])}catch(i){throw oo(i)}if(s&&s.length>0)throw oo(new Error,DI.ROLE_ALREADY_EXISTS(e.role),Pl.CONFLICT,void 0,void 0,!0);e.id||(e.id=iz());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await CI.insert(n),im.signalUserChange(new am(process.pid)),e=sm(e),e}a(Ez,"addRole");async function fz(e){let t=nm.alterRoleValidation(e);if(t)throw t;e=sm(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await CI.update(r)}catch(n){throw oo(n)}if(s&&s?.message==="updated 0 of 1 records")throw oo(new Error,"Invalid role id",Pl.BAD_REQUEST,void 0,void 0,!0);return await im.signalUserChange(new am(process.pid)),e}a(fz,"alterRole");async function hz(e){let t=nm.dropRoleValidation(e);if(t)throw oo(new Error,t,Pl.BAD_REQUEST,void 0,void 0,!0);let r=new _z(Ml.SYSTEM_SCHEMA_NAME,Ml.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await cz(r));if(s.length===0)throw oo(new Error,DI.ROLE_NOT_FOUND,Pl.NOT_FOUND,void 0,void 0,!0);let n=new lz(Ml.SYSTEM_SCHEMA_NAME,Ml.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await om(n)),o=!1;if(az.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].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 uz(c),im.signalUserChange(new am(process.pid)),`${s[0].role} successfully deleted`}a(hz,"dropRole");async function mz(){return om({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(mz,"listRoles")});var BI=m((eae,vI)=>{"use strict";var Sz=Q(),gn=require("joi"),pz=ve(),MI=require("moment"),Tz=require("fs-extra"),um=require("path"),Rz=require("lodash"),xa=A(),{LOG_LEVELS:ni}=A(),gz="YYYY-MM-DD hh:mm:ss",Az=um.resolve(__dirname,"../logs");vI.exports=function(e){return pz.validateBySchema(e,Oz)};var Oz=gn.object({from:gn.custom(PI),until:gn.custom(PI),level:gn.valid(ni.NOTIFY,ni.FATAL,ni.ERROR,ni.WARN,ni.INFO,ni.DEBUG,ni.TRACE),order:gn.valid("asc","desc"),limit:gn.number().min(1),start:gn.number().min(0),log_name:gn.custom(Nz)});function PI(e,t){if(MI(e,MI.ISO_8601).format(gz)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(PI,"validateDatetime");function Nz(e,t){if(Rz.invert(xa.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=Sz.get(xa.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?xa.LOG_NAMES.HDB:e,i=n===xa.LOG_NAMES.INSTALL?um.join(Az,xa.LOG_NAMES.INSTALL):um.join(s,n);return Tz.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Nz,"validateReadLogPath")});var _m=m((rae,FI)=>{"use strict";var vl=A(),bz=x(),yz=Q(),Iz=BI(),lm=require("path"),HI=require("fs-extra"),{once:wz}=require("events"),{handleHDBError:Cz,hdb_errors:Uz}=W(),{PACKAGE_ROOT:Dz}=A(),Lz=lm.join(Dz,"logs"),Mz=1e3,Pz=200;FI.exports=vz;async function vz(e){let t=Iz(e);if(t)throw Cz(t,t.message,Uz.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=yz.get(vl.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?vl.LOG_NAMES.HDB:e.log_name,n=s===vl.LOG_NAMES.INSTALL?lm.join(Lz,vl.LOG_NAMES.INSTALL):lm.join(r,s),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,l=e.until!==void 0,_=l?new Date(e.until):void 0,d=e.limit===void 0?Mz:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,T=0;E==="desc"&&!u&&!_&&(T=Math.max(HI.statSync(n).size-(h+5)*Pz,0));let p=HI.createReadStream(n,{start:T});p.on("error",b=>{bz.error(b)});let R=0,O=[],k="",$;p.on("data",b=>{let P=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;b=k+b;let z=0,F;for(;(F=P.exec(b))&&!p.destroyed;){$&&($.message=b.slice(z,F.index),U($));let[Oe,Ze,iu]=F,Li=iu.split("] ["),Vo=Li[0],Fn=Li[1];Li.splice(0,2),$={timestamp:Ze,thread:Vo,level:Fn,tags:Li,message:""},z=F.index+Oe.length}k=b.slice(z)}),p.on("end",b=>{p.destroyed||$&&($.message=k.trim(),U($))}),p.resume();function U(b){let P,z,F;switch(!0){case(i&&c&&l):P=new Date(b.timestamp),z=new Date(u),F=new Date(_),b.level===o&&P>=z&&P<=F&&R<f?R++:b.level===o&&P>=z&&P<=F&&(An(b,E,O),R++,R===h&&p.destroy());break;case(i&&c):P=new Date(b.timestamp),z=new Date(u),b.level===o&&P>=z&&R<f?R++:b.level===o&&P>=z&&(An(b,E,O),R++,R===h&&p.destroy());break;case(i&&l):P=new Date(b.timestamp),F=new Date(_),b.level===o&&P<=F&&R<f?R++:b.level===o&&P<=F&&(An(b,E,O),R++,R===h&&p.destroy());break;case(c&&l):P=new Date(b.timestamp),z=new Date(u),F=new Date(_),P>=z&&P<=F&&R<f?R++:P>=z&&P<=F&&(An(b,E,O),R++,R===h&&p.destroy());break;case i:b.level===o&&R<f?R++:b.level===o&&(An(b,E,O),R++,R===h&&p.destroy());break;case c:P=new Date(b.timestamp),z=new Date(u),P>=z&&R<f?R++:P>=z&&R>=f&&(An(b,E,O),R++,R===h&&p.destroy());break;case l:P=new Date(b.timestamp),F=new Date(_),P<=F&&R<f?R++:P<=F&&R>=f&&(An(b,E,O),R++,R===h&&p.destroy());break;default:R<f?R++:(An(b,E,O),R++,R===h&&p.destroy())}}return a(U,"onLogMessage"),await wz(p,"close"),O}a(vz,"readLog");function An(e,t,r){t==="desc"?Bz(e,r):t==="asc"?Hz(e,r):r.push(e)}a(An,"pushLineToResult");function Bz(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(Bz,"insertDescending");function Hz(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(Hz,"insertAscending")});var Hl=m((aae,kI)=>{"use strict";var dm=require("joi"),{string:Bl,boolean:qI,date:Fz}=dm.types(),qz=ve(),{validateSchemaExists:nae,validateTableExists:iae,validateSchemaName:oae}=rs(),Gz=A(),xz=Be(),GI=Q();GI.initSync();var kz=Bl.invalid(GI.get(Gz.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(xz.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(),xI={operation:Bl.valid("add_node","update_node"),node_name:kz,subscriptions:dm.array().items({table:Bl.optional(),schema:Bl.required(),subscribe:qI.required(),publish:qI.required().custom($z),start_time:Fz.iso()}).min(1).required()};function Vz(e){return qz.validateBySchema(e,dm.object(xI))}a(Vz,"addUpdateNodeValidator");function $z(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($z,"checkForFalsy");kI.exports={addUpdateNodeValidator:Vz,validation_schema:xI}});var $I=m((uae,VI)=>{var Yz=ve(),Kz={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};VI.exports=function(e){return Yz.validateObject(e,Kz)}});var fm=m((lae,YI)=>{"use strict";var Wz=A().OPERATIONS_ENUM,Em=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=Wz.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};YI.exports=Em});var WI=m((dae,KI)=>{"use strict";var Qz={OPERATION:"operation",REFRESH:"refresh"},hm=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},mm=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};KI.exports={JWTTokens:hm,TOKEN_TYPE_ENUM:Qz,JWTRSAKeys:mm}});var $a=m((fae,XI)=>{"use strict";var Va=require("jsonwebtoken"),Sm=require("fs-extra"),pm=V(),yr=A(),{handleHDBError:kt,hdb_errors:zz}=W(),{HTTP_STATUS_CODES:Vt,AUTHENTICATION_ERROR_MSGS:$t}=zz,ka=x(),QI=ju(),gm=br(),Jz=Ar().update,Xz=fm(),Zz=qs(),{UserEventMsg:jz}=Fr(),On=Q();On.initSync();var Tm=require("path"),{JWTTokens:eJ,JWTRSAKeys:tJ,TOKEN_TYPE_ENUM:Fl}=WI(),rJ=On.get(yr.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?On.get(yr.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",sJ=On.get(yr.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?On.get(yr.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",ql="RS256",Rm;XI.exports={createTokens:nJ,validateOperationToken:oJ,refreshOperationToken:iJ,validateRefreshToken:JI};async function nJ(e){if(pm.isEmpty(e)||typeof e!="object")throw kt(new Error,$t.INVALID_AUTH_OBJECT,Vt.BAD_REQUEST,void 0,void 0,!0);if(pm.isEmpty(e.username))throw kt(new Error,$t.USERNAME_REQUIRED,Vt.BAD_REQUEST,void 0,void 0,!0);if(pm.isEmpty(e.password))throw kt(new Error,$t.PASSWORD_REQUIRED,Vt.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await gm.findAndValidateUser(e.username,e.password),!t)throw kt(new Error,$t.INVALID_CREDENTIALS,Vt.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw ka.error(E),kt(new Error,$t.INVALID_CREDENTIALS,Vt.UNAUTHORIZED,void 0,void 0,!0)}let r=await Gl(),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 zI(i,r.private_key,r.passphrase),c=await Va.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:sJ,algorithm:ql,subject:Fl.REFRESH}),u=QI.hash(c),l=new Xz(yr.SYSTEM_SCHEMA_NAME,yr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),_,d;try{_=await Jz(l)}catch(E){ka.error(E),d=E}if(d!==void 0||_.skipped_hashes.length>0)throw kt(new Error,$t.REFRESH_TOKEN_SAVE_FAILED,Vt.INTERNAL_SERVER_ERROR);return Zz.signalUserChange(new jz(process.pid)),new eJ(o,c)}a(nJ,"createTokens");async function zI(e,t,r){return await Va.sign(e,{key:t,passphrase:r},{expiresIn:rJ,algorithm:ql,subject:Fl.OPERATION})}a(zI,"signOperationToken");async function Gl(){if(Rm===void 0)try{let e=Tm.join(On.getHdbBasePath(),yr.LICENSE_KEY_DIR_NAME,yr.JWT_ENUM.JWT_PASSPHRASE_NAME),t=Tm.join(On.getHdbBasePath(),yr.LICENSE_KEY_DIR_NAME,yr.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=Tm.join(On.getHdbBasePath(),yr.LICENSE_KEY_DIR_NAME,yr.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await Sm.readFile(e)).toString(),n=(await Sm.readFile(t)).toString(),i=(await Sm.readFile(r)).toString();Rm=new tJ(i,n,s)}catch(e){throw ka.error(e),kt(new Error,$t.NO_ENCRYPTION_KEYS,Vt.INTERNAL_SERVER_ERROR)}return Rm}a(Gl,"getJWTRSAKeys");async function iJ(e){if(!e)throw kt(new Error,$t.INVALID_BODY,Vt.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw kt(new Error,$t.REFRESH_TOKEN_REQUIRED,Vt.BAD_REQUEST,void 0,void 0,!0);await JI(e.refresh_token);let t=await Gl(),r=await Va.decode(e.refresh_token);return{operation_token:await zI({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(iJ,"refreshOperationToken");async function oJ(e){try{let t=await Gl(),r=await Va.verify(e,t.public_key,{algorithms:ql,subject:Fl.OPERATION});return await gm.findAndValidateUser(r.username,void 0,!1)}catch(t){throw ka.warn(t),t.name&&t.name==="TokenExpiredError"?kt(new Error,$t.TOKEN_EXPIRED,Vt.FORBIDDEN):kt(new Error,$t.INVALID_TOKEN,Vt.UNAUTHORIZED)}}a(oJ,"validateOperationToken");async function JI(e){let t;try{let r=await Gl(),s=await Va.verify(e,r.public_key,{algorithms:ql,subject:Fl.REFRESH});t=await gm.findAndValidateUser(s.username,void 0,!1)}catch(r){throw ka.warn(r),r.name&&r.name==="TokenExpiredError"?kt(new Error,$t.TOKEN_EXPIRED,Vt.FORBIDDEN):kt(new Error,$t.INVALID_TOKEN,Vt.UNAUTHORIZED)}if(!QI.validate(t.refresh_token,e))throw kt(new Error,$t.INVALID_TOKEN,Vt.UNAUTHORIZED);return t}a(JI,"validateRefreshToken")});var Am=m((Sae,ew)=>{"use strict";var aJ=$I(),ao=require("passport"),cJ=require("passport-local").Strategy,uJ=require("passport-http").BasicStrategy,lJ=require("util"),_J=br(),jI=lJ.callbackify(_J.findAndValidateUser),mae=rr(),dJ=A(),ZI=$a();ao.use(new cJ(function(e,t,r){jI(e,t,r)}));ao.use(new uJ(function(e,t,r){jI(e,t,r)}));ao.serializeUser(function(e,t){t(null,e)});ao.deserializeUser(function(e,t){t(null,e)});function EJ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let s,n;if(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("Must login")}switch(a(i,"handleResponse"),s){case"Basic":ao.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===dJ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?ZI.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):ZI.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:ao.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(EJ,"authorize");function fJ(e,t){let r=aJ(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!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(fJ,"checkPermissions");ew.exports={authorize:EJ,checkPermissions:fJ}});var co=m((Tae,tw)=>{"use strict";var Om=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},Nm=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};tw.exports={Node:Om,NodeSubscription:Nm}});var sw=m((gae,rw)=>{"use strict";var hJ=A().OPERATIONS_ENUM,bm=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=hJ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};rw.exports=bm});var Ya=m((Oae,nw)=>{"use strict";var ym=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},Im=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,s,n,i,o,c){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};nw.exports={RemotePayloadObject:ym,RemotePayloadSubscription:Im}});var ow=m((bae,iw)=>{"use strict";var wm=class{static{a(this,"TableSizeObject")}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}};iw.exports=wm});var uw=m((Uae,cw)=>{"use strict";var mJ=ow(),Iae=xe(),aw=ye(),SJ=x(),{getSchemaPath:wae,getTransactionAuditStorePath:Cae}=we(),{getDatabases:pJ}=(de(),re(Ne));cw.exports=TJ;async function TJ(e){let t=new mJ;try{let r=pJ()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await aw.environmentDataSize(schema_path,e.name),o=await aw.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=s.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=n.entryCount}catch(r){SJ.warn(`unable to stat table dbi due to ${r}`)}return t}a(TJ,"lmdbGetTableSize")});var _w=m((Lae,lw)=>{"use strict";var Cm=class{static{a(this,"SystemInformationObject")}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}};lw.exports=Cm});var uo=m((Bae,hw)=>{"use strict";var RJ=require("fs-extra"),gJ=require("path"),Ut=require("systeminformation"),Nn=x(),AJ=nt(),Um=Be(),kl=A(),OJ=uw(),fw=Yn(),{getThreadInfo:dw}=dt(),Gm=Q();Gm.initSync();var NJ=_w(),{openEnvironment:Pae}=ye(),{getSchemaPath:vae}=we(),{database:bJ}=(de(),re(Ne)),xl;hw.exports={getHDBProcessInfo:Pm,getNetworkInfo:Bm,getDiskInfo:vm,getMemoryInfo:Mm,getCPUInfo:Lm,getTimeInfo:Dm,getSystemInformation:Hm,systemInformation:yJ,getTableSize:Fm,getMetrics:qm};function Dm(){return Ut.time()}a(Dm,"getTimeInfo");async function Lm(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:l,..._}=await Ut.cpu();_.cpu_speed=await Ut.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:T,raw_currentload_user:p,cpus:R,...O}=await Ut.currentLoad();return O.cpus=[],R.forEach(k=>{let{raw_load:$,raw_load_idle:U,raw_load_irq:b,raw_load_nice:P,raw_load_system:z,raw_load_user:F,...Oe}=k;O.cpus.push(Oe)}),_.current_load=O,_}catch(e){return Nn.error(`error in getCPUInfo: ${e}`),{}}}a(Lm,"getCPUInfo");async function Mm(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Ut.mem();return Object.assign(n,process.memoryUsage())}catch(e){return Nn.error(`error in getMemoryInfo: ${e}`),{}}}a(Mm,"getMemoryInfo");async function Pm(){let e={core:[],clustering:[]};try{let t=await Ut.processes(),r;try{r=Number.parseInt(await RJ.readFile(gJ.join(Gm.get(kl.CONFIG_PARAMS.ROOTPATH),kl.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===kl.NODE_ERROR_CODES.ENOENT)Nn.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return Nn.error(`error in getHDBProcessInfo: ${t}`),e}}a(Pm,"getHDBProcessInfo");async function vm(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Ut.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,...l}=await Ut.fsStats();return e.read_write=l,e.size=await Ut.fsSize(),e}catch(t){return Nn.error(`error in getDiskInfo: ${t}`),e}}a(vm,"getDiskInfo");async function Bm(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Ut.networkInterfaceDefault(),e.latency=await Ut.inetChecksite("google.com"),(await Ut.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:l,ieee8021xState:_,carrier_changes:d,...E}=s;e.interfaces.push(E)}),(await Ut.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return Nn.error(`error in getNetworkInfo: ${t}`),e}}a(Bm,"getNetworkInfo");async function Hm(){if(xl!==void 0)return xl;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Ut.osInfo();e=c;let u=await Ut.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,xl=e,xl}catch(t){return Nn.error(`error in getSystemInformation: ${t}`),e}}a(Hm,"getSystemInformation");async function Fm(){let e=[],t=await fw.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await OJ(s));return e}a(Fm,"getTableSize");async function qm(){let e=await fw.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let o=bJ({database:r,table:n}).getStats();s[n]={puts:o.puts,deletes:o.deletes,txns:o.txns,pageFlushes:o.pageFlushes,writes:o.writes,pagesWritten:o.pagesWritten,timeDuringTxns:o.timeDuringTxns,timeStartTxns:o.timeStartTxns,timePageFlushes:o.timePageFlushes,timeSync:o.timeSync}}catch(i){Nn.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(qm,"getMetrics");async function Ew(){if(Gm.get(kl.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await AJ.getNATSReferences(),r=await t.streams.info(Um.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(Um.WORK_QUEUE_CONSUMER_NAMES.stream_name,Um.WORK_QUEUE_CONSUMER_NAMES.durable_name),n={ingest:{stream:{...r.state},consumer:{num_ack_pending:s._info.num_ack_pending,num_redelivered:s._info.num_redelivered,num_waiting:s._info.num_waiting,num_pending:s._info.num_pending}}};return r.config?.sources&&(n.ingest.stream.sources=r.config.sources),n}}a(Ew,"getNatsStreamInfo");async function yJ(e){let t=new NJ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await Hm(),t.time=Dm(),t.cpu=await Lm(),t.memory=await Mm(),t.disk=await vm(),t.network=await Bm(),t.harperdb_processes=await Pm(),t.table_size=await Fm(),t.metrics=await qm(),t.threads=await dw(),t.replication=await Ew(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await Hm();break;case"time":t.time=Dm();break;case"cpu":t.cpu=await Lm();break;case"memory":t.memory=await Mm();break;case"disk":t.disk=await vm();break;case"network":t.network=await Bm();break;case"harperdb_processes":t.harperdb_processes=await Pm();break;case"table_size":t.table_size=await Fm();break;case"database_metrics":case"metrics":t.metrics=await qm();break;case"threads":t.threads=await dw();break;case"replication":t.replication=await Ew();break;default:break}return t}a(yJ,"systemInformation")});var Ka=m((Fae,IJ)=>{IJ.exports={name:"harperdb",version:"4.2.0-alpha.13",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{node:">=14.0.0","preferred-node":"18.15.0","go-lang":"1.19.12","nats-server":"2.9.21"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.383.0","@aws-sdk/lib-storage":"3.383.0","@aws-sdk/abort-controller":"3.370.0","@endo/static-module-record":"^0.7.16","@fastify/autoload":"~5.7.1","@fastify/compress":"~6.4.0","@fastify/cors":"~8.3.0","@fastify/static":"~6.10.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"1.7.4","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2",esbuild:"^0.18.0","fast-glob":"3.3.1",fastify:"~4.21.0","fastify-plugin":"~4.5.0","fs-extra":"11.1.1",graphql:"^16.6.0","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.9.2",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.1",lmdb:"2.8.4",lodash:"4.17.21",mathjs:"11.9.1",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.0",msgpackr:"1.9.7",nats:"2.16.0",needle:"3.2.0","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.4.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.15.0",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0",ses:"^0.18.1","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.18.11","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.0","validate.js":"0.13.1",ws:"^8.13.0",yaml:"2.3.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"0.27.2",chai:"4.3.7","chai-integer":"0.1.0",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^4.9.4","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var xm=m((xae,mw)=>{"use strict";var qae=require("fs-extra"),Gae=x();mw.exports={version:wJ,printVersion:UJ,nodeVersion:CJ};var bn=Ka();function wJ(){if(bn)return bn.version}a(wJ,"version");function CJ(){if(bn&&bn.engines&&bn.engines["preferred-node"])return bn.engines["preferred-node"]}a(CJ,"nodeVersion");function UJ(){bn&&console.log(`HarperDB Version ${bn.version}`)}a(UJ,"printVersion")});var ks=m((Yae,Rw)=>{"use strict";var DJ=Ar(),km=V(),LJ=require("util"),ii=A(),Sw=Q();Sw.initSync();var MJ=Am(),pw=gr(),{Node:Vae,NodeSubscription:$ae}=co(),PJ=Xi(),vJ=sw(),{RemotePayloadObject:BJ,RemotePayloadSubscription:HJ}=Ya(),{handleHDBError:FJ,hdb_errors:qJ}=W(),{HTTP_STATUS_CODES:GJ,HDB_ERROR_MSGS:xJ}=qJ,kJ=os(),VJ=uo(),$J=xm(),{getDatabases:YJ}=(de(),re(Ne)),KJ=LJ.promisify(MJ.authorize),WJ=pw.searchByHash,QJ=pw.searchByValue;Rw.exports={authHeaderToUser:zJ,isEmpty:JJ,getNodeRecord:XJ,upsertNodeRecord:ZJ,buildNodePayloads:jJ,checkClusteringEnabled:e2,getAllNodeRecords:t2,getSystemInfo:r2,reverseSubscription:Tw};async function zJ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await KJ(t,null),e}a(zJ,"authHeaderToUser");function JJ(e){return e==null}a(JJ,"isEmpty");async function XJ(e){let t=new PJ(ii.SYSTEM_SCHEMA_NAME,ii.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return WJ(t)}a(XJ,"getNodeRecord");async function ZJ(e){let t=new vJ(ii.SYSTEM_SCHEMA_NAME,ii.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return DJ.upsert(t)}a(ZJ,"upsertNodeRecord");function Tw(e){if(km.isEmpty(e.subscribe)||km.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(Tw,"reverseSubscription");function jJ(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:l}=c,_=km.getTableHashAttribute(u,l),{subscribe:d,publish:E}=Tw(c),f=YJ()[u]?.[l],h=new HJ(u,l,_,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);n.push(h)}return new BJ(r,t,n,s)}a(jJ,"buildNodePayloads");function e2(){if(!Sw.get(ii.CONFIG_PARAMS.CLUSTERING_ENABLED))throw FJ(new Error,xJ.CLUSTERING_NOT_ENABLED,GJ.BAD_REQUEST,void 0,void 0,!0)}a(e2,"checkClusteringEnabled");async function t2(){let e=new kJ(ii.SYSTEM_SCHEMA_NAME,ii.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await QJ(e))}a(t2,"getAllNodeRecords");async function r2(){let e=await VJ.getSystemInformation();return{hdb_version:$J.version(),node_version:e.node_version,platform:e.platform}}a(r2,"getSystemInfo")});var Vm=m((Wae,ww)=>{"use strict";var Vl=nt(),gw=V(),Aw=Be(),Ow=A(),$l=x(),Nw=Ul(),s2=gh(),{RemotePayloadObject:n2}=Ya(),{handleHDBError:bw,hdb_errors:i2}=W(),{HTTP_STATUS_CODES:yw}=i2,{NodeSubscription:Iw}=co();ww.exports=o2;async function o2(e,t){let r;try{r=await Vl.request(`${t}.${Aw.REQUEST_SUFFIX}`,new n2(Ow.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),$l.trace("Response from remote describe all request:",r)}catch(o){$l.error(`addNode received error from describe all request to remote node: ${o}`);let c=Vl.requestErrorHandler(o,"add_node",t);throw bw(new Error,c,yw.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===Aw.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw bw(new Error,o,yw.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:u}=o;if(c===Ow.SYSTEM_SCHEMA_NAME){await Vl.createLocalTableStream(c,u);let h=new Iw(c,u,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let l=gw.doesSchemaExist(c),_=s[c]!==void 0,d=u?gw.doesTableExist(c,u):!0,E=u?s?.[c]?.[u]!==void 0:!0;if(!l&&!_||!d&&!E){n.push(o);continue}if(!l&&_&&($l.trace(`addNode creating schema: ${c}`),await Nw.createSchema({operation:"create_schema",schema:c})),!d&&E){$l.trace(`addNode creating table: ${u} in schema: ${c} with attributes ${JSON.stringify(s[c][u].attributes)}`);let h=new s2(c,u,s[c][u].hash_attribute);s[c][u].attributes&&(h.attributes=s[c][u].attributes),await Nw.createTable(h)}await Vl.createLocalTableStream(c,u);let f=new Iw(c,u,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:n}}a(o2,"reviewSubscriptions")});var Wl=m((zae,Dw)=>{"use strict";var{handleHDBError:Yl,hdb_errors:a2}=W(),{HTTP_STATUS_CODES:Kl}=a2,{addUpdateNodeValidator:c2}=Hl(),Wa=x(),Uw=A(),Cw=Be(),u2=V(),$m=nt(),Qa=ks(),l2=Q(),_2=Vm(),{Node:d2,NodeSubscription:E2}=co(),{broadcast:f2}=dt(),h2="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",m2="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",S2=l2.get(Uw.CONFIG_PARAMS.CLUSTERING_NODENAME);Dw.exports=p2;async function p2(e,t=!1){Wa.trace("addNode called with:",e),Qa.checkClusteringEnabled();let r=c2(e);if(r)throw Yl(r,r.message,Kl.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await Qa.getNodeRecord(s);if(!u2.isEmptyOrZeroLength(d))throw Yl(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,Kl.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await _2(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=h2,o;let c=Qa.buildNodePayloads(n,S2,Uw.OPERATIONS_ENUM.ADD_NODE,await Qa.getSystemInfo());Wa.trace("addNode sending remote payload:",c);let u;try{u=await $m.request(`${s}.${Cw.REQUEST_SUFFIX}`,c)}catch(d){Wa.error(`addNode received error from request: ${d}`);let E=$m.requestErrorHandler(d,"add_node",s);throw Yl(new Error,E,Kl.INTERNAL_SERVER_ERROR,"error",E)}if(u.status===Cw.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw Yl(new Error,d,Kl.INTERNAL_SERVER_ERROR,"error",d)}Wa.trace(u);let l=[];for(let d=0,E=n.length;d<E;d++){let f=n[d];Wa.trace("Add node updating work stream for node:",s,"subscriptions:",f),await $m.updateWorkStream(f,s),n[d].start_time===void 0&&delete n[d].start_time,l.push(new E2(f.schema,f.table,f.publish,f.subscribe))}let _=new d2(s,l,u.system_info);return await Qa.upsertNodeRecord(_),f2({type:"nats_update"}),i.length>0?o.message=m2:o.message=`Successfully added '${s}' to manifest`,o}a(p2,"addNode")});var Km=m((Xae,Pw)=>{"use strict";var{handleHDBError:Ql,hdb_errors:T2}=W(),{HTTP_STATUS_CODES:zl}=T2,{addUpdateNodeValidator:R2}=Hl(),za=x(),Mw=A(),Lw=Be(),g2=V(),Ym=nt(),Ja=ks(),A2=Q(),{cloneDeep:O2}=require("lodash"),N2=Vm(),{NodeSubscription:b2}=co(),{broadcast:y2}=dt(),I2="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",w2="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",C2=A2.get(Mw.CONFIG_PARAMS.CLUSTERING_NODENAME);Pw.exports=U2;async function U2(e){za.trace("updateNode called with:",e),Ja.checkClusteringEnabled();let t=R2(e);if(t)throw Ql(t,t.message,zl.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=O2(await Ja.getNodeRecord(r));if(g2.isEmptyOrZeroLength(s))throw Ql(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,zl.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await N2(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=I2,o;let c=Ja.buildNodePayloads(n,C2,Mw.OPERATIONS_ENUM.UPDATE_NODE,await Ja.getSystemInfo());za.trace("updateNode sending remote payload:",c);let u;try{u=await Ym.request(`${r}.${Lw.REQUEST_SUFFIX}`,c)}catch(l){za.error(`updateNode received error from request: ${l}`);let _=Ym.requestErrorHandler(l,"update_node",r);throw Ql(new Error,_,zl.INTERNAL_SERVER_ERROR,"error",_)}if(u.status===Lw.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${u.message}`;throw Ql(new Error,l,zl.INTERNAL_SERVER_ERROR,"error",l)}za.trace(u);for(let l=0,_=n.length;l<_;l++){let d=n[l];za.trace(`updateNode updating work stream for node: ${r} subscription:`,d),await Ym.updateWorkStream(d,r),n[l].start_time===void 0&&delete n[l].start_time}return await D2(s[0],n,u.system_info),i.length>0?o.message=w2:o.message=`Successfully updated '${r}'`,o}a(U2,"updateNode");async function D2(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let u=0,l=e.subscriptions.length;u<l;u++){let _=s.subscriptions[u];if(_.schema===o.schema&&_.table===o.table){_.publish=o.publish,_.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new b2(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Ja.upsertNodeRecord(s),y2({type:"nats_update"})}a(D2,"updateNodeTable")});var qw=m((jae,Fw)=>{"use strict";var Hw=require("joi"),{string:vw}=Hw.types(),L2=ve(),Bw=A(),M2=Q(),P2=Be();Fw.exports=v2;function v2(e){let t=vw.invalid(M2.get(Bw.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(P2.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=Hw.object({operation:vw.valid(Bw.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return L2.validateBySchema(e,r)}a(v2,"removeNodeValidator")});var Xl=m((tce,Yw)=>{"use strict";var{handleHDBError:Gw,hdb_errors:B2}=W(),{HTTP_STATUS_CODES:xw}=B2,H2=qw(),Xa=x(),kw=ks(),F2=V(),Jl=A(),Vw=Be(),$w=nt(),q2=Q(),{RemotePayloadObject:G2}=Ya(),{NodeSubscription:x2}=co(),k2=Ma(),V2=Jn(),{broadcast:$2}=dt(),Y2=q2.get(Jl.CONFIG_PARAMS.CLUSTERING_NODENAME);Yw.exports=K2;async function K2(e){Xa.trace("removeNode called with:",e),kw.checkClusteringEnabled();let t=H2(e);if(t)throw Gw(t,t.message,xw.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await kw.getNodeRecord(r);if(F2.isEmptyOrZeroLength(s))throw Gw(new Error,`Node '${r}' was not found.`,xw.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new G2(Jl.OPERATIONS_ENUM.REMOVE_NODE,Y2,[]),i,o=!1;try{i=await $w.request(`${r}.${Vw.REQUEST_SUFFIX}`,n),Xa.trace("Remove node reply from remote node:",r,i)}catch(u){Xa.error("removeNode received error from request:",u),o=!0}for(let u=0,l=s.subscriptions.length;u<l;u++){let _=s.subscriptions[u];Xa.trace(`Remove node removing subscription: ${_.schema}.${_.table} for node: ${r}`);let d=new x2(_.schema,_.table,!1,!1);await $w.updateWorkStream(d,r)}let c=new k2(Jl.SYSTEM_SCHEMA_NAME,Jl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await V2.deleteRecord(c),$2({type:"nats_update"}),i?.status===Vw.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Xa.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(K2,"removeNode")});var Qw=m((sce,Ww)=>{"use strict";var Kw=require("joi"),{string:W2,array:Q2}=Kw.types(),z2=ve(),J2=Hl();Ww.exports=X2;function X2(e){let t=Kw.object({operation:W2.valid("configure_cluster").required(),connections:Q2.items(J2.validation_schema).required()});return z2.validateBySchema(e,t)}a(X2,"configureClusterValidator")});var Wm=m((ice,jw)=>{"use strict";var Z2=A(),Zl=x(),j2=V(),e3=Xl(),t3=Wl(),zw=ks(),r3=Qw(),{handleHDBError:Jw,hdb_errors:s3}=W(),{HTTP_STATUS_CODES:Xw}=s3,n3="Configure cluster complete.",i3="Failed to configure the cluster. Check the logs for more details.",o3="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";jw.exports=a3;async function a3(e){Zl.trace("configure cluster called with:",e),zw.checkClusteringEnabled();let t=r3(e);if(t)throw Jw(t,t.message,Xw.BAD_REQUEST,void 0,void 0,!0);let r=await zw.getAllNodeRecords(),s=[];for(let E=0,f=r.length;E<f;E++)s.push(Zw(e3,{operation:Z2.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[E].name},r[E].name));let n=await Promise.allSettled(s);Zl.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let E=0;E<o;E++){let f=e.connections[E];i.push(Zw(t3,f,f.node_name))}let c=await Promise.allSettled(i);Zl.trace("All results from configure_cluster add node:",c);let u=[],l=[],_=!1,d=n.concat(c);for(let E=0,f=d.length;E<f;E++){let h=d[E];h.status==="rejected"&&(Zl.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(_=!0);let T=h?.value?.result;typeof T=="string"&&T.includes("Successfully removed")||h.status==="rejected"||l.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(j2.isEmptyOrZeroLength(u))return{message:n3,connections:l};if(_)return{message:o3,failed_nodes:u,connections:l};throw Jw(new Error,i3,Xw.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(a3,"configureCluster");async function Zw(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(Zw,"functionWrapper")});var tC=m((ace,eC)=>{"use strict";var jl=require("joi"),c3=ve(),{validateSchemaExists:u3,validateTableExists:l3,validateSchemaName:_3}=rs(),d3=jl.object({operation:jl.string().valid("purge_stream"),schema:jl.string().custom(u3).custom(_3).required(),table:jl.string().custom(l3).required()});function E3(e){return c3.validateBySchema(e,d3)}a(E3,"purgeStreamValidator");eC.exports=E3});var Qm=m((uce,rC)=>{"use strict";var{handleHDBError:f3,hdb_errors:h3}=W(),{HTTP_STATUS_CODES:m3}=h3,S3=tC(),p3=nt(),T3=ks();rC.exports=R3;async function R3(e){let t=S3(e);if(t)throw f3(t,t.message,m3.BAD_REQUEST,void 0,void 0,!0);T3.checkClusteringEnabled();let{schema:r,table:s}=e;return await p3.purgeTableStream(r,s),`Successfully purged table '${r}.${s}'`}a(R3,"purgeStream")});var Xm=m((_ce,cC)=>{"use strict";var Jm=ks(),g3=nt(),iC=Q(),e_=A(),oi=Be(),A3=V(),zm=x(),{RemotePayloadObject:O3}=Ya(),{ErrorCode:sC}=require("nats"),nC=iC.get(e_.CONFIG_PARAMS.CLUSTERING_ENABLED),oC=iC.get(e_.CONFIG_PARAMS.CLUSTERING_NODENAME);cC.exports={clusterStatus:N3,buildNodeStatus:aC};async function N3(){let e={node_name:oC,is_enabled:nC,connections:[]};if(!nC)return e;let t=await Jm.getAllNodeRecords();if(A3.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(aC(t[s],e.connections));return await Promise.allSettled(r),e}a(N3,"clusterStatus");async function aC(e,t){let r=e.name,s=new O3(e_.OPERATIONS_ENUM.CLUSTER_STATUS,oC,void 0,await Jm.getSystemInfo()),n,i,o=oi.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await g3.request(oi.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===oi.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=oi.CLUSTER_STATUS_STATUSES.CLOSED,zm.error(`Error getting node status from ${r} `,n))}catch(u){zm.warn(`Error getting node status from ${r}`,u),u.code===sC.NoResponders?o=oi.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===sC.Timeout?o=oi.CLUSTER_STATUS_STATUSES.TIMEOUT:o=oi.CLUSTER_STATUS_STATUSES.CLOSED}let c=new b3(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let u={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==e_.PRE_4_0_0_VERSION&&await Jm.upsertNodeRecord(u)}catch(u){zm.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(aC,"buildNodeStatus");function b3(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(b3,"NodeStatusObject")});var jm=m((Ece,uC)=>{"use strict";var{handleHDBError:y3,hdb_errors:I3}=W(),{HTTP_STATUS_CODES:w3}=I3,C3=nt(),U3=ks(),Zm=V(),t_=require("joi"),D3=ve(),L3=2e3,M3=t_.object({timeout:t_.number().min(1),connected_nodes:t_.boolean(),routes:t_.boolean()});uC.exports=P3;async function P3(e){U3.checkClusteringEnabled();let t=D3.validateBySchema(e,M3);if(t)throw y3(t,t.message,w3.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||Zm.autoCastBoolean(s),o=n===void 0||Zm.autoCastBoolean(n),c={nodes:[]},u=await C3.getServerList(r??L3),l={};if(i)for(let _=0,d=u.length;_<d;_++){let E=u[_].statsz;E&&(l[u[_].server.name]=E.routes)}for(let _=0,d=u.length;_<d;_++){if(u[_].statsz)continue;let E=u[_].server,f=u[_].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[_].response_time};i&&(h.connected_nodes=l[E.name]?l[E.name].map(T=>T.name.slice(0,-4)):[]),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(T=>({host:T.split(":")[0],port:Zm.autoCast(T.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(P3,"clusterNetwork")});var EC=m((hce,dC)=>{"use strict";var eS=require("joi"),lC=ve(),{route_constraints:_C}=Ff();dC.exports={setRoutesValidator:v3,deleteRoutesValidator:B3};function v3(e){let t=eS.object({server:eS.valid("hub","leaf").required(),routes:_C.required()});return lC.validateBySchema(e,t)}a(v3,"setRoutesValidator");function B3(e){let t=eS.object({routes:_C.required()});return lC.validateBySchema(e,t)}a(B3,"deleteRoutesValidator")});var rS=m((Sce,SC)=>{"use strict";var ai=Nr(),tS=V(),r_=A(),fC=EC(),{handleHDBError:hC,hdb_errors:H3}=W(),{HTTP_STATUS_CODES:mC}=H3,F3="cluster routes successfully set",q3="cluster routes successfully deleted";SC.exports={setRoutes:G3,getRoutes:x3,deleteRoutes:k3};function G3(e){let t=fC.setRoutesValidator(e);if(t)throw hC(t,t.message,mC.BAD_REQUEST,void 0,void 0,!0);let r=ai.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,u=e.routes.length;c<u;c++){let l=e.routes[c];l.port=tS.autoCast(l.port);let _=s.some(E=>E.host===l.host&&E.port===l.port),d=n.some(E=>E.host===l.host&&E.port===l.port);_||d?i.push(l):(s.push(l),o.push(l))}return e.server==="hub"?ai.updateConfigValue(r_.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):ai.updateConfigValue(r_.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:F3,set:o,skipped:i}}a(G3,"setRoutes");function x3(){let e=ai.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(x3,"getRoutes");function k3(e){let t=fC.deleteRoutesValidator(e);if(t)throw hC(t,t.message,mC.BAD_REQUEST,void 0,void 0,!0);let r=ai.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let l=0,_=e.routes.length;l<_;l++){let d=e.routes[l],E=!1;for(let f=0,h=s.length;f<h;f++){let T=s[f];if(d.host===T.host&&d.port===T.port){s.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,T=n.length;h<T;h++){let p=n[h];if(d.host===p.host&&d.port===p.port){n.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(s=tS.isEmptyOrZeroLength(s)?null:s,ai.updateConfigValue(r_.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=tS.isEmptyOrZeroLength(n)?null:n,ai.updateConfigValue(r_.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:q3,deleted:i,skipped:o}}a(k3,"deleteRoutes")});var TC=m((Tce,pC)=>{"use strict";var Za=require("alasql"),ci=require("recursive-iterator"),Vr=x(),V3=V(),ja=A(),sS=class{static{a(this,"sql_statement_bucket")}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,Y3(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=>ja.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=>!ja.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][ja.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=$3(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(l=>({attribute_name:l.attribute}));let u=this.affected_attributes.get(i).get(o).filter(l=>!ja.SEARCH_WILDCARDS.includes(l));c.forEach(({attribute_name:l})=>{let _=new Za.yy.Column({columnid:l});n.tableid&&(_.tableid=n.tableid),this.ast.columns.push(_),u.includes(l)||u.push(l)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function $3(e){return e.filter(t=>t[ja.PERMS_CRUD_ENUM.READ])}a($3,"filterReadRestrictedAttrs");function Y3(e,t,r,s,n){K3(e,t,r,s,n)}a(Y3,"interpretAST");function ec(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(ec,"addSchemaTableToMap");function K3(e,t,r,s,n){if(!e){Vr.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Za.yy.Insert?J3(e,t,r):e instanceof Za.yy.Select?W3(e,t,r,s,n):e instanceof Za.yy.Update?Q3(e,t,r):e instanceof Za.yy.Delete?z3(e,t,r):Vr.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(K3,"getRecordAttributesAST");function W3(e,t,r,s,n){if(!e){Vr.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(V3.isEmptyOrZeroLength(i)){Vr.error("No schema specified");return}e.from.forEach(c=>{ec(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),ec(c.table,t,r,s,n)});let o=new ci(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.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{Vr.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(c.columnid)<0&&t.get(l).get(u).push(c.columnid)}if(e.where){let c=new ci(e.where),u=e.from[0].tableid;for(let{node:l}of c)if(l&&l.columnid){let _=l.tableid?l.tableid:u;if(!t.get(i).has(_))if(r.has(_))_=r.get(_);else{Vr.info(`table specified as ${_} not found.`);continue}t.get(i).get(_).indexOf(l.columnid)<0&&t.get(i).get(_).push(l.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ci(c.on);for(let{node:l}of u)if(l&&l.columnid){let _=l.tableid,d=n.get(_);if(!t.get(d).has(_))if(r.has(_))_=r.get(_);else{Vr.info(`table specified as ${_} not found.`);continue}t.get(d).get(_).indexOf(l.columnid)<0&&t.get(d).get(_).push(l.columnid)}}),e.order){let c=new ci(e.order);for(let{node:u}of c)if(u&&u.columnid){let l=u.tableid,_=s.has(l)?s.get(l):i;if(l||(l=e.from[0].tableid),!t.get(_).has(l))if(r.has(l))l=r.get(l);else{Vr.info(`table specified as ${l} not found.`);return}t.get(_).get(l).indexOf(u.columnid)<0&&t.get(_).get(l).push(u.columnid)}}}a(W3,"getSelectAttributes");function Q3(e,t,r){if(!e){Vr.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new ci(e.columns),n=e.table.databaseid;ec(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&nS(e.table.tableid,n,i.columnid,t,r)}a(Q3,"getUpdateAttributes");function z3(e,t,r){if(!e){Vr.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new ci(e.where),n=e.table.databaseid;ec(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&nS(e.table.tableid,n,i.columnid,t,r)}a(z3,"getDeleteAttributes");function J3(e,t,r){if(!e){Vr.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new ci(e.columns),n=e.into.databaseid;ec(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&nS(e.into.tableid,n,i.columnid,t,r)}a(J3,"getInsertAttributes");function nS(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(nS,"pushAttribute");pC.exports=sS});var aS=m((gce,OC)=>{var s_=Oa(),RC=require("chalk"),lr=x(),gC=require("prompt"),{promisify:X3}=require("util"),iS=A(),Z3=require("fs-extra"),j3=require("path"),eX=V(),tX=xm(),AC=Q();AC.initSync();var rX=require("moment"),sX=X3(gC.get),nX=j3.join(AC.getHdbBasePath(),iS.LICENSE_KEY_DIR_NAME,iS.LICENSE_FILE_NAME,iS.LICENSE_FILE_NAME);OC.exports={getFingerprint:oX,setLicense:iX,parseLicense:oS,register:aX,getRegistrationInfo:uX};async function iX(e){if(e&&e.key&&e.company){try{lr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await oS(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw lr.error(r),lr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(iX,"setLicense");async function oX(){let e={};try{e=await s_.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw lr.error(r),lr.error(t),new Error(r)}return e}a(oX,"getFingerprint");async function oS(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");lr.info("Validating license input...");let r=s_.validateLicense(e,t);if(lr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(lr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(lr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{lr.info("writing license to disk"),await Z3.writeFile(nX,JSON.stringify({license_key:e,company:t}))}catch(s){throw lr.error("Failed to write License"),s}return"Registration successful."}a(oS,"parseLicense");async function aX(){let e=await cX();return oS(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(aX,"register");async function cX(){let e=await s_.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:RC.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:RC.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{gC.start()}catch(s){lr.error(s)}let r;try{r=await sX(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(cX,"promptForRegistration");async function uX(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await s_.getLicense()}catch(r){throw lr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(eX.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=tX.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=rX.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(uX,"getRegistrationInfo")});var bC=m((Oce,NC)=>{"use strict";var lX=Be(),cS=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,l,_,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+lX.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:l,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:_,port:d,routes:E,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};NC.exports=cS});var wC=m((bce,IC)=>{"use strict";var yC=Be(),uS=class{static{a(this,"LeafConfigObject")}constructor(t,r,s,n,i,o,c,u,l,_,d){this.port=t,d===null&&(d=void 0),this.server_name=r+yC.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+yC.SERVER_SUFFIX.LEAF},this.tls={cert_file:l,key_file:_,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};IC.exports=uS});var UC=m((Ice,CC)=>{"use strict";var lS=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};CC.exports=lS});var LC=m((Cce,DC)=>{"use strict";var _X=Be(),_S=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+_X.SERVER_SUFFIX.ADMIN,this.password=r}};DC.exports=_S});var fS=m((Dce,vC)=>{"use strict";var tc=require("path"),a_=require("fs-extra"),dX=bC(),EX=wC(),fX=UC(),hX=LC(),dS=br(),lo=V(),Yt=Nr(),o_=A(),n_=Be(),{CONFIG_PARAMS:ze}=o_,sc=x(),c_=Q(),MC=Ps(),ES=nt(),rc="clustering",mX=1e4,PC=5;vC.exports={generateNatsConfig:SX,removeNatsConfig:pX};async function SX(e=!1,t=void 0){c_.initSync();let r=c_.get(ze.ROOTPATH),s=tc.join(r,rc,n_.PID_FILES.HUB),n=tc.join(r,rc,n_.PID_FILES.LEAF),i=Yt.getConfigFromFile(ze.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=tc.join(r,rc,n_.NATS_CONFIG_FILES.HUB_SERVER),c=tc.join(r,rc,n_.NATS_CONFIG_FILES.LEAF_SERVER),u=Yt.getConfigFromFile(ze.CLUSTERING_TLS_CERTIFICATE),l=Yt.getConfigFromFile(ze.CLUSTERING_TLS_PRIVATEKEY),_=Yt.getConfigFromFile(ze.CLUSTERING_TLS_CERT_AUTH),d=Yt.getConfigFromFile(ze.CLUSTERING_TLS_INSECURE),E=Yt.getConfigFromFile(ze.CLUSTERING_TLS_VERIFY),f=Yt.getConfigFromFile(ze.CLUSTERING_NODENAME),h=Yt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await ES.checkNATSServerInstalled()||u_("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let T=await dS.listUsers(),p=Yt.getConfigFromFile(ze.CLUSTERING_USER),R=await dS.getClusterUser();(lo.isEmpty(R)||R.active!==!0)&&u_(`Invalid cluster user '${p}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await i_(ze.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await i_(ze.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await i_(ze.CLUSTERING_HUBSERVER_NETWORK_PORT),await i_(ze.CLUSTERING_LEAFSERVER_NETWORK_PORT));let O=[],k=[];for(let[Oe,Ze]of T.entries())Ze.role.role===o_.ROLE_TYPES_ENUM.CLUSTER_USER&&Ze.active&&(O.push(new hX(Ze.username,MC.decrypt(Ze.hash))),k.push(new fX(Ze.username,MC.decrypt(Ze.hash))));let $=[],{hub_routes:U}=Yt.getClusteringRoutes();if(!lo.isEmptyOrZeroLength(U))for(let Oe of U)$.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${Oe.host}:${Oe.port}`);let b=new dX(Yt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_NETWORK_PORT),f,s,u,l,_,d,E,h,Yt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_CLUSTER_NAME),Yt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),$,O,k);_==null&&(delete b.tls.ca_file,delete b.leafnodes.tls.ca_file),t=lo.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===o_.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await a_.writeJson(o,b),sc.trace(`Hub server config written to ${o}`));let P=`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,z=`tls://${R.uri_encoded_name}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,F=new EX(Yt.getConfigFromFile(ze.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,n,i,[P],[z],O,k,u,l,_,d);_==null&&delete F.tls.ca_file,(t===void 0||t===o_.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await a_.writeJson(c,F),sc.trace(`Leaf server config written to ${c}`))}a(SX,"generateNatsConfig");async function i_(e){let t=c_.get(e);return lo.isEmpty(t)&&u_(`port undefined for '${e}'`),await lo.isPortTaken(t)&&u_(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(i_,"isPortAvailable");function u_(e){let t=`Error generating clustering config: ${e}`;sc.error(t),console.error(t),process.exit(1)}a(u_,"generateNatsConfigError");async function pX(e){let{port:t,config_file:r}=ES.getServerConfig(e),{username:s,decrypt_hash:n}=await dS.getClusterUser(),i=0,o=500;for(;i<PC;){try{let l=await ES.createConnection(t,s,n,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){sc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=PC)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 lo.async_set_timeout(o*i)}let c="0".repeat(mX),u=tc.join(c_.get(ze.ROOTPATH),rc,r);await a_.writeFile(u,c),await a_.remove(u),sc.notify(e,"started.")}a(pX,"removeNatsConfig")});var xC=m((Mce,GC)=>{"use strict";var _r=Q(),TX=Oa(),oe=A(),nc=Be(),Vs=require("path"),{PACKAGE_ROOT:__}=A(),BC=Q(),l_=V(),_o="/dev/null",RX=Vs.join(__,"launchServiceScripts"),HC=Vs.join(__,"utility/scripts"),gX=Vs.join(HC,oe.HDB_RESTART_SCRIPT),FC=Vs.resolve(__,"dependencies",`${process.platform}-${process.arch}`,nc.NATS_BINARY_NAME);function qC(){let t=TX.licenseSearch().ram_allocation||oe.RAM_ALLOCATION_ENUM.DEFAULT,r=oe.MEM_SETTING_KEY+t,s={[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return l_.noBootFile()&&(s[oe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=l_.getEnvCliRootPath()),{name:oe.PROCESS_DESCRIPTORS.HDB,script:oe.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:__}}a(qC,"generateMainServerConfig");var AX=9930;function OX(){_r.initSync(!0);let e=_r.get(oe.CONFIG_PARAMS.ROOTPATH),t=Vs.join(e,"clustering",nc.NATS_CONFIG_FILES.HUB_SERVER),r=Vs.join(_r.get(oe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),oe.LOG_NAMES.HDB),s=BC.get(oe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=nc.LOG_LEVEL_FLAGS[_r.get(oe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==AX?"-"+s:""),script:FC,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=_o,i.error_file=_o),i}a(OX,"generateNatsHubServerConfig");var NX=9940;function bX(){_r.initSync(!0);let e=_r.get(oe.CONFIG_PARAMS.ROOTPATH),t=Vs.join(e,"clustering",nc.NATS_CONFIG_FILES.LEAF_SERVER),r=Vs.join(_r.get(oe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),oe.LOG_NAMES.HDB),s=BC.get(oe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=nc.LOG_LEVEL_FLAGS[_r.get(oe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==NX?"-"+s:""),script:FC,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=_o,i.error_file=_o),i}a(bX,"generateNatsLeafServerConfig");function yX(){_r.initSync();let e=Vs.join(_r.get(oe.CONFIG_PARAMS.LOGGING_ROOT),oe.LOG_NAMES.HDB),t={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:oe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:RX,autorestart:!1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=_o,t.error_file=_o),t}a(yX,"generateClusteringUpgradeV4ServiceConfig");function IX(){let e={[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.RESTART_HDB};return l_.noBootFile()&&(e[oe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=l_.getEnvCliRootPath()),{...{name:oe.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:HC},script:gX}}a(IX,"generateRestart");function wX(){return{apps:[qC()]}}a(wX,"generateAllServiceConfigs");GC.exports={generateAllServiceConfigs:wX,generateMainServerConfig:qC,generateRestart:IX,generateNatsHubServerConfig:OX,generateNatsLeafServerConfig:bX,generateClusteringUpgradeV4ServiceConfig:yX}});var rU=m((Gce,tU)=>{"use strict";var Te=A(),CX=V(),ic=fS(),oc=nt(),ls=Be(),yn=xC(),d_=Q(),$s=x(),UX=ks(),{startWorker:kC,onMessageFromWorkers:DX}=dt(),LX=uo(),MX=require("util"),$C=require("child_process"),{execFile:PX}=$C,vce=MX.promisify($C.exec),Bce=require("systeminformation"),fe;tU.exports={enterPM2Mode:vX,start:ui,stop:hS,reload:YC,restart:KC,list:mS,describe:QC,connect:Ys,kill:GX,startAllServices:xX,startService:SS,getUniqueServicesList:zC,restartAllServices:kX,isServiceRegistered:JC,reloadStopStart:XC,restartHdb:WC,deleteProcess:FX,startClusteringProcesses:jC,startClusteringThreads:eU,isHdbRestartRunning:qX,isClusteringRunning:$X,stopClustering:VX,reloadClustering:YX};var{PACKAGE_ROOT:Hce}=A(),Fce=A(),{loggerWithTag:qce}=$s,ac=!1;DX(e=>{e.type==="restart"&&d_.initSync(!0)});function vX(){ac=!0}a(vX,"enterPM2Mode");function Ys(){return fe||(fe=require("pm2")),new Promise((e,t)=>{fe.connect((r,s)=>{$s.setupConsoleLogging(),r&&t(r),e(s)})})}a(Ys,"connect");var Kt,BX=10,VC;function ui(e){if(ac)return HX(e);let t=PX(e.script,e.args.split(" "),e);t.name=e.name,t.on("exit",n=>{let i=Kt.indexOf(t);i>-1&&Kt.splice(i,1),!VC&&n>0&&(e.restarts=(e.restarts||0)+1,e.restarts<BX&&ui(e))});let r={serviceName:e.name.replace(/ /g,"-")};function s(n){let i=d_.get(Te.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),o=/\[\d+][^\[]+\[(\w+)]/g,c,u=0,l;for(;c=o.exec(n);){if(c.index&&ls.LOG_LEVEL_HIERARCHY[i]>=ls.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===ls.LOG_LEVELS.ERR||l===ls.LOG_LEVELS.WRN?$s.OUTPUTS.STDERR:$s.OUTPUTS.STDOUT;$s.logCustomLevel(l||"info",E,r,n.slice(u,c.index).trim())}let[_,d]=c;u=c.index+_.length,l=ls.LOG_LEVELS[d]}if(ls.LOG_LEVEL_HIERARCHY[i]>=ls.LOG_LEVEL_HIERARCHY[l||"info"]){let _=l===ls.LOG_LEVELS.ERR||l===ls.LOG_LEVELS.WRN?$s.OUTPUTS.STDERR:$s.OUTPUTS.STDOUT;$s.logCustomLevel(l||"info",_,r,n.slice(u).trim())}}if(a(s,"extractMessages"),t.stdout.on("data",s),t.stderr.on("data",s),t.unref(),!Kt){Kt=[];let n=a(()=>{VC=!0,Kt&&(Kt.map(i=>i.kill()),process.exit(0))},"kill_children");process.on("exit",n),process.on("SIGINT",n),process.on("SIGQUIT",n),process.on("SIGTERM",n)}Kt.push(t)}a(ui,"start");function HX(e){return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.start(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(HX,"startWithPM2");function hS(e){if(!ac){for(let t of Kt||[])t.name===e&&(Kt.splice(Kt.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.stop(e,async(s,n)=>{s&&(fe.disconnect(),r(s)),fe.delete(e,(i,o)=>{i&&(fe.disconnect(),r(s)),fe.disconnect(),t(o)})})})}a(hS,"stop");function YC(e){return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.reload(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(YC,"reload");function KC(e){if(!ac)for(let t of Kt||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.restart(e,(s,n)=>{fe.disconnect(),t(n)})})}a(KC,"restart");function FX(e){return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.delete(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(FX,"deleteProcess");async function WC(){await ui(yn.generateRestart())}a(WC,"restartHdb");async function qX(){let e=await mS();for(let t in e)if(e[t].name===Te.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(qX,"isHdbRestartRunning");function mS(){return new Promise(async(e,t)=>{try{await Ys()}catch(r){t(r)}fe.list((r,s)=>{r&&(fe.disconnect(),t(r)),fe.disconnect(),e(s)})})}a(mS,"list");function QC(e){return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.describe(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(QC,"describe");function GX(){if(!ac){for(let e of Kt||[])e.kill();Kt=[];return}return new Promise(async(e,t)=>{try{await Ys()}catch(r){t(r)}fe.killDaemon((r,s)=>{r&&(fe.disconnect(),t(r)),fe.disconnect(),e(s)})})}a(GX,"kill");async function xX(){try{await jC(),await eU(),await ui(yn.generateAllServiceConfigs())}catch(e){throw fe.disconnect(),e}}a(xX,"startAllServices");async function SS(e){try{let t;switch(e=e.toLowerCase(),e){case Te.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=yn.generateMainServerConfig();break;case Te.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=yn.generateNatsIngestServiceConfig();break;case Te.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=yn.generateNatsReplyServiceConfig();break;case Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=yn.generateNatsHubServerConfig(),await ui(t),await ic.removeNatsConfig(e);return;case Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=yn.generateNatsLeafServerConfig(),await ui(t),await ic.removeNatsConfig(e);return;case Te.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=yn.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await ui(t)}catch(t){throw fe.disconnect(),t}}a(SS,"startService");async function zC(){try{let e=await mS(),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 fe.disconnect(),e}}a(zC,"getUniqueServicesList");async function kX(e=[]){try{let t=!1,r=await zC();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===Te.PROCESS_DESCRIPTORS.HDB?t=!0:await KC(o))}t&&await XC(Te.PROCESS_DESCRIPTORS.HDB)}catch(t){throw fe.disconnect(),t}}a(kX,"restartAllServices");async function JC(e){if(Kt?.find(r=>r.name===e))return!0;let t=await LX.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(JC,"isServiceRegistered");async function XC(e){let t=e===Te.PROCESS_DESCRIPTORS.HDB?d_.get(Te.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):d_.get(Te.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await QC(e),s=CX.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await hS(e),await SS(e)):e===Te.PROCESS_DESCRIPTORS.HDB?await WC():await YC(e)}a(XC,"reloadStopStart");var ZC;async function jC(){for(let e in Te.CLUSTERING_PROCESSES){let t=Te.CLUSTERING_PROCESSES[e];await SS(t)}}a(jC,"startClusteringProcesses");async function eU(){ZC=kC(Te.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Te.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await oc.createWorkQueueStream(ls.WORK_QUEUE_CONSUMER_NAMES),await oc.updateIngestStreamConsumer(),await oc.updateLocalStreams();let e=await UX.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Te.PRE_4_0_0_VERSION){$s.info("Starting clustering upgrade 4.0.0 process"),kC(Te.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(eU,"startClusteringThreads");async function VX(){for(let e in Te.CLUSTERING_PROCESSES)if(e!==Te.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Te.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await ZC.terminate();else{let t=Te.CLUSTERING_PROCESSES[e];await hS(t)}}a(VX,"stopClustering");async function $X(){for(let e in Te.CLUSTERING_PROCESSES){let t=Te.CLUSTERING_PROCESSES[e];if(await JC(t)===!1)return!1}return!0}a($X,"isClusteringRunning");async function YX(){await ic.generateNatsConfig(!0),await oc.reloadNATSHub(),await oc.reloadNATSLeaf(),await ic.removeNatsConfig(Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await ic.removeNatsConfig(Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(YX,"reloadClustering")});var NS=m((kce,cU)=>{"use strict";var KX=require("minimist"),{isMainThread:RS,parentPort:iU}=require("worker_threads"),He=A(),{PROCESS_DESCRIPTORS_VALIDATE:cc}=He,_s=x(),gS=V(),E_=fS(),Eo=nt(),pS=Be(),oU=Nr(),ds=rU(),sU=uo(),WX=EE(),{restartWorkers:f_,onMessageByType:QX}=dt(),{handleHDBError:zX,hdb_errors:JX}=W(),{HTTP_STATUS_CODES:XX}=JX,h_=Q();h_.initSync();var uc=`Restarting HarperDB. This may take up to ${He.RESTART_TIMEOUT_MS/1e3} seconds.`,ZX="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",nU="Clustering is not enabled so cannot be restarted",jX="Invalid service",li,$r;cU.exports={restart:aU,restartService:AS};RS&&QX(He.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?AS({service:e.workerType}):aU({operation:"restart"})});async function aU(e){$r=Object.keys(e).length===0,li=await ds.isServiceRegistered(He.HDB_PROC_DESCRIPTOR);let t=KX(process.argv);if(t.service){await AS(t);return}if($r&&!li){console.error(ZX);return}if($r&&console.log(uc),li){ds.enterPM2Mode(),_s.notify(uc);let r=WX(Object.keys(He.CONFIG_PARAM_MAP),!0);return gS.isEmptyOrZeroLength(Object.keys(r))||oU.updateConfigValue(void 0,void 0,r,!0,!0),t4(),uc}return RS?(_s.notify(uc),await OS(),setTimeout(()=>{f_()},50)):iU.postMessage({type:He.ITC_EVENT_TYPES.RESTART}),uc}a(aU,"restart");async function AS(e){let{service:t}=e;if(He.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw zX(new Error,jX,XX.BAD_REQUEST,void 0,void 0,!0);if(li=await ds.isServiceRegistered(He.HDB_PROC_DESCRIPTOR),!RS)return iU.postMessage({type:He.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case cc.clustering:if(!h_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=nU;break}$r&&console.log("Restarting clustering"),_s.notify("Restarting clustering"),await OS();break;case cc.clustering_config:case cc["clustering config"]:if(!h_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=nU;break}$r&&console.log("Restarting clustering_config"),_s.notify("Restarting clustering_config"),await ds.reloadClustering();break;case"custom_functions":case"custom functions":case cc.harperdb:case cc.http_workers:if($r&&!li){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}$r&&console.log("Restarting http_workers"),_s.notify("Restarting http_workers"),li?await ds.restart(He.HDB_PROC_DESCRIPTOR):setTimeout(()=>{f_("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(_s.error(r),$r&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(AS,"restartService");async function e4(){await Eo.publishToStream(`${pS.SUBJECT_PREFIXES.TXN}.${pS.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,pS.WORK_QUEUE_CONSUMER_NAMES.stream_name,Eo.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(e4,"postDummyNatsMsg");async function t4(){await OS(),await ds.restart(He.HDB_PROC_DESCRIPTOR),await gS.async_set_timeout(2e3),h_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await TS(),$r&&(await Eo.closeConnection(),process.exit(0))}a(t4,"restartPM2Mode");async function OS(){if(!oU.getConfigFromFile(He.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await sU.getHDBProcessInfo()).clustering.length===0)_s.trace("Clustering not running, restart will start clustering services"),await E_.generateNatsConfig(!0),await ds.startClusteringProcesses(),await ds.startClusteringThreads(),await TS(),$r&&await Eo.closeConnection();else{await e4(),await E_.generateNatsConfig(!0),li?(_s.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await ds.restart(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ds.restart(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await sU.getHDBProcessInfo()).clustering.forEach(n=>{_s.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await gS.async_set_timeout(3e3),await TS(),await Eo.updateLocalStreams(),$r&&await Eo.closeConnection(),_s.trace("Restart clustering restarting ingest and reply service threads");let t=f_(He.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=f_(He.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(OS,"restartClustering");async function TS(){await E_.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await E_.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(TS,"removeNatsConfig")});var TU=m((Yce,pU)=>{"use strict";var $ce=require("lodash"),Wt=A(),{handleHDBError:uU,hdb_errors:r4}=W(),{HDB_ERROR_MSGS:s4,HTTP_STATUS_CODES:n4}=r4,bS=x();pU.exports={getRolePermissions:o4};var _i=Object.create(null),i4=a(e=>({key:e,perms:{}}),"perms_template_obj"),EU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),fU=a((e=!1,t=!1,r=!1,s=!1)=>({[Wt.PERMS_CRUD_ENUM.READ]:e,[Wt.PERMS_CRUD_ENUM.INSERT]:t,[Wt.PERMS_CRUD_ENUM.UPDATE]:r,[Wt.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),yS=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...fU(t,r,s,n)}),"table_perms_template"),lU=a((e,t=fU())=>({attribute_name:e,describe:SU(t),[lc]:t[lc],[IS]:t[IS],[wS]:t[wS]}),"attr_perms_template"),_U=a((e,t=!1)=>({attribute_name:e,describe:t,[lc]:t}),"timestamp_attr_perms_template"),{READ:lc,INSERT:IS,UPDATE:wS}=Wt.PERMS_CRUD_ENUM,hU=Object.values(Wt.PERMS_CRUD_ENUM),mU=[lc,IS,wS];function o4(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[Wt.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(_i[t]&&_i[t].key===s)return _i[t].perms;let n=a4(e,r);return _i[t]?_i[t].key=s:_i[t]=i4(s),_i[t].perms=n,n}catch(r){if(!e[Wt.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Wt.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Wt.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 bS.error(s),bS.debug(r),uU(new Error,s4.OUTDATED_PERMS_TRANSLATION_ERROR,n4.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
6
|
+
${r.stack}`;throw bS.error(s),uU(new Error)}}}a(o4,"getRolePermissions");function a4(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[Wt.SYSTEM_SCHEMA_NAME]=s[Wt.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]=c4(t[i]);return}r[i]=EU(),s[i]?(s[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],u=t[i][o],l=u4(c,u);r[i].describe||hU.forEach(_=>{l[_]&&(r[i].describe=!0)}),r[i].tables[o]=l}else r[i].tables[o]=yS()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=yS()})}),r}a(a4,"translateRolePermissions");function c4(e){let t=EU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=yS(!0,!0,!0,!0,!0)}),t}a(c4,"createStructureUserPermissions");function u4(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((l,_)=>{let{attribute_name:d}=_,E=_;return Wt.TIME_STAMP_NAMES.includes(d)&&(E=_U(d,_[lc])),l[d]=E,l},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=lU(o);return t.attributes.forEach(({attribute:l})=>{if(i[l]){let _=i[l];_.describe=SU(_),n.attribute_permissions.push(_),c||l4(_,u)}else if(l!==o){let _;Wt.TIME_STAMP_NAMES.includes(l)?_=_U(l):_=lU(l),n.attribute_permissions.push(_)}}),c||n.attribute_permissions.push(u),n.describe=dU(n),n}else return e.describe=dU(e),e}a(u4,"getTableAttrPerms");function dU(e){return hU.filter(t=>e[t]).length>0}a(dU,"getSchemaTableDescribePerm");function SU(e){return mU.filter(t=>e[t]).length>0}a(SU,"getAttributeDescribePerm");function l4(e,t){mU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(l4,"checkForHashPerms")});var RU={};je(RU,{Resources:()=>m_,keyArrayToString:()=>fo,resetResources:()=>_4,resources:()=>In});function _4(){return In=new m_}function fo(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var m_,In,_c=Se(()=>{xn();m_=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,s,n){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:s,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!n)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let l=2;for(;(l=c.indexOf("/",l))>-1;){let _=this.get(c.slice(0,l));_&&(_.hasSubPaths=!0),l+=2}}}getMatch(t,r){let s=2,n;for(;(s=t.indexOf("/",s))>-1;){let c=t.slice(0,s),u=this.get(c);if(u){if(u.relativeURL=t.slice(s),!u.hasSubPaths)return u;n=u}s+=2}if(n)return n;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return n=this.get(o),n?n.relativeURL=i>-1?t.slice(i):"":n||(n=this.get(""),n&&(n.relativeURL="")),n}getResource(t,r){let s=this.getMatch(t);if(s)return t=s.relativeURL,s.Resource.getResource(this.pathToId(t,s.Resource),r)}call(t,r,s){return Ye(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(_4,"resetResources");a(fo,"keyArrayToString")});var ho,CS=Se(()=>{ho=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}append(t,r,s){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase(),i=super.get(n);if(i){let o=i[1];s?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var dc={};je(dc,{authentication:()=>yU,login:()=>R4,logout:()=>g4,start:()=>T4});async function yU(e,t){let r=e.headers,s=r.authorization,n=r.cookie,i=r.origin,o=[];if(i){let f=e.isOperationsServer?h4?f4:[]:E4?d4:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h={"Access-Control-Allow-Methods":"POST, GET, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Accept, Content-Type, Authorization","Access-Control-Allow-Origin":i};return S_&&(h["Access-Control-Allow-Credentials"]="true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),S_&&o.push("Access-Control-Allow-Credentials","true")}}let c,u;if(S_){let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(f);if(h>=0){let T=n.indexOf(";",h),p=n.indexOf("=",h);c=n.slice(p+1,T===-1?n.length:T),u=await AU.get(c)}e.session=u||(u={})}e.user=null;let l=a((f,h,T)=>{let p=new R_.AuthAuditLog(f,h,Tt.AUTH_AUDIT_TYPES.AUTHENTICATION,e.headers["x-forwarded-for"]??e.ip,e.method,e.pathname);p.auth_strategy=T,c&&(p.session_id=c),e.headers.referer&&(p.referer=e.headers.referer),e.headers.origin&&(p.origin=e.headers.origin),h===Tt.AUTH_AUDIT_STATUS.SUCCESS?gU.notify(p):gU.error(p)},"authAuditLog"),_;if(s){if(_=mo.get(s),!_){let[f,h]=s.split(" "),T,p;try{switch(f){case"Basic":[T,p]=atob(h).split(":"),_=T||p?await tt.auth(T,p):null;break;case"Bearer":try{_=await(0,T_.validateOperationToken)(h)}catch(R){if(R.message==="invalid token")try{return await(0,T_.validateRefreshToken)(h),{status:-1}}catch{throw R}}break}}catch(R){return p4&&(mo.get(h)||(mo.set(h,h),l(T,Tt.AUTH_AUDIT_STATUS.FAILURE,f))),{status:401,body:Ks({error:R.message},e)}}mo.set(s,_),S4&&l(_.username,Tt.AUTH_AUDIT_STATUS.SUCCESS,f)}e.user=_}else u?.user?e.user=await tt.auth(u.user,null,!1):m4&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")&&(e.user=_=await(0,p_.getSuperUser)());S_&&(e.session.update=function(f){if(!c){c=(0,NU.v4)();let T=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${c}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",T):d?.headers?.set&&d.headers.set("Set-Cookie",T)}return f.id=c,AU.put(f)},e.login=async function(f,h){e.user=await tt.auth(f,h),e.session.update({user:e.user.username})},(_&&!u||u?.user?.username!==_?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let d=await t(e);if(!d)return d;d.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&In.loginPath?(d.status=302,d.headers.set("Location",In.loginPath(e))):d.headers.set("WWW-Authenticate","Basic"));let E=o.length;if(E>0){let f=d.headers;f||(d.headers=f=new ho);for(let h=0;h<E;){let T=o[h++];f.set(T,o[h++])}}return o=null,d}function T4({server:e,port:t}){e.request(yU,{port:t||"all"}),OU||(OU=!0,setInterval(()=>{mo=new Map},Ir.get(Tt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),bU.user.addListener(()=>{mo=new Map}))}async function R4(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function g4(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var p_,T_,NU,Ir,Tt,R_,bU,gU,d4,E4,f4,h4,AU,S_,m4,S4,p4,mo,OU,g_=Se(()=>{p_=C(br());es();_c();T_=C($a());de();NU=require("uuid"),Ir=C(Q()),Tt=C(A()),R_=C(x());So();bU=C(ba());CS();gU=(0,R_.loggerWithTag)("auth-event");Ir.initSync();d4=Ir.get(Tt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),E4=Ir.get(Tt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS),f4=Ir.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),h4=Ir.get(Tt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS);tt.auth=p_.findAndValidateUser;AU=rt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),S_=Ir.get(Tt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,m4=Ir.get(Tt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??!0,S4=Ir.get(Tt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,p4=Ir.get(Tt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,mo=new Map;a(yU,"authentication");a(T4,"start");a(R4,"login");a(g4,"logout")});var MU=m((sue,LU)=>{"use strict";var he=require("joi"),IU=require("fs-extra"),wU=require("path"),Qs=ve(),CU=Q(),UU=A(),DU=x(),{hdb_errors:A4}=W(),{HDB_ERROR_MSGS:Dt}=A4,Ws=/^[a-zA-Z0-9-_]+$/;LU.exports={getDropCustomFunctionValidator:N4,setCustomFunctionValidator:b4,addComponentValidator:C4,dropCustomFunctionProjectValidator:U4,packageComponentValidator:D4,deployComponentValidator:L4,setComponentFileValidator:y4,getComponentFileValidator:w4,dropComponentFileValidator:I4};function A_(e,t,r){try{let s=CU.get(UU.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=wU.join(s,t);return IU.existsSync(n)?e?t:r.message(Dt.PROJECT_EXISTS):e?r.message(Dt.NO_PROJECT):t}catch(s){return DU.error(s),r.message(Dt.VALIDATION_ERR)}}a(A_,"checkProjectExists");function Ec(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Ec,"checkFilePath");function O4(e,t,r,s){try{let n=CU.get(UU.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=wU.join(n,e,t,r+".js");return IU.existsSync(i)?r:s.message(Dt.NO_FILE)}catch(n){return DU.error(n),s.message(Dt.VALIDATION_ERR)}}a(O4,"checkFileExists");function N4(e){let t=he.object({project:he.string().pattern(Ws).custom(A_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),type:he.string().valid("helpers","routes").required(),file:he.string().pattern(Ws).custom(O4.bind(null,e.project,e.type)).custom(Ec).required().messages({"string.pattern.base":Dt.BAD_FILE_NAME})});return Qs.validateBySchema(e,t)}a(N4,"getDropCustomFunctionValidator");function b4(e){let t=he.object({project:he.string().pattern(Ws).custom(A_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),type:he.string().valid("helpers","routes").required(),file:he.string().custom(Ec).required(),function_content:he.string().required()});return Qs.validateBySchema(e,t)}a(b4,"setCustomFunctionValidator");function y4(e){let t=he.object({project:he.string().pattern(Ws).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),file:he.string().custom(Ec).required(),payload:he.string().optional(),encoding:he.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Qs.validateBySchema(e,t)}a(y4,"setComponentFileValidator");function I4(e){let t=he.object({project:he.string().pattern(Ws).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),file:he.string().custom(Ec).optional()});return Qs.validateBySchema(e,t)}a(I4,"dropComponentFileValidator");function w4(e){let t=he.object({project:he.string().required(),file:he.string().custom(Ec).required(),encoding:he.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Qs.validateBySchema(e,t)}a(w4,"getComponentFileValidator");function C4(e){let t=he.object({project:he.string().pattern(Ws).custom(A_.bind(null,!1)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME})});return Qs.validateBySchema(e,t)}a(C4,"addComponentValidator");function U4(e){let t=he.object({project:he.string().pattern(Ws).custom(A_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME})});return Qs.validateBySchema(e,t)}a(U4,"dropCustomFunctionProjectValidator");function D4(e){let t=he.object({project:he.string().pattern(Ws).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),skip_node_modules:he.boolean()});return Qs.validateBySchema(e,t)}a(D4,"packageComponentValidator");function L4(e){let t=he.object({project:he.string().pattern(Ws).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),payload:he.string().optional().messages({"string.pattern.base":Dt.BAD_PACKAGE}),package:he.string().optional()});return Qs.validateBySchema(e,t)}a(L4,"deployComponentValidator")});var MS=m((iue,BU)=>{"use strict";var be=require("fs-extra"),US=require("fast-glob"),me=require("path"),PU=require("tar-fs"),M4=require("uuid").v4,DS=require("normalize-path"),Es=MU(),Rt=x(),Ie=A(),$e=Q(),O_=Nr(),P4=V(),{PACKAGE_ROOT:v4}=A(),{handleHDBError:it,hdb_errors:B4}=W(),{HDB_ERROR_MSGS:wn,HTTP_STATUS_CODES:ot}=B4,H4=me.join(v4,"application-template"),LS=me.join($e.get(Ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function vU(){let e=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw it(new Error,wn.NOT_ENABLED,ot.BAD_REQUEST,void 0,void 0,!0)}a(vU,"isCFEnabled");function F4(){Rt.trace("getting custom api status");let e={};try{e={is_enabled:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw it(new Error,wn.FUNCTION_STATUS,ot.INTERNAL_SERVER_ERROR,Rt.ERR,t)}return e}a(F4,"customFunctionsStatus");function q4(){Rt.trace("getting custom api endpoints");let e={},t=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{US.sync(DS(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:US.sync(DS(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:US.sync(DS(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw it(new Error,wn.GET_FUNCTIONS,ot.INTERNAL_SERVER_ERROR,Rt.ERR,r)}return e}a(q4,"getCustomFunctions");function G4(e){e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=Es.getDropCustomFunctionValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);Rt.trace("getting custom api endpoint file content");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=me.join(r,s,n,i+".js");try{return be.readFileSync(o,{encoding:"utf8"})}catch(c){throw it(new Error,wn.GET_FUNCTION,ot.INTERNAL_SERVER_ERROR,Rt.ERR,c)}}a(G4,"getCustomFunction");function x4(e){vU(),e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=Es.setCustomFunctionValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);Rt.trace("setting custom function file content");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return be.outputFileSync(me.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw it(new Error,wn.SET_FUNCTION,ot.INTERNAL_SERVER_ERROR,Rt.ERR,c)}}a(x4,"setCustomFunction");function k4(e){e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=Es.getDropCustomFunctionValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);Rt.trace("dropping custom function file");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return be.unlinkSync(me.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw it(new Error,wn.DROP_FUNCTION,ot.INTERNAL_SERVER_ERROR,Rt.ERR,o)}}a(k4,"dropCustomFunction");function V4(e){vU(),e.project&&(e.project=me.parse(e.project).name);let t=Es.addComponentValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);Rt.trace("adding component");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=me.join(r,s);return be.mkdirSync(n,{recursive:!0}),be.copySync(H4,n),`Successfully added project: ${s}`}catch(n){throw it(new Error,wn.ADD_FUNCTION,ot.INTERNAL_SERVER_ERROR,Rt.ERR,n)}}a(V4,"addComponent");function $4(e){e.project&&(e.project=me.parse(e.project).name);let t=Es.dropCustomFunctionProjectValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);Rt.trace("dropping custom function project");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=$e.get(Ie.CONFIG_PARAMS.APPS);if(!P4.isEmptyOrZeroLength(n)){let i=!1;for(let[o,c]of n.entries())if(c.name===s){n.splice(o,1),i=!0;break}if(i)return O_.updateConfigValue(Ie.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=me.join(r,s);return be.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw it(new Error,wn.DROP_FUNCTION_PROJECT,ot.INTERNAL_SERVER_ERROR,Rt.ERR,i)}}a($4,"dropCustomFunctionProject");async function Y4(e){e.project&&(e.project=me.parse(e.project).name);let t=Es.packageComponentValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;Rt.trace("packaging component",s);let n;try{n=await be.realpath(me.join(r,s))}catch(u){if(u.code!==Ie.NODE_ERROR_CODES.ENOENT)throw u;try{n=await be.realpath(me.join($e.get(Ie.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(l){if(l.code===Ie.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await be.ensureDir(LS);let i=me.join(LS,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(me.join(n,"node_modules"))}),PU.pack(n,o).pipe(be.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=be.readFileSync(i,{encoding:"base64"});return await be.remove(i),{project:s,payload:c}}a(Y4,"packageComponent");async function K4(e){e.project&&(e.project=me.parse(e.project).name);let t=Es.deployComponentValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,package:i}=e;if(Rt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");if(n){let o=me.join(r,s);i="file:"+o,await be.ensureDir(o);let c,u;do c=me.join(LS,M4()+".tar"),u=await be.pathExists(c);while(u);await be.outputFile(c,n,{encoding:"base64"});let l=be.createReadStream(c);l.pipe(PU.extract(o)),await new Promise(_=>l.on("end",_)),await be.unlink(c)}return O_.updateConfigValue(`${s}_package`,i,void 0,!1,!1,!0),`Successfully deployed: ${s}`}a(K4,"deployComponent");async function W4(){let e=O_.getConfiguration(),t=[];for(let s in e)if(e[s]?.package){if(e[s].package.startsWith("file:"))continue;t.push(Object.assign(e[s],{name:s}))}let r=a(async(s,n)=>{let i=await be.readdir(s,{withFileTypes:!0});for(let o of i){let c=o.name;if(c.startsWith(".")||c==="node_modules")continue;let u=me.join(s,c);if(await o.isDirectory()){let l={name:c,entries:[]};n.entries.push(l),await r(u,l)}else{let l=await be.stat(u),_={name:me.basename(c),mtime:l.mtime,size:l.size};n.entries.push(_)}}return n},"walk_dir");return r($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),{name:$e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT).split(me.sep).slice(-1).pop(),entries:t})}a(W4,"getComponents");async function Q4(e){let t=Es.getComponentFileValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{return await be.readFile(me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),e.project,e.file),r)}catch(s){throw s.code===Ie.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${me.join(e.project,e.file)}'`):s}}a(Q4,"getComponentFile");async function z4(e){let t=Es.setComponentFileValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),e.project,e.file);return e.payload!==void 0?(await be.ensureFile(s),await be.outputFile(s,e.payload,r)):await be.ensureDir(s),"Successfully set component: "+e.file}a(z4,"setComponentFile");async function J4(e){let t=Es.dropComponentFileValidator(e);if(t)throw it(t,t.message,ot.BAD_REQUEST);let r=e.file?me.join(e.project,e.file):e.project,s=me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),r);return await be.pathExists(s)&&await be.remove(s),O_.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(J4,"dropComponent");BU.exports={customFunctionsStatus:F4,getCustomFunctions:q4,getCustomFunction:G4,setCustomFunction:x4,dropCustomFunction:k4,addComponent:V4,dropCustomFunctionProject:$4,packageComponent:Y4,deployComponent:K4,getComponents:W4,getComponentFile:Q4,setComponentFile:z4,dropComponent:J4}});var PS=m((aue,FU)=>{"use strict";var hs=require("joi"),HU=ve();FU.exports={readTransactionLogValidator:X4,deleteTransactionLogsBeforeValidator:Z4};function X4(e){let t=hs.object({schema:hs.string().required(),table:hs.string().required(),from:hs.date().timestamp(),to:hs.date().timestamp(),limit:hs.number().min(1)});return HU.validateBySchema(e,t)}a(X4,"readTransactionLogValidator");function Z4(e){let t=hs.object({schema:hs.string().required(),table:hs.string().required(),timestamp:hs.date().timestamp().required()});return HU.validateBySchema(e,t)}a(Z4,"deleteTransactionLogsBeforeValidator")});var b_=m((uue,VU)=>{"use strict";var vS=A(),N_=nt(),qU=V(),GU=Q(),xU=Ps(),{handleHDBError:po,hdb_errors:j4}=W(),{HTTP_STATUS_CODES:To}=j4,{readTransactionLogValidator:eZ,deleteTransactionLogsBeforeValidator:tZ}=PS(),kU="This operation relies on clustering and cannot run with it disable.",rZ="Logs successfully deleted from transaction log.",sZ="All logs successfully deleted from transaction log.";VU.exports={readTransactionLog:nZ,deleteTransactionLogsBefore:iZ};async function*nZ(e){let t=eZ(e);if(t)throw po(t,t.message,To.BAD_REQUEST,void 0,void 0,!0);if(!GU.get(vS.CONFIG_PARAMS.CLUSTERING_ENABLED))throw po(new Error,kU,To.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=qU.checkSchemaTableExist(r,s);if(n)throw po(new Error,n,To.NOT_FOUND,void 0,void 0,!0);let i=xU.createNatsTableStreamName(r,s),o=await N_.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let l={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===vS.OPERATIONS_ENUM.DELETE&&(l.hash_values=c?.entry?.hash_values),yield l}}a(nZ,"readTransactionLog");async function iZ(e){let t=tZ(e);if(t)throw po(t,t.message,To.BAD_REQUEST,void 0,void 0,!0);if(!GU.get(vS.CONFIG_PARAMS.CLUSTERING_ENABLED))throw po(new Error,kU,To.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=qU.checkSchemaTableExist(r,s);if(i)throw po(new Error,i,To.NOT_FOUND,void 0,void 0,!0);let o=xU.createNatsTableStreamName(r,s),{jsm:c}=await N_.getNATSReferences(),u=await N_.getStreamInfo(o),l=new Date(u.state.first_ts).getTime();if(n<=l)return`No transactions exist before: ${n}`;let _=rZ,d,E=new Date(u.state.last_ts).getTime();return n>E?(d=u.state.last_seq+1,_=sZ):d=(await N_.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),_}a(iZ,"deleteTransactionLogsBefore")});var C_=m((_ue,JU)=>{"use strict";var y_=require("joi"),I_=require("path"),$U=require("fs-extra"),{exec:oZ}=require("child_process"),aZ=require("util"),YU=aZ.promisify(oZ),fc=A(),{handleHDBError:Ro,hdb_errors:cZ}=W(),{HTTP_STATUS_CODES:go}=cZ,mc=Q(),uZ=ve(),hc=x();mc.initSync();var BS=mc.get(fc.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),KU="npm install --omit=dev --json",lZ=`${KU} --dry-run`;JU.exports={installModules:fZ,auditModules:hZ,installAllRootModules:_Z,uninstallRootModule:dZ,linkHarperdb:EZ};async function _Z(e=!1){await w_(),await Sc(e?"npm install --ignore-scripts":"npm install",mc.get(fc.CONFIG_PARAMS.ROOTPATH))}a(_Z,"installAllRootModules");async function dZ(e){await Sc(`npm uninstall ${e}`,mc.get(fc.CONFIG_PARAMS.ROOTPATH))}a(dZ,"uninstallRootModule");async function EZ(){await w_(),await Sc(`npm link ${fc.PACKAGE_ROOT}`,mc.get(fc.CONFIG_PARAMS.ROOTPATH))}a(EZ,"linkHarperdb");async function Sc(e,t=void 0){let{stdout:r,stderr:s}=await YU(e,{cwd:t});if(s&&!s.includes("Debugger listening"))throw new Error(s.replace(`
|
|
7
|
+
`,""));return hc.trace(r,s),r.replace(`
|
|
8
|
+
`,"")}a(Sc,"runCommand");async function fZ(e){hc.info(`starting installModules for request: ${e}`);let t=zU(e);if(t)throw Ro(t,t.message,go.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?lZ:KU;await w_(),await QU(r);let i={};for(let o=0,c=r.length;o<c;o++){let u=r[o];i[u]={npm_output:null,npm_error:null};let l=I_.join(BS,u),_,d=null;try{let{stdout:E,stderr:f}=await YU(n,{cwd:l});_=E?E.replace(`
|
|
9
9
|
`,""):null,d=f?f.replace(`
|
|
10
|
-
`,""):null}catch(E){E.stderr?i[u].npm_error=
|
|
11
|
-
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}o(VU,"parseNPMStdErr");async function lZ(e){Ec.info(`starting auditModules for request: ${e}`);let t=YU(e);if(t)throw Sa(t,t.message,pa.BAD_REQUEST);let{projects:r}=e;await N_(),await $U(r);let s={};for(let n=0,i=r.length;n<i;n++){let a=r[n],c=O_.join(LS,a);s[a]={npm_output:null,npm_error:null};try{let u=await hc("npm audit --json",c);s[a].npm_output=JSON.parse(u)}catch(u){s[a].npm_error=VU(u.stderr)}}return Ec.info(`finished auditModules with response ${s}`),s}o(lZ,"auditModules");async function N_(){try{return await hc("npm -v"),!0}catch{throw Sa(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",pa.BAD_REQUEST,void 0,void 0,!0)}}o(N_,"checkNPMInstalled");async function $U(e){if(!Array.isArray(e)||e.length===0)throw Sa(new Error,"projects argument must be an array with at least 1 element",pa.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],a=O_.join(LS,i.toString());if(!await GU.pathExists(a)){t.push(i);continue}let u=O_.join(a,"package.json");await GU.pathExists(u)||r.push(i)}if(t.length>0)throw Sa(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,pa.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Sa(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,pa.BAD_REQUEST,void 0,void 0,!0)}o($U,"checkProjectPaths");function YU(e){let t=A_.object({projects:A_.array().min(1).items(A_.string()).required(),dry_run:A_.boolean().default(!1)});return nZ.validateBySchema(e,t)}o(YU,"modulesValidator")});var QU=m((iue,WU)=>{"use strict";var MS=class{static{o(this,"PermissionTableResponseObject")}constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};WU.exports=MS});var JU=m((oue,zU)=>{"use strict";var PS=class{static{o(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};zU.exports=PS});var BS=m((uue,ZU)=>{"use strict";var XU=QU(),_Z=JU(),{HDB_ERROR_MSGS:dZ}=rr(),vS=class{static{o(this,"PermissionResponseObject")}constructor(){this.error=dZ.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 XU(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new _Z(c,n[c]);i.push(u)});let a=`${r}_${s}`;if(this.unauthorized_access[a])this.unauthorized_access[a].required_attribute_permissions=i;else{let c=new XU(r,s,[],i);this.unauthorized_access[a]=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}};ZU.exports=vS});var C_=m((_ue,fD)=>{"use strict";var HS=Rr(),y_=Tr(),Ir=yl(),pc=$n(),FS=zn(),EZ=Jh(),fZ=TI(),Tc=Or(),I_=im(),it=q(),hZ=cm(),mZ=Vl(),SZ=Vm(),pZ=Wl(),TZ=$m(),RZ=Ym(),gZ=Qm(),AZ=Jm(),qS=jm(),Ws=x(),OZ=hC(),GS=nS(),tD=gS(),yr=g(),rD=hU(),NZ=ca(),sD=ko(),nD=(S_(),re(lc)),iD=Ar(),dr=CS(),bZ=require("alasql"),aD=g_(),oD=b_(),cD=BS(),{handleHDBError:Qt,hdb_errors:uD}=W(),{HDB_ERROR_MSGS:gt,HTTP_STATUS_CODES:mc}=uD,P=new Map,lD="delete",wn="insert",Qs="read",_i="update",Sc="describe",jU=pc.describeSchema.name,eD=pc.describeTable.name,_D={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},yZ="catchup",IZ="handleGetJob",wZ="handleGetJobsByStartDate",w_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},CZ=[Ir.createTable.name,Ir.createAttribute.name,Ir.dropTable.name,Ir.dropAttribute.name],dD={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},F=class{static{o(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};P.set(HS.insert.name,new F(!1,[wn]));P.set(HS.update.name,new F(!1,[_i]));P.set(HS.upsert.name,new F(!1,[wn,_i]));P.set(y_.searchByConditions.name,new F(!1,[Qs]));P.set(y_.searchByHash.name,new F(!1,[Qs]));P.set(y_.searchByValue.name,new F(!1,[Qs]));P.set(y_.search.name,new F(!1,[Qs]));P.set(Ir.createSchema.name,new F(!0,[]));P.set(Ir.createTable.name,new F(!0,[]));P.set(Ir.createAttribute.name,new F(!1,[wn]));P.set(Ir.dropSchema.name,new F(!0,[]));P.set(Ir.dropTable.name,new F(!0,[]));P.set(Ir.dropAttribute.name,new F(!0,[]));P.set(pc.describeSchema.name,new F(!1,[Qs]));P.set(pc.describeTable.name,new F(!1,[Qs]));P.set(FS.deleteRecord.name,new F(!1,[lD]));P.set(Tc.addUser.name,new F(!0,[]));P.set(Tc.alterUser.name,new F(!0,[]));P.set(Tc.dropUser.name,new F(!0,[]));P.set(Tc.listUsersExternal.name,new F(!0,[]));P.set(I_.listRoles.name,new F(!0,[]));P.set(I_.addRole.name,new F(!0,[]));P.set(I_.alterRole.name,new F(!0,[]));P.set(I_.dropRole.name,new F(!0,[]));P.set(hZ.name,new F(!0,[]));P.set(mZ.name,new F(!0,[]));P.set(SZ.name,new F(!0,[]));P.set(pZ.name,new F(!0,[]));P.set(TZ.name,new F(!0,[]));P.set(RZ.name,new F(!0,[]));P.set(qS.setRoutes.name,new F(!0,[]));P.set(qS.getRoutes.name,new F(!0,[]));P.set(qS.deleteRoutes.name,new F(!0,[]));P.set(iD.setConfiguration.name,new F(!0,[]));P.set(gZ.clusterStatus.name,new F(!0,[]));P.set(AZ.name,new F(!0,[]));P.set(GS.getFingerprint.name,new F(!0,[]));P.set(GS.setLicense.name,new F(!0,[]));P.set(FS.deleteFilesBefore.name,new F(!0,[]));P.set(FS.deleteAuditLogsBefore.name,new F(!0,[]));P.set(tD.restart.name,new F(!0,[]));P.set(tD.restartService.name,new F(!0,[]));P.set(EZ.name,new F(!0,[]));P.set(fZ.name,new F(!0,[Qs]));P.set(NZ.systemInformation.name,new F(!0,[]));P.set(iD.getConfiguration.name,new F(!0,[]));P.set(aD.readTransactionLog.name,new F(!0,[]));P.set(aD.deleteTransactionLogsBefore.name,new F(!0,[]));P.set(oD.installModules.name,new F(!0,[]));P.set(oD.auditModules.name,new F(!0,[]));P.set(sD.createTokens.name,new F(!1,[]));P.set(sD.refreshOperationToken.name,new F(!1,[]));P.set(nD.login.name,new F(!1,[]));P.set(nD.logout.name,new F(!1,[]));P.set(dr.customFunctionsStatus.name,new F(!0,[]));P.set(dr.getCustomFunctions.name,new F(!0,[]));P.set(dr.getComponents.name,new F(!0,[]));P.set(dr.getComponentFile.name,new F(!0,[]));P.set(dr.setComponentFile.name,new F(!0,[]));P.set(dr.dropComponent.name,new F(!0,[]));P.set(dr.getCustomFunction.name,new F(!0,[]));P.set(dr.setCustomFunction.name,new F(!0,[]));P.set(dr.dropCustomFunction.name,new F(!0,[]));P.set(dr.addComponent.name,new F(!0,[]));P.set(dr.dropCustomFunctionProject.name,new F(!0,[]));P.set(dr.packageComponent.name,new F(!0,[]));P.set(dr.deployComponent.name,new F(!0,[]));P.set(GS.getRegistrationInfo.name,new F(!1,[]));P.set(Tc.userInfo.name,new F(!1,[]));P.set(pc.describeAll.name,new F(!1,[]));P.set(IZ,new F(!1,[]));P.set(wZ,new F(!0,[]));P.set(yZ,new F(!0,[]));P.set(w_.CSV_DATA_LOAD,new F(!1,[wn,_i]));P.set(w_.CSV_URL_LOAD,new F(!1,[wn,_i]));P.set(w_.CSV_FILE_LOAD,new F(!1,[wn,_i]));P.set(w_.IMPORT_FROM_S3,new F(!1,[wn,_i]));P.set(dD.EXPORT_TO_S3,new F(!0,[]));P.set(dD.EXPORT_LOCAL,new F(!0,[]));P.set(yr.VALID_SQL_OPS_ENUM.DELETE,new F(!1,[lD]));P.set(yr.VALID_SQL_OPS_ENUM.SELECT,new F(!1,[Qs]));P.set(yr.VALID_SQL_OPS_ENUM.INSERT,new F(!1,[wn]));P.set(yr.VALID_SQL_OPS_ENUM.UPDATE,new F(!1,[_i]));fD.exports={verifyPerms:DZ,verifyPermsAst:UZ,verifyBulkLoadAttributePerms:MZ};function UZ(e,t,r){if(Ws.isEmptyOrZeroLength(e))throw it.info("verify_perms_ast has an empty user parameter"),Qt(new Error);if(Ws.isEmptyOrZeroLength(t))throw it.info("verify_perms_ast has an empty user parameter"),Qt(new Error);if(Ws.isEmptyOrZeroLength(r))throw it.info("verify_perms_ast has a null operation parameter"),Qt(new Error);try{let s=new cD,n=new OZ(e),i=n.getSchemas(),a=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw it.info("No schemas defined in verifyPermsAst(), will not continue."),Qt(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&_D[r])throw Qt(new Error,gt.DROP_SYSTEM,mc.FORBIDDEN);if(c&&!u)return null;let l=rD.getRolePermissions(t.role);t.role.permission=l,!c&&e instanceof bZ.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(l));for(let d=0;d<i.length;d++){let E=n.getTablesBySchemaName(i[d]);E&&a.set(i[d],E)}let _=ED(t,r,a,s);return _||(a.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=n.getAttributesBySchemaTableName(E,d[f]),T=kS(t.role.permission,E,d[f]);xS(h,T,r,d[f],E,s)}}),s.getPermsResponse())}catch(s){throw Qt(s)}}o(UZ,"verifyPermsAst");function DZ(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw it.info("null required parameter in verifyPerms"),Qt(new Error,gt.DEFAULT_INVALID_REQUEST,mc.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema,i=e.table,a=new Map;n&&i&&a.set(n,[i]);let c=new cD;if(Ws.isEmptyOrZeroLength(e.hdb_user.role)||Ws.isEmptyOrZeroLength(e.hdb_user.role.permission))return it.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(gt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,l=e.hdb_user.role.permission.structure_user,_=a.has(yr.SYSTEM_SCHEMA_NAME)||n===yr.SYSTEM_SCHEMA_NAME;if(_&&_D[r])throw Qt(new Error,gt.DROP_SYSTEM,mc.FORBIDDEN);if(u&&!_||l===!0&&(r===Ir.createSchema.name||r===Ir.dropSchema.name))return null;if(CZ.indexOf(r)>=0&&(l===!0||Array.isArray(l)))return l===!0||l.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=rD.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===jU||r===eD){if(n===yr.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(gt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===jU&&(!d[n]||!d[n][Sc]))return c.handleInvalidItem(gt.SCHEMA_NOT_FOUND(n));if(r===eD&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][Sc]))return c.handleInvalidItem(gt.TABLE_NOT_FOUND(n,i))}}let E=ED(e.hdb_user,r,a,c,s);if(E)return E;if(P.get(r)&&P.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&yr.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let T=[],S=d[n].tables[i];S[yr.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(O=>O[yr.PERMS_CRUD_ENUM.READ]).forEach(O=>{T.push(O.attribute_name)}):T=global.hdb_schema[n][i].attributes.map(y=>y.attribute),e.get_attributes=T)}let f=LZ(e),h=kS(e.hdb_user.role.permission,n,i);return xS(f,h,r,i,n,c,s),c.getPermsResponse()}o(DZ,"verifyPerms");function ED(e,t,r,s,n){if(Ws.arrayHasEmptyValues([e,t,r]))throw it.info("hasPermissions has an invalid parameter"),Qt(new Error);let i=r.has("system"),a=e.role.permission;if(a.super_user&&(!i||P.get(t).requires_su))return null;if(!P.get(t))throw it.info(`operation ${t} not found.`),Qt(new Error,gt.OP_NOT_FOUND(t),mc.BAD_REQUEST);if(P.get(t)&&P.get(t).requires_su)return it.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(gt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!a[u]||a[u][Sc]===!1){s.addInvalidItem(gt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(gt.SCHEMA_NOT_FOUND(u));continue}let l=r.get(u);for(let _ of l){let d=a[u].tables[_];if(!d||d[Sc]===!1)s.addInvalidItem(gt.TABLE_NOT_FOUND(u,_));else try{let E=[],f=P.get(t).perms;!Ws.isEmpty(n)&&f.includes(n)&&(f=[n]);for(let h=0;h<f.length;h++){let T=f[h],S=d[T];(S==null||S===!1)&&(it.info(`Required ${T} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),E.push(T))}E.length>0&&s.addUnauthorizedTable(u,_,E)}catch(E){let f=gt.UNKNOWN_OP_AUTH_ERROR(t,u,_);throw it.error(f),it.error(E),Qt(uD.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?s.getPermsResponse():null}o(ED,"hasPermissions");function xS(e,t,r,s,n,i,a){if(!e||!t)throw it.info("no attributes specified in checkAttributePerms."),Qt(new Error);let c=P.get(r).perms;if(!c||c==="")throw it.info(`no permissions found for ${r} in checkAttributePerms().`),Qt(new Error);if(Ws.isEmptyOrZeroLength(t))return it.info("No role permissions set (this is OK)."),null;a&&c.includes(a)&&(c=[a]);let u={};for(let _ of e){let d=t.get(_);if(d){if(d[Sc]===!1){i.addInvalidItem(gt.ATTR_NOT_FOUND(n,s,_),n,s);continue}if(c)for(let E of c){if(yr.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Qs)throw Qt(new Error,gt.SYSTEM_TIMESTAMP_PERMS_ERR,mc.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(gt.ATTR_NOT_FOUND(n,s,_),n,s)}let l=Object.keys(u);l.length>0&&i.addUnauthorizedAttributes(l,n,s,u)}o(xS,"checkAttributePerms");function LZ(e){let t=new Set;try{if(e.action)return t;if(e.operation===yr.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){it.info(r)}return t}o(LZ,"getRecordAttributes");function kS(e,t,r){let s=new Map;if(Ws.isEmpty(e))return it.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{it.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}o(kS,"getAttributePermissions");function MZ(e,t,r,s,n,i,a){let c=new Set(i),u=kS(e,s,n);xS(c,u,t,n,s,a,r)}o(MZ,"verifyBulkLoadAttributePerms")});var D_=m((Eue,TD)=>{"use strict";TD.exports={evaluateSQL:KZ,processAST:pD,convertSQLToAST:SD,checkASTPermissions:mD};var PZ=Rr(),hD=require("util"),vZ=hD.callbackify(PZ.insert),BZ=Tr().search,HZ=Jy().update,FZ=hD.callbackify(HZ),qZ=Zy().convertDelete,Cn=require("alasql"),GZ=C_(),U_=q(),xZ=Rl(),kZ=x(),Rc=g(),{hdb_errors:VZ,handleHDBError:VS}=W(),{HTTP_STATUS_CODES:$S}=VZ;xZ(Cn);var $Z=403,YZ="There was a problem performing this insert. Please check the logs and try again.",YS=class{static{o(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function KZ(e,t){let r=e.parsed_sql_object;if(!r){r=SD(e.sql);let s,n=r.ast.statements[0];if(n instanceof Cn.yy.Insert?s=n.into.databaseid:n instanceof Cn.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Cn.yy.Update||n instanceof Cn.yy.Delete?s=n.table.databaseid:U_.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Cn.yy.Select)&&kZ.isEmptyOrZeroLength(s))return t("No schema specified",null)}pD(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}o(KZ,"evaluateSQL");function mD(e,t){let r;try{r=GZ.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}o(mD,"checkASTPermissions");function SD(e){let t=new YS;if(!e)throw VS(new Error,"The 'sql' parameter is missing from the request body",$S.BAD_REQUEST);try{let r=e.trim(),s=Cn.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
12
|
-
`);throw s[1]?VS(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,$S.BAD_REQUEST):VS(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",$S.BAD_REQUEST)}return t}o(SD,"convertSQLToAST");function pD(e,t,r){try{let s=WZ;if(!e.bypass_auth&&!t.permissions_checked){let i=mD(e,t);if(i&&i.length>0)return r($Z,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Rc.VALID_SQL_OPS_ENUM.SELECT:s=BZ,n=t.ast.statements[0];break;case Rc.VALID_SQL_OPS_ENUM.INSERT:s=QZ;break;case Rc.VALID_SQL_OPS_ENUM.UPDATE:s=FZ;break;case Rc.VALID_SQL_OPS_ENUM.DELETE:s=qZ;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,a)=>{if(i){r(i);return}r(null,a)})}catch(s){return r(s)}}o(pD,"processAST");function WZ(e,t){U_.info(e),t("unknown sql statement")}o(WZ,"nullFunction");function QZ({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(a=>a.columnid);try{n.records=zZ(i,e.values)}catch(a){return r(a)}vZ(n,(a,c)=>{if(a)return r(a);try{delete c.new_attributes,delete c.txn_time}catch(u){U_.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}o(QZ,"convertInsert");function zZ(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]]=Cn.compile(`SELECT ${n.toString()} AS [${Rc.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw U_.error(r),new Error(YZ)}}o(zZ,"createDataObjects")});var KS=m((hue,gD)=>{"use strict";var{S3:JZ,GetObjectCommand:XZ}=require("@aws-sdk/client-s3");gD.exports={getFileStreamFromS3:ZZ,getS3AuthObj:RD};async function ZZ(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await RD(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new XZ(r))).Body}o(ZZ,"getFileStreamFromS3");function RD(e,t,r){return new JZ({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}o(RD,"getS3AuthObj")});var L_=m((Sue,DD)=>{"use strict";var ND=Tr(),jZ=D_(),ej=KS(),{AsyncParser:tj,Transform:rj}=require("json2csv"),Ac=require("stream"),Er=x(),WS=require("fs-extra"),sj=require("path"),wr=q(),{promisify:bD}=require("util"),gc=x(),{handleHDBError:Je,hdb_errors:nj}=W(),{HDB_ERROR_MSGS:zt,HTTP_STATUS_CODES:Xe}=nj,{streamAsJSON:ij}=FE(),{Upload:aj}=require("@aws-sdk/lib-storage"),AD=["search_by_value","search_by_hash","sql"],OD=["json","csv"],yD="json",ID="csv",oj="Successfully exported JSON locally.",cj="Successfully exported CSV locally.",uj=1e3,lj=ND.searchByHash,_j=ND.searchByValue,dj=bD(jZ.evaluateSQL),Ej=bD(Ac.finished);DD.exports={export_to_s3:Sj,export_local:fj,toCsvStream:wD};async function fj(e){wr.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=CD(e);if(!Er.isEmpty(t))throw wr.error(t),Je(new Error,t,Xe.BAD_REQUEST,void 0,void 0,!0);if(Er.isEmpty(e.path))throw wr.error(zt.MISSING_VALUE("path")),Je(new Error,zt.MISSING_VALUE("path"),Xe.BAD_REQUEST,void 0,void 0,!0);let r=(Er.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(sj.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Er.buildFolderPath(e.path,r);await hj(e.path);let n=await UD(e);return await mj(s,e.format,n)}o(fj,"export_local");async function hj(e){if(wr.trace("in confirmPath"),Er.isEmptyOrZeroLength(e))throw Je(new Error,`Invalid path: ${e}`,Xe.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await WS.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,wr.error(s),Je(new Error,s,Xe.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 wr.error(r),Je(new Error,r,Xe.BAD_REQUEST,void 0,void 0,!0)}return!0}o(hj,"confirmPath");async function mj(e,t,r){if(wr.trace("in saveToLocal"),gc.isEmptyOrZeroLength(e))throw Je(new Error,zt.INVALID_VALUE("file_path"),Xe.BAD_REQUEST,void 0,void 0,!0);if(gc.isEmptyOrZeroLength(t))throw Je(new Error,zt.INVALID_VALUE("Source format"),Xe.BAD_REQUEST,void 0,void 0,!0);if(gc.isEmpty(r))throw Je(new Error,zt.NOT_FOUND("Data"),Xe.BAD_REQUEST,void 0,void 0,!0);if(t===yD){let s=WS.createWriteStream(e);return ij(r).pipe(s),await Ej(s),{message:oj,path:e}}else if(t===ID){let s=WS.createWriteStream(e),n=Ac.Readable.from(r),i={},a={objectMode:!0};return await new tj(i,a).fromInput(n).toOutput(s).promise(!1),{message:cj,path:e}}throw Je(new Error,zt.INVALID_VALUE("format"),Xe.BAD_REQUEST)}o(mj,"saveToLocal");async function Sj(e){if(!e.s3||Object.keys(e.s3).length===0)throw Je(new Error,zt.MISSING_VALUE("S3 object"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Je(new Error,zt.MISSING_VALUE("aws_access_key_id"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Je(new Error,zt.MISSING_VALUE("aws_secret_access_key"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.bucket))throw Je(new Error,zt.MISSING_VALUE("bucket"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.key))throw Je(new Error,zt.MISSING_VALUE("key"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.region))throw Je(new Error,zt.MISSING_VALUE("region"),Xe.BAD_REQUEST);let t=CD(e);if(!Er.isEmpty(t))throw Je(new Error,t,Xe.BAD_REQUEST);wr.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await UD(e)}catch(u){throw wr.error(u),u}let s,n=await ej.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,a=new Ac.PassThrough;if(e.format===ID){i=e.s3.key+".csv";let u=wD(r);u.on("error",l=>{throw l}),u.pipe(a)}else if(e.format===yD){i=e.s3.key+".json";let u=new Ac.Readable;u.pipe(a),u.on("error",d=>{throw d}),u.push("[");let l=r.length,_="";for(let[d,E]of r.entries()){let f=d===l-1?JSON.stringify(E):JSON.stringify(E)+",";_+=f,d!==0&&d%uj===0&&(u.push(_),_="")}_.length!==0&&u.push(_),u.push("]"),u.push(null)}else throw Je(new Error,zt.INVALID_VALUE("format"),Xe.BAD_REQUEST);return new aj({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:a}}).done()}o(Sj,"export_to_s3");function wD(e){let t=Ac.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),r={},s={objectMode:!0},n=new rj(r,s);return t.pipe(n)}o(wD,"toCsvStream");function CD(e){if(wr.trace("in exportCoreValidation"),Er.isEmpty(e.format))return"format missing";if(OD.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${OD.join(", ")}`;let t=e.search_operation.operation;if(Er.isEmpty(t))return"search_operation.operation missing";if(AD.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${AD.join(", ")}`}o(CD,"exportCoreValidation");async function UD(e){wr.trace("in getRecords");let t,r;if(gc.isEmpty(e.search_operation)||gc.isEmptyOrZeroLength(e.search_operation.operation))throw Je(new Error,zt.INVALID_VALUE("Search operation"),Xe.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=_j;break;case"search_by_hash":t=lj;break;case"sql":t=dj;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,wr.error(r),Je(new Error,r,Xe.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}o(UD,"getRecords")});var HD={};Ze(HD,{contentTypes:()=>vD,findBestSerializer:()=>B_,getDeserializer:()=>Ta,registerContentHandlers:()=>zS,serialize:()=>JS,serializeMessage:()=>$s});function pj(e){try{return e?.[0]===123?JSON.parse(e):e}catch{return e}}function zS(e){e.register(Rj,{serializers:[{regex:/^application\/json$/,serializer:M_.streamAsJSON},{regex:/^application\/cbor$/,serializer:function(t){return new di.EncoderStream(Oc).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?v_.Readable.from((0,hs.encodeIter)(t,Oc)):(0,hs.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,QS.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,hs.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,di.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function B_(e){let t=e.headers.accept,r,s=0,n,i,a=t?t.toLowerCase().split(/\s*,\s*/):[];for(let c of a){let[u,...l]=c.split(/\s*;\s*/),_=1,d={q:1};for(let f of l){let h=f.indexOf("=");d[f.substring(0,h)]=f.substring(h+1)}_=+d.q;let E=dt.get(u);if(E){let f=(E.q||1)*_;f>s&&(r=E,n=E.type||u,s=f,i=d)}}if(!r){if(t)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(dt.keys()).join(", "))}};r=dt.get("application/json"),n="application/json"}return{serializer:r,type:n,parameters:i}}function JS(e,t,r){let s=t.headers["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null&&(r.headers["Content-Type"]=e.contentType,r.headers.Vary="Accept-Encoding",n=e.data),e instanceof Uint8Array)r.headers["Content-Type"]="application/octet-stream",r.headers.Vary="Accept-Encoding",n=e;else{let i=B_(t);if(r.headers.Vary="Accept, Accept-Encoding",r.headers["Content-Type"]=i.type,e[Symbol.iterator]&&i.serializer.serializeStream){let a=i.serializer.serializeStream(e);return s&&(r.headers["Content-Encoding"]="br",a=a.pipe((0,P_.createBrotliCompress)({}))),a}n=i.serializer.serialize(e)}return s?(r.headers["Content-Encoding"]="br",new Promise((i,a)=>(0,P_.brotliCompress)(n,(c,u)=>{c?a(c):i(u)}))):n}function $s(e,t){if(e?.contentType!=null&&e.data!=null)return e;let r=t.serialize;if(r)return r(e);let s=B_(t);return r=t.serialize=s.serializer.serialize,r(e)}function gj(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function Ta(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=dt.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=dt.get(e)?.deserialize||MD(e,s);return a=>gj(a).then(i)}return dt.get(e)?.deserialize||MD(e,s)}function MD(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return s=>({contentType:e,data:s.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>({contentType:e,data:r})}function Aj(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let s=r.next();return s.then?s.then(n=>({value:t(n.value),done:n.done})):{value:t(s.value),done:s.done}},return(s){return r.return(s)},throw(s){return r.throw(s)}}}}}var M_,QS,hs,di,P_,v_,PD,Oc,dt,vD,LD,BD,Tj,Rj,fa=pe(()=>{M_=D(FE()),QS=D(L_()),hs=require("msgpackr"),di=require("cbor-x"),P_=require("zlib"),v_=require("stream");on();PD=require("../index"),Oc={useRecords:!1,useToJSON:!0};ht.contentType=function(e,t){dt.set(e,t)};dt=new Map,vD=dt;(0,PD._assignPackageExport)("contentTypes",vD);dt.set("application/json",{serializeStream:M_.streamAsJSON,serialize:JSON.stringify,deserialize:JSON.parse,q:.8});LD=new di.Encoder(Oc);dt.set("application/cbor",{serializeStream(e){return new di.EncoderStream(Oc).end(e)},serialize:LD.encode,deserialize:LD.decode,q:1});dt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?v_.Readable.from((0,hs.encodeIter)(e,Oc)):(0,hs.pack)(e)},serialize:hs.pack,deserialize:hs.unpack,q:.9});dt.set("text/csv",{serializeStream(e){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,QS.toCsvStream)(e)},q:.1});dt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});dt.set("text/event-stream",{serializeStream:function(e){return v_.Readable.from(Aj(e,this.serialize))},serialize:function(e){if(e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
10
|
+
`,""):null}catch(E){E.stderr?i[u].npm_error=WU(E.stderr):i[u].npm_error=E.message;continue}try{i[u].npm_output=JSON.parse(_)}catch{i[u].npm_output=_}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return hc.info(`finished installModules with response ${i}`),i}a(fZ,"installModules");function WU(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
|
|
11
|
+
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(WU,"parseNPMStdErr");async function hZ(e){hc.info(`starting auditModules for request: ${e}`);let t=zU(e);if(t)throw Ro(t,t.message,go.BAD_REQUEST);let{projects:r}=e;await w_(),await QU(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=I_.join(BS,o);s[o]={npm_output:null,npm_error:null};try{let u=await Sc("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=WU(u.stderr)}}return hc.info(`finished auditModules with response ${s}`),s}a(hZ,"auditModules");async function w_(){try{return await Sc("npm -v"),!0}catch{throw Ro(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",go.BAD_REQUEST,void 0,void 0,!0)}}a(w_,"checkNPMInstalled");async function QU(e){if(!Array.isArray(e)||e.length===0)throw Ro(new Error,"projects argument must be an array with at least 1 element",go.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=I_.join(BS,i.toString());if(!await $U.pathExists(o)){t.push(i);continue}let u=I_.join(o,"package.json");await $U.pathExists(u)||r.push(i)}if(t.length>0)throw Ro(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,go.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ro(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,go.BAD_REQUEST,void 0,void 0,!0)}a(QU,"checkProjectPaths");function zU(e){let t=y_.object({projects:y_.array().min(1).items(y_.string()).required(),dry_run:y_.boolean().default(!1)});return uZ.validateBySchema(e,t)}a(zU,"modulesValidator")});var ZU=m((Eue,XU)=>{"use strict";var HS=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};XU.exports=HS});var eD=m((hue,jU)=>{"use strict";var FS=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};jU.exports=FS});var GS=m((Sue,rD)=>{"use strict";var tD=ZU(),mZ=eD(),{HDB_ERROR_MSGS:SZ}=rr(),qS=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=SZ.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 tD(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new mZ(c,n[c]);i.push(u)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new tD(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}};rD.exports=qS});var M_=m((Tue,pD)=>{"use strict";var xS=Ar(),U_=gr(),Cr=Ul(),Rc=Yn(),kS=Jn(),pZ=jh(),TZ=AI(),gc=br(),D_=cm(),at=x(),RZ=_m(),gZ=Wl(),AZ=Km(),OZ=Xl(),NZ=Wm(),bZ=Qm(),yZ=Xm(),IZ=jm(),VS=rS(),zs=V(),wZ=TC(),$S=aS(),iD=NS(),wr=A(),oD=TU(),CZ=uo(),aD=$a(),cD=(g_(),re(dc)),uD=Nr(),dr=MS(),UZ=require("alasql"),lD=b_(),_D=C_(),dD=GS(),{handleHDBError:Qt,hdb_errors:ED}=W(),{HDB_ERROR_MSGS:gt,HTTP_STATUS_CODES:pc}=ED,M=new Map,fD="delete",Cn="insert",Js="read",di="update",Tc="describe",sD=Rc.describeSchema.name,nD=Rc.describeTable.name,hD={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},DZ="catchup",LZ="handleGetJob",MZ="handleGetJobsByStartDate",L_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},PZ=[Cr.createTable.name,Cr.createAttribute.name,Cr.dropTable.name,Cr.dropAttribute.name],mD={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},H=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};M.set(xS.insert.name,new H(!1,[Cn]));M.set(xS.update.name,new H(!1,[di]));M.set(xS.upsert.name,new H(!1,[Cn,di]));M.set(U_.searchByConditions.name,new H(!1,[Js]));M.set(U_.searchByHash.name,new H(!1,[Js]));M.set(U_.searchByValue.name,new H(!1,[Js]));M.set(U_.search.name,new H(!1,[Js]));M.set(Cr.createSchema.name,new H(!0,[]));M.set(Cr.createTable.name,new H(!0,[]));M.set(Cr.createAttribute.name,new H(!1,[Cn]));M.set(Cr.dropSchema.name,new H(!0,[]));M.set(Cr.dropTable.name,new H(!0,[]));M.set(Cr.dropAttribute.name,new H(!0,[]));M.set(Rc.describeSchema.name,new H(!1,[Js]));M.set(Rc.describeTable.name,new H(!1,[Js]));M.set(kS.deleteRecord.name,new H(!1,[fD]));M.set(gc.addUser.name,new H(!0,[]));M.set(gc.alterUser.name,new H(!0,[]));M.set(gc.dropUser.name,new H(!0,[]));M.set(gc.listUsersExternal.name,new H(!0,[]));M.set(D_.listRoles.name,new H(!0,[]));M.set(D_.addRole.name,new H(!0,[]));M.set(D_.alterRole.name,new H(!0,[]));M.set(D_.dropRole.name,new H(!0,[]));M.set(RZ.name,new H(!0,[]));M.set(gZ.name,new H(!0,[]));M.set(AZ.name,new H(!0,[]));M.set(OZ.name,new H(!0,[]));M.set(NZ.name,new H(!0,[]));M.set(bZ.name,new H(!0,[]));M.set(VS.setRoutes.name,new H(!0,[]));M.set(VS.getRoutes.name,new H(!0,[]));M.set(VS.deleteRoutes.name,new H(!0,[]));M.set(uD.setConfiguration.name,new H(!0,[]));M.set(yZ.clusterStatus.name,new H(!0,[]));M.set(IZ.name,new H(!0,[]));M.set($S.getFingerprint.name,new H(!0,[]));M.set($S.setLicense.name,new H(!0,[]));M.set(kS.deleteFilesBefore.name,new H(!0,[]));M.set(kS.deleteAuditLogsBefore.name,new H(!0,[]));M.set(iD.restart.name,new H(!0,[]));M.set(iD.restartService.name,new H(!0,[]));M.set(pZ.name,new H(!0,[]));M.set(TZ.name,new H(!0,[Js]));M.set(CZ.systemInformation.name,new H(!0,[]));M.set(uD.getConfiguration.name,new H(!0,[]));M.set(lD.readTransactionLog.name,new H(!0,[]));M.set(lD.deleteTransactionLogsBefore.name,new H(!0,[]));M.set(_D.installModules.name,new H(!0,[]));M.set(_D.auditModules.name,new H(!0,[]));M.set(aD.createTokens.name,new H(!1,[]));M.set(aD.refreshOperationToken.name,new H(!1,[]));M.set(cD.login.name,new H(!1,[]));M.set(cD.logout.name,new H(!1,[]));M.set(dr.customFunctionsStatus.name,new H(!0,[]));M.set(dr.getCustomFunctions.name,new H(!0,[]));M.set(dr.getComponents.name,new H(!0,[]));M.set(dr.getComponentFile.name,new H(!0,[]));M.set(dr.setComponentFile.name,new H(!0,[]));M.set(dr.dropComponent.name,new H(!0,[]));M.set(dr.getCustomFunction.name,new H(!0,[]));M.set(dr.setCustomFunction.name,new H(!0,[]));M.set(dr.dropCustomFunction.name,new H(!0,[]));M.set(dr.addComponent.name,new H(!0,[]));M.set(dr.dropCustomFunctionProject.name,new H(!0,[]));M.set(dr.packageComponent.name,new H(!0,[]));M.set(dr.deployComponent.name,new H(!0,[]));M.set($S.getRegistrationInfo.name,new H(!1,[]));M.set(gc.userInfo.name,new H(!1,[]));M.set(Rc.describeAll.name,new H(!1,[]));M.set(LZ,new H(!1,[]));M.set(MZ,new H(!0,[]));M.set(DZ,new H(!0,[]));M.set(L_.CSV_DATA_LOAD,new H(!1,[Cn,di]));M.set(L_.CSV_URL_LOAD,new H(!1,[Cn,di]));M.set(L_.CSV_FILE_LOAD,new H(!1,[Cn,di]));M.set(L_.IMPORT_FROM_S3,new H(!1,[Cn,di]));M.set(mD.EXPORT_TO_S3,new H(!0,[]));M.set(mD.EXPORT_LOCAL,new H(!0,[]));M.set(wr.VALID_SQL_OPS_ENUM.DELETE,new H(!1,[fD]));M.set(wr.VALID_SQL_OPS_ENUM.SELECT,new H(!1,[Js]));M.set(wr.VALID_SQL_OPS_ENUM.INSERT,new H(!1,[Cn]));M.set(wr.VALID_SQL_OPS_ENUM.UPDATE,new H(!1,[di]));pD.exports={verifyPerms:BZ,verifyPermsAst:vZ,verifyBulkLoadAttributePerms:FZ};function vZ(e,t,r){if(zs.isEmptyOrZeroLength(e))throw at.info("verify_perms_ast has an empty user parameter"),Qt(new Error);if(zs.isEmptyOrZeroLength(t))throw at.info("verify_perms_ast has an empty user parameter"),Qt(new Error);if(zs.isEmptyOrZeroLength(r))throw at.info("verify_perms_ast has a null operation parameter"),Qt(new Error);try{let s=new dD,n=new wZ(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw at.info("No schemas defined in verifyPermsAst(), will not continue."),Qt(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&hD[r])throw Qt(new Error,gt.DROP_SYSTEM,pc.FORBIDDEN);if(c&&!u)return null;let l=oD.getRolePermissions(t.role);t.role.permission=l,!c&&e instanceof UZ.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(l));for(let d=0;d<i.length;d++){let E=n.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let _=SD(t,r,o,s);return _||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=n.getAttributesBySchemaTableName(E,d[f]),T=KS(t.role.permission,E,d[f]);YS(h,T,r,d[f],E,s)}}),s.getPermsResponse())}catch(s){throw Qt(s)}}a(vZ,"verifyPermsAst");function BZ(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw at.info("null required parameter in verifyPerms"),Qt(new Error,gt.DEFAULT_INVALID_REQUEST,pc.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 dD;if(zs.isEmptyOrZeroLength(e.hdb_user.role)||zs.isEmptyOrZeroLength(e.hdb_user.role.permission))return at.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(gt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,l=e.hdb_user.role.permission.structure_user,_=o.has(wr.SYSTEM_SCHEMA_NAME)||n===wr.SYSTEM_SCHEMA_NAME;if(_&&hD[r])throw Qt(new Error,gt.DROP_SYSTEM,pc.FORBIDDEN);if(u&&!_||l===!0&&(r===Cr.createSchema.name||r===Cr.dropSchema.name))return null;if(PZ.indexOf(r)>=0&&(l===!0||Array.isArray(l)))return l===!0||l.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=oD.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===sD||r===nD){if(n===wr.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(gt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===sD&&(!d[n]||!d[n][Tc]))return c.handleInvalidItem(gt.SCHEMA_NOT_FOUND(n));if(r===nD&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][Tc]))return c.handleInvalidItem(gt.TABLE_NOT_FOUND(n,i))}}let E=SD(e.hdb_user,r,o,c,s);if(E)return E;if(M.get(r)&&M.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&wr.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let T=[],p=d[n].tables[i];p[wr.PERMS_CRUD_ENUM.READ]&&(p.attribute_permissions.length>0?p.attribute_permissions.filter(O=>O[wr.PERMS_CRUD_ENUM.READ]).forEach(O=>{T.push(O.attribute_name)}):T=global.hdb_schema[n][i].attributes.map(R=>R.attribute),e.get_attributes=T)}let f=HZ(e),h=KS(e.hdb_user.role.permission,n,i);return YS(f,h,r,i,n,c,s),c.getPermsResponse()}a(BZ,"verifyPerms");function SD(e,t,r,s,n){if(zs.arrayHasEmptyValues([e,t,r]))throw at.info("hasPermissions has an invalid parameter"),Qt(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||M.get(t).requires_su))return null;if(!M.get(t))throw at.info(`operation ${t} not found.`),Qt(new Error,gt.OP_NOT_FOUND(t),pc.BAD_REQUEST);if(M.get(t)&&M.get(t).requires_su)return at.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(gt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][Tc]===!1){s.addInvalidItem(gt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(gt.SCHEMA_NOT_FOUND(u));continue}let l=r.get(u);for(let _ of l){let d=o[u].tables[_];if(!d||d[Tc]===!1)s.addInvalidItem(gt.TABLE_NOT_FOUND(u,_));else try{let E=[],f=M.get(t).perms;!zs.isEmpty(n)&&f.includes(n)&&(f=[n]);for(let h=0;h<f.length;h++){let T=f[h],p=d[T];(p==null||p===!1)&&(at.info(`Required ${T} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),E.push(T))}E.length>0&&s.addUnauthorizedTable(u,_,E)}catch(E){let f=gt.UNKNOWN_OP_AUTH_ERROR(t,u,_);throw at.error(f),at.error(E),Qt(ED.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?s.getPermsResponse():null}a(SD,"hasPermissions");function YS(e,t,r,s,n,i,o){if(!e||!t)throw at.info("no attributes specified in checkAttributePerms."),Qt(new Error);let c=M.get(r).perms;if(!c||c==="")throw at.info(`no permissions found for ${r} in checkAttributePerms().`),Qt(new Error);if(zs.isEmptyOrZeroLength(t))return at.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let _ of e){let d=t.get(_);if(d){if(d[Tc]===!1){i.addInvalidItem(gt.ATTR_NOT_FOUND(n,s,_),n,s);continue}if(c)for(let E of c){if(wr.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Js)throw Qt(new Error,gt.SYSTEM_TIMESTAMP_PERMS_ERR,pc.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(gt.ATTR_NOT_FOUND(n,s,_),n,s)}let l=Object.keys(u);l.length>0&&i.addUnauthorizedAttributes(l,n,s,u)}a(YS,"checkAttributePerms");function HZ(e){let t=new Set;try{if(e.action)return t;if(e.operation===wr.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){at.info(r)}return t}a(HZ,"getRecordAttributes");function KS(e,t,r){let s=new Map;if(zs.isEmpty(e))return at.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{at.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(KS,"getAttributePermissions");function FZ(e,t,r,s,n,i,o){let c=new Set(i),u=KS(e,s,n);YS(c,u,t,n,s,o,r)}a(FZ,"verifyBulkLoadAttributePerms")});var v_=m((gue,OD)=>{"use strict";OD.exports={evaluateSQL:XZ,processAST:AD,convertSQLToAST:gD,checkASTPermissions:RD};var qZ=Ar(),TD=require("util"),GZ=TD.callbackify(qZ.insert),xZ=gr().search,kZ=jy().update,VZ=TD.callbackify(kZ),$Z=tI().convertDelete,Un=require("alasql"),YZ=M_(),P_=x(),KZ=Nl(),WZ=V(),Ac=A(),{hdb_errors:QZ,handleHDBError:WS}=W(),{HTTP_STATUS_CODES:QS}=QZ;KZ(Un);var zZ=403,JZ="There was a problem performing this insert. Please check the logs and try again.",zS=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function XZ(e,t){let r=e.parsed_sql_object;if(!r){r=gD(e.sql);let s,n=r.ast.statements[0];if(n instanceof Un.yy.Insert?s=n.into.databaseid:n instanceof Un.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Un.yy.Update||n instanceof Un.yy.Delete?s=n.table.databaseid:P_.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Un.yy.Select)&&WZ.isEmptyOrZeroLength(s))return t("No schema specified",null)}AD(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(XZ,"evaluateSQL");function RD(e,t){let r;try{r=YZ.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(RD,"checkASTPermissions");function gD(e){let t=new zS;if(!e)throw WS(new Error,"The 'sql' parameter is missing from the request body",QS.BAD_REQUEST);try{let r=e.trim(),s=Un.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
12
|
+
`);throw s[1]?WS(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,QS.BAD_REQUEST):WS(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",QS.BAD_REQUEST)}return t}a(gD,"convertSQLToAST");function AD(e,t,r){try{let s=ZZ;if(!e.bypass_auth&&!t.permissions_checked){let i=RD(e,t);if(i&&i.length>0)return r(zZ,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Ac.VALID_SQL_OPS_ENUM.SELECT:s=xZ,n=t.ast.statements[0];break;case Ac.VALID_SQL_OPS_ENUM.INSERT:s=jZ;break;case Ac.VALID_SQL_OPS_ENUM.UPDATE:s=VZ;break;case Ac.VALID_SQL_OPS_ENUM.DELETE:s=$Z;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(AD,"processAST");function ZZ(e,t){P_.info(e),t("unknown sql statement")}a(ZZ,"nullFunction");function jZ({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=ej(i,e.values)}catch(o){return r(o)}GZ(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){P_.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(jZ,"convertInsert");function ej(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]]=Un.compile(`SELECT ${n.toString()} AS [${Ac.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw P_.error(r),new Error(JZ)}}a(ej,"createDataObjects")});var JS=m((Oue,bD)=>{"use strict";var{S3:tj,GetObjectCommand:rj}=require("@aws-sdk/client-s3");bD.exports={getFileStreamFromS3:sj,getS3AuthObj:ND};async function sj(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await ND(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new rj(r))).Body}a(sj,"getFileStreamFromS3");function ND(e,t,r){return new tj({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(ND,"getS3AuthObj")});var B_=m((bue,vD)=>{"use strict";var wD=gr(),nj=v_(),ij=JS(),{AsyncParser:oj,Transform:aj}=require("json2csv"),Nc=require("stream"),Er=V(),XS=require("fs-extra"),cj=require("path"),Ur=x(),{promisify:CD}=require("util"),Oc=V(),{handleHDBError:Je,hdb_errors:uj}=W(),{HDB_ERROR_MSGS:zt,HTTP_STATUS_CODES:Xe}=uj,{streamAsJSON:lj}=xE(),{Upload:_j}=require("@aws-sdk/lib-storage"),yD=["search_by_value","search_by_hash","sql"],ID=["json","csv"],UD="json",DD="csv",dj="Successfully exported JSON locally.",Ej="Successfully exported CSV locally.",fj=1e3,hj=wD.searchByHash,mj=wD.searchByValue,Sj=CD(nj.evaluateSQL),pj=CD(Nc.finished);vD.exports={export_to_s3:Aj,export_local:Tj,toCsvStream:LD};async function Tj(e){Ur.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=MD(e);if(!Er.isEmpty(t))throw Ur.error(t),Je(new Error,t,Xe.BAD_REQUEST,void 0,void 0,!0);if(Er.isEmpty(e.path))throw Ur.error(zt.MISSING_VALUE("path")),Je(new Error,zt.MISSING_VALUE("path"),Xe.BAD_REQUEST,void 0,void 0,!0);let r=(Er.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(cj.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Er.buildFolderPath(e.path,r);await Rj(e.path);let n=await PD(e);return await gj(s,e.format,n)}a(Tj,"export_local");async function Rj(e){if(Ur.trace("in confirmPath"),Er.isEmptyOrZeroLength(e))throw Je(new Error,`Invalid path: ${e}`,Xe.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await XS.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,Ur.error(s),Je(new Error,s,Xe.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 Ur.error(r),Je(new Error,r,Xe.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Rj,"confirmPath");async function gj(e,t,r){if(Ur.trace("in saveToLocal"),Oc.isEmptyOrZeroLength(e))throw Je(new Error,zt.INVALID_VALUE("file_path"),Xe.BAD_REQUEST,void 0,void 0,!0);if(Oc.isEmptyOrZeroLength(t))throw Je(new Error,zt.INVALID_VALUE("Source format"),Xe.BAD_REQUEST,void 0,void 0,!0);if(Oc.isEmpty(r))throw Je(new Error,zt.NOT_FOUND("Data"),Xe.BAD_REQUEST,void 0,void 0,!0);if(t===UD){let s=XS.createWriteStream(e);return lj(r).pipe(s),await pj(s),{message:dj,path:e}}else if(t===DD){let s=XS.createWriteStream(e),n=Nc.Readable.from(r),i={},o={objectMode:!0};return await new oj(i,o).fromInput(n).toOutput(s).promise(!1),{message:Ej,path:e}}throw Je(new Error,zt.INVALID_VALUE("format"),Xe.BAD_REQUEST)}a(gj,"saveToLocal");async function Aj(e){if(!e.s3||Object.keys(e.s3).length===0)throw Je(new Error,zt.MISSING_VALUE("S3 object"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Je(new Error,zt.MISSING_VALUE("aws_access_key_id"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Je(new Error,zt.MISSING_VALUE("aws_secret_access_key"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.bucket))throw Je(new Error,zt.MISSING_VALUE("bucket"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.key))throw Je(new Error,zt.MISSING_VALUE("key"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.region))throw Je(new Error,zt.MISSING_VALUE("region"),Xe.BAD_REQUEST);let t=MD(e);if(!Er.isEmpty(t))throw Je(new Error,t,Xe.BAD_REQUEST);Ur.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await PD(e)}catch(u){throw Ur.error(u),u}let s,n=await ij.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Nc.PassThrough;if(e.format===DD){i=e.s3.key+".csv";let u=LD(r);u.on("error",l=>{throw l}),u.pipe(o)}else if(e.format===UD){i=e.s3.key+".json";let u=new Nc.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let l=r.length,_="";for(let[d,E]of r.entries()){let f=d===l-1?JSON.stringify(E):JSON.stringify(E)+",";_+=f,d!==0&&d%fj===0&&(u.push(_),_="")}_.length!==0&&u.push(_),u.push("]"),u.push(null)}else throw Je(new Error,zt.INVALID_VALUE("format"),Xe.BAD_REQUEST);return new _j({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Aj,"export_to_s3");function LD(e){let t=Nc.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),r={},s={objectMode:!0},n=new aj(r,s);return t.pipe(n)}a(LD,"toCsvStream");function MD(e){if(Ur.trace("in exportCoreValidation"),Er.isEmpty(e.format))return"format missing";if(ID.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${ID.join(", ")}`;let t=e.search_operation.operation;if(Er.isEmpty(t))return"search_operation.operation missing";if(yD.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${yD.join(", ")}`}a(MD,"exportCoreValidation");async function PD(e){Ur.trace("in getRecords");let t,r;if(Oc.isEmpty(e.search_operation)||Oc.isEmptyOrZeroLength(e.search_operation.operation))throw Je(new Error,zt.INVALID_VALUE("Search operation"),Xe.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=mj;break;case"search_by_hash":t=hj;break;case"sql":t=Sj;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Ur.error(r),Je(new Error,r,Xe.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(PD,"getRecords")});var xD={};je(xD,{contentTypes:()=>qD,findBestSerializer:()=>G_,getDeserializer:()=>Ao,registerContentHandlers:()=>jS,serialize:()=>ep,serializeMessage:()=>Ks});function Oj(e){try{return e?.[0]===123?JSON.parse(e):e}catch{return e}}function jS(e){e.register(bj,{serializers:[{regex:/^application\/json$/,serializer:H_.streamAsJSON},{regex:/^application\/cbor$/,serializer:function(t){return new Ei.EncoderStream(bc).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?q_.Readable.from((0,ms.encodeIter)(t,bc)):(0,ms.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,ZS.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,ms.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,Ei.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function G_(e){let t=e.headers.accept,r,s=0,n,i,o=t?t.toLowerCase().split(/\s*,\s*/):[];for(let c of o){let[u,...l]=c.split(/\s*;\s*/),_=1,d={q:1};for(let f of l){let h=f.indexOf("=");d[f.substring(0,h)]=f.substring(h+1)}_=+d.q;let E=Et.get(u);if(E){let f=(E.q||1)*_;f>s&&(r=E,n=E.type||u,s=f,i=d)}}if(!r){if(t)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(Et.keys()).join(", "))}};r=Et.get("application/json"),n="application/json"}return{serializer:r,type:n,parameters:i}}function ep(e,t,r){let s=t.headers["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null&&(r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),n=e.data),e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=G_(t);if(r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),e[Symbol.iterator]&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e);return s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,F_.createBrotliCompress)({}))),o}n=i.serializer.serialize(e)}return s?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,F_.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ks(e,t){if(e?.contentType!=null&&e.data!=null)return e;let r=t.serialize;if(r)return r(e);let s=G_(t);return r=t.serialize=s.serializer.serialize,r(e)}function yj(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function Ao(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=Et.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=Et.get(e)?.deserialize||HD(e,s);return o=>yj(o).then(i)}return Et.get(e)?.deserialize||HD(e,s)}function HD(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return s=>({contentType:e,data:s.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>({contentType:e,data:r})}function Ij(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let s=r.next();return s.then?s.then(n=>({value:t(n.value),done:n.done})):{value:t(s.value),done:s.done}},return(s){return r.return(s)},throw(s){return r.throw(s)}}}}}var H_,ZS,ms,Ei,F_,q_,FD,bc,Et,qD,BD,GD,Nj,bj,So=Se(()=>{H_=C(xE()),ZS=C(B_()),ms=require("msgpackr"),Ei=require("cbor-x"),F_=require("zlib"),q_=require("stream");es();FD=require("../index"),bc={useRecords:!1,useToJSON:!0};tt.contentType=function(e,t){Et.set(e,t)};Et=new Map,qD=Et;(0,FD._assignPackageExport)("contentTypes",qD);Et.set("application/json",{serializeStream:H_.streamAsJSON,serialize:JSON.stringify,deserialize:JSON.parse,q:.8});BD=new Ei.Encoder(bc);Et.set("application/cbor",{serializeStream(e){return new Ei.EncoderStream(bc).end(e)},serialize:BD.encode,deserialize:BD.decode,q:1});Et.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?q_.Readable.from((0,ms.encodeIter)(e,bc)):(0,ms.pack)(e)},serialize:ms.pack,deserialize:ms.unpack,q:.9});Et.set("text/csv",{serializeStream(e){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,ZS.toCsvStream)(e)},q:.1});Et.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});Et.set("text/event-stream",{serializeStream:function(e){return q_.Readable.from(Ij(e,this.serialize))},serialize:function(e){if(e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
13
13
|
`),e.data){let r=e.data;typeof r=="object"&&(r=JSON.stringify(r)),t+="data: "+r+`
|
|
14
14
|
`}return e.id&&(t+="id: "+e.id+`
|
|
15
15
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
16
16
|
`),t+`
|
|
17
17
|
`}else return"data: "+e+`
|
|
18
18
|
|
|
19
|
-
`},q:.8});
|
|
20
|
-
`,t)}var Ei,VD,$D,Nc,XS,YD,G_,KD,q_,ZS,WD,F_,jS,QD,zD,H_,FD,qD,yj,wj,GD,JD,xD,kD,Uj,ZD,Un,Dj,Ra=pe(()=>{Ei=require("worker_threads"),VD=D(_t());de();$D=D(q()),Nc=require("path"),XS=require("fs/promises"),YD=D(vt()),G_=D(Q()),KD=D(g());(0,G_.initSync)();q_=new Map,ZS=(0,G_.get)(KD.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3,WD=ZS>0;o(Oj,"setAnalyticsEnabled");o(fi,"recordAction");o(x_,"recordActionBinary");F_=0,jS=1e3,QD="analytics-report",zD=[];o(ep,"addAnalyticsListener");o(Nj,"sendAnalytics");H_="sum-";o(bj,"aggregation");FD=0,qD=0,yj=o(()=>new Promise(setImmediate),"rest");o(Ij,"cleanup");wj=36e5;o(tp,"getAnalyticsTable");(0,VD.setChildListenerByType)(QD,XD);o(Cj,"startScheduledTasks");xD=0,kD=new Map,Uj=!1;o(XD,"recordAnalytics");Dj=1e6;o(Lj,"logAnalytics")});var ip={};Ze(ip,{start:()=>vj});async function Pj(e,t){let r=e.headers.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Au(e);let s=performance.now(),n;try{let i=new np;e.responseHeaders=i;let a=e.url.slice(1),c=sp.getMatch(a);if(!c)return t(e);let u={url:c.relativeURL},l=c.Resource,_=await Ye(e,()=>{if(r==="POST"||r==="PUT"||r==="PATCH"||r==="QUERY")try{e.data=Ta(e.headers["content-type"],!0)(e.body)}catch(T){throw new bc.ClientError(T,400)}switch(e.authorize=!0,r){case"GET":case"HEAD":return l.get(u,e);case"POST":return l.post(u,e.data,e);case"PUT":return l.put(u,e.data,e);case"DELETE":return l.delete(u,e);case"PATCH":return l.patch(u,e.data,e);case"OPTIONS":i.Allow="GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACe, QUERY, COPY, MOVE";return;case"CONNECT":return l.connect(u,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(u,e.data,e);case"COPY":return l.copy(u,e.headers.destination,e);case"MOVE":return l.move(u,e.headers.destination,e);case"BREW":throw new bc.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new bc.ServerError(`Method ${r} is not recognized`,501)}}),d=performance.now()-s,E=200,f;if(_==null)E=r==="GET"||r==="HEAD"?404:204;else if(f=e?.lastModified){Mj[0]=f;let T=String.fromCharCode(34,(At[0]&63)+62,(At[0]>>6)+(At[1]<<2&63)+62,(At[1]>>4)+(At[2]<<4&63)+62,(At[2]>>2)+62,(At[3]&63)+62,(At[3]>>6)+(At[4]<<2&63)+62,(At[4]>>4)+(At[5]<<4&63)+62,(At[5]>>2)+62,(At[6]&63)+62,(At[6]>>6)+(At[7]<<2&63)+62,34),S=e.headers["if-none-match"];S&&T==S?(_?.onDone&&_.onDone(),E=304,_=void 0):i.ETag=T}e.createdResource&&(E=201),e.newLocation&&(i.Location=e.newLocation);let h={status:E,headers:i,body:void 0};return i["Server-Timing"]=`db;dur=${d.toFixed(2)}`,fi(d,"TTFB",n,r),x_(E<400,"success",n,r),_!==void 0&&(h.body=JS(_,e,h),r==="HEAD"&&(h.body=void 0)),h}catch(i){let a=performance.now()-s;fi(a,"TTFB",n,r),x_(!1,"success",n,r),i.http_resp_code||console.error(i);let c={};return i.http_resp_code===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),c.Allow=i.allow.map(u=>u.toUpperCase()).join(", "))),{status:i.http_resp_code||500,headers:c,body:$s(i.toString(),e)}}}function vj(e){if(jD)return;jD=!0,sp=e.resources,e.server.http(async(r,s)=>{if(!r.isWebSocket)return Pj(r,s)}),e.server.ws(async(r,s,n)=>{eL++,rp||(setTimeout(()=>{console.log("connection count",eL,"mem",Math.round(process.memoryUsage().heapUsed/1e6)),rp=!1},1e3),rp=!0),t(s);let i=new Jr;r.on("error",console.error);let a;r.on("message",o(function(d){a||(a=Ta(s.headers["content-type"]));let E=a(d);i.push(E)},"message"));let c;r.on("close",()=>{i.emit("close"),c&&c.return()}),await n;let u,l=await sp.call(s.pathname.slice(1),s,(_,d)=>(u=!0,_.connect(i)));if(!u)r.send($s(`No resource was found to handle ${s.pathname}`,s));else{c=l[Symbol.asyncIterator]();let _;for(;!(_=await c.next()).done;)r.send($s(_.value,s))}r.close()});function t(r){let s=r.pathname,n=s.lastIndexOf(".");if(n>-1){let i=s.slice(n+1),a=EXTENSION_TYPES[i];a&&(r.headers.accept=a)}}o(t,"startRequest")}var bc,At,Mj,jD,sp,eL,rp,np,tL=pe(()=>{fa();Ra();bc=D(W());Ou();to();Gn();At=new Uint8Array(8),Mj=new Float64Array(At.buffer,0,1);o(Pj,"http");eL=0;o(vj,"start");np=class{static{o(this,"Headers")}set(t,r){this[t]=r}}});var ap=m((Bue,rL)=>{var{recordAction:V_,recordActionBinary:Bj}=(Ra(),re(k_)),Hj=require("fastify-plugin"),Fj=200;rL.exports=Hj(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n,i)=>{let a=n.getResponseTime(),c=performance.now(),u=n.context.config,l,_,d;u.isOperation?(l=s.body?.operation,_="operation"):(l=u.url,_="fastify-route",d=u.method),V_(a,"TTFB",l,d,_),Bj(n.raw.statusCode<400,"success",l,d,_);let E=Fj;i?.pipe?(i.on("data",h=>{E+=h.length}),i.on("end",()=>{V_(performance.now()-c,"transfer",l,d,_),V_(E,"bytes-sent",l,d,_)})):(E+=i?.length||0,V_(E,"bytes-sent",l,d,_));let f=a.toFixed(3);n.header("Server-Timing",`db;dur=${f}`)}),r()},{name:"hdb-request-time"})});var lp=m((Hue,oL)=>{var Q_=require("clone"),z_=ve(),qj=x(),K_=g(),Gj=q(),$_=require("fs"),op=require("joi"),{string:W_}=op.types(),{hdb_errors:xj,handleHDBError:yc}=W(),{HDB_ERROR_MSGS:kj,HTTP_STATUS_CODES:Y_}=xj,{common_validators:ga}=ts(),sL=1e9,nL=" is required",Vj=["insert","update","upsert"],cp={database:{presence:!1,format:ga.schema_format,length:ga.schema_length},schema:{presence:!1,format:ga.schema_format,length:ga.schema_length},table:{presence:!0,format:ga.schema_format,length:ga.schema_length},action:{inclusion:{within:Vj,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},$j={schema:W_.required(),table:W_.required(),action:W_.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Yj,AWS_SECRET:Kj,AWS_BUCKET:Wj,AWS_FILE_KEY:Qj,REGION:zj}=K_.S3_BUCKET_AUTH_KEYS,Jj={s3:{presence:!0},[`s3.${Yj}`]:{presence:!0,type:"String"},[`s3.${Kj}`]:{presence:!0,type:"String"},[`s3.${Wj}`]:{presence:!0,type:"String"},[`s3.${Qj}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${zj}`]:{presence:!0,type:"String"}},iL=Q_(cp);iL.data.presence={message:nL};var aL=Q_(cp);aL.file_path.presence={message:nL};var Xj=Object.assign(Q_(cp),Jj),up=Q_($j);up.csv_url=W_.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();up.passthrough_headers=op.object();function Zj(e){let t=z_.validateObject(e,iL);return J_(e,t)}o(Zj,"dataObject");function jj(e){let t=z_.validateBySchema(e,op.object(up));return J_(e,t)}o(jj,"urlObject");function e5(e){let t=z_.validateObject(e,aL);return J_(e,t)}o(e5,"fileObject");function t5(e){let t=z_.validateObject(e,Xj);return J_(e,t)}o(t5,"s3FileObject");function J_(e,t){if(!t){let r=qj.checkGlobalSchemaTable(e.schema,e.table);if(r)return yc(new Error,r,Y_.BAD_REQUEST);if(e.operation===K_.OPERATIONS_ENUM.CSV_FILE_LOAD){try{$_.accessSync(e.file_path,$_.constants.R_OK|$_.constants.F_OK)}catch(s){return s.code===K_.NODE_ERROR_CODES.ENOENT?yc(s,`No such file or directory ${s.path}`,Y_.BAD_REQUEST):s.code===K_.NODE_ERROR_CODES.EACCES?yc(s,`Permission denied ${s.path}`,Y_.BAD_REQUEST):yc(s)}try{let s=$_.statSync(e.file_path).size;if(s>sL)return yc(new Error,kj.MAX_FILE_SIZE_ERR(s,sL),Y_.BAD_REQUEST)}catch(s){Gj.error(s),console.error(s)}}}return t}o(J_,"postValidateChecks");oL.exports={dataObject:Zj,urlObject:jj,fileObject:e5,s3FileObject:t5}});var _p=m((que,cL)=>{"use strict";var Ic=q(),X_=g();async function r5(e,t,r,s=void 0){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===X_.OPERATIONS_ENUM.INSERT||t.operation===X_.OPERATIONS_ENUM.UPDATE||t.operation===X_.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===X_.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(Ic.info(i.message),i):i.http_resp_msg?(Ic.error(`Error calling operation: ${e.name}`),Ic.error(i.http_resp_msg),i):(Ic.error(`Error calling operation: ${e.name}`),Ic.error(i),i)}}o(r5,"callOperationFunctionAsAwait");cL.exports={callOperationFunctionAsAwait:r5}});var lL=m((xue,uL)=>{"use strict";var dp=class{static{o(this,"BulkLoadFileObject")}constructor(t,r,s,n,i,a,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=a,this.role_perms=c}},Ep=class{static{o(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};uL.exports={BulkLoadFileObject:dp,BulkLoadDataObject:Ep}});var dL=m((Vue,_L)=>{"use strict";var fp=class{static{o(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};_L.exports=fp});var Rp=m((zue,CL)=>{"use strict";var Z_=Rr(),ed=lp(),s5=require("needle"),Yr=g(),Yue=Be(),Aa=x(),{handleHDBError:Fe,hdb_errors:gL}=W(),{HTTP_STATUS_CODES:Ot,HDB_ERROR_MSGS:at,CHECK_LOGS_WRAPPER:mi}=gL,Oa=q(),hp=require("papaparse");Aa.promisifyPapaParse();var Kr=require("fs-extra"),n5=require("path"),{chain:EL}=require("stream-chain"),fL=require("stream-json/streamers/StreamArray"),hL=require("stream-json/utils/Batch"),mL=require("stream-chain/utils/comp"),{finished:SL}=require("stream"),i5=Q(),AL=_p(),a5=KS(),{BulkLoadFileObject:Sp,BulkLoadDataObject:o5}=lL(),pp=BS(),{verifyBulkLoadAttributePerms:OL}=C_(),Kue=dL(),Wue=rt(),Que=Ls(),{databases:c5}=(de(),re(Ne)),{coerceType:u5}=(td(),re(gp)),pL="No records parsed from csv file.",hi=`${i5.get("HDB_ROOT")}/tmp`,{schema_regex:l5}=ts(),TL=1024*1024*2,RL=5e3,_5={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};CL.exports={csvDataLoad:d5,csvURLLoad:E5,csvFileLoad:f5,importFromS3:h5};async function d5(e,t){let r=ed.dataObject(e);if(r)throw Fe(r,r.message,Ot.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=yL(e.schema,e.table),i=hp.parse(e.data,{header:!0,skipEmptyLines:!0,transform:mp.bind(null,n),dynamicTyping:!1}),a=new pp;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&OL(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,a);let c=a.getPermsResponse();if(c)throw Fe(new Error,c,Ot.BAD_REQUEST,void 0,void 0,!0);let u=new o5(e.action,e.schema,e.table,i.data);return s=await AL.callOperationFunctionAsAwait(IL,u,null),s.message===pL?pL:wL(s.records,s.number_written)}catch(n){throw Si(n)}}o(d5,"csvDataLoad");async function E5(e){let t=ed.urlObject(e);if(t)throw Fe(t,t.message,Ot.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${hi}/${r}`;try{await m5(e,r)}catch(n){throw Oa.error(at.DOWNLOAD_FILE_ERR(r)+" - "+n),Fe(n,mi(at.DOWNLOAD_FILE_ERR(r)))}try{let n=new Sp(this.job_operation_function.name,e.action,e.schema,e.table,s,Yr.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Tp(n);return await j_(s),i}catch(n){throw await j_(s),Si(n)}}o(E5,"csvURLLoad");async function f5(e){let t=ed.fileObject(e);if(t)throw Fe(t,t.message,Ot.BAD_REQUEST,void 0,void 0,!0);let r=new Sp(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Yr.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Tp(r)}catch(s){throw Si(s)}}o(f5,"csvFileLoad");async function h5(e){let t=ed.s3FileObject(e);if(t)throw Fe(t,t.message,Ot.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=n5.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${hi}/${n}`;let i=new Sp(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await S5(n,e);let a=await Tp(i);return await j_(r),a}catch(s){throw await j_(r),Si(s)}}o(h5,"importFromS3");async function m5(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await s5("get",e.csv_url,s)}catch(s){let n=`Error downloading CSV file from ${e.csv_url}, status code: ${s.statusCode}. Check the log for more information.`;throw Fe(s,n,s.statusCode,Yr.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}T5(r,e.csv_url),await p5(t,r.raw)}o(m5,"downloadCSVFile");async function S5(e,t){try{let r=`${hi}/${e}`;await Kr.mkdirp(hi),await Kr.writeFile(`${hi}/${e}`,"",{flag:"a+"});let s=await Kr.createWriteStream(r),n=await a5.getFileStreamFromS3(t);await new Promise((i,a)=>{n.on("error",function(c){a(c)}),n.pipe(s).on("error",function(c){a(c)}).on("close",function(){Oa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Oa.error(at.S3_DOWNLOAD_ERR+" - "+r),Fe(r,mi(at.S3_DOWNLOAD_ERR))}}o(S5,"downloadFileFromS3");async function p5(e,t){try{await Kr.mkdirp(hi),await Kr.writeFile(`${hi}/${e}`,t)}catch(r){throw Oa.error(at.WRITE_TEMP_FILE_ERR),Fe(r,mi(at.DEFAULT_BULK_LOAD_ERR))}}o(p5,"writeFileToTempFolder");async function j_(e){if(e)try{await Kr.access(e),await Kr.unlink(e)}catch{Oa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}o(j_,"deleteTempFile");function T5(e,t){if(e.statusCode!==gL.HTTP_STATUS_CODES.OK)throw Fe(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Ot.BAD_REQUEST);if(!_5[e.headers["content-type"]])throw Fe(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Ot.BAD_REQUEST);if(!e.raw)throw Fe(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Ot.BAD_REQUEST)}o(T5,"validateURLResponse");async function Tp(e){try{let t;switch(e.file_type){case Yr.VALID_S3_FILE_TYPES.CSV:t=await R5(e);break;case Yr.VALID_S3_FILE_TYPES.JSON:t=await g5(e);break;default:throw Fe(new Error,at.DEFAULT_BULK_LOAD_ERR,Ot.BAD_REQUEST,Yr.LOG_LEVELS.ERROR,at.INVALID_FILE_EXT_ERR(e))}return wL(t.records,t.number_written)}catch(t){throw Si(t)}}o(Tp,"fileLoad");async function NL(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let a={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await Z_.validation(a);e.role_perms&&e.role_perms.super_user!==!0&&OL(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=Fe(c);r(u)}}o(NL,"validateChunk");async function bL(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;Aa.autoCastJSONDeep(i),n&&n.pause();let a=s.meta?s.meta.fields:null;if(a)i.forEach(c=>{!Aa.isEmpty(c)&&!Aa.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(l=>c.add(l))}),a=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await AL.callOperationFunctionAsAwait(IL,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=Fe(c,mi(at.INSERT_CSV_ERR),Ot.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,at.INSERT_CSV_ERR+" - "+c);r(u)}}o(bL,"insertChunk");async function R5(e){let t={records:0,number_written:0},r=yL(e.schema,e.table);try{let s=new pp,n=Kr.createReadStream(e.file_path,{highWaterMark:TL});n.setEncoding("utf8"),await hp.parsePromise(n,NL.bind(null,e,s),mp.bind(null,r));let i=s.getPermsResponse();if(i)throw Fe(new Error,i,Ot.BAD_REQUEST);return n=Kr.createReadStream(e.file_path,{highWaterMark:TL}),n.setEncoding("utf8"),await hp.parsePromise(n,bL.bind(null,e,t),mp.bind(null,r)),n.destroy(),t}catch(s){throw Fe(s,mi(at.PAPA_PARSE_ERR),Ot.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,at.PAPA_PARSE_ERR+s)}}o(R5,"callPapaParse");function yL(e,t){let r=c5[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>u5(i,n));return s}o(yL,"createTransformMap");function mp(e,t,r){let s=e.get(r);return s?s(t):Aa.autoCast(t)}o(mp,"typeFunction");async function g5(e){let t={records:0,number_written:0},r=o(s=>{throw s},"throwErr");try{let s=new pp,n=EL([Kr.createReadStream(e.file_path,{encoding:"utf-8"}),fL.withParser(),c=>c.value,new hL({batchSize:RL}),mL(async c=>{await NL(e,s,r,c)})]);await new Promise((c,u)=>{SL(n,l=>{l?u(l):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw Fe(new Error,i,Ot.BAD_REQUEST);let a=EL([Kr.createReadStream(e.file_path,{encoding:"utf-8"}),fL.withParser(),c=>c.value,new hL({batchSize:RL}),mL(async c=>{await bL(e,t,r,c)})]);return await new Promise((c,u)=>{SL(a,l=>{l?u(l):c()}),a.resume()}),t}catch(s){throw Fe(s,mi(at.INSERT_JSON_ERR),Ot.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,at.INSERT_JSON_ERR+s)}}o(g5,"insertJson");async function IL(e){let t={};try{e.data&&e.data.length>0&&A5(e.data[0])?t=await O5(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Oa.info(t.message))}catch(r){throw Si(r)}return t}o(IL,"callBulkFileLoad");function A5(e){let t=Object.keys(e);for(let r of t)if(!l5.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}o(A5,"validateColumnNames");async function O5(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=Z_.insert;break;case"update":i=Z_.update;break;case"upsert":i=Z_.upsert;break;default:throw Fe(new Error,at.INVALID_ACTION_PARAM_ERR(s),Ot.BAD_REQUEST,Yr.LOG_LEVELS.ERROR,at.INVALID_ACTION_PARAM_ERR(s))}try{let a=await i(n),c;switch(s){case"insert":c=a.inserted_hashes;break;case"update":c=a.update_hashes;break;case"upsert":c=a.upserted_hashes;break;default:break}if(Array.isArray(a.skipped_hashes)&&a.skipped_hashes.length>0){let _=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)a.skipped_hashes.indexOf(e[d][_])>=0&&e.splice(d,1)}let u=Aa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:a.new_attributes}}catch(a){throw Si(a)}}o(O5,"bulkFileLoad");function wL(e,t){return`successfully loaded ${t} of ${e} records`}o(wL,"buildResponseMsg");function Si(e){return Fe(e,mi(at.DEFAULT_BULK_LOAD_ERR),Ot.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,at.DEFAULT_BULK_LOAD_ERR+" - "+e)}o(Si,"buildTopLevelErrMsg")});var DL=m((Xue,UL)=>{"use strict";var Ap=class{static{o(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};UL.exports=Ap});var PL=m((jue,ML)=>{"use strict";var N5=g(),LL=require("moment"),b5=require("uuid").v4,Op=class{static{o(this,"JobObject")}constructor(){this.id=b5(),this.type=void 0,this.start_datetime=LL().valueOf(),this.created_datetime=LL().valueOf(),this.end_datetime=void 0,this.status=N5.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};ML.exports=Op});var Np=m((tle,GL)=>{"use strict";var y5=require("uuid").v4,HL=Rr(),FL=Tr(),I5=is(),w5=Ji(),C5=DL(),qe=g(),U5=PL(),D5=_m(),Cr=q(),L5=fo(),Na=x(),{promisify:M5}=require("util"),pi=require("moment"),P5=D_(),rd=lp(),vL=Nf(),{deleteTransactionLogsBeforeValidator:v5}=US(),{handleHDBError:B5,hdb_errors:H5}=W(),{HTTP_STATUS_CODES:F5}=H5,BL=FL.searchByValue,q5=FL.searchByHash,G5=HL.insert,x5=M5(P5.evaluateSQL),k5=HL.update;GL.exports={addJob:Y5,updateJob:W5,handleGetJob:V5,handleGetJobsByStartDate:$5,getJobById:qL};async function V5(e){try{let t=await qL(e.id);return Na.isEmptyOrZeroLength(t)||(t[0]={...t[0]},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 Cr.error("There was an error getting job",t),new Error(r)}}o(V5,"handleGetJob");async function $5(e){try{let t=await K5(e);if(Cr.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=pi(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=pi(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 Cr.error(r),new Error(r)}}o($5,"handleGetJobsByStartDate");async function Y5(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Na.isEmptyOrZeroLength(e.operation)){let _="job parameter is invalid";return Cr.info(_),t.error=_,t}if(!qe.JOB_TYPE_ENUM[e.operation])return Cr.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case qe.OPERATIONS_ENUM.CSV_FILE_LOAD:s=rd.fileObject(e);break;case qe.OPERATIONS_ENUM.CSV_URL_LOAD:s=rd.urlObject(e);break;case qe.OPERATIONS_ENUM.CSV_DATA_LOAD:s=rd.dataObject(e);break;case qe.OPERATIONS_ENUM.IMPORT_FROM_S3:s=rd.s3FileObject(e);break;case qe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case qe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=vL(e,"date");break;case qe.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=vL(e,"timestamp");break;case qe.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=v5(e);break;default:break}if(s)throw B5(s,s.message,F5.BAD_REQUEST,void 0,void 0,!0);let n=new U5;n.type=e.operation===qe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?qe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new I5(qe.SYSTEM_SCHEMA_NAME,qe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),a;try{a=Array.from(await BL(i))}catch(_){let d=`There was an error inserting a new job: ${_}`;return Cr.error(d),t}let c=Array.isArray(a)?a:Object.keys(a);if(c&&c.length>0){n.id=y5();try{a=await BL(i)}catch(_){let d=`There was an error inserting a new job: ${_}`;return Cr.error(d),t}if(c=Array.isArray(a)?a:Object.keys(a),c&&c.length>0)return Cr.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new L5(qe.SYSTEM_SCHEMA_NAME,qe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),l;try{l=await G5(u)}catch(_){return Cr.error(`There was an error inserting a job for job type: ${e.operation} -- ${_}`),t.success=!1,t}if(l.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let _=`Created a job with type ${n.type} and id ${n.id}`;t.message=_,t.createdJob=n,t.success=!0,Cr.trace(_)}return t}o(Y5,"addJob");async function K5(e){let t=pi(e.from_date,pi.ISO_8601),r=pi(e.to_date,pi.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 C5(s,e.hdb_user);try{return await x5(n)}catch(i){throw Cr.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.")}}o(K5,"getJobsInDateRange");async function qL(e){if(Na.isEmptyOrZeroLength(e))return Na.errorizeMessage("Invalid job ID specified.");let t=new w5(qe.SYSTEM_SCHEMA_NAME,qe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await q5(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return Cr.error(s),Na.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}o(qL,"getJobById");async function W5(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Na.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===qe.JOB_STATUS_ENUM.COMPLETE||e.status===qe.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=pi().valueOf());let t=new D5(qe.SYSTEM_SCHEMA_NAME,qe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await k5(t),r}o(W5,"updateJob")});var KL=m((sle,YL)=>{"use strict";var xL=x(),Jt=g(),Q5=require("moment"),sd=Rp(),nd=q(),kL=Np(),VL=L_(),$L=zn(),z5=_t(),J5=g_(),bp=class{static{o(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function X5(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(xL.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(xL.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Jt.JOB_TYPE_ENUM.csv_file_load:await zs(e,sd.csvFileLoad);break;case Jt.JOB_TYPE_ENUM.csv_url_load:await zs(e,sd.csvURLLoad);break;case Jt.JOB_TYPE_ENUM.csv_data_load:await zs(e,sd.csvDataLoad);break;case Jt.JOB_TYPE_ENUM.import_from_s3:await zs(e,sd.importFromS3);break;case Jt.JOB_TYPE_ENUM.empty_trash:break;case Jt.JOB_TYPE_ENUM.export_local:await zs(e,VL.export_local);break;case Jt.JOB_TYPE_ENUM.export_to_s3:await zs(e,VL.export_to_s3);break;case Jt.JOB_TYPE_ENUM.delete_files_before:case Jt.JOB_TYPE_ENUM.delete_records_before:await zs(e,$L.deleteFilesBefore);break;case Jt.JOB_TYPE_ENUM.delete_audit_logs_before:await zs(e,$L.deleteAuditLogsBefore);break;case Jt.JOB_TYPE_ENUM.delete_transaction_logs_before:await zs(e,J5.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}o(X5,"parseMessage");async function zs(e,t){try{e.job.status=Jt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Q5().valueOf(),await kL.updateJob(e.job),await Z5(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):nd.error(`There was an error running ${t.name} job with id ${e.job.id}`),nd.error(s),e.job.message=s,e.job.status=Jt.JOB_STATUS_ENUM.ERROR;try{await kL.updateJob(e.job)}catch(n){throw nd.error(`Unable to update job with id ${e.job.id}`),n}throw r}}o(zs,"runJob");async function Z5(e){nd.trace("launching job thread:",e),z5.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Jt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}o(Z5,"launchJobThread");YL.exports={parseMessage:X5,RunnerMessage:bp}});var QL=m((ile,WL)=>{"use strict";var yp=class{static{o(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};WL.exports=yp});var _M=m((ole,Dp)=>{"use strict";var cd=Tr(),Cp=D_(),id=Rp(),Js=yl(),ad=$n(),Cc=zn(),j5=Jh(),wc=Or(),od=im(),Nt=CS(),ot=q(),e8=cm(),t8=Vl(),r8=Vm(),s8=Wl(),n8=$m(),i8=Ym(),a8=Qm(),o8=Jm(),Ip=jm(),zL=L_(),c8=C_(),Up=Np(),I=g(),{hdb_errors:Dc,handleHDBError:Uc}=W(),{HTTP_STATUS_CODES:JL}=Dc,wp=nS(),XL=gS(),aM=require("util"),ba=Rr(),u8=ln(),l8=ca(),ZL=KL(),jL=ko(),eM=(S_(),re(lc)),tM=Ar(),rM=g_(),sM=b_(),{setServerUtilities:_8}=(td(),re(gp)),{CONTEXT:d8}=(Xr(),re(IE)),{_assignPackageExport:E8}=require("../index"),{transformReq:f8}=x(),h8=_p(),nM=cd.searchByHash,m8=cd.searchByValue,S8=aM.promisify(cd.search),p8=aM.promisify(Cp.evaluateSQL),T8={[I.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[I.OPERATIONS_ENUM.CREATE_TABLE]:!0,[I.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[I.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[I.OPERATIONS_ENUM.DROP_TABLE]:!0,[I.OPERATIONS_ENUM.DROP_SCHEMA]:!0},B=QL();async function oM(e,t){try{if(e.body.operation!=="read_log"&&(ot.log_level===I.LOG_LEVELS.INFO||ot.log_level===I.LOG_LEVELS.DEBUG||ot.log_level===I.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...a}=e.body;ot.info(a)}}catch(s){ot.error(s)}let r=await h8.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return T8[e.body.operation]&&u8.setSchemaDataToGlobal(s=>{s&&ot.error(s)}),r}o(oM,"processLocalTransaction");var iM=g8();Dp.exports={chooseOperation:cM,getOperationFunction:uM,operation:lM,processLocalTransaction:oM};_8(Dp.exports);function cM(e){let t;try{t=uM(e)}catch(n){throw ot.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=Cp.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let a=Cp.checkASTPermissions(e,i);if(a)throw ot.error(`${JL.FORBIDDEN} from operation ${e.operation}`),ot.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),Uc(new Error,a,Dc.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==I.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==I.OPERATIONS_ENUM.LOGIN&&e.operation!==I.OPERATIONS_ENUM.LOGOUT){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 a=c8.verifyPerms(i,n);if(a)throw ot.error(`${JL.FORBIDDEN} from operation ${e.operation}`),ot.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),Uc(new Error,a,Dc.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw Uc(n,"There was an error when trying to choose an operation path")}return r}o(cM,"chooseOperation");function uM(e){if(ot.trace(`getOperationFunction with operation: ${e.operation}`),iM.has(e.operation))return iM.get(e.operation);throw Uc(new Error,Dc.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Dc.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}o(uM,"getOperationFunction");E8("operation",lM);function lM(e,t){e.hdb_user=this[d8]?.user,e.bypass_auth=!t;let r=cM(e);return oM({body:e},r)}o(lM,"operation");async function R8(e){ot.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[I.CLUSTERING_FLAG]=!0;let a;switch(i.operation){case I.OPERATIONS_ENUM.INSERT:a=await ba.insert(i);break;case I.OPERATIONS_ENUM.UPDATE:a=await ba.update(i);break;case I.OPERATIONS_ENUM.UPSERT:a=await ba.upsert(i);break;case I.OPERATIONS_ENUM.DELETE:a=await Cc.deleteRecord(i);break;default:ot.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,a,e)}catch(a){ot.info("Invalid operation in transaction"),ot.error(a)}}o(R8,"catchup");async function ms(e){f8(e);let t,r;try{r=await Up.addJob(e),t=r.createdJob,ot.info("addJob result",r);let s=new ZL.RunnerMessage(t,e);return await ZL.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw ot.error(n),Uc(s,n)}}o(ms,"executeJob");function g8(){let e=new Map;return e.set(I.OPERATIONS_ENUM.INSERT,new B(ba.insert)),e.set(I.OPERATIONS_ENUM.UPDATE,new B(ba.update)),e.set(I.OPERATIONS_ENUM.UPSERT,new B(ba.upsert)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new B(cd.searchByConditions)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_HASH,new B(nM)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_ID,new B(nM)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_VALUE,new B(m8)),e.set(I.OPERATIONS_ENUM.SEARCH,new B(S8)),e.set(I.OPERATIONS_ENUM.SQL,new B(p8)),e.set(I.OPERATIONS_ENUM.CSV_DATA_LOAD,new B(ms,id.csvDataLoad)),e.set(I.OPERATIONS_ENUM.CSV_FILE_LOAD,new B(ms,id.csvFileLoad)),e.set(I.OPERATIONS_ENUM.CSV_URL_LOAD,new B(ms,id.csvURLLoad)),e.set(I.OPERATIONS_ENUM.IMPORT_FROM_S3,new B(ms,id.importFromS3)),e.set(I.OPERATIONS_ENUM.CREATE_SCHEMA,new B(Js.createSchema)),e.set(I.OPERATIONS_ENUM.CREATE_DATABASE,new B(Js.createSchema)),e.set(I.OPERATIONS_ENUM.CREATE_TABLE,new B(Js.createTable)),e.set(I.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new B(Js.createAttribute)),e.set(I.OPERATIONS_ENUM.DROP_SCHEMA,new B(Js.dropSchema)),e.set(I.OPERATIONS_ENUM.DROP_DATABASE,new B(Js.dropSchema)),e.set(I.OPERATIONS_ENUM.DROP_TABLE,new B(Js.dropTable)),e.set(I.OPERATIONS_ENUM.DROP_ATTRIBUTE,new B(Js.dropAttribute)),e.set(I.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new B(ad.describeSchema)),e.set(I.OPERATIONS_ENUM.DESCRIBE_DATABASE,new B(ad.describeSchema)),e.set(I.OPERATIONS_ENUM.DESCRIBE_TABLE,new B(ad.describeTable)),e.set(I.OPERATIONS_ENUM.DESCRIBE_ALL,new B(ad.describeAll)),e.set(I.OPERATIONS_ENUM.DELETE,new B(Cc.deleteRecord)),e.set(I.OPERATIONS_ENUM.ADD_USER,new B(wc.addUser)),e.set(I.OPERATIONS_ENUM.ALTER_USER,new B(wc.alterUser)),e.set(I.OPERATIONS_ENUM.DROP_USER,new B(wc.dropUser)),e.set(I.OPERATIONS_ENUM.LIST_USERS,new B(wc.listUsersExternal)),e.set(I.OPERATIONS_ENUM.LIST_ROLES,new B(od.listRoles)),e.set(I.OPERATIONS_ENUM.ADD_ROLE,new B(od.addRole)),e.set(I.OPERATIONS_ENUM.ALTER_ROLE,new B(od.alterRole)),e.set(I.OPERATIONS_ENUM.DROP_ROLE,new B(od.dropRole)),e.set(I.OPERATIONS_ENUM.USER_INFO,new B(wc.userInfo)),e.set(I.OPERATIONS_ENUM.READ_LOG,new B(e8)),e.set(I.OPERATIONS_ENUM.ADD_NODE,new B(t8)),e.set(I.OPERATIONS_ENUM.UPDATE_NODE,new B(r8)),e.set(I.OPERATIONS_ENUM.REMOVE_NODE,new B(s8)),e.set(I.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new B(n8)),e.set(I.OPERATIONS_ENUM.PURGE_STREAM,new B(i8)),e.set(I.OPERATIONS_ENUM.SET_CONFIGURATION,new B(tM.setConfiguration)),e.set(I.OPERATIONS_ENUM.CLUSTER_STATUS,new B(a8.clusterStatus)),e.set(I.OPERATIONS_ENUM.CLUSTER_NETWORK,new B(o8)),e.set(I.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new B(Ip.setRoutes)),e.set(I.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new B(Ip.getRoutes)),e.set(I.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new B(Ip.deleteRoutes)),e.set(I.OPERATIONS_ENUM.EXPORT_TO_S3,new B(ms,zL.export_to_s3)),e.set(I.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new B(ms,Cc.deleteFilesBefore)),e.set(I.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new B(ms,Cc.deleteFilesBefore)),e.set(I.OPERATIONS_ENUM.EXPORT_LOCAL,new B(ms,zL.export_local)),e.set(I.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new B(Up.handleGetJobsByStartDate)),e.set(I.OPERATIONS_ENUM.GET_JOB,new B(Up.handleGetJob)),e.set(I.OPERATIONS_ENUM.GET_FINGERPRINT,new B(wp.getFingerprint)),e.set(I.OPERATIONS_ENUM.SET_LICENSE,new B(wp.setLicense)),e.set(I.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new B(wp.getRegistrationInfo)),e.set(I.OPERATIONS_ENUM.RESTART,new B(XL.restart)),e.set(I.OPERATIONS_ENUM.RESTART_SERVICE,new B(XL.restartService)),e.set(I.OPERATIONS_ENUM.CATCHUP,new B(R8)),e.set(I.OPERATIONS_ENUM.SYSTEM_INFORMATION,new B(l8.systemInformation)),e.set(I.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new B(ms,Cc.deleteAuditLogsBefore)),e.set(I.OPERATIONS_ENUM.READ_AUDIT_LOG,new B(j5)),e.set(I.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new B(jL.createTokens)),e.set(I.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new B(jL.refreshOperationToken)),e.set(I.OPERATIONS_ENUM.LOGIN,new B(eM.login)),e.set(I.OPERATIONS_ENUM.LOGOUT,new B(eM.logout)),e.set(I.OPERATIONS_ENUM.GET_CONFIGURATION,new B(tM.getConfiguration)),e.set(I.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new B(Nt.customFunctionsStatus)),e.set(I.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new B(Nt.getCustomFunctions)),e.set(I.OPERATIONS_ENUM.GET_COMPONENT_FILE,new B(Nt.getComponentFile)),e.set(I.OPERATIONS_ENUM.GET_COMPONENTS,new B(Nt.getComponents)),e.set(I.OPERATIONS_ENUM.SET_COMPONENT_FILE,new B(Nt.setComponentFile)),e.set(I.OPERATIONS_ENUM.DROP_COMPONENT,new B(Nt.dropComponent)),e.set(I.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new B(Nt.getCustomFunction)),e.set(I.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new B(Nt.setCustomFunction)),e.set(I.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new B(Nt.dropCustomFunction)),e.set(I.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new B(Nt.addComponent)),e.set(I.OPERATIONS_ENUM.ADD_COMPONENT,new B(Nt.addComponent)),e.set(I.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new B(Nt.dropCustomFunctionProject)),e.set(I.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new B(Nt.packageComponent)),e.set(I.OPERATIONS_ENUM.PACKAGE_COMPONENT,new B(Nt.packageComponent)),e.set(I.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new B(Nt.deployComponent)),e.set(I.OPERATIONS_ENUM.DEPLOY_COMPONENT,new B(Nt.deployComponent)),e.set(I.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new B(rM.readTransactionLog)),e.set(I.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new B(ms,rM.deleteTransactionLogsBefore)),e.set(I.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new B(sM.installModules)),e.set(I.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new B(sM.auditModules)),e.set(I.OPERATIONS_ENUM.GET_BACKUP,new B(Js.getBackup)),e}o(g8,"initializeOperationFunctionMap")});var ld=m((ule,fM)=>{"use strict";var Lp=g(),A8=x(),Lc=q(),{handleHDBError:Mp,hdb_errors:ud}=W(),{isMainThread:O8}=require("worker_threads"),{Readable:N8}=require("stream"),dM=require("os"),b8=require("util"),y8=Tm(),I8=b8.promisify(y8.authorize),EM=_M(),{Gzip:w8}=require("zlib");function C8(e){let t=`Found an uncaught exception with message: ${e.message}. ${dM.EOL}Stack: ${e.stack} ${dM.EOL}Terminating ${O8?"HDB":"thread"}.`;console.error(t),Lc.fatal(t),process.exit(1)}o(C8,"handleServerUncaughtException");function U8(e,t,r){if(Lc[e.logLevel||"error"](e),e.http_resp_code)return typeof e.http_resp_msg!="object"?r.code(e.http_resp_code).send({error:e.http_resp_msg||e.message}):r.code(e.http_resp_code).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:ud.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)}o(U8,"serverErrorHandler");function D8(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=Mp(new Error,"Invalid JSON.",ud.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(A8.isEmpty(e.body.operation)){let s=Mp(new Error,"Request body must include an 'operation' property.",ud.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}o(D8,"reqBodyValidationHandler");function L8(e,t,r){let s;e.body.operation!==Lp.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==Lp.OPERATIONS_ENUM.LOGIN&&e.body.operation!==Lp.OPERATIONS_ENUM.LOGOUT?I8(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{Lc.warn(n),Lc.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(Mp(n,i,ud.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}o(L8,"authHandler");async function M8(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=EM.chooseOperation(e.body);let n=await EM.processLocalTransaction(e,s);if(n instanceof N8&&n.headers){for(let[i,a]of n.headers)t.header(i,a);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),n=n.pipe(new w8))}return n}catch(n){throw Lc.error(n),n}}o(M8,"handlePostRequest");fM.exports={authHandler:L8,handlePostRequest:M8,handleServerUncaughtException:C8,serverErrorHandler:U8,reqBodyValidationHandler:D8}});var pM=m((_le,SM)=>{"use strict";var P8=require("fastify-plugin"),{handlePostRequest:hM,authHandler:v8,reqBodyValidationHandler:B8}=ld();async function H8(e){e.decorate("hdbCore",{preValidation:[B8,v8],request:t=>mM(hM(t)),requestWithoutAuthentication:t=>mM(hM(t,!0))})}o(H8,"hdbCore");async function mM(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}o(mM,"convertAsyncIterators");SM.exports=P8(H8)});var RM=m((Ele,TM)=>{"use strict";var Pp=require("fs"),ya=Q();ya.initSync();var{CONFIG_PARAMS:Mc}=g(),F8=1024*1024*1024;function q8(e){let t=ya.get(Mc.CUSTOMFUNCTIONS_NETWORK_TIMEOUT),r=ya.get(Mc.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT),s={bodyLimit:F8,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0};if(e){let n=ya.get(Mc.CUSTOMFUNCTIONS_TLS_PRIVATEKEY),i=ya.get(Mc.CUSTOMFUNCTIONS_TLS_CERTIFICATE),a=ya.get(Mc.OPERATIONSAPI_TLS_CERT_AUTH);s.https={allowHTTP1:!0,key:Pp.readFileSync(`${n}`),cert:Pp.readFileSync(i)+(a?`
|
|
19
|
+
`},q:.8});Et.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,s]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let n=t[r];Array.isArray(n)?n.push(s):t.key=[n,s]}else t[r]=s},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});GD={type:"application/json",serializeStream:H_.streamAsJSON,serialize:JSON.stringify,deserialize:Oj,q:.8};Et.set("*/*",GD);Et.set("",GD);a(Oj,"tryJSONParse");a(jS,"registerContentHandlers");Nj=require("fastify-plugin"),bj=Nj(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=G_(s.raw);n.type(c),n.serializer(o.serializeStream||o.serialize)}),r()},{name:"content-type-negotiation"});a(G_,"findBestSerializer");a(ep,"serialize");a(Ks,"serializeMessage");a(yj,"streamToBuffer");a(Ao,"getDeserializer");a(HD,"deserializerUnknownType");a(Ij,"transformIterable")});var Y_={};je(Y_,{addAnalyticsListener:()=>np,recordAction:()=>Ss,recordActionBinary:()=>Oo,setAnalyticsEnabled:()=>wj});function wj(e){XD=e}function Ss(e,t,r,s,n){if(!XD)return;let i=t+(r?"-"+r:"");s&&(i+="-"+s);let o=V_.get(i);o?(o.push(e),o.total+=e):(o=[e],o.total=e,o.description={metric:t,path:r,method:s,type:n},V_.set(i,o)),k_||Cj()}function Oo(e,t,r,s,n){Ss(e?1:0,t,r,s,n)}function np(e){jD.push(e)}function Cj(){k_=performance.now(),setTimeout(()=>{let e=performance.now()-k_;k_=0;let t=[],r={time:Date.now(),period:e,threadId:fi.threadId,metrics:t};for(let[n,i]of V_)if(i.sort){i.sort();let o=i.length;t.push(Object.assign(i.description,{median:i[o>>1],mean:i.total/o,p95:i[Math.floor(o*.95)],p90:i[Math.floor(o*.9)],count:o}))}else t.push(i);let s=process.memoryUsage();t.push({metric:"memory",threadId:fi.threadId,...s});for(let n of jD)n(t);V_=new Map,fi.parentPort?fi.parentPort.postMessage({type:ZD,report:r}):tL({report:r})},sp).unref()}async function Uj(e,t=6e4){let r=ip(),s;for(let _ of r.primaryStore.getRange({start:x_+"z",end:x_,reverse:!0}))if(_.value?.time){s=_.value.time;break}if(Date.now()-t<s)return;let n,i=new Map,o;for(let{key:_,value:d}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!d)continue;if(n){if(_>n+t)break}else n=_;o=_;let{metrics:E}=d;for(let f of E||[]){let{path:h,method:T,type:p,metric:R,count:O,threadId:k,...$}=f;O||(O=1);let U=R+(h?"-"+h:"");T&&(U+="-"+T);let b=i.get(U);if(b)for(let P in $){let z=$[P];if(typeof z=="number"){let F=b.count||1;b[P]=(b[P]*F+z*O)/(b.count=F+O)}}else b=Object.assign({period:t},f),i.set(U,b)}await Dj()}for(let[_,d]of i)d.id=x_+Math.round(o)+"-"+_,d.time=o,r.put(d);let c=Date.now(),{idle:u,active:l}=performance.eventLoopUtilization();r.put({id:x_+Math.round(c)+"-main-thread-utilization",metric:"main-thread-utilization",idle:u-kD,active:l-VD,time:c}),kD=u,VD=l}async function Lj(e,t){let r=ip(),s=Date.now()-e;for(let n of r.primaryStore.getKeys({start:!1,end:s}))r.primaryStore.remove(n)}function ip(){return $D||($D=rt({table:"hdb_analytics",database:"system",expiration:864e3,audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"values"}]}))}function Pj(){eL=!0,setInterval(async()=>{await Uj(sp,rp),await Lj(Mj,sp)},rp/2).unref()}function tL(e,t){let r=e.report;r.threadId=t?.threadId||fi.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(YD+=s.mean*s.count);r.totalBytesProcessed=YD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(KD.get(t))}),KD.set(t,t.performance.eventLoopUtilization())),r.id=(0,zD.getNextMonotonicTime)(),ip().put(r),eL||Pj(),vj&&(rL=Hj(r))}async function Hj(e){if(await rL,!Dn){let r=(0,yc.dirname)((0,QD.getLogFilePath)());try{Dn=await(0,tp.open)((0,yc.join)(r,"analytics.log"),"r+")}catch{Dn=await(0,tp.open)((0,yc.join)(r,"analytics.log"),"w+")}}let t=(await Dn.stat()).size;if(t>Bj){let r=Buffer.alloc(t);await Dn.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await Dn.write(r,{position:0}),await Dn.truncate(r.length),t=r.length}await Dn.write(JSON.stringify(e)+`
|
|
20
|
+
`,t)}var fi,WD,QD,yc,tp,zD,$_,JD,V_,rp,XD,k_,sp,ZD,jD,x_,kD,VD,Dj,Mj,$D,eL,YD,KD,vj,rL,Dn,Bj,hi=Se(()=>{fi=require("worker_threads"),WD=C(dt());de();QD=C(x()),yc=require("path"),tp=require("fs/promises"),zD=C(vt()),$_=C(Q()),JD=C(A());es();(0,$_.initSync)();V_=new Map,rp=(0,$_.get)(JD.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3,XD=rp>0;a(wj,"setAnalyticsEnabled");a(Ss,"recordAction");tt.recordAnalytics=Ss;a(Oo,"recordActionBinary");k_=0,sp=1e3,ZD="analytics-report",jD=[];a(np,"addAnalyticsListener");a(Cj,"sendAnalytics");x_="sum-";a(Uj,"aggregation");kD=0,VD=0,Dj=a(()=>new Promise(setImmediate),"rest");a(Lj,"cleanup");Mj=36e5;a(ip,"getAnalyticsTable");(0,WD.setChildListenerByType)(ZD,tL);a(Pj,"startScheduledTasks");YD=0,KD=new Map,vj=!1;a(tL,"recordAnalytics");Bj=1e6;a(Hj,"logAnalytics")});var cp={};je(cp,{start:()=>Gj});async function qj(e,t){let r=e.headers.accept==="text/event-stream"?"CONNECT":e.method;e.search&&bu(e);let s=performance.now(),n,i=new ho;try{e.responseHeaders=i;let o=e.url.slice(1),c=ap.getMatch(o);if(!c)return t(e);let u={url:c.relativeURL},l=c.Resource,_=await Ye(e,()=>{if(r==="POST"||r==="PUT"||r==="PATCH"||r==="QUERY")try{e.data=Ao(e.headers["content-type"],!0)(e.body)}catch(R){throw new Ic.ClientError(R,400)}switch(e.authorize=!0,r){case"GET":case"HEAD":return l.get(u,e);case"POST":return l.post(u,e.data,e);case"PUT":return l.put(u,e.data,e);case"DELETE":return l.delete(u,e);case"PATCH":return l.patch(u,e.data,e);case"OPTIONS":i.set("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return l.connect(u,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(u,e.data,e);case"COPY":return l.copy(u,e.headers.destination,e);case"MOVE":return l.move(u,e.headers.destination,e);case"BREW":throw new Ic.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ic.ServerError(`Method ${r} is not recognized`,501)}}),d=performance.now()-s,E=200,f;if(_==null)E=r==="GET"||r==="HEAD"?404:204;else if(f=e?.lastModified){Fj[0]=f;let R=String.fromCharCode(34,(At[0]&63)+62,(At[0]>>6)+(At[1]<<2&63)+62,(At[1]>>4)+(At[2]<<4&63)+62,(At[2]>>2)+62,(At[3]&63)+62,(At[3]>>6)+(At[4]<<2&63)+62,(At[4]>>4)+(At[5]<<4&63)+62,(At[5]>>2)+62,(At[6]&63)+62,(At[6]>>6)+(At[7]<<2&63)+62,34),O=e.headers["if-none-match"];O&&R==O?(_?.onDone&&_.onDone(),E=304,_=void 0):i.set("ETag",R)}e.createdResource&&(E=201),e.newLocation&&i.set("Location",e.newLocation);let h={status:E,headers:i,body:void 0},T=`db;dur=${d.toFixed(2)}`,p=_?.wasLoadedFromSource?.();return p!==void 0&&(p?T+=", miss":f&&i.set("Age",Math.round((Date.now()-f)/1e3))),i.append("Server-Timing",T,!0),Ss(d,"TTFB",n,r),Oo(E<400,"success",n,r),_!==void 0&&(h.body=ep(_,e,h),r==="HEAD"&&(h.body=void 0)),h}catch(o){let c=performance.now()-s;return Ss(c,"TTFB",n,r),Oo(!1,"success",n,r),o.statusCode||console.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.set("Allow",o.allow.map(u=>u.toUpperCase()).join(", ")))),{status:o.statusCode||500,headers:i,body:Ks(o.toString(),e)}}}function Gj(e){if(sL)return;sL=!0,ap=e.resources,e.server.http(async(r,s)=>{if(!r.isWebSocket)return qj(r,s)}),e.server.ws(async(r,s,n)=>{nL++,op||(setTimeout(()=>{console.log("connection count",nL,"mem",Math.round(process.memoryUsage().heapUsed/1e6)),op=!1},1e3),op=!0),t(s);let i=new Jr;r.on("error",console.error);let o;r.on("message",a(function(d){o||(o=Ao(s.headers["content-type"]));let E=o(d);i.push(E)},"message"));let c;r.on("close",()=>{i.emit("close"),c&&c.return()}),await n;let u,l=await ap.call(s.pathname.slice(1),s,(_,d)=>(u=!0,_.connect(i)));if(!u)r.send(Ks(`No resource was found to handle ${s.pathname}`,s));else{c=l[Symbol.asyncIterator]();let _;for(;!(_=await c.next()).done;)r.send(Ks(_.value,s))}r.close()});function t(r){let s=r.pathname,n=s.lastIndexOf(".");if(n>-1){let i=s.slice(n+1),o=EXTENSION_TYPES[i];o&&(r.headers.accept=o)}}a(t,"startRequest")}var Ic,At,Fj,sL,ap,nL,op,iL=Se(()=>{So();hi();Ic=C(W());yu();na();xn();CS();At=new Uint8Array(8),Fj=new Float64Array(At.buffer,0,1);a(qj,"http");nL=0;a(Gj,"start")});var up=m((Kue,oL)=>{var{recordAction:K_,recordActionBinary:xj}=(hi(),re(Y_)),kj=require("fastify-plugin"),Vj=200;oL.exports=kj(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n,i)=>{let o=n.getResponseTime(),c=performance.now(),u=n.context.config,l,_,d;u.isOperation?(l=s.body?.operation,_="operation"):(l=u.url,_="fastify-route",d=u.method),K_(o,"TTFB",l,d,_),xj(n.raw.statusCode<400,"success",l,d,_);let E=Vj;i?.pipe?(i.on("data",h=>{E+=h.length}),i.on("end",()=>{K_(performance.now()-c,"transfer",l,d,_),K_(E,"bytes-sent",l,d,_)})):(E+=i?.length||0,K_(E,"bytes-sent",l,d,_));let f=o.toFixed(3);n.header("Server-Timing",`db;dur=${f}`)}),r()},{name:"hdb-request-time"})});var Ep=m((Wue,_L)=>{var X_=require("clone"),Z_=ve(),$j=V(),z_=A(),Yj=x(),W_=require("fs"),lp=require("joi"),{string:J_}=lp.types(),{hdb_errors:Kj,handleHDBError:wc}=W(),{HDB_ERROR_MSGS:Wj,HTTP_STATUS_CODES:Q_}=Kj,{common_validators:No}=rs(),aL=1e9,cL=" is required",Qj=["insert","update","upsert"],_p={database:{presence:!1,format:No.schema_format,length:No.schema_length},schema:{presence:!1,format:No.schema_format,length:No.schema_length},table:{presence:!0,format:No.schema_format,length:No.schema_length},action:{inclusion:{within:Qj,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},zj={schema:J_.required(),table:J_.required(),action:J_.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Jj,AWS_SECRET:Xj,AWS_BUCKET:Zj,AWS_FILE_KEY:jj,REGION:e5}=z_.S3_BUCKET_AUTH_KEYS,t5={s3:{presence:!0},[`s3.${Jj}`]:{presence:!0,type:"String"},[`s3.${Xj}`]:{presence:!0,type:"String"},[`s3.${Zj}`]:{presence:!0,type:"String"},[`s3.${jj}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${e5}`]:{presence:!0,type:"String"}},uL=X_(_p);uL.data.presence={message:cL};var lL=X_(_p);lL.file_path.presence={message:cL};var r5=Object.assign(X_(_p),t5),dp=X_(zj);dp.csv_url=J_.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();dp.passthrough_headers=lp.object();function s5(e){let t=Z_.validateObject(e,uL);return j_(e,t)}a(s5,"dataObject");function n5(e){let t=Z_.validateBySchema(e,lp.object(dp));return j_(e,t)}a(n5,"urlObject");function i5(e){let t=Z_.validateObject(e,lL);return j_(e,t)}a(i5,"fileObject");function o5(e){let t=Z_.validateObject(e,r5);return j_(e,t)}a(o5,"s3FileObject");function j_(e,t){if(!t){let r=$j.checkGlobalSchemaTable(e.schema,e.table);if(r)return wc(new Error,r,Q_.BAD_REQUEST);if(e.operation===z_.OPERATIONS_ENUM.CSV_FILE_LOAD){try{W_.accessSync(e.file_path,W_.constants.R_OK|W_.constants.F_OK)}catch(s){return s.code===z_.NODE_ERROR_CODES.ENOENT?wc(s,`No such file or directory ${s.path}`,Q_.BAD_REQUEST):s.code===z_.NODE_ERROR_CODES.EACCES?wc(s,`Permission denied ${s.path}`,Q_.BAD_REQUEST):wc(s)}try{let s=W_.statSync(e.file_path).size;if(s>aL)return wc(new Error,Wj.MAX_FILE_SIZE_ERR(s,aL),Q_.BAD_REQUEST)}catch(s){Yj.error(s),console.error(s)}}}return t}a(j_,"postValidateChecks");_L.exports={dataObject:s5,urlObject:n5,fileObject:i5,s3FileObject:o5}});var fp=m((zue,dL)=>{"use strict";var Cc=x(),ed=A();async function a5(e,t,r,s=void 0){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===ed.OPERATIONS_ENUM.INSERT||t.operation===ed.OPERATIONS_ENUM.UPDATE||t.operation===ed.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===ed.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(Cc.info(i.message),i):i.http_resp_msg?(Cc.error(`Error calling operation: ${e.name}`),Cc.error(i.http_resp_msg),i):(Cc.error(`Error calling operation: ${e.name}`),Cc.error(i),i)}}a(a5,"callOperationFunctionAsAwait");dL.exports={callOperationFunctionAsAwait:a5}});var fL=m((Xue,EL)=>{"use strict";var hp=class{static{a(this,"BulkLoadFileObject")}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}},mp=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};EL.exports={BulkLoadFileObject:hp,BulkLoadDataObject:mp}});var mL=m((jue,hL)=>{"use strict";var Sp=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};hL.exports=Sp});var Op=m((ile,ML)=>{"use strict";var td=Ar(),sd=Ep(),c5=require("needle"),Yr=A(),tle=Be(),bo=V(),{handleHDBError:Fe,hdb_errors:bL}=W(),{HTTP_STATUS_CODES:Ot,HDB_ERROR_MSGS:ct,CHECK_LOGS_WRAPPER:Si}=bL,yo=x(),pp=require("papaparse");bo.promisifyPapaParse();var Kr=require("fs-extra"),u5=require("path"),{chain:SL}=require("stream-chain"),pL=require("stream-json/streamers/StreamArray"),TL=require("stream-json/utils/Batch"),RL=require("stream-chain/utils/comp"),{finished:gL}=require("stream"),l5=Q(),yL=fp(),_5=JS(),{BulkLoadFileObject:Rp,BulkLoadDataObject:d5}=fL(),gp=GS(),{verifyBulkLoadAttributePerms:IL}=M_(),rle=mL(),sle=nt(),nle=Ps(),{databases:E5}=(de(),re(Ne)),{coerceType:f5}=(nd(),re(Np)),AL="No records parsed from csv file.",mi=`${l5.get("HDB_ROOT")}/tmp`,{schema_regex:h5}=rs(),OL=1024*1024*2,NL=5e3,m5={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};ML.exports={csvDataLoad:S5,csvURLLoad:p5,csvFileLoad:T5,importFromS3:R5};async function S5(e,t){let r=sd.dataObject(e);if(r)throw Fe(r,r.message,Ot.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=UL(e.schema,e.table),i=pp.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Tp.bind(null,n),dynamicTyping:!1}),o=new gp;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&IL(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw Fe(new Error,c,Ot.BAD_REQUEST,void 0,void 0,!0);let u=new d5(e.action,e.schema,e.table,i.data);return s=await yL.callOperationFunctionAsAwait(DL,u,null),s.message===AL?AL:LL(s.records,s.number_written)}catch(n){throw pi(n)}}a(S5,"csvDataLoad");async function p5(e){let t=sd.urlObject(e);if(t)throw Fe(t,t.message,Ot.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${mi}/${r}`;try{await g5(e,r)}catch(n){throw yo.error(ct.DOWNLOAD_FILE_ERR(r)+" - "+n),Fe(n,Si(ct.DOWNLOAD_FILE_ERR(r)))}try{let n=new Rp(this.job_operation_function.name,e.action,e.schema,e.table,s,Yr.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Ap(n);return await rd(s),i}catch(n){throw await rd(s),pi(n)}}a(p5,"csvURLLoad");async function T5(e){let t=sd.fileObject(e);if(t)throw Fe(t,t.message,Ot.BAD_REQUEST,void 0,void 0,!0);let r=new Rp(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Yr.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Ap(r)}catch(s){throw pi(s)}}a(T5,"csvFileLoad");async function R5(e){let t=sd.s3FileObject(e);if(t)throw Fe(t,t.message,Ot.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=u5.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${mi}/${n}`;let i=new Rp(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await A5(n,e);let o=await Ap(i);return await rd(r),o}catch(s){throw await rd(r),pi(s)}}a(R5,"importFromS3");async function g5(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await c5("get",e.csv_url,s)}catch(s){let n=`Error downloading CSV file from ${e.csv_url}, status code: ${s.statusCode}. Check the log for more information.`;throw Fe(s,n,s.statusCode,Yr.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}N5(r,e.csv_url),await O5(t,r.raw)}a(g5,"downloadCSVFile");async function A5(e,t){try{let r=`${mi}/${e}`;await Kr.mkdirp(mi),await Kr.writeFile(`${mi}/${e}`,"",{flag:"a+"});let s=await Kr.createWriteStream(r),n=await _5.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(){yo.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw yo.error(ct.S3_DOWNLOAD_ERR+" - "+r),Fe(r,Si(ct.S3_DOWNLOAD_ERR))}}a(A5,"downloadFileFromS3");async function O5(e,t){try{await Kr.mkdirp(mi),await Kr.writeFile(`${mi}/${e}`,t)}catch(r){throw yo.error(ct.WRITE_TEMP_FILE_ERR),Fe(r,Si(ct.DEFAULT_BULK_LOAD_ERR))}}a(O5,"writeFileToTempFolder");async function rd(e){if(e)try{await Kr.access(e),await Kr.unlink(e)}catch{yo.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(rd,"deleteTempFile");function N5(e,t){if(e.statusCode!==bL.HTTP_STATUS_CODES.OK)throw Fe(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Ot.BAD_REQUEST);if(!m5[e.headers["content-type"]])throw Fe(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Ot.BAD_REQUEST);if(!e.raw)throw Fe(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Ot.BAD_REQUEST)}a(N5,"validateURLResponse");async function Ap(e){try{let t;switch(e.file_type){case Yr.VALID_S3_FILE_TYPES.CSV:t=await b5(e);break;case Yr.VALID_S3_FILE_TYPES.JSON:t=await y5(e);break;default:throw Fe(new Error,ct.DEFAULT_BULK_LOAD_ERR,Ot.BAD_REQUEST,Yr.LOG_LEVELS.ERROR,ct.INVALID_FILE_EXT_ERR(e))}return LL(t.records,t.number_written)}catch(t){throw pi(t)}}a(Ap,"fileLoad");async function wL(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 td.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&IL(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=Fe(c);r(u)}}a(wL,"validateChunk");async function CL(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;bo.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!bo.isEmpty(c)&&!bo.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(l=>c.add(l))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await yL.callOperationFunctionAsAwait(DL,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=Fe(c,Si(ct.INSERT_CSV_ERR),Ot.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,ct.INSERT_CSV_ERR+" - "+c);r(u)}}a(CL,"insertChunk");async function b5(e){let t={records:0,number_written:0},r=UL(e.schema,e.table);try{let s=new gp,n=Kr.createReadStream(e.file_path,{highWaterMark:OL});n.setEncoding("utf8"),await pp.parsePromise(n,wL.bind(null,e,s),Tp.bind(null,r));let i=s.getPermsResponse();if(i)throw Fe(new Error,i,Ot.BAD_REQUEST);return n=Kr.createReadStream(e.file_path,{highWaterMark:OL}),n.setEncoding("utf8"),await pp.parsePromise(n,CL.bind(null,e,t),Tp.bind(null,r)),n.destroy(),t}catch(s){throw Fe(s,Si(ct.PAPA_PARSE_ERR),Ot.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,ct.PAPA_PARSE_ERR+s)}}a(b5,"callPapaParse");function UL(e,t){let r=E5[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>f5(i,n));return s}a(UL,"createTransformMap");function Tp(e,t,r){let s=e.get(r);return s?s(t):bo.autoCast(t)}a(Tp,"typeFunction");async function y5(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new gp,n=SL([Kr.createReadStream(e.file_path,{encoding:"utf-8"}),pL.withParser(),c=>c.value,new TL({batchSize:NL}),RL(async c=>{await wL(e,s,r,c)})]);await new Promise((c,u)=>{gL(n,l=>{l?u(l):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw Fe(new Error,i,Ot.BAD_REQUEST);let o=SL([Kr.createReadStream(e.file_path,{encoding:"utf-8"}),pL.withParser(),c=>c.value,new TL({batchSize:NL}),RL(async c=>{await CL(e,t,r,c)})]);return await new Promise((c,u)=>{gL(o,l=>{l?u(l):c()}),o.resume()}),t}catch(s){throw Fe(s,Si(ct.INSERT_JSON_ERR),Ot.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,ct.INSERT_JSON_ERR+s)}}a(y5,"insertJson");async function DL(e){let t={};try{e.data&&e.data.length>0&&I5(e.data[0])?t=await w5(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",yo.info(t.message))}catch(r){throw pi(r)}return t}a(DL,"callBulkFileLoad");function I5(e){let t=Object.keys(e);for(let r of t)if(!h5.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(I5,"validateColumnNames");async function w5(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=td.insert;break;case"update":i=td.update;break;case"upsert":i=td.upsert;break;default:throw Fe(new Error,ct.INVALID_ACTION_PARAM_ERR(s),Ot.BAD_REQUEST,Yr.LOG_LEVELS.ERROR,ct.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 _=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][_])>=0&&e.splice(d,1)}let u=bo.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw pi(o)}}a(w5,"bulkFileLoad");function LL(e,t){return`successfully loaded ${t} of ${e} records`}a(LL,"buildResponseMsg");function pi(e){return Fe(e,Si(ct.DEFAULT_BULK_LOAD_ERR),Ot.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,ct.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(pi,"buildTopLevelErrMsg")});var vL=m((ale,PL)=>{"use strict";var bp=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};PL.exports=bp});var FL=m((ule,HL)=>{"use strict";var C5=A(),BL=require("moment"),U5=require("uuid").v4,yp=class{static{a(this,"JobObject")}constructor(){this.id=U5(),this.type=void 0,this.start_datetime=BL().valueOf(),this.created_datetime=BL().valueOf(),this.end_datetime=void 0,this.status=C5.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};HL.exports=yp});var Ip=m((_le,$L)=>{"use strict";var D5=require("uuid").v4,xL=Ar(),kL=gr(),L5=os(),M5=Xi(),P5=vL(),qe=A(),v5=FL(),B5=fm(),Dr=x(),H5=ma(),Io=V(),{promisify:F5}=require("util"),Ti=require("moment"),q5=v_(),id=Ep(),qL=If(),{deleteTransactionLogsBeforeValidator:G5}=PS(),{handleHDBError:x5,hdb_errors:k5}=W(),{HTTP_STATUS_CODES:V5}=k5,GL=kL.searchByValue,$5=kL.searchByHash,Y5=xL.insert,K5=F5(q5.evaluateSQL),W5=xL.update;$L.exports={addJob:J5,updateJob:Z5,handleGetJob:Q5,handleGetJobsByStartDate:z5,getJobById:VL};async function Q5(e){try{let t=await VL(e.id);return Io.isEmptyOrZeroLength(t)||(t[0]={...t[0]},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 Dr.error("There was an error getting job",t),new Error(r)}}a(Q5,"handleGetJob");async function z5(e){try{let t=await X5(e);if(Dr.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=Ti(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Ti(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 Dr.error(r),new Error(r)}}a(z5,"handleGetJobsByStartDate");async function J5(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Io.isEmptyOrZeroLength(e.operation)){let _="job parameter is invalid";return Dr.info(_),t.error=_,t}if(!qe.JOB_TYPE_ENUM[e.operation])return Dr.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case qe.OPERATIONS_ENUM.CSV_FILE_LOAD:s=id.fileObject(e);break;case qe.OPERATIONS_ENUM.CSV_URL_LOAD:s=id.urlObject(e);break;case qe.OPERATIONS_ENUM.CSV_DATA_LOAD:s=id.dataObject(e);break;case qe.OPERATIONS_ENUM.IMPORT_FROM_S3:s=id.s3FileObject(e);break;case qe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case qe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=qL(e,"date");break;case qe.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=qL(e,"timestamp");break;case qe.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=G5(e);break;default:break}if(s)throw x5(s,s.message,V5.BAD_REQUEST,void 0,void 0,!0);let n=new v5;n.type=e.operation===qe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?qe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new L5(qe.SYSTEM_SCHEMA_NAME,qe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await GL(i))}catch(_){let d=`There was an error inserting a new job: ${_}`;return Dr.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=D5();try{o=await GL(i)}catch(_){let d=`There was an error inserting a new job: ${_}`;return Dr.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Dr.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new H5(qe.SYSTEM_SCHEMA_NAME,qe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),l;try{l=await Y5(u)}catch(_){return Dr.error(`There was an error inserting a job for job type: ${e.operation} -- ${_}`),t.success=!1,t}if(l.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let _=`Created a job with type ${n.type} and id ${n.id}`;t.message=_,t.createdJob=n,t.success=!0,Dr.trace(_)}return t}a(J5,"addJob");async function X5(e){let t=Ti(e.from_date,Ti.ISO_8601),r=Ti(e.to_date,Ti.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 P5(s,e.hdb_user);try{return await K5(n)}catch(i){throw Dr.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(X5,"getJobsInDateRange");async function VL(e){if(Io.isEmptyOrZeroLength(e))return Io.errorizeMessage("Invalid job ID specified.");let t=new M5(qe.SYSTEM_SCHEMA_NAME,qe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await $5(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return Dr.error(s),Io.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(VL,"getJobById");async function Z5(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Io.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===qe.JOB_STATUS_ENUM.COMPLETE||e.status===qe.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Ti().valueOf());let t=new B5(qe.SYSTEM_SCHEMA_NAME,qe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await W5(t),r}a(Z5,"updateJob")});var JL=m((Ele,zL)=>{"use strict";var YL=V(),Jt=A(),j5=require("moment"),od=Op(),ad=x(),KL=Ip(),WL=B_(),QL=Jn(),e8=dt(),t8=b_(),wp=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function r8(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(YL.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(YL.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Jt.JOB_TYPE_ENUM.csv_file_load:await Xs(e,od.csvFileLoad);break;case Jt.JOB_TYPE_ENUM.csv_url_load:await Xs(e,od.csvURLLoad);break;case Jt.JOB_TYPE_ENUM.csv_data_load:await Xs(e,od.csvDataLoad);break;case Jt.JOB_TYPE_ENUM.import_from_s3:await Xs(e,od.importFromS3);break;case Jt.JOB_TYPE_ENUM.empty_trash:break;case Jt.JOB_TYPE_ENUM.export_local:await Xs(e,WL.export_local);break;case Jt.JOB_TYPE_ENUM.export_to_s3:await Xs(e,WL.export_to_s3);break;case Jt.JOB_TYPE_ENUM.delete_files_before:case Jt.JOB_TYPE_ENUM.delete_records_before:await Xs(e,QL.deleteFilesBefore);break;case Jt.JOB_TYPE_ENUM.delete_audit_logs_before:await Xs(e,QL.deleteAuditLogsBefore);break;case Jt.JOB_TYPE_ENUM.delete_transaction_logs_before:await Xs(e,t8.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(r8,"parseMessage");async function Xs(e,t){try{e.job.status=Jt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=j5().valueOf(),await KL.updateJob(e.job),await s8(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):ad.error(`There was an error running ${t.name} job with id ${e.job.id}`),ad.error(s),e.job.message=s,e.job.status=Jt.JOB_STATUS_ENUM.ERROR;try{await KL.updateJob(e.job)}catch(n){throw ad.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Xs,"runJob");async function s8(e){ad.trace("launching job thread:",e),e8.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Jt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(s8,"launchJobThread");zL.exports={parseMessage:r8,RunnerMessage:wp}});var ZL=m((hle,XL)=>{"use strict";var Cp=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};XL.exports=Cp});var hM=m((Sle,Pp)=>{"use strict";var _d=gr(),Lp=v_(),cd=Op(),Zs=Ul(),ud=Yn(),Dc=Jn(),n8=jh(),Uc=br(),ld=cm(),Nt=MS(),ut=x(),i8=_m(),o8=Wl(),a8=Km(),c8=Xl(),u8=Wm(),l8=Qm(),_8=Xm(),d8=jm(),Up=rS(),jL=B_(),E8=M_(),Mp=Ip(),I=A(),{hdb_errors:Mc,handleHDBError:Lc}=W(),{HTTP_STATUS_CODES:eM}=Mc,Dp=aS(),tM=NS(),lM=require("util"),wo=Ar(),f8=_n(),h8=uo(),rM=JL(),sM=$a(),nM=(g_(),re(dc)),iM=Nr(),oM=b_(),aM=C_(),{setServerUtilities:m8}=(nd(),re(Np)),{CONTEXT:S8}=(Xr(),re(DE)),{_assignPackageExport:p8}=require("../index"),{transformReq:T8}=V(),R8=fp(),cM=_d.searchByHash,g8=_d.searchByValue,A8=lM.promisify(_d.search),O8=lM.promisify(Lp.evaluateSQL),N8={[I.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[I.OPERATIONS_ENUM.CREATE_TABLE]:!0,[I.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[I.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[I.OPERATIONS_ENUM.DROP_TABLE]:!0,[I.OPERATIONS_ENUM.DROP_SCHEMA]:!0},B=ZL();async function _M(e,t){try{if(e.body.operation!=="read_log"&&(ut.log_level===I.LOG_LEVELS.INFO||ut.log_level===I.LOG_LEVELS.DEBUG||ut.log_level===I.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;ut.info(o)}}catch(s){ut.error(s)}let r=await R8.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return N8[e.body.operation]&&f8.setSchemaDataToGlobal(s=>{s&&ut.error(s)}),r}a(_M,"processLocalTransaction");var uM=y8();Pp.exports={chooseOperation:dM,getOperationFunction:EM,operation:fM,processLocalTransaction:_M};m8(Pp.exports);function dM(e){let t;try{t=EM(e)}catch(n){throw ut.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=Lp.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=Lp.checkASTPermissions(e,i);if(o)throw ut.error(`${eM.FORBIDDEN} from operation ${e.operation}`),ut.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),Lc(new Error,o,Mc.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==I.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==I.OPERATIONS_ENUM.LOGIN&&e.operation!==I.OPERATIONS_ENUM.LOGOUT){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=E8.verifyPerms(i,n);if(o)throw ut.error(`${eM.FORBIDDEN} from operation ${e.operation}`),ut.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),Lc(new Error,o,Mc.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw Lc(n,"There was an error when trying to choose an operation path")}return r}a(dM,"chooseOperation");function EM(e){if(ut.trace(`getOperationFunction with operation: ${e.operation}`),uM.has(e.operation))return uM.get(e.operation);throw Lc(new Error,Mc.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Mc.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(EM,"getOperationFunction");p8("operation",fM);function fM(e,t){e.hdb_user=this[S8]?.user,e.bypass_auth=!t;let r=dM(e);return _M({body:e},r)}a(fM,"operation");async function b8(e){ut.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[I.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case I.OPERATIONS_ENUM.INSERT:o=await wo.insert(i);break;case I.OPERATIONS_ENUM.UPDATE:o=await wo.update(i);break;case I.OPERATIONS_ENUM.UPSERT:o=await wo.upsert(i);break;case I.OPERATIONS_ENUM.DELETE:o=await Dc.deleteRecord(i);break;default:ut.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){ut.info("Invalid operation in transaction"),ut.error(o)}}a(b8,"catchup");async function ps(e){T8(e);let t,r;try{r=await Mp.addJob(e),t=r.createdJob,ut.info("addJob result",r);let s=new rM.RunnerMessage(t,e);return await rM.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw ut.error(n),Lc(s,n)}}a(ps,"executeJob");function y8(){let e=new Map;return e.set(I.OPERATIONS_ENUM.INSERT,new B(wo.insert)),e.set(I.OPERATIONS_ENUM.UPDATE,new B(wo.update)),e.set(I.OPERATIONS_ENUM.UPSERT,new B(wo.upsert)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new B(_d.searchByConditions)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_HASH,new B(cM)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_ID,new B(cM)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_VALUE,new B(g8)),e.set(I.OPERATIONS_ENUM.SEARCH,new B(A8)),e.set(I.OPERATIONS_ENUM.SQL,new B(O8)),e.set(I.OPERATIONS_ENUM.CSV_DATA_LOAD,new B(ps,cd.csvDataLoad)),e.set(I.OPERATIONS_ENUM.CSV_FILE_LOAD,new B(ps,cd.csvFileLoad)),e.set(I.OPERATIONS_ENUM.CSV_URL_LOAD,new B(ps,cd.csvURLLoad)),e.set(I.OPERATIONS_ENUM.IMPORT_FROM_S3,new B(ps,cd.importFromS3)),e.set(I.OPERATIONS_ENUM.CREATE_SCHEMA,new B(Zs.createSchema)),e.set(I.OPERATIONS_ENUM.CREATE_DATABASE,new B(Zs.createSchema)),e.set(I.OPERATIONS_ENUM.CREATE_TABLE,new B(Zs.createTable)),e.set(I.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new B(Zs.createAttribute)),e.set(I.OPERATIONS_ENUM.DROP_SCHEMA,new B(Zs.dropSchema)),e.set(I.OPERATIONS_ENUM.DROP_DATABASE,new B(Zs.dropSchema)),e.set(I.OPERATIONS_ENUM.DROP_TABLE,new B(Zs.dropTable)),e.set(I.OPERATIONS_ENUM.DROP_ATTRIBUTE,new B(Zs.dropAttribute)),e.set(I.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new B(ud.describeSchema)),e.set(I.OPERATIONS_ENUM.DESCRIBE_DATABASE,new B(ud.describeSchema)),e.set(I.OPERATIONS_ENUM.DESCRIBE_TABLE,new B(ud.describeTable)),e.set(I.OPERATIONS_ENUM.DESCRIBE_ALL,new B(ud.describeAll)),e.set(I.OPERATIONS_ENUM.DELETE,new B(Dc.deleteRecord)),e.set(I.OPERATIONS_ENUM.ADD_USER,new B(Uc.addUser)),e.set(I.OPERATIONS_ENUM.ALTER_USER,new B(Uc.alterUser)),e.set(I.OPERATIONS_ENUM.DROP_USER,new B(Uc.dropUser)),e.set(I.OPERATIONS_ENUM.LIST_USERS,new B(Uc.listUsersExternal)),e.set(I.OPERATIONS_ENUM.LIST_ROLES,new B(ld.listRoles)),e.set(I.OPERATIONS_ENUM.ADD_ROLE,new B(ld.addRole)),e.set(I.OPERATIONS_ENUM.ALTER_ROLE,new B(ld.alterRole)),e.set(I.OPERATIONS_ENUM.DROP_ROLE,new B(ld.dropRole)),e.set(I.OPERATIONS_ENUM.USER_INFO,new B(Uc.userInfo)),e.set(I.OPERATIONS_ENUM.READ_LOG,new B(i8)),e.set(I.OPERATIONS_ENUM.ADD_NODE,new B(o8)),e.set(I.OPERATIONS_ENUM.UPDATE_NODE,new B(a8)),e.set(I.OPERATIONS_ENUM.REMOVE_NODE,new B(c8)),e.set(I.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new B(u8)),e.set(I.OPERATIONS_ENUM.PURGE_STREAM,new B(l8)),e.set(I.OPERATIONS_ENUM.SET_CONFIGURATION,new B(iM.setConfiguration)),e.set(I.OPERATIONS_ENUM.CLUSTER_STATUS,new B(_8.clusterStatus)),e.set(I.OPERATIONS_ENUM.CLUSTER_NETWORK,new B(d8)),e.set(I.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new B(Up.setRoutes)),e.set(I.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new B(Up.getRoutes)),e.set(I.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new B(Up.deleteRoutes)),e.set(I.OPERATIONS_ENUM.EXPORT_TO_S3,new B(ps,jL.export_to_s3)),e.set(I.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new B(ps,Dc.deleteFilesBefore)),e.set(I.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new B(ps,Dc.deleteFilesBefore)),e.set(I.OPERATIONS_ENUM.EXPORT_LOCAL,new B(ps,jL.export_local)),e.set(I.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new B(Mp.handleGetJobsByStartDate)),e.set(I.OPERATIONS_ENUM.GET_JOB,new B(Mp.handleGetJob)),e.set(I.OPERATIONS_ENUM.GET_FINGERPRINT,new B(Dp.getFingerprint)),e.set(I.OPERATIONS_ENUM.SET_LICENSE,new B(Dp.setLicense)),e.set(I.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new B(Dp.getRegistrationInfo)),e.set(I.OPERATIONS_ENUM.RESTART,new B(tM.restart)),e.set(I.OPERATIONS_ENUM.RESTART_SERVICE,new B(tM.restartService)),e.set(I.OPERATIONS_ENUM.CATCHUP,new B(b8)),e.set(I.OPERATIONS_ENUM.SYSTEM_INFORMATION,new B(h8.systemInformation)),e.set(I.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new B(ps,Dc.deleteAuditLogsBefore)),e.set(I.OPERATIONS_ENUM.READ_AUDIT_LOG,new B(n8)),e.set(I.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new B(sM.createTokens)),e.set(I.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new B(sM.refreshOperationToken)),e.set(I.OPERATIONS_ENUM.LOGIN,new B(nM.login)),e.set(I.OPERATIONS_ENUM.LOGOUT,new B(nM.logout)),e.set(I.OPERATIONS_ENUM.GET_CONFIGURATION,new B(iM.getConfiguration)),e.set(I.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new B(Nt.customFunctionsStatus)),e.set(I.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new B(Nt.getCustomFunctions)),e.set(I.OPERATIONS_ENUM.GET_COMPONENT_FILE,new B(Nt.getComponentFile)),e.set(I.OPERATIONS_ENUM.GET_COMPONENTS,new B(Nt.getComponents)),e.set(I.OPERATIONS_ENUM.SET_COMPONENT_FILE,new B(Nt.setComponentFile)),e.set(I.OPERATIONS_ENUM.DROP_COMPONENT,new B(Nt.dropComponent)),e.set(I.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new B(Nt.getCustomFunction)),e.set(I.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new B(Nt.setCustomFunction)),e.set(I.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new B(Nt.dropCustomFunction)),e.set(I.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new B(Nt.addComponent)),e.set(I.OPERATIONS_ENUM.ADD_COMPONENT,new B(Nt.addComponent)),e.set(I.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new B(Nt.dropCustomFunctionProject)),e.set(I.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new B(Nt.packageComponent)),e.set(I.OPERATIONS_ENUM.PACKAGE_COMPONENT,new B(Nt.packageComponent)),e.set(I.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new B(Nt.deployComponent)),e.set(I.OPERATIONS_ENUM.DEPLOY_COMPONENT,new B(Nt.deployComponent)),e.set(I.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new B(oM.readTransactionLog)),e.set(I.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new B(ps,oM.deleteTransactionLogsBefore)),e.set(I.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new B(aM.installModules)),e.set(I.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new B(aM.auditModules)),e.set(I.OPERATIONS_ENUM.GET_BACKUP,new B(Zs.getBackup)),e}a(y8,"initializeOperationFunctionMap")});var Ed=m((Tle,pM)=>{"use strict";var vp=A(),I8=V(),Pc=x(),{handleHDBError:Bp,hdb_errors:dd}=W(),{isMainThread:w8}=require("worker_threads"),{Readable:C8}=require("stream"),mM=require("os"),U8=require("util"),D8=Am(),L8=U8.promisify(D8.authorize),SM=hM(),{Gzip:M8}=require("zlib");function P8(e){let t=`Found an uncaught exception with message: ${e.message}. ${mM.EOL}Stack: ${e.stack} ${mM.EOL}Terminating ${w8?"HDB":"thread"}.`;console.error(t),Pc.fatal(t),process.exit(1)}a(P8,"handleServerUncaughtException");function v8(e,t,r){if(Pc[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:dd.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(v8,"serverErrorHandler");function B8(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=Bp(new Error,"Invalid JSON.",dd.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(I8.isEmpty(e.body.operation)){let s=Bp(new Error,"Request body must include an 'operation' property.",dd.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(B8,"reqBodyValidationHandler");function H8(e,t,r){let s;e.body.operation!==vp.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==vp.OPERATIONS_ENUM.LOGIN&&e.body.operation!==vp.OPERATIONS_ENUM.LOGOUT?L8(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{Pc.warn(n),Pc.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(Bp(n,i,dd.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}a(H8,"authHandler");async function F8(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=SM.chooseOperation(e.body);let n=await SM.processLocalTransaction(e,s);if(n instanceof C8&&n.headers){for(let[i,o]of n.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),n=n.pipe(new M8))}return n}catch(n){throw Pc.error(n),n}}a(F8,"handlePostRequest");pM.exports={authHandler:H8,handlePostRequest:F8,handleServerUncaughtException:P8,serverErrorHandler:v8,reqBodyValidationHandler:B8}});var AM=m((gle,gM)=>{"use strict";var q8=require("fastify-plugin"),{handlePostRequest:TM,authHandler:G8,reqBodyValidationHandler:x8}=Ed();async function k8(e){e.decorate("hdbCore",{preValidation:[x8,G8],request:t=>RM(TM(t,response)),requestWithoutAuthentication:(t,r)=>RM(TM(t,r,!0))})}a(k8,"hdbCore");async function RM(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}a(RM,"convertAsyncIterators");gM.exports=q8(k8)});var NM=m((Ole,OM)=>{"use strict";var Hp=require("fs"),Co=Q();Co.initSync();var{CONFIG_PARAMS:vc}=A(),V8=1024*1024*1024;function $8(e){let t=Co.get(vc.CUSTOMFUNCTIONS_NETWORK_TIMEOUT),r=Co.get(vc.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT),s={bodyLimit:V8,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0};if(e){let n=Co.get(vc.CUSTOMFUNCTIONS_TLS_PRIVATEKEY),i=Co.get(vc.CUSTOMFUNCTIONS_TLS_CERTIFICATE),o=Co.get(vc.OPERATIONSAPI_TLS_CERT_AUTH);s.https={allowHTTP1:!0,key:Hp.readFileSync(`${n}`),cert:Hp.readFileSync(i)+(o?`
|
|
21
21
|
|
|
22
|
-
`+Pp.readFileSync(a):"")},s.http2=!0}return s}o(q8,"getServerOptions");TM.exports=q8});var OM=m((hle,AM)=>{"use strict";var vp=Q();vp.initSync();var{CONFIG_PARAMS:gM}=g();function G8(){let e=vp.get(gM.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=vp.get(gM.CUSTOMFUNCTIONS_NETWORK_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}o(G8,"getCORSOptions");AM.exports=G8});var yM=m((Sle,bM)=>{"use strict";var NM=Q();NM.initSync();var x8=g();function k8(){return NM.get(x8.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}o(k8,"getHeaderTimeoutConfig");bM.exports=k8});var Fp={};Ze(Fp,{customFunctionsServer:()=>Y8,handleFile:()=>$8,ready:()=>Q8});async function $8(e,t,r,s){if(!Xs){let c=Bp.get(Hp.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS);Xs=qM(c),ht.http((await Xs).server)}let n=await Xs,i=(0,wM.dirname)(r),a=t.replace(/\/routes\/.*/g,"");a.startsWith("/")&&(a=a.slice(1)),IM.has(i)||(IM.add(i),n.register(W8(i,a)))}async function Y8(){try{Ue.info("In Custom Functions Fastify server"+process.cwd()),Ue.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ue.debug(`Custom Functions server process ${process.pid} starting up.`),await K8();let e=Bp.get(Hp.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=e&&(e===!0||e.toUpperCase()===TRUE_COMPARE_VAL),r;try{r=Xs=await qM(t)}catch(s){throw Ue.error(`Custom Functions buildServer error: ${s}`),s}try{await r.ready()}catch(s){throw Ue.error(`Custom Functions server.ready() error: ${s}`),s}r.server.cantCleanupProperly=!0}catch(e){Ue.error(`Custom Functions ${process.pid} Error: ${e}`),Ue.error(e),process.exit(1)}}async function K8(){try{Ue.info("Custom Functions starting configuration."),await PM.setUsersToGlobal(),Ue.info("Custom Functions completed configuration.")}catch(e){Ue.error(e)}}function W8(e,t){return async function(r){try{Ue.info("Custom Functions starting buildRoutes"),Ue.trace("Loading fastify routes folder "+e),(0,CM.existsSync)(e)&&r.register(MM.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ue.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,a)=>{n?.message?Ue.error(n.message):n&&Ue.error(n),a()})}catch(s){Ue.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function qM(e){Ue.info("Custom Functions starting buildServer.");let t=(0,vM.default)(e),r=(0,UM.default)(t);r.server.headersTimeout=(0,HM.default)(),r.setErrorHandler(FM.serverErrorHandler);let s=(0,BM.default)();return s&&r.register(DM.default,s),r.register(function(n,i,a){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),a()}),r.register(LM.default),await r.register(V8),await r.after(),zS(r),Ue.info("Custom Functions completed buildServer."),r}function Q8(){if(Xs)return Xs.then?Xs.then(e=>e.ready()):Xs.ready()}var wM,CM,UM,DM,LM,MM,Bp,Hp,Ue,V8,PM,vM,BM,HM,FM,Xs,IM,GM=pe(()=>{wM=require("path"),CM=require("fs"),UM=D(require("fastify")),DM=D(require("@fastify/cors")),LM=D(ap()),MM=D(require("@fastify/autoload")),Bp=D(Q()),Hp=D(g()),Ue=D(q()),V8=D(pM()),PM=D(Or()),vM=D(RM()),BM=D(OM()),HM=D(yM()),FM=D(ld());fa();on();IM=new Set;o($8,"handleFile");o(Y8,"customFunctionsServer");o(K8,"setUp");o(W8,"buildRouteFolder");o(qM,"buildServer");o(Q8,"ready")});var qp={};Ze(qp,{start:()=>z8});function z8(e){let t=e.root;return{handleFile(r,s,n){kM||(kM=!0,e.server.http(async(i,a)=>{if(!i.isWebSocket){let c=xM.get(i.pathname);if(c)return{handlesHeaders:!0,body:(0,VM.default)(i,c)}}return a(i)},{runFirst:!0})),t&&(s.startsWith("/"+t)?s=s.slice(t.length+1):s.startsWith(t)&&(s=s.slice(t.length))),xM.set(s,n)}}}var VM,xM,kM,$M=pe(()=>{VM=D(require("send")),xM=new Map;o(z8,"start")});function Z8(e,t=1,r){if(Gp++,(0,Ti.startWorker)("server/threads/threadServer.js",{name:Ed.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((a,c)=>{function u(l){l.type===Ed.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),a(s))}o(u,"onMessage"),s.on("message",u),s.on("error",c)});X8.push(n),await n,Ia.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",a=>{if(a.requestId){let c=dd.get(a.requestId);c&&c(a)}}),s.on("exit",i),s.on("shutdown",i);function i(){let a=Ia.indexOf(s);a>-1&&Ia.splice(a,1)}if(o(i,"removeWorker"),wa){let a=wa;wa=[];for(let c of a)zM[c.localPort](c)}}}),r){let s=setInterval(()=>{xp?xp=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Ti.shutdownWorkers)(),Gp=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function JM(e=0,t){if(typeof e=="string")try{(0,fd.existsSync)(e)&&(0,fd.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=j8:r=e6(t):r=kp;let s=(0,WM.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData},zM[e]=i=>{xp=!0,r(i,(a,c)=>{if(!a){YM?(YM.deliverSocket(i,e,c),i.resume()):Gp>0?(wa.length===0&&setTimeout(()=>{wa.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),wa.push(i)):(console.log("start up a dynamic thread to handle request"),Z8(0));return}a.requests++,i._handle.fd>=0?a.postMessage({port:e,fd:i._handle.fd,data:c}):n6(i,a,e)})}).listen(e);s.on("error",i=>{console.error("Error in socket server",i)}),process.env._UNREF_SERVER&&s.unref();let n=$o();return QM.info(`HarperDB ${n.version} Server running on port ${e}`),s}function kp(e,t){let r,s=0;for(let n of Ia){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=_d)return _d=i,t(r);s=i}_d=0,t(r)}function j8(e,t){let r=e.remoteAddress,s=Ca.get(r),n=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=n,t(s.worker);kp(e,i=>{Ca.set(r,{worker:i,lastUsed:n}),t(i)})}function e6(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){s.on("data",i=>{s._handle.readStop();let c=i.toString("latin1").match(t)?.[1],u=Ca.get(c),l=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=l,n(u.worker);kp(s,_=>{Ca.set(c,{worker:_,lastUsed:l}),n(_,i)})})}o(r,"findByHeaderAffinity")}function r6(){_d=0;for(let e of Ia)e.expectedIdle=e.recentELU.idle+t6,e.requests=1;Ia.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function n6(e,t,r){let s=s6++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),dd.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),dd.delete(s)),n.event=="destroy"&&(e.destroy(),dd.delete(s))})}var Ti,WM,Ed,QM,fd,J8,Ia,wa,zM,YM,Gp,X8,xp,_d,KM,Ca,t6,dd,s6,XM=pe(()=>{Ti=D(_t()),WM=require("net"),Ed=D(g()),QM=D(q()),fd=require("fs"),{isMainThread:J8}=require("worker_threads"),Ia=[],wa=[],zM=[],Gp=0,X8=[];J8&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&console.error("uncaughtException",e)});o(Z8,"startHTTPWorker");o(JM,"startSocketServer");_d=0;o(kp,"findMostIdleWorker");KM=36e5,Ca=new Map;o(j8,"findByRemoteAddressAffinity");o(e6,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ca)r.lastUsed+KM<e&&Ca.delete(t)},KM).unref();t6=1e3;o(r6,"updateWorkerIdleness");(0,Ti.setMonitorListener)(r6);dd=new Map,s6=1;o(n6,"proxySocket")});var rP=m((wle,tP)=>{"use strict";var i6=require("cluster"),Wr=Q();Wr.initSync();var jM=g(),ble=require("util"),Zs=q(),Vp=require("fs"),a6=require("fastify"),yle=$o(),o6=require("@fastify/cors"),c6=require("@fastify/compress"),u6=require("@fastify/static"),l6=ap(),_6=require("path"),{PACKAGE_ROOT:d6}=g(),E6=ln(),f6=x(),h6=Or(),m6=go(),{server:S6}=(on(),re(wE)),{authHandler:p6,handlePostRequest:T6,serverErrorHandler:R6,reqBodyValidationHandler:g6}=ld(),Ile=require("net"),{registerContentHandlers:A6}=(fa(),re(HD)),O6=1024*1024*1024,eP="TRUE",{HDB_SETTINGS_NAMES:gi,CONFIG_PARAMS:N6}=jM,b6=gi.CORS_ENABLED_KEY,y6="CORS_ACCESSLIST",I6=gi.SERVER_TIMEOUT_KEY,w6=gi.SERVER_KEEP_ALIVE_TIMEOUT_KEY,C6=gi.SERVER_HEADERS_TIMEOUT_KEY,U6=gi.PRIVATE_KEY_KEY,D6=gi.CERT_KEY,L6=gi.HTTP_SECURE_ENABLED_KEY,Ri;tP.exports={hdbServer:ZM,start:ZM};async function ZM(e){try{Zs.info("In Fastify server"+process.cwd()),Zs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Zs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=i6.isMaster,await M6();let t=Wr.get(L6),r=t&&(t===!0||t.toUpperCase()===eP);Ri=P6(r),await Ri.ready(),e||(e={}),e.isOperationsServer=!0,Ri.server.cantCleanupProperly=!0;try{S6.http(Ri.server,e),Ri.server.closeIdleConnections||await Ri.listen({port:0,host:"::"})}catch(s){throw Ri.close(),Zs.error(s),Zs.error(`Error configuring ${server_type} server`),s}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Zs.fatal(t),process.exit(1)}}o(ZM,"operationsServer");async function M6(){Zs.trace("Configuring HarperDB process."),E6.setSchemaDataToGlobal(),await h6.setUsersToGlobal(),await m6.getLicense()}o(M6,"setUp");function P6(e){Zs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=v6(e),r=a6(t);r.server.headersTimeout=H6(),r.setErrorHandler(R6);let s=B6();s&&r.register(o6,s),r.register(function(i,a,c){i.setNotFoundHandler(function(u,l){r.server.emit("unhandled",u.raw,l.raw)}),c()}),r.register(l6),r.register(c6),r.register(u6,{root:_6.join(d6,"docs")}),A6(r);let n=Wr.get(jM.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,a){return!f6.isEmpty(n)&&n.toString().toLowerCase()==="true"?a.sendFile("index.html"):a.callNotFound()}),r.post("/",{preValidation:[g6,p6],config:{isOperation:!0}},async function(i,a){return i.body?.operation?.startsWith("restart")&&a.header("Connection","close"),T6(i,a)}),r.get("/health",()=>"HarperDB is running."),Zs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}o(P6,"buildServer");function v6(e){let t=Wr.get(I6),r=Wr.get(w6),s={bodyLimit:O6,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1};if(e){let n=Wr.get(U6),i=Wr.get(D6),a=Wr.get(N6.OPERATIONSAPI_TLS_CERT_AUTH),c={allowHTTP1:!0,key:Vp.readFileSync(n),cert:Vp.readFileSync(i)+(a?`
|
|
22
|
+
`+Hp.readFileSync(o):"")},s.http2=!0}return s}a($8,"getServerOptions");OM.exports=$8});var IM=m((ble,yM)=>{"use strict";var Fp=Q();Fp.initSync();var{CONFIG_PARAMS:bM}=A();function Y8(){let e=Fp.get(bM.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=Fp.get(bM.CUSTOMFUNCTIONS_NETWORK_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(Y8,"getCORSOptions");yM.exports=Y8});var UM=m((Ile,CM)=>{"use strict";var wM=Q();wM.initSync();var K8=A();function W8(){return wM.get(K8.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}a(W8,"getHeaderTimeoutConfig");CM.exports=W8});var xp={};je(xp,{customFunctionsServer:()=>J8,handleFile:()=>z8,ready:()=>j8});async function z8(e,t,r,s){if(!js){let c=qp.get(Gp.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS);js=VM(c),tt.http((await js).server)}let n=await js,i=(0,LM.dirname)(r),o=t.replace(/\/routes\/.*/g,"");o.startsWith("/")&&(o=o.slice(1)),DM.has(i)||(DM.add(i),n.register(Z8(i,o)))}async function J8(){try{Ue.info("In Custom Functions Fastify server"+process.cwd()),Ue.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ue.debug(`Custom Functions server process ${process.pid} starting up.`),await X8();let e=qp.get(Gp.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=e&&(e===!0||e.toUpperCase()===TRUE_COMPARE_VAL),r;try{r=js=await VM(t)}catch(s){throw Ue.error(`Custom Functions buildServer error: ${s}`),s}try{await r.ready()}catch(s){throw Ue.error(`Custom Functions server.ready() error: ${s}`),s}r.server.cantCleanupProperly=!0}catch(e){Ue.error(`Custom Functions ${process.pid} Error: ${e}`),Ue.error(e),process.exit(1)}}async function X8(){try{Ue.info("Custom Functions starting configuration."),await FM.setUsersToGlobal(),Ue.info("Custom Functions completed configuration.")}catch(e){Ue.error(e)}}function Z8(e,t){return async function(r){try{Ue.info("Custom Functions starting buildRoutes"),Ue.trace("Loading fastify routes folder "+e),(0,MM.existsSync)(e)&&r.register(HM.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ue.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?Ue.error(n.message):n&&Ue.error(n),o()})}catch(s){Ue.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function VM(e){Ue.info("Custom Functions starting buildServer.");let t=(0,qM.default)(e),r=(0,PM.default)(t);r.server.headersTimeout=(0,xM.default)(),r.setErrorHandler(kM.serverErrorHandler);let s=(0,GM.default)();return s&&r.register(vM.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(BM.default),await r.register(Q8),await r.after(),jS(r),Ue.info("Custom Functions completed buildServer."),r}function j8(){if(js)return js.then?js.then(e=>e.ready()):js.ready()}var LM,MM,PM,vM,BM,HM,qp,Gp,Ue,Q8,FM,qM,GM,xM,kM,js,DM,$M=Se(()=>{LM=require("path"),MM=require("fs"),PM=C(require("fastify")),vM=C(require("@fastify/cors")),BM=C(up()),HM=C(require("@fastify/autoload")),qp=C(Q()),Gp=C(A()),Ue=C(x()),Q8=C(AM()),FM=C(br()),qM=C(NM()),GM=C(IM()),xM=C(UM()),kM=C(Ed());So();es();DM=new Set;a(z8,"handleFile");a(J8,"customFunctionsServer");a(X8,"setUp");a(Z8,"buildRouteFolder");a(VM,"buildServer");a(j8,"ready")});var kp={};je(kp,{start:()=>e6});function e6(e){let t=e.root;return{handleFile(r,s,n){KM||(KM=!0,e.server.http(async(i,o)=>{if(!i.isWebSocket){let c=YM.get(i.pathname);if(c)return{handlesHeaders:!0,body:(0,WM.default)(i,c)}}return o(i)},{runFirst:!0})),t&&(s.startsWith("/"+t)?s=s.slice(t.length+1):s.startsWith(t)&&(s=s.slice(t.length))),YM.set(s,n)}}}var WM,YM,KM,QM=Se(()=>{WM=C(require("send")),YM=new Map;a(e6,"start")});function s6(e,t=1,r){if(Vp++,(0,Ri.startWorker)("server/threads/threadServer.js",{name:md.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(l){l.type===md.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});r6.push(n),await n,Uo.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=hd.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=Uo.indexOf(s);o>-1&&Uo.splice(o,1)}if(a(i,"removeWorker"),Do){let o=Do;Do=[];for(let c of o)ZM[c.localPort](c)}}}),r){let s=setInterval(()=>{$p?$p=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Ri.shutdownWorkers)(),Vp=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function jM(e=0,t){if(typeof e=="string")try{(0,pd.existsSync)(e)&&(0,pd.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=n6:r=i6(t):r=Yp;let s=(0,XM.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData},ZM[e]=i=>{$p=!0,r(i,(o,c)=>{if(!o){zM?(zM.deliverSocket(i,e,c),i.resume()):Vp>0?(Do.length===0&&setTimeout(()=>{Do.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),Do.push(i)):(console.log("start up a dynamic thread to handle request"),s6(0));return}o.requests++;let u=i._handle.fd;Sd.trace("Socket",u,"from",i.remoteAddress," routed to worker",o.threadId),u>=0?o.postMessage({port:e,fd:u,data:c}):u6(i,o,e)})}).listen(e);s.on("error",i=>{console.error("Error in socket server",i)}),process.env._UNREF_SERVER&&s.unref();let n=Ka();return Sd.info(`HarperDB ${n.version} Server running on port ${e}`),s}function Yp(e,t){let r,s=0;for(let n of Uo){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=fd)return fd=i,t(r);s=i}fd=0,t(r)}function n6(e,t){let r=e.remoteAddress,s=Lo.get(r),n=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=n,t(s.worker);Yp(e,i=>{Lo.set(r,{worker:i,lastUsed:n}),t(i)})}function i6(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){s.on("data",i=>{s._handle.readStop();let c=i.toString("latin1").match(t)?.[1],u=Lo.get(c),l=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=l,n(u.worker);Yp(s,_=>{Lo.set(c,{worker:_,lastUsed:l}),n(_,i)})})}a(r,"findByHeaderAffinity")}function a6(){fd=0;for(let e of Uo)e.expectedIdle=e.recentELU.idle+o6,e.requests=1;Uo.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function u6(e,t,r){let s=c6++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),hd.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),hd.delete(s)),n.event=="destroy"&&(e.destroy(),hd.delete(s))})}var Ri,XM,md,Sd,pd,t6,Uo,Do,ZM,zM,Vp,r6,$p,fd,JM,Lo,o6,hd,c6,eP=Se(()=>{Ri=C(dt()),XM=require("net"),md=C(A()),Sd=C(x()),pd=require("fs"),{isMainThread:t6}=require("worker_threads"),Uo=[],Do=[],ZM=[],Vp=0,r6=[];t6&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&console.error("uncaughtException",e)});a(s6,"startHTTPWorker");a(jM,"startSocketServer");fd=0;a(Yp,"findMostIdleWorker");JM=36e5,Lo=new Map;a(n6,"findByRemoteAddressAffinity");a(i6,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Lo)r.lastUsed+JM<e&&Lo.delete(t)},JM).unref();o6=1e3;a(a6,"updateWorkerIdleness");(0,Ri.setMonitorListener)(a6);hd=new Map,c6=1;a(u6,"proxySocket")});var iP=m((Fle,nP)=>{"use strict";var l6=require("cluster"),Wr=Q();Wr.initSync();var rP=A(),vle=require("util"),en=x(),Kp=require("fs"),_6=require("fastify"),Ble=Ka(),d6=require("@fastify/cors"),E6=require("@fastify/compress"),f6=require("@fastify/static"),h6=up(),m6=require("path"),{PACKAGE_ROOT:S6}=A(),p6=_n(),T6=V(),R6=br(),g6=Oa(),{server:A6}=(es(),re(wu)),{authHandler:O6,handlePostRequest:N6,serverErrorHandler:b6,reqBodyValidationHandler:y6}=Ed(),Hle=require("net"),{registerContentHandlers:I6}=(So(),re(xD)),w6=1024*1024*1024,sP="TRUE",{HDB_SETTINGS_NAMES:Ai,CONFIG_PARAMS:C6}=rP,U6=Ai.CORS_ENABLED_KEY,D6="CORS_ACCESSLIST",L6=Ai.SERVER_TIMEOUT_KEY,M6=Ai.SERVER_KEEP_ALIVE_TIMEOUT_KEY,P6=Ai.SERVER_HEADERS_TIMEOUT_KEY,v6=Ai.PRIVATE_KEY_KEY,B6=Ai.CERT_KEY,H6=Ai.HTTP_SECURE_ENABLED_KEY,gi;nP.exports={hdbServer:tP,start:tP};async function tP(e){try{en.info("In Fastify server"+process.cwd()),en.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),en.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=l6.isMaster,await F6();let t=Wr.get(H6),r=t&&(t===!0||t.toUpperCase()===sP);gi=q6(r),await gi.ready(),e||(e={}),e.isOperationsServer=!0,gi.server.cantCleanupProperly=!0;try{A6.http(gi.server,e),gi.server.closeIdleConnections||await gi.listen({port:0,host:"::"})}catch(s){throw gi.close(),en.error(s),en.error(`Error configuring ${server_type} server`),s}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),en.fatal(t),process.exit(1)}}a(tP,"operationsServer");async function F6(){en.trace("Configuring HarperDB process."),p6.setSchemaDataToGlobal(),await R6.setUsersToGlobal(),await g6.getLicense()}a(F6,"setUp");function q6(e){en.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=G6(e),r=_6(t);r.server.headersTimeout=k6(),r.setErrorHandler(b6);let s=x6();s&&r.register(d6,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,l){r.server.emit("unhandled",u.raw,l.raw)}),c()}),r.register(h6),r.register(E6),r.register(f6,{root:m6.join(S6,"docs")}),I6(r);let n=Wr.get(rP.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!T6.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.callNotFound()}),r.post("/",{preValidation:[y6,O6],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),N6(i,o)}),r.get("/health",()=>"HarperDB is running."),en.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(q6,"buildServer");function G6(e){let t=Wr.get(L6),r=Wr.get(M6),s={bodyLimit:w6,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1};if(e){let n=Wr.get(v6),i=Wr.get(B6),o=Wr.get(C6.OPERATIONSAPI_TLS_CERT_AUTH),c={allowHTTP1:!0,key:Kp.readFileSync(n),cert:Kp.readFileSync(i)+(o?`
|
|
23
23
|
|
|
24
|
-
`+Vp.readFileSync(a):"")};s.http2=!0,s.https=c}return s}o(v6,"getServerOptions");function B6(){let e=Wr.get(b6),t=Wr.get(y6),r;return e&&(e===!0||e.toUpperCase()===eP)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}o(B6,"getCORSOpts");function H6(){return Wr.get(C6)}o(H6,"getHeaderTimeoutConfig")});var zp={};Ze(zp,{disableNATS:()=>q6,setNATSReplicator:()=>$p,start:()=>F6});function F6(){md.default.get(Sd.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&x6()}function q6(e=!0){oP=e}function x6(){if(oP)return;let e=Gr(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];$p(n,r,i)}}Jp((r,s)=>{$p(r.tableName,r.databaseName,r),s&&uP(r)}),!sP&&(sP=!0)}function $p(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.Source?.isNATSReplicator)return;let s;r.sourcedFrom(class extends ft{static{o(this,"NATSReplicator")}put(a){let c;return s?.put&&(!s.put.reliesOnPrototype||s.prototype.put)&&(c=s.put(this[ie],a,this.getContext())),n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[ie],record:a},c)}delete(){let a;return s?.delete&&(!s.delete.reliesOnPrototype||s.prototype.delete)&&(a=s.delete(this[ie],this.getContext())),n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[ie]},a)}publish(a){let c;return s?.publish&&(!s.publish.reliesOnPrototype||s.prototype.publish)&&(c=s.publish(this[ie],a,this.getContext())),n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[ie],record:a},c)}invalidate(a){if(n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[ie]}),s?.invalidate&&(!s.invalidate.reliesOnPrototype||s.prototype.invalidate))return s.invalidate(this[ie],this.getContext())}static defineSchema(a){uP(a)}static mergeSource(a,c){return s=a,s?.get&&(!s.get.reliesOnPrototype||s.prototype.get)&&(c.replicationSource?this.get=async(u,l)=>{let _=await s.get(u,l);return _&&n(l).addWrite(t,{operation:"put",table:e,id:u,record:_}),_}:this.get=(u,l)=>s.get(u,l)),this}static subscribe(){let a=new Jr;return(0,nP.setSubscription)(t,e,a),a}static subscribeOnThisThread(a){return a<G6}static isNATSReplicator=!0});function n(i){let a=i?.transaction?.nats;return a||(i?.transaction?(i.transaction.push(a=i.transaction.nats=new hd(i.transaction,i)),a.user=i.user):a=cP),a}o(n,"getNATSTransaction")}function uP(e){let t=md.default.get(Sd.default.CONFIG_PARAMS.CLUSTERING_NODENAME);(0,Kp.publishToStream)(`${Wp.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,Qp.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var Kp,Wp,Qp,nP,iP,md,Sd,aP,oP,G6,cP,sP,hd,Yp,lP=pe(()=>{de();Xr();Kp=D(rt()),Wp=D(Be()),Qp=D(Ls());to();nP=D(Xp()),iP=D(vt()),md=D(Q()),Sd=D(g()),aP=D(q());o(F6,"start");o(q6,"disableNATS");G6=2;o(x6,"assignReplicationSource");o($p,"setNATSReplicator");o(uP,"publishSchema");hd=class{constructor(t,r){this.transaction=t;this.options=r}static{o(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r,s){let n=this.writes_by_db.get(t);if(n||this.writes_by_db.set(t,n=[]),s?.then)return s.then(()=>n.push(r));n.push(r)}commit(t){let r=md.default.get(Sd.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let a=[],c=[],u,l;for(let _ of i){let d=_.table,E=_.operation=="put"?"upsert":_.operation;u||(aP.trace(`Sending transaction event ${E}`),l=u={operation:E,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&(u.records=a)),u.table===d&&u.operation===E?(a.push(_.record),c.push(_.id)):l=l.next={operation:E,table:d,id:_.id,record:_.record}}s.push((0,Kp.publishToStream)(`${Wp.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,Qp.createNatsTableStreamName)(n,u.table),void 0,u))}return Promise.all(s)}},Yp=class extends hd{static{o(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,iP.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit()}};cP=new Yp});async function dP({clientId:e,user:t,listener:r,clean:s}){let n;if(e&&!s){let i=await Zp.getResource(e,{});n=new eT(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await Zp.get(e);i&&i.delete()}n=new Td(e,t)}return n}function jp(){return pd++,pd>65500&&(pd=1),pd}var _P,Pc,Zp,pd,Td,eT,EP=pe(()=>{de();uc();_P=D(vt()),Pc=D(q());Gn();Zp=et({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]});o(dP,"getSession");pd=1;o(jp,"getNextMessageId");Td=class{static{o(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,omitCurrent:i,startTime:a}=t,c=n.indexOf("?"),u,l;if(c>-1?(u=n.slice(c),l=n.slice(0,c)):l=n,!l)throw new Error("No topic provided");let _=!1,d;if((l.endsWith("+")||l.endsWith("#"))&&(_=!0,l.endsWith("+")&&(d=!0),l=l.slice(0,l.length-1)),l.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");if(l.indexOf("#")>-1||l.indexOf("+")>-1)throw new Error("Only trailing wildcards are supported");let E=this.subscriptions.find(O=>O.topic===n);E&&(E.end(),this.subscriptions.splice(this.subscriptions.indexOf(E),1));let f={search:u,user:this.user,startTime:a,omitCurrent:i,isCollection:_,shallowWildcard:d,url:""},h=yn.getMatch(l);if(!h)throw new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);f.url=h.relativeURL;let T=h.path,S=h.Resource,y=await Ye(f,async()=>{let O=await S.subscribe(f);if(!O)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!O[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let H of O)try{let Y;if(H.type&&H.type!=="put"&&H.type!=="delete"&&H.type!=="message"||s&&!s(H))continue;r?(H.topic=n,Y=this.needsAcknowledge(H)):Y=jp();let A=H.id;Array.isArray(A)&&(A=da(A)),A==null&&(A=""),this.listener(T+"/"+A,H.value,Y,t)}catch(Y){(0,Pc.warn)(Y)}})(),O});return y.topic=n,y.qos=t.qos,this.subscriptions.push(y),y}resume(){}needsAcknowledge(t){return jp()}acknowledge(t){}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);r&&r.end()}async publish(t,r){let{topic:s,retain:n}=t;t.data=r,t.user=this.user;let i=yn.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);t.url=i.relativeURL;let a=i.Resource;return Ye(t,()=>n?r===void 0?a.delete(t,t):a.put(t,t.data,t):a.publish(t,t.data,t))}setListener(t){this.listener=t}disconnect(){for(let t of this.subscriptions)t.end();this.subscriptions=[]}},eT=class extends Td{static{o(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=jp();return this.awaitingAcks.set(r,{topic:t.topic,timestamp:t.timestamp}),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t);let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Pc.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let a=i.startTime;return a||(a=i.startTime=(0,_P.getNextMonotonicTime)()),(0,Pc.trace)("Added durable subscription",i.topic,a),{qos:i.qos,topic:i.topic,startTime:a}}),Zp.put(this.sessionRecord)),t.qos}}});var sT={};Ze(sT,{start:()=>V6});async function V6({server:e,port:t,webSocket:r,securePort:s,requireAuthentication:n}){let i=e.mqtt={requireAuthentication:n};r&&e.ws((a,c,u)=>{if(a.protocol==="mqtt"){let{onMessage:l,onClose:_}=mP(a,(d,E)=>{if(a.send(d),E&&a._socket.writableNeedDrain)return new Promise(f=>this._socket.once("drain",f))},c,Promise.resolve(u).then(()=>c?.user),i);a.on("message",l),a.on("close",_),a.on("error",d=>{(0,js.info)("WebSocket error",d)})}},{subProtocol:"mqtt"}),(t||s)&&e.socket(async a=>{let c;k6&&a.remoteAddress.includes("127.0.0.1")&&(c=await(0,SP.getSuperUser)());let{onMessage:u,onClose:l}=mP(a,_=>a.write(_),null,c,i);a.on("data",u),a.on("close",l),a.on("error",_=>{(0,js.info)("Socket error",_)})},{port:t,securePort:s})}function mP(e,t,r,s,n){hP||(hP=!0,ep(_=>{_.push({metric:"mqtt-connections",connections:tT})})),tT++;let i,a={protocolVersion:4},c=(0,Rd.parser)({protocolVersion:5});function u(_){c.parse(_)}o(u,"onMessage");function l(){tT--,i?.disconnect()}return o(l,"onClose"),c.on("packet",async _=>{s?.then&&(s=await s),i?.then&&await i;try{switch(_.cmd){case"connect":if(a.protocolVersion=_.protocolVersion,_.username)try{s=await ht.auth(_.username,_.password.toString()),(0,rT.get)(en.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&fP.notify({username:s.username,status:en.AUTH_AUDIT_STATUS.SUCCESS,type:en.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,rT.get)(en.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&fP.error({username:s.username,status:en.AUTH_AUDIT_STATUS.FAILURE,type:en.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),d({cmd:"connack",reasonCode:134,returnCode:134})}if(!s&&n.requireAuthentication)return d({cmd:"connack",reasonCode:134,returnCode:134});try{n.authorizeClient?.(_,s),i=dP({user:s,..._}),i=await i}catch(O){return(0,js.error)(O),d({cmd:"connack",reasonCode:O.code||128,returnCode:O.code||128})}d({cmd:"connack",sessionPresent:i.sessionWasPresent,reasonCode:0,returnCode:0}),i.setListener((O,H,Y,A)=>{try{let w=O.indexOf("/",1),G=w>0?O.slice(0,w):O;d({cmd:"publish",topic:O,payload:E(H),messageId:Y||Math.floor(Math.random()*1e8),qos:A.qos},G)}catch(w){(0,js.error)(w),i?.disconnect()}}),i.sessionWasPresent&&await i.resume();break;case"subscribe":let f=[];for(let O of _.subscriptions){let H;try{H=(await i.addSubscription(O,O.qos>=1)).qos||0}catch(Y){(0,js.error)(Y),H=128}f.push(H)}await i.committed,d({cmd:"suback",granted:f,messageId:_.messageId});break;case"unsubscribe":for(let O of _.unsubscriptions)i.removeSubscription(O);d({cmd:"unsuback",messageId:_.messageId});break;case"pubrel":d({cmd:"pubcomp",messageId:_.messageId,reasonCode:0});return;case"publish":let h=_.qos===2?"pubrec":"puback",T=e.deserialize||(e.deserialize=Ta(r?.headers["content-type"])),S=_.payload?.length>0?T(_.payload):void 0,y;try{y=await i.publish(_,S)}catch(O){console.warn(O),_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:128},_.topic)}_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:y===!1?144:0},_.topic);break;case"pubrec":d({cmd:"pubrel",messageId:_.messageId,reasonCode:0});break;case"pubcomp":case"puback":i.acknowledge(_.messageId);break;case"pingreq":d({cmd:"pingresp"});break;case"disconnect":i?.disconnect(),e.close?e.close():e.end();break}}catch(f){console.error(f),d({cmd:"disconnect"})}function d(f,h){let T=(0,Rd.generate)(f,a);t(T),fi(T.length,"bytes-sent",h,f.cmd,"mqtt")}o(d,"sendPacket");function E(f){return r?$s(f,r):JSON.stringify(f)}o(E,"serialize")}),{onMessage:u,onClose:l}}var Rd,SP,rT,en,js,fP,k6,hP,tT,pP=pe(()=>{Rd=require("mqtt-packet");EP();SP=D(Or());fa();Ra();on();rT=D(Q()),en=D(g()),js=D(q()),fP=(0,js.loggerWithTag)("auth-event"),k6=!0;o(V6,"start");tT=0;o(mP,"onSocket")});var wP={};Ze(wP,{loadComponent:()=>gd,loadComponentDirectories:()=>IP});function IP(e,t){t&&(iT=t),e&&(aT=e);let r=[];if((0,Ss.existsSync)(nT)){let n=(0,Ss.readdirSync)(nT,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let a=i.name,c=(0,Ur.join)(nT,a);r.push(gd(c,iT,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(gd(s,iT,s)),Promise.all(r).then(()=>{yP=!0})}async function gd(e,t,r,s,n){if(!RP.has(e)){RP.set(e,!0),n&&(aT=n);try{let i,a=(0,Ur.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Ss.existsSync)(a)?i=(0,gP.parseDocument)((0,Ss.readFileSync)(a,"utf8"),{simpleKeys:!0}).toJSON():i=W6;let c=[];for(let u in i){let l=i[u];if(!l)continue;let _,d=l.package;if(d){let E=e,f;for(;!(0,Ss.existsSync)(f=(0,Ur.join)(E,"node_modules",u));)if(E=(0,Ur.dirname)(E),E.length<(0,bP.getHdbBasePath)().length){f=null;break}if(f)_=await gd(f,t,r,!1);else throw new Error(`Unable to find package ${u}:${d}`)}else _=K6[u];if(_)try{c.push(_);let E=o(S=>(S.origin=r,et(S)),"ensureTable"),f=l.network||(l.port||l.securePort)&&l,h=f?.securePort||f?.https&&f.port,T=!f?.https&&f?.port;if(vc.isMainThread&&(_=await _.startOnMainThread?.({server:ht,ensureTable:E,port:T,securePort:h,resources:t,...l})||_,s&&f))for(let S of[T,h])try{if(+S&&!TP.includes(S)){TP.push(S);let y=oT.get(cT.CONFIG_PARAMS.HTTP_SESSION_AFFINITY);JM(S,y)}}catch(y){console.error("Error listening on socket",S,y,u)}if(t.isWorker&&(_=await _.start?.({server:ht,ensureTable:E,port:T,securePort:h,resources:t,...l})||_),aT.set(_,!0),_.handleFile&&l.files){if(l.files.includes(".."))throw(0,NP.handleHDBError)("Can not reference parent directories");let S=(0,Ur.join)(e,l.files);for(let y of await(0,AP.default)(S,{onlyFiles:!1,objectMode:!0})){let{path:O,dirent:H}=y,Y=(0,Ur.relative)(e,O),A=(0,Ur.basename)(e),w=l.path||"/";w=w.startsWith("/")?w:w.startsWith("./")?"/"+A+w.slice(2):w==="."?"/"+A:"/"+A+"/"+w,w+=(w.endsWith("/")?"":"/")+Y;try{if(H.isFile()){let G=await Y6(O);vc.isMainThread&&await _.setupFile?.(G,w,O,t),t.isWorker&&await _.handleFile?.(G,w,O,t)}else vc.isMainThread&&await _.setupDirectory?.(w,O,t),t.isWorker&&await _.handleDirectory?.(w,O,t)}catch(G){console.error(`Could not load ${H.isFile()?"file":"directory"} ${O} using ${l.module} for application ${e}`,G),t.set(l.path||"/",new Bc(G))}}}}catch(E){console.error(`Could not load component ${u} for application ${e}`,E),t.set(l.path||"/",new Bc(E),null,!0)}}if(vc.isMainThread&&!yP&&(0,OP.watchDir)(e,async()=>IP()),i.extensionModule)return await bu((0,Ur.join)(e,i.extensionModule))}catch(i){console.error(`Could not load application directory ${e}`,i),t.set("",new Bc(i))}}}var Ss,Ur,vc,gP,oT,cT,AP,OP,NP,bP,$6,Y6,nT,aT,yP,iT,K6,W6,TP,RP,Bc,CP=pe(()=>{Ss=require("fs"),Ur=require("path"),vc=require("worker_threads"),gP=require("yaml"),oT=D(Q()),cT=D(g());dg();mg();Sg();tL();GM();$M();AP=D(require("fast-glob")),OP=D(_t());LE();on();NP=D(W());Xr();de();XM();bP=D(Q()),$6=D(rP());S_();lP();pP();({readFile:Y6}=Ss.promises),nT=oT.get(cT.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),aT=new Map;o(IP,"loadComponentDirectories");K6={REST:ip,graphqlSchema:DE,jsResource:PE,fastifyRoutes:Fp,login:BE,static:qp,operationsApi:$6,customFunctions:{},clustering:zp,authentication:lc,mqtt:sT},W6={REST:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}},TP=[],RP=new Map;o(gd,"loadComponent");Bc=class extends ft{constructor(r){super();this.error=r}static{o(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var vP=m((r_e,PP)=>{"use strict";var Nd=require("fs-extra"),uT=require("path"),Ad=q(),UP=x(),Od=g(),MP=Q(),Q6=Ar();PP.exports=z6;async function z6(){let e=J6(),t=MP.get(Od.CONFIG_PARAMS.ROOTPATH),r=uT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+Od.PACKAGE_ROOT}},n=uT.join(t,"node_modules");await Nd.ensureDir(n);let i,a=!0,c=!1;try{i=await Nd.readJson(r)}catch(u){if(UP.isEmptyOrZeroLength(e))return;if(u.code!==Od.NODE_ERROR_CODES.ENOENT)throw u;a=!1}if(!UP.isEmptyOrZeroLength(e)){for(let{name:u,package:l}of e){let _=await DP(l);s.dependencies[u]=_+l}if(!a){Ad.notify("Installing components"),await LP(r,s);return}for(let{name:u,package:l}of e){let _=i.dependencies[u],d=await DP(l);if(_===void 0||_!==d+l){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(Ad.notify("Removing component",u),c=!0);c&&(Ad.notify("Updating components."),await LP(r,s))}o(z6,"installComponents");function J6(){let e=Q6.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}o(J6,"getComponentsConfig");async function DP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":uT.extname(e)||await Nd.pathExists(e)?"file:":"github:"}o(DP,"getPkgPrefix");async function LP(e,t){Ad.trace("npm installing components package.json",t),await Nd.writeFile(e,JSON.stringify(t,null," ")),await b_().installAllRootModules(MP.get(Od.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}o(LP,"installPackages")});var FP=m((n_e,HP)=>{var{isMainThread:BP}=require("worker_threads"),{getTables:X6}=(de(),re(Ne)),{loadComponentDirectories:Z6,loadComponent:j6}=(CP(),re(wP)),{resetResources:e9}=(uc(),re(mU)),t9=vP(),r9=Ar(),{dirname:s9}=require("path"),{getConnection:n9}=rt(),i9=Q(),a9=g(),lT=new Map;async function o9(e=!1){!BP&&i9.get(a9.CONFIG_PARAMS.CLUSTERING_ENABLED)&&n9(),BP&&await t9();let t=e9();X6(),t.isWorker=e,await j6(s9(r9.getConfigFilePath()),t,"hdb",!0,lT),await Z6(lT,t);let r=[];for(let[s]of lT)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}o(o9,"loadRootComponents");HP.exports.loadRootComponents=o9});var _t=m((o_e,Mn)=>{"use strict";var{Worker:c9,MessageChannel:u9,parentPort:ps,isMainThread:hT,threadId:l9,workerData:Hc}=require("worker_threads"),{PACKAGE_ROOT:_9}=g(),{join:xP,isAbsolute:d9,extname:yd}=require("path"),{server:E9}=(on(),re(wE)),{watch:f9,readdir:h9}=require("fs/promises"),{totalmem:qP}=require("os"),mT=g(),Ai=q(),a_e=g(),{randomBytes:m9}=require("crypto"),S9=1024*1024,Ln=[],Dn=[],p9=50,kP=1e4,T9="restart",VP="request_thread_info",$P="resource_report",YP="thread_info",KP="added-port",R9="ack",_T;Mn.exports={startWorker:dT,restartWorkers:ST,shutdownWorkers:N9,workers:Ln,setMonitorListener:L9,onMessageFromWorkers:b9,onMessageByType:y9,broadcast:I9,broadcastWithAcknowledgement:C9,setChildListenerByType:O9,getWorkerIndex:QP,getTicketKeys:zP,setMainIsWorker:g9,restartNumber:Hc?.restartNumber||1};var WP;function QP(){return Hc?Hc.workerIndex:WP?0:void 0}o(QP,"getWorkerIndex");function g9(e){WP=e}o(g9,"setMainIsWorker");var bd;function zP(){return bd||(bd=hT?m9(48):Hc.ticketKeys,bd)}o(zP,"getTicketKeys");Object.defineProperty(E9,"workerIndex",{get(){return QP()}});var JP={[VP](e,t){U9(t)},[$P](e,t){D9(t,e)}};function dT(e,t={}){let r=process.constrainedMemory?.()||qP();r=Math.min(r,qP());let s=Math.max(Math.floor(r/S9/(1+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>7,16),64),i=[];for(let c of Dn){let{port1:u,port2:l}=new u9;c.postMessage({type:KP,port:u},[u]),i.push(l)}yd(e)||(e+=".js");let a=new c9(d9(e)?e:xP(_9,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:i,workerIndex:t.workerIndex,name:t.name,restartNumber:Mn.exports.restartNumber,ticketKeys:zP()},transferList:i},t));return wd(a,!0),a.unexpectedRestarts=t.unexpectedRestarts||0,a.startCopy=()=>{dT(e,t)},a.on("error",c=>{console.error("Worker error:",c),Ai.error("Worker error:",c)}),a.on("exit",c=>{Ln.splice(Ln.indexOf(a),1),!a.wasShutdown&&t.autoRestart!==!1&&(a.unexpectedRestarts<p9?(t.unexpectedRestarts=a.unexpectedRestarts+1,dT(e,t)):Ai.error(`Thread has been restarted ${a.restarts} times and will not be restarted`))}),a.on("message",c=>{JP[c.type]?.(c,a)}),Ln.push(a),P9(),t.onStarted&&t.onStarted(a),a.name=t.name,a}o(dT,"startWorker");var A9=[mT.THREAD_TYPES.HTTP];async function ST(e=null,t=2,r=!0){if(hT){if(r){let{loadRootComponents:n}=FP();await n()}Mn.exports.restartNumber++,t<1&&(t=t*Ln.length);let s=[];for(let n of Ln.slice(0)){if(e&&n.name!==e||n.wasShutdown)continue;n.postMessage({restartNumber:Mn.exports.restartNumber,type:mT.ITC_EVENT_TYPES.SHUTDOWN}),n.wasShutdown=!0,n.emit("shutdown",{});let i=A9.indexOf(n.name)>-1,a=new Promise(c=>{let u=setTimeout(()=>n.terminate(),kP*2).unref();n.on("exit",()=>{clearTimeout(u),s.splice(s.indexOf(a)),!i&&r&&n.startCopy(),c()})});s.push(a),i&&r&&(n.startCopy(),s.length>=t&&await Promise.race(s))}await Promise.all(s)}else ps.postMessage({type:T9,workerType:e})}o(ST,"restartWorkers");function O9(e,t){JP[e]=t}o(O9,"setChildListenerByType");function N9(e){return ST(e,1/0,!1)}o(N9,"shutdownWorkers");var XP=[];function b9(e){XP.push(e)}o(b9,"onMessageFromWorkers");var ET=new Map;function y9(e,t){let r=ET.get(e);r||ET.set(e,r=[]),r.push(t)}o(y9,"onMessageByType");function I9(e){for(let t of Dn)try{t.postMessage(e)}catch(r){Ai.error("Unable to send message to worker",r)}}o(I9,"broadcast");var Id=new Map,w9=1;function C9(e){return new Promise(t=>{let r=0;for(let s of Dn)try{let n=w9++,i=o(()=>{Id.delete(n),--r===0&&t(),s!==ps&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,Id.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,a]of Id)a.port===s&&a()})),s.postMessage(e),r++}catch(n){Ai.error("Unable to send message to worker",n)}r===0&&t()})}o(C9,"broadcastWithAcknowledgement");function U9(e){e.postMessage({type:YP,workers:ZP()})}o(U9,"sendThreadInfo");function ZP(){let e=Date.now();return Ln.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}o(ZP,"getChildWorkerInfo");function D9(e,t){e.resources=t,e.resources.updated=Date.now()}o(D9,"recordResourceReport");var fT;function L9(e){fT=e}o(L9,"setMonitorListener");var M9=1e3,GP=!1;function P9(){GP||(GP=!0,setInterval(()=>{for(let e of Ln){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}fT&&fT()},M9).unref())}o(P9,"startMonitoring");var v9=1e3;if(ps){wd(ps);for(let e of Hc.addPorts)wd(e);setInterval(()=>{let e=process.memoryUsage();ps.postMessage({type:$P,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},v9).unref(),_T=o(()=>new Promise((e,t)=>{ps.on("message",r),ps.postMessage({type:VP});function r(s){s.type===YP&&(ps.off("message",r),e(s.workers))}o(r,"receiveThreadInfo")}),"getThreadInfo")}else _T=ZP;Mn.exports.getThreadInfo=_T;function wd(e,t){Dn.push(e),e.on("message",r=>{if(r.type===KP)wd(r.port);else if(r.type===R9){let s=Id.get(r.id);s&&s()}else{for(let n of XP)n(r,e);let s=ET.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){Ai.error(i)}}}).on("close",()=>{Dn.splice(Dn.indexOf(e),1)}).on("exit",()=>{Dn.splice(Dn.indexOf(e),1)}),t?e.refCount=100:e.unref()}o(wd,"addPort");if(hT){let e,t,r=o(async(s,n)=>{n&&(e=n);for(let i of await h9(s,{withFileTypes:!0}))i.isDirectory()&&r(xP(s,i.name));for await(let{filename:i}of f9(s,{persistent:!1}))(yd(i)===".ts"||yd(i)===".js"||yd(i)===".graphql")&&(t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await ST(),Ai.info("Reloaded HarperDB components")},100))},"watch_dir");Mn.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else ps.on("message",async e=>{let{type:t}=e;t===mT.ITC_EVENT_TYPES.SHUTDOWN&&(Mn.exports.restartNumber=e.restartNumber,ps.unref(),setTimeout(()=>{Ai.warn("Thread did not voluntarily terminate",l9),process.exit(0)},kP).unref())})});function AT(e){let t=e.auditStore=e.openDB(sv.AUDIT_STORE_NAME,H9);t.rootStore=e;let r=[];return t.addDeleteRemovalCallback=function(s,n){return r[s]=n,{remove(){delete r[s]}}},(0,iv.getWorkerIndex)()===0&&e.on("aftercommit",()=>{TT||(TT=setTimeout(()=>{if(TT=null,t.rootStore.status!=="closed")for(let{key:s,value:n}of t.getRange({start:[0,0],end:[Date.now()-jP,0]})){if((n[0]&15)===gT){let i=s[1];r[i]?.(s[2])}t.remove(s)}},jP/10).unref())}),t}function Dd(e,t,r){let s=cv[r.type],n=3;if(t?t.length>80?(s|=Cd,n=(0,tn.writeKey)(t,Ts,e?14:6),pT.setUint16(2,n)):(n=(0,tn.writeKey)(t,Ts,e?11:3),Ts[1]=n):Ts[1]=0,e){s|=ov;let i=s&Cd?6:3;pT.setFloat64(i,e),t||(n=i+8)}return Ts[0]=s,s&Cd?pT.setUint16(4,0):Ts[2]=0,r.value?Buffer.concat([Ts.slice(0,n),r.value]):Ts.subarray(0,n)}function Pn(e,t){let r=e[0],s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)),n=r&Cd,i=n?6:3,a;r&ov&&(a=s.getFloat64(i),i+=8);let c;n?c=s.getUint16(2):c=e[1];let u=r&RT?t.decoder.decode(e.subarray(c||i)):void 0;return{type:cv[r&7],value:u,lastVersion:a,get user(){return c?(0,tn.readKey)(e,i,c):void 0}}}var tn,Ud,sv,nv,iv,av,Ts,pT,B9,H9,jP,TT,RT,ev,gT,tv,rv,Cd,ov,cv,Fc=pe(()=>{tn=require("ordered-binary"),Ud=D(Q()),sv=D(xe()),nv=D(g()),iv=D(_t()),av=D(x());(0,Ud.initSync)();Ts=Buffer.alloc(1024),pT=new DataView(Ts.buffer,Ts.byteOffset,1024),B9={writeKey(e,t,r){if(Array.isArray(e)){let s=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength));return s.setFloat64(r,e[0]),s.setUint32(r+8,e[1]),(0,tn.writeKey)(e[2],t,r+12)}else return(0,tn.writeKey)(e,t,r)},readKey(e,t,r){if(e[t]>40){let s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength));return[s.getFloat64(t),s.getUint32(t+8),(0,tn.readKey)(e,t+12,r)]}else return(0,tn.readKey)(e,t,r)}},H9={encoding:"binary",keyEncoder:B9},jP=(0,av.convertToMS)((0,Ud.get)(nv.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,TT=null;o(AT,"openAuditStore");RT=16,ev=1,gT=2,tv=3,rv=4,Cd=128,ov=64,cv={put:ev|RT,[ev]:"put",delete:gT,[gT]:"delete",message:tv|RT,[tv]:"message",invalidate:rv,[rv]:"invalidate"};o(Dd,"createAuditEntry");o(Pn,"readAuditEntry")});var OT,Oi,F9,qc,Ld,uv=pe(()=>{OT=D(vt());Fc();Oi=Symbol("completion"),F9=100,qc=class{static{o(this,"DatabaseTransaction")}writes=[];hasWrittenTime;username;lmdbDb;auditStore;readTxn;constructor(t,r,s){this.lmdbDb=t,this.username=r?.username,this.auditStore=s}getReadTxn(){return this.readTxn||(this.readTxn=this.lmdbDb.useReadTransaction())}resetReadSnapshot(){this.readTxn&&(this.readTxn.done(),this.readTxn=null)}addWrite(t){this.writes.push(t)}validate(){for(let t of this.writes||[])t.validate?.()}commit(t=(0,OT.getNextMonotonicTime)(),r=!0,s=0){this.resetReadSnapshot();let n,i=[],a=0,c;this.hasWrittenTime=!1;let u=o(_=>{let d=_.commit(t,s);if(d&&(d[Oi]&&(i||(i=[]),i.push(d[Oi])),c=_.store,this.auditStore)){d.user=this.username,d.lastVersion=_.lastVersion,d.newTxnTime&&!this.hasWrittenTime&&(t=d.newTxnTime),this.hasWrittenTime=!0;let E=[t,_.store.tableId,_.key];_.invalidated&&(E.invalidated=!0),this.auditStore.put(E,Dd(_.lastVersion,this.username,d))}},"doWrite"),l=o(()=>{let _=this.writes[a++];if(_)if(_.key){let d=_.store.getEntry(_.key),E=s===0&&_.lastVersion!==void 0?_.lastVersion:_.lastVersion=d?.version??null,f=_.store.ifVersion(_.key,E,l);n=n||f}else l();else for(let d of this.writes)u(d)},"nextCondition");return this.writes.length<F9>>s?l():(s=1,n=this.writes[0].store.transaction(()=>{for(let _ of this.writes)u(_);return!0})),n?.then(_=>_?(c&&i.push(c.flushed),Promise.all(i).then(()=>(this.writes=[],{txnTime:t}))):this.commit(t,r,s+1))}abort(){this.resetReadSnapshot(),this.writes=[]}},Ld=class extends qc{static{o(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit(this.timestamp)}get timestamp(){return this._timestamp||(this._timestamp=(0,OT.getNextMonotonicTime)())}getReadTxn(){}}});function Ev(e,t,r,s,n){let i=e.primaryStore.env.path,a=e.primaryStore.tableId;Da||((0,Ni.onMessageByType)(_v,d=>{let E=d.auditIds;bT(d.path,E,d.txnId)}),(0,Ni.onMessageByType)(dv,d=>{(0,Rs.trace)("confirming to proceed with txn",d.txnId)}),Da=Object.create(null));let c=Da[i]||(Da[i]=[]);c.auditStore=e.auditStore;let u=c[a];u||(u=c[a]=new Map,u.envs=c,u.tableId=a,u.store=e.primaryStore),t=da(t);let l=new NT(r);l.startTime=s,n&&(l.includeDescendants=n);let _=u.get(t);return _?_.push(l):(u.set(t,_=[l]),_.tables=u,_.key=t),l.subscriptions=_,l}function bT(e,t,r,s){if(!Da)return;let n=Da[e];if(n){if(Ua&&Ua+1!==r){(0,Rs.trace)("Waiting to ensure latest txn id",Ua,"proceeds",r,s);let i=(async()=>{for(let[a,c]of Md)a<r&&((0,Rs.trace)("Txn",r,"waiting for txn",a),await c);if(Ua+1!==r){await(0,Ni.broadcastWithAcknowledgement)({type:dv,txnId:r});for(let[a,c]of Md)a<r&&((0,Rs.trace)("Txn",r,"waiting for txn",a),await c)}Md.delete(r),(0,Rs.trace)("Proceeding with txn id",r),Ua=r-1,bT(e,t,r,s)})();return Md.set(r,i),i}(0,Rs.trace)("Notifying with txn id",r,s),Ua=r;try{n.auditStore.resetReadTxn()}catch(i){throw i.message+=" in "+e,i}e:for(let i of t){let[a,c,u]=i,l=n[c];if(!l)continue;(0,lv.writeKey)(i,G9,0);let _=i[3];_&&(i.length=3);let d,E=da(u),f;do{let h=l.get(E);if(h){for(let S of h)if(!(f&&!S.includeDescendants)){if(S.startTime>=a){(0,Rs.info)("omitting",u,S.startTime,a);continue}try{if(S.crossThreads===!1&&!s)continue;if(d===void 0){let y=n.auditStore.get(i);if(!y||(d=Pn(y,l.store),d.type!=="message"&&l.store.getEntry(i[2])?.version!==i[0])||_&&d.type!=="invalidate")continue e}S.listener(u,d,a)}catch(y){console.error(y),(0,Rs.info)(y)}}}if(E==null)break;let T=E.lastIndexOf?.("/",E.length-2);T>-1?E=E.slice(0,T+1):E=null,f=!0}while(!0)}}}function fv(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",({next:i,last:a,txnId:c})=>{let u,l=[];if(t)do{if(i.flag&q9)continue;let _;i.meta&&i.meta.store===t&&(_=i.meta.key)&&(typeof _[2]=="symbol"&&(_[2]=null),_.invalidated&&(_[3]=!0),l.push(_))}while(i!=a&&(i=i.next));l.length!==0&&((0,Ni.broadcast)({type:_v,path:n,auditIds:l,txnId:c,start:u}),bT(n,l,c,!0))})}}var Rs,Ni,lv,_v,dv,q9,Da,G9,NT,Ua,Md,hv=pe(()=>{Rs=D(q()),Ni=D(_t()),lv=require("ordered-binary");to();uc();Fc();_v="transaction",dv="transaction-await",q9=67108864,G9=Buffer.alloc(4096);o(Ev,"addSubscription");NT=class extends Jr{static{o(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t}end(){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}}toJSON(){return{name:"subscription"}}},Md=new Map;o(bT,"notifyFromTransactionData");o(fv,"listenToCommits")});var gp={};Ze(gp,{coerceType:()=>Pd,makeTable:()=>Bd,setServerUtilities:()=>Y9});function Bd(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:a,databaseName:c,auditStore:u,schemaDefined:l,dbisDB:_}=e,{expirationMS:d,audit:E,trackDeletes:f}=e,{attributes:h}=e;h||(h=[]),fv(i,u);let T=0,S,y,O={},H,Y,A,w;for(let z of h)(z.assignCreatedTime||z.name==="__createdtime__")&&(H=z),(z.assignUpdatedTime||z.name==="__updatedtime__")&&(Y=z),z.expiresAt&&(A=z),z.isPrimaryKey&&(O=z);let G;E&&WT();class k extends ft{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=a;static databaseName=c;static attributes=h;static expirationTimer;static createdTimeProperty=H;static updatedTimeProperty=Y;static dbisDB=_;static schemaDefined=l;static sourcedFrom(p,N){if(N&&(this.sourceOptions=N,N.expiration&&this.setTTLExpiration(N.expiration)),this.Source)if(this.Source.mergeSource)this.Source=this.Source.mergeSource(p,this.sourceOptions);else if(p.mergeSource)this.Source=p.mergeSource(this.Source,this.sourceOptions);else throw new Error("Can not assign multiple sources to a table with no source providing a (static) mergeSource method");else this.Source=p;return(async()=>{let L=!1,b=o(async C=>{let v=C.value,U=C.table?Pe[c][C.table]:k;if(c===Qr.SYSTEM_SCHEMA_NAME&&(C.table===Qr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||C.table===Qr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!0),C.id===void 0&&(C.id=v[U.primaryKey],C.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(C));let M=await U.getResource(C.id,C,Gc);switch(C.type){case"put":return M._writeUpdate(v,Gc);case"delete":return M._writeDelete(Gc);case"publish":return M._writePublish(v,Gc);case"invalidate":return M.invalidate(Gc);default:Ii.error("Unknown operation",C.type,C.id)}},"writeUpdate");try{let C=p.subscribe&&(!p.subscribe.reliesOnPrototype||p.prototype.subscribe);C&&f==null&&(f=!0);let v=p.subscribeOnThisThread?p.subscribeOnThisThread((0,yi.getWorkerIndex)()):(0,yi.getWorkerIndex)()===0,U=C&&v&&await p.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(U)for await(let M of U)try{if(!(M.type==="transaction"?M.writes[0]:M)){console.error("Bad subscription event");continue}let J=Ye(M,()=>{if(M.type==="transaction"){let Z=[];for(let K of M.writes){K[Oe]=M;try{Z.push(b(K))}catch(te){throw te.message+=" writing "+JSON.stringify(K)+" of event "+JSON.stringify(M),te}}return Promise.all(Z)}else if(M.type==="define_schema"){let Z=this.attributes.slice(0),K;for(let te of M.attributes)Z.find(De=>De.name===te.name)||(Z.push(te),K=!0);K&&(et({table:n,database:c,attributes:Z,origin:"cluster"}),Vc.signalSchemaChange(new $c.SchemaEventMsg(process.pid,Qr.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return b(M)});M.onCommit&&(J?.then&&L&&Vc.signalUserChange(new $c.UserEventMsg(process.pid)),J?.then?J.then(M.onCommit):M.onCommit())}catch(V){console.error("error in subscription handler",V)}}catch(C){console.error(C)}})(),this}static getResource(p,N,L){let b=super.getResource(p,N,L);if(p!=null)try{if(b.hasOwnProperty(ce))return b;let C=b._txnForRequest();if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let v,U,V={transaction:C?.getReadTxn()},J;return ct(p,N,V,(Z,K)=>{K?U(K):(b[ce]=Z?.value,b[Xt]=Z?.version,J=!0,v?.(b))}),J?b:new Promise((Z,K)=>{v=Z,U=K})}catch(C){throw C.message.includes("Unable to serialize object")&&(C.message+=": "+JSON.stringify(p)),C}return b}static setTTLExpiration(p){(0,yi.getWorkerIndex)()===0&&(d=p*1e3,this.expirationTimer&&clearInterval(this.expirationTimer),this.expirationTimer=setInterval(()=>{if(this.primaryStore.rootStore.status!=="open")return clearInterval(this.expirationTimer);for(let{key:N,value:L,version:b}of this.primaryStore.getRange({start:!1,versions:!0}))b<Date.now()-d&&b>0&&L?.__invalidated__==null&&k.evict(N,L,b)},d).unref())}static enableAuditing(){E=!0,WT(),k.audit=!0}static coerceId(p){return p===""?null:Pd(p,O)}static async dropTable(){if(delete Pe[c][n],c===a){for(let p in r)_.remove(k.tableName+"/"+p),r[p].drop();_.remove(k.tableName+"/"),i.drop(),await _.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Vc.signalSchemaChange(new $c.SchemaEventMsg(process.pid,Qr.OPERATIONS_ENUM.DROP_TABLE,c,n))}static Source;static get(p,N){return p&&typeof p=="object"&&!Array.isArray(p)&&p.url===""?{recordCount:this.getRecordCount(),records:"./",name:n,database:c,attributes:h}:super.get(p,N)}get(p){if(typeof p=="string")return this.getProperty(p);if(this[ws])return this.search(p);if(p?.property)return this.getProperty(p.property);if(this.doesExist()||this[Oe]?.hasOwnProperty("returnNonexistent")&&this[Oe].returnNonexistent)return this}static allowRead(p,N){if(!p)return!1;let L=p.role.permission;if(L.super_user)return!0;if(L[n]?.read){let b=L[n].attribute_permissions;if(b){N||(N={});let C=N.select;if(C){let v=yT(b,"read");N.select=C.filter(U=>v[U])}else N.select=b.filter(v=>v.read).map(v=>v.attribute_name);return N}else return!0}}allowUpdate(p,N,L){if(!p)return!1;let b=p.role.permission;if(b.super_user)return!0;if(b[n]?.update){let C=b[n].attribute_permissions;if(C){let v=yT(C,"update");for(let U in N)if(!v[U])return!1;if(L)for(let U of C){let M=U.attribute_name;!U.update&&!(M in N)&&(N[M]=this.getProperty(M))}}else return!0}}allowCreate(p,N){return this.allowUpdate(p,{})}static allowCreate(p,N){if(!p)return!1;let L=p.role.permission;if(L.super_user)return!0;if(L[n]?.insert){let b=L[n].attribute_permissions;if(b){let C=yT(b,"insert");for(let v in N)if(!C[v])return!1}else return!0}}static allowDelete(p){if(!p)return!1;let N=p.role.permission;if(N.super_user||N[n]?.delete)return!0}update(p,N){if(!this._txnForRequest())throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let b;if(typeof p=="object"&&p){if(N)for(let C in this[ce])p[C]===void 0&&(p[C]=void 0);b=this[Et],b&&(p=Object.assign(b,p)),this[Et]=b=p}return!this[ce]&&t&&!(b||(b=this[Et]))?.[t]&&(b||(b=this[Et]=Object.create(null)),b[t]=this[ie]),this._writeUpdate(this),this}invalidate(p){this._txnForRequest().addWrite({key:this[ie],store:i,invalidated:!0,lastVersion:this[Xt],nodeName:this[Oe]?.nodeName,commit:(L,b)=>{if(b)return;let C={__invalidated__:L};for(let V in r)C[V]=this.getProperty(V);let v=k.Source,U,M=this[ie];return p?.isNotification||v?.invalidate&&(!v.invalidate.reliesOnPrototype||v.prototype.invalidate)&&(U=v.invalidate(M,this)),i.put(this[ie],C,L),{type:E&&"invalidate",[Oi]:U}}})}static evict(p,N,L){let b=this.Source;if(b?.get&&(!b.get.reliesOnPrototype||b.prototype.get)){let C;if(!N){let v=i.getEntry(p);if(!v)return;N=v.value,L=v.version}if(N)for(let v in r)C||(C={__invalidated__:0}),C[v]=N[v];return C?i.put(p,C,L,L):i.remove(p,L)}else return i.remove(p,L)}lock(){throw new Error("Not yet implemented")}static operation(p,N){return p.table||=n,p.schema||=c,Ov.operation(p,N)}async put(p){this.update(p,!0)}_writeUpdate(p,N){let L=this._txnForRequest();if(this[ie]===void 0)throw new Error("Can not save record without an id");let b=this[ce],C,v,U=this[ie];b||(this[ce]={}),L.addWrite({key:U,store:i,lastVersion:this[Xt],nodeName:this[Oe]?.nodeName,validate:()=>{this.validate(p)},commit:(M,V)=>{let J;if(V){if(C)return;let K=i.getEntry(U);b=K?.value;let te=this[Oe];te&&K?.version>(te.lastModified||0)&&(te.lastModified=K.version)}if(!v){if(v=!0,N?.isNotification)p=so(p);else{if(p[pv]&&(C=!Su(p),C))return;t&&p[t]!==U&&(p[t]=U),Y&&(p[Y.name]=Y.type==="Date"?new Date(M):Y.type==="String"?new Date(M).toISOString():M),H&&(b?p[H.name]=b[H.name]:p[H.name]=H.type==="Date"?new Date(M):H.type==="String"?new Date(M).toISOString():M),p=so(p);let K=k.Source;K?.put&&(!K.put.reliesOnPrototype||K.prototype.put)&&(J=K.put(U,p,this))}if(p[ce])throw new Error("Can not assign a record with a record property");this[ce]=p}if(Ii.trace("Checking timestamp for put",U,this[Xt]>M,this[Xt],M),this[Xt]>M)return E&&{type:"put",value:i.encoder.encode(p)};let Z=i.encoder.encode(p);return i.put(this[ie],(0,La.asBinary)(Z),M),ge(this[ie],b,p),b===null&&!V&&Hn(-1),{type:E&&"put",value:Z,[Oi]:J}}})}async delete(p){return typeof p=="string"?this.deleteProperty(p):this[ce]?this._writeDelete(p):!1}_writeDelete(p){let N=this._txnForRequest(),L,b=this[ie],C;return N.addWrite({key:b,store:i,lastVersion:this[Xt],nodeName:this[Oe]?.nodeName,commit:(v,U)=>{let M=this[ce];if(U){let V=i.getEntry(b);M=V?.value;let J=this[Oe];J&&V?.version>(J.lastModified||0)&&(J.lastModified=V.version)}if(!L&&(L=!0,!p?.isNotification)){let V=k.Source;V?.delete&&(!V.delete.reliesOnPrototype||V.prototype.delete)&&(C=V.delete(b,this))}if(!(this[Xt]>v))return ge(this[ie],M),Ii.trace("Write delete entry",E||f,v),E||f?(i.put(this[ie],null,v),E||KT(),U||Hn(1)):i.remove(this[ie]),{type:E&&"delete",[Oi]:C}}}),!0}search(p){let N=this._txnForRequest();if(!p)throw new Error("No query provided");let L=p.reverse===!0,b=p.conditions;b?b.length===void 0&&(b=Array.from(b)):b=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this[ie]&&(b=[{attribute:null,comparator:"prefix",value:this[ie]}].concat(b));for(let K of b){let te=K[0]??K.attribute,De=te==null?O:h.find(sn=>sn.name==te);if(De)De.type&&(K[1]===void 0?K.value=C(K.value,De):K[1]=C(K[1],De));else if(te!=null)throw(0,bi.handleHDBError)(new Error,`${te} is not a defined attribute`,404)}function C(K,te){return Array.isArray(K)?K.map(De=>Pd(De,te)):Pd(K,te)}o(C,"coerceTypedValues"),b.length>1&&(b=(0,gv.sortBy)(b,K=>{if(K.estimated_count===void 0){let te=K.comparator||K.search_type;if(te===xc.SEARCH_TYPES.EQUALS){let De=K[0]??K.attribute;if(De==null||De===t)K.estimated_count=1;else{let sn=r[De];K.estimated_count=sn?sn.getValuesCount(K[1]??K.value):1/0}}else te===xc.SEARCH_TYPES.CONTAINS||te===xc.SEARCH_TYPES.ENDS_WITH||te==="ne"?K.estimated_count=1/0:te===xc.SEARCH_TYPES.STARTS_WITH||te==="prefix"?K.estimated_count=k9:K.estimated_count=x9}return K.estimated_count}));let v=N.getReadTxn();v.use();let U=p.select,M=b[0],V;if(!M)V=i.getRange(L?{end:!1,reverse:!0,transaction:v,lazy:U?.length<4}:{start:!1,transaction:v,lazy:U?.length<4}).map(({value:K})=>K?new Promise(te=>setImmediate(()=>te(K))):La.SKIP);else{let K=OE(M,v,L,k,p.allowFullScan);if(!p.operator||p.operator.toLowerCase()==="and"){let te=b.slice(1).map(NE);V=Z(K,te)}else{for(let De=1;De<b.length;De++){let sn=b[De],eE=OE(sn,v,L,k,p.allowFullScan);K=K.concat(eE)}let te=new Set;K=K.filter(De=>te.has(De)?!1:(te.add(De),!0)),V=Z(K)}}(p.offset||p.limit!==void 0)&&(V=V.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0)),V.onDone=()=>{v.done()};let J=this[Oe];function Z(K,te){let De=te?.length,sn={transaction:v,lazy:De>0||U?.length<4,alwaysPrefetch:!0};return K.map(eE=>new Promise(tE=>ct(eE,J,sn,NB=>{let rE=NB?.value;if(!rE)return tE(La.SKIP);for(let sE=0;sE<De;sE++)if(!te[sE](rE))return tE(La.SKIP);tE(rE)})))}return o(Z,"idsToRecords"),V}async subscribe(p){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||et({table:n,database:c,schemaDefined:l,attributes:h,audit:!0});let N=Ev(k,this[ie]??null,function(v,U,M){try{this.send({id:v,timestamp:M,...U})}catch(V){console.error(V)}},p.startTime,this[ws]),L=this[ie],b=p.previousCount;b>1e3&&(b=1e3);let C=p.startTime;if(this[ws]){if(C){if(b)throw new bi.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:v,value:U}of u.getRange({start:[C,Number.MAX_SAFE_INTEGER]})){let[M,V,J]=v;if(v.length>3&&(J=v.slice(2)),V!==s)continue;let Z=Pn(U,i);(L==null||Rv(L,J))&&N.send({id:J,timestamp:M,...Z}),N.startTime=M}}else if(b){let v=[];for(let{key:U,value:M}of u.getRange({start:"z",end:!1,reverse:!0}))try{let[V,J,Z]=U;if(U.length>3&&(Z=U.slice(2)),J!==s)continue;if(L==null||Rv(L,Z)){let K=Pn(M,i);if(v.push({id:Z,timestamp:V,...K}),--b<=0)break}}catch(V){Ii.error("Error getting history entry",U,V)}for(let U=v.length;U>0;)N.send(v[--U]);v[0]&&(N.startTime=v[0].timestamp)}else if(!p.omitCurrent)for(let{key:v,value:U,version:M}of i.getRange({start:L??!1,end:L==null?void 0:[L,Av.MAXIMUM_KEY],versions:!0}))U&&N.send({id:v,timestamp:M,value:U})}else{b&&!C&&(C=0);let v=this[Xt];if(C<v){let U=[],M=v;do{let V=[M,s,L],J=u.get(V);if(J){p.omitCurrent=!0;let Z=Pn(J,i);U.push({id:L,timestamp:M,...Z}),M=Z.lastVersion}else break;b&&b--}while(M>C&&b!==0);for(let V=U.length;V>0;)N.send(U[--V]);N.startTime=v}!p.omitCurrent&&this.doesExist()&&N.send({id:L,timestamp:this[Xt],value:this})}return p.listener&&N.on("data",p.listener),N}doesExist(){return!!this[ce]}async publish(p,N){this._writePublish(p,N)}_writePublish(p,N){let L=this._txnForRequest(),b=this[ie]||null,C,v;L.addWrite({store:i,key:b,lastVersion:this[Xt],nodeName:this[Oe]?.nodeName,validate:()=>{this.validate(p)},commit:(U,M)=>{if(this.validate(p),!v&&(v=!0,!N?.isNotification)){let Z=k.Source;Z?.publish&&(!Z.publish.reliesOnPrototype||Z.prototype.publish)&&(C=Z.publish(b,p,this))}let V=M>0?i.get(b):this[ce];V===void 0&&!M&&(E||f)&&(E||KT(),Hn(1));let J={type:"message",value:i.encoder.encode(p),[Oi]:C};return!L.hasWrittenTime&&this[Xt]>U&&(U=J.newTxnTime=this[Xt]+.001),i.put(b,V??null,U),J}})}_txnForRequest(){let p=this[Oe],N=p?.transaction;if(N){let L;return(L=N?.find(b=>b.lmdbDb?.path===i.path))||N.push(L=new qc(i,p.user,u)),L}else return new Ld(i,p.user,u)}validate(p){let N;for(let L=0,b=h.length;L<b;L++){let C=h[L];if(C.type){let v=p[C.name];if(v!=null)switch(C.type){case"Int":case"Float":(typeof v!="number"||C.type==="Int"&&v!==Math.floor(v))&&(N||(N=[])).push(`Property ${C.name} must be an ${C.type==="Int"?"integer":"number"}`);break;case"ID":typeof v=="string"||v?.length>0&&v.every?.(U=>typeof U=="string")||(N||(N=[])).push(`Property ${C.name} must be a string, number, or an array (of strings and numbers)`);break;case"String":typeof v!="string"&&(N||(N=[])).push(`Property ${C.name} must be a string`)}}C.required&&p[C.name]==null&&(N||(N=[])).push(`Property ${C.name} is required`)}if(N)throw new bi.ClientError(N.join(". "))}getUpdatedTime(){return this[Xt]}static async addAttributes(p){let N=h.slice(0);for(let L of p){if(!L.name)throw new bi.ClientError("Attribute name is required");if(L.name.match(/[`/]/))throw new bi.ClientError("Attribute names cannot include backticks or forward slashes");N.push(L)}return et({table:n,database:c,schemaDefined:l,attributes:N}),k.indexingOperation}static async removeAttributes(p){let N=h.filter(L=>!p.includes(L.name));return et({table:n,database:c,schemaDefined:l,attributes:N}),k.indexingOperation}static getRecordCount(){let p=0;for(let{key:N,value:L}of i.getRange({end:!1}))p++,N[0]?.description==="deletions"&&(p+=L||0);return i.getStats().entryCount-p}static updatedAttributes(){Tu(this,this)}static async deleteHistory(p=0){let N;for(let{key:L,value:b}of u.getRange({start:[0,0],end:[p,0]})){await new Promise(M=>setImmediate(M));let[C,v,U]=L;L.length>3&&(U=L.slice(2)),v===s&&(N=i.remove(U))}await N}static async*getHistory(p=0,N=1/0){for(let{key:L,value:b}of u.getRange({start:[p,0],end:[N,0]})){await new Promise(V=>setImmediate(V));let[C,v,U]=L;if(L.length>3&&(U=L.slice(2)),v!==s)continue;let M=Pn(b,i);M.id=U,M.timestamp=C,yield M}}static async getHistoryOfRecord(p){let N=[],L=i.getEntry(p);if(!L)return N;let b=L.version,C=0;do{await new Promise(M=>setImmediate(M));let v=[b,s,p],U=u.get(v);if(U){let M=Pn(U,i);M.timestamp=b,N.push(M),b=M.lastVersion}else break}while(C<1e3);return N.reverse()}static cleanup(){G?.remove()}}k.updatedAttributes();let X=k.prototype;return X[pv]=!0,d&&k.setTTLExpiration(d/1e3),A&&OB(),k;function ge(z,p,N){let L;for(let b in r){let C=r[b],v=C.isIndexing,U=N?.[b],M=p?.[b];if(U===M&&!v)continue;L=!0;let V=(0,kc.getIndexedValues)(M);if(V){mv&&C.prefetch(V.map(J=>({key:J,value:z})),Tv);for(let J=0,Z=V.length;J<Z;J++)C.remove(V[J],z)}if(V=(0,kc.getIndexedValues)(U),V){mv&&C.prefetch(V.map(J=>({key:J,value:z})),Tv);for(let J=0,Z=V.length;J<Z;J++)C.put(V[J],z)}}return L}o(ge,"updateIndices");function ct(z,p,N,L){let b=o(()=>{let C=N.transaction;if(C?.isDone)throw new Error("Invalid read transaction");let v;C&&!C.hasRunLoadRecord&&(v=!0,C.hasRunLoadRecord=!0);let U;try{U=i.getEntry(z,N)}catch(Z){throw Z.message+=". The read txn is "+JSON.stringify(C)+" first loadRecord: "+v,console.error(Z),console.error("reader list",i.readerList()),console.error("reader check",i.readerCheck()),console.error("reader list",i.readerList()),Z}let M,V,J;if(U?(p&&U?.version>(p.lastModified||0)&&(p.lastModified=U.version),V=U.version,M=U.value,(V<0||!M||typeof M.__invalidated__=="number"||d&&V<Date.now()-d)&&(J=!0)):J=!0,J&&!N?.allowInvalidated){let Z=k.Source;if(Z&&Z.get&&(!Z.get.reliesOnPrototype||Z.prototype.get))return Ga(z,M,V,p).then(te=>{if(te?.value?.[ce])throw new Error("Can not assign a record with a record property");L(te)},te=>{L(null,te)})}if(U?.value?.[ce])throw new Error("Can not assign a record with a record property");L(U)},"whenPrefetched");if(!N.alwaysPrefetch&&(z==null||i.cache?.get(z)))return b();i.prefetch([z],b)}o(ct,"loadRecord");function Di(){w=new Set,(0,yi.onMessageByType)("transaction",z),i.on("aftercommit",z);function z(){for(let p of w)p()}o(z,"onCommit")}o(Di,"setupCommitListeners");async function Ga(z,p=null,N,L){if(N<0){let U;return w||Di(),await new Promise(M=>{let V,J=o(()=>{if(U=i.getEntry(z),!U||U.version>0){if(clearTimeout(V),w.delete(J),typeof U?.value?.__invalidated__=="number")return M(Ga(z,U.value,U.version,L));M(U)}},"listener");w.add(J),V=setTimeout(()=>{w.delete(J),M(Ga(z,U?.value,void 0,L))},1e4).unref()})}let b=p?.__invalidated__,C=-(N||1);i.put(z,p,C,N);let v={transaction:L?.transaction};try{let U=await k.Source.get(z,v),M=v.lastModified||N;(!M||d&&M<Date.now()-d)&&(M=(0,kc.getNextMonotonicTime)());let J=ge(z,p,U)&&N||b>0;return U?(t&&(U[t]=z),typeof U.toJSON=="function"&&(U=U.toJSON()),i.put(z,U,M,C)):i.remove(z,C),J&&E&&u.put([M,s,z],Dd(b,null,U?{type:"put",value:i.encoder.encode(U)}:{type:"delete"})),{version:M,value:U}}catch(U){throw i.put(z,p,N,C),U}}o(Ga,"getFromSource");function Hn(z){T||(T=i.get([Sv,IT.threadId])||0),T+=z,y||(y=setTimeout(()=>{y=null,i.rootStore.status==="open"&&i.put([Sv,IT.threadId],T)},50))}o(Hn,"recordDeletion");function KT(){S||(S=setTimeout(()=>{if(S=null,i.rootStore.status==="open"){for(let{key:z,value:p}of i.getRange({start:!0}))if(p===null){let N=i.getEntry(z);N?.value===null&&i.remove(z,N.version),Hn(-1)}}},k.getRecordCount()*100+$9).unref())}o(KT,"enqueueDeletionCleanup");function WT(){G=u?.addDeleteRemovalCallback(s,z=>{let p=i.getEntry(z);p?.value===null&&i.remove(z,p.version),Hn(-1)})}o(WT,"addDeleteRemoval");function OB(){(0,yi.getWorkerIndex)()===0&&setInterval(async()=>{try{let z=A.name,p=r[z];if(!p)throw new Error(`expiresAt attribute ${A} must be indexed`);for(let{value:N}of p.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let L=i.getEntry(N);L.value?.[z]<Date.now()&&k.evict(N,L.value,L.version),await new Promise(b=>setImmediate(b))}}catch(z){Ii.error("Error in evicting old records",z)}},V9).unref()}o(OB,"runRecordExpirationEviction")}function yT(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function Tv(){}function Y9(e){Ov=e}function Pd(e,t){let r=t?.type;return e===null?e:r==="Int"?parseInt(e):r==="Float"?parseFloat(e):r==="Date"?(typeof e!="number"&&!K9.test(e)&&(e+="Z"),new Date(e)):r?e:(0,vd.autoCast)(e)}function Rv(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}var Qr,La,kc,gv,IT,xc,Yc,bi,Vc,$c,Ii,Av,yi,vd,Ov,x9,k9,V9,mv,Sv,Xt,pv,C_e,Gc,$9,K9,td=pe(()=>{Qr=D(g()),La=require("lmdb"),kc=D(vt()),gv=require("lodash"),IT=require("worker_threads");Xr();uv();xc=D(xe()),Yc=D(Q());hv();bi=D(W()),Vc=D(Hs()),$c=D(Fr());de();Ou();Ii=D(q());gu();Gn();Av=require("ordered-binary"),yi=D(_t());Fc();vd=D(x()),x9=1e8,k9=1e7,V9=6e4;Yc.initSync();mv=Yc.get(Qr.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Sv=Symbol.for("deletions"),Xt=Symbol.for("version"),pv=Symbol.for("incremental-update"),C_e=Symbol("source-resource"),Gc={isNotification:!0,allowInvalidated:!0},$9=(0,vd.convertToMS)(Yc.get(Qr.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;o(Bd,"makeTable");o(yT,"attributesAsObject");o(Tv,"noop");o(Y9,"setServerUtilities");K9=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;o(Pd,"coerceType");o(Rv,"isDescendantId")});var Ne={};Ze(Ne,{database:()=>vo,databases:()=>Pe,dropDatabase:()=>Fh,dropTableMeta:()=>Z9,getDatabases:()=>Gr,getTables:()=>W9,onUpdatedTable:()=>Jp,readMetaDb:()=>Kc,resetDatabases:()=>Q9,table:()=>et,tables:()=>sr});function W9(){return Gd||Gr(),sr||{}}function Gr(){if(Gd)return Pe;Gd=!0,Ba=new Map;let e=(0,bt.getHdbBasePath)()&&(0,Me.join)((0,bt.getHdbBasePath)(),Zt.DATABASES_DIR_NAME),t=(0,bt.get)(Zt.CONFIG_PARAMS.SCHEMAS)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,bt.get)(Zt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,fr.existsSync)(e)?e:(0,Me.join)((0,bt.getHdbBasePath)(),Zt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,fr.existsSync)(e))for(let r of(0,fr.readdirSync)(e,{withFileTypes:!0})){let s=(0,Me.basename)(r.name,".mdb");r.isFile()&&(0,Me.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Kc((0,Me.join)(e,r.name),null,s)}if((0,fr.existsSync)((0,va.getBaseSchemaPath)())){for(let r of(0,fr.readdirSync)((0,va.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,Me.join)((0,va.getBaseSchemaPath)(),r.name),n=(0,Me.join)((0,va.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,fr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,Me.extname)(i.name).toLowerCase()===".mdb"){let a=(0,Me.join)(n,i.name);Kc((0,Me.join)(s,i.name),(0,Me.basename)(i.name,".mdb"),r.name,a,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,fr.existsSync)(n))for(let a of(0,fr.readdirSync)(n,{withFileTypes:!0}))a.isFile()&&(0,Me.extname)(a.name).toLowerCase()===".mdb"&&Kc((0,Me.join)(n,a.name),(0,Me.basename)(a.name,".mdb"),r);let i=s.tables;if(i)for(let a in i){let c=i[a],u=(0,Me.join)(c.path,(0,Me.basename)(a+".mdb"));(0,fr.existsSync)(u)&&Kc(u,a,r,null,!0)}}for(let r in Pe){let s=Ba.get(r);if(s){let n=Pe[r];r.includes("delete")&&Le.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Le.trace(`delete table class ${i}`),delete n[i])}else if(delete Pe[r],r==="data"){for(let n in sr)delete sr[n];delete sr[xd]}}return Ba=null,Pe}}function Q9(){Gd=!1;for(let[,e]of vn)e.needsDeletion=!0;Gr();for(let[e,t]of vn)t.needsDeletion&&!e.endsWith("system.mdb")&&(console.log("closing database",e),t.close().then(()=>console.log("closed database",e)),vn.delete(e));return Pe}function Kc(e,t,r=UT,s,n){let i=new wT.default(e,!1);e.includes("delete")&&Le.trace(`reading meta data from ${e}`);try{let a=vn.get(e);a?a.needsDeletion=!1:(a=(0,Hd.open)(i),vn.set(e,a));let c=new wi.default(!1),u=a.dbisDb||(a.dbisDb=a.openDB(Ma.INTERNAL_DBIS_NAME,c)),l=a.auditStore;l||(s?(0,fr.existsSync)(s)&&(i.path=s,l=(0,Hd.open)(i),l.isLegacy=!0):l=AT(a));let _=Iv(r),d=_[xd],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[T,S]=f.toString().split("/");e.includes("delete")&&Le.trace(`read key ${f}`),S===""?S=h.name:S||(S=T,T=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(T);let y=E.get(T);y||E.set(T,y={attributes:[]}),(S==null||h.is_hash_attribute)&&(y.primary=h),S!=null&&y.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:T,primary:S}=h;if(!S){for(let X of T)if(X.is_hash_attribute||X.isPrimaryKey){S=X;break}if(!S)throw new Error(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(T)}`)}let y=_[f],O={},H=[],Y,A,w=typeof S.audit=="boolean"?S.audit:(0,bt.get)(Zt.CONFIG_PARAMS.LOGGING_AUDITLOG),G=S.trackDeletes,k=S.expiration;if(y)O=y.indices,H=y.attributes,y.schemaVersion++;else{Y=S.tableId,Y?Y>=(u.get(Pa)||0)&&u.putSync(Pa,Y+1):(S.tableId=Y=u.get(Pa),Y||(Y=1),u.putSync(Pa,Y+1),u.putSync(S.key,S));let X=new wi.default(!S.is_hash_attribute,S.is_hash_attribute);Le.trace(`openDB ${S.key} from ${r}`),A=a.openDB(S.key,X),A.rootStore=a,A.tableId=Y}for(let X of T){X.attribute=X.name;try{if(!X.is_hash_attribute&&(X.indexed||X.attribute&&!X.name)){if(!O[X.name]){let ct=new wi.default(!X.is_hash_attribute,X.is_hash_attribute);Le.trace(`openDB ${X.key} from ${r}`),O[X.name]=a.openDB(X.key,ct)}let ge=H.find(ct=>ct.name===X.name);ge?H.splice(H.indexOf(ge),1,X):H.push(X)}}catch(ge){Le.error("Error trying to update attribute",X,H,O,ge)}}if(!y){Le.trace(`creating table class ${f}`,Object.keys(_)),y=wv(_,f,Bd({primaryStore:A,auditStore:l,audit:w,expirationMS:k&&k*1e3,trackDeletes:G,tableName:f,tableId:Y,primaryKey:S.name,databasePath:n?r+"/"+f:r,databaseName:r,indices:O,attributes:T,schemaDefined:S.schemaDefined,dbisDB:u})),y.schemaVersion=1;for(let X of DT)X(y)}}return a}catch(a){throw a.message+=` opening database ${e}`,a}}function Iv(e){let t=Pe[e];if(t||(e==="data"?t=Pe[e]=sr:e==="system"?Object.defineProperty(Pe,"system",{value:t=Object.create(null),configurable:!0}):t=Pe[e]=Object.create(null)),Ba&&!Ba.has(e)){let r=new Set;t[xd]=r,Ba.set(e,r)}return t}function wv(e,t,r){return e[t]=r,r}function vo({database:e,table:t}){e||(e=UT),Gr();let r=Iv(e),s=(0,Me.join)((0,bt.getHdbBasePath)(),Zt.DATABASES_DIR_NAME),n=t&&(0,bt.get)(Zt.CONFIG_PARAMS.SCHEMAS)?.[e]?.tables?.[t]?.path;s=n||(0,bt.get)(Zt.CONFIG_PARAMS.SCHEMAS)?.[e]?.path||process.env.STORAGE_PATH||(0,bt.get)(Zt.CONFIG_PARAMS.STORAGE_PATH)||((0,fr.existsSync)(s)?s:(0,Me.join)((0,bt.getHdbBasePath)(),Zt.LEGACY_DATABASES_DIR_NAME));let i=(0,Me.join)(s,(n?t:e)+".mdb"),a=vn.get(i);if(!a){let c=new wT.default(i,!1);a=(0,Hd.open)(c),vn.set(i,a)}return a}async function Fh(e){if(!Pe[e])throw new Error("Schema does not exist");let t=Pe[e];for(let r in t){let n=t[r].primaryStore.rootStore;vn.delete(n.path),n.status==="open"&&(await n.close(),await Nv.remove(n.path))}if(e==="data"){for(let r in sr)delete sr[r];delete sr[xd]}delete Pe[e]}function et({table:e,database:t,expiration:r,attributes:s,audit:n,trackDeletes:i,schemaDefined:a,origin:c}){t||(t=UT);let u=vo({database:t,table:e}),l=Pe[t],_=l?.[e];if(u.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let d,E,f,h;a==null&&(a=!0);let T=new wi.default(!1);for(let A of s)A.attribute?(A.name=A.attribute,A.indexed=!0):A.attribute=A.name,A.expiresAt&&(A.indexed=!0);let S,y;if(_){if(Le.trace(`${e} table already exists`),d=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);_.attributes.splice(0,_.attributes.length,...s)}else{let A=u.auditStore;A||(A=AT(u)),E=s.find(X=>X.isPrimaryKey)||{},d=E.name,E.is_hash_attribute=!0,E.schemaDefined=a,i&&(E.trackDeletes=!0),n=E.audit=typeof n=="boolean"?n:(0,bt.get)(Zt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(E.expiration=r),c&&(E.origins?E.origins.includes(c)||E.origins.push(c):E.origins=[c]),Le.trace(`${e} table loading, opening primary store`);let w=new wi.default(!1,!0),G=e+"/";Le.trace(`openDB ${G} from ${t}`);let k=u.openDB(G,w);k.rootStore=u,Le.trace(`openDB ${Ma.INTERNAL_DBIS_NAME} from ${t}`),h=u.dbisDb=u.openDB(Ma.INTERNAL_DBIS_NAME,T),k.tableId=h.get(Pa),k.tableId||(k.tableId=1),h.putSync(Pa,k.tableId+1),E.tableId=k.tableId,_=wv(l,e,Bd({primaryStore:k,auditStore:A,audit:n,trackDeletes:i,expirationMS:r&&r*1e3,primaryKey:d,tableName:e,tableId:k.tableId,databasePath:t,databaseName:t,indices:{},attributes:s,schemaDefined:a,dbisDB:h})),_.schemaVersion=1,S=!0,Y(),h.put(G,E)}Le.trace(`${e} table loading, getting stored attributes`),f=_.indices,h||Le.trace(`openDB ${Ma.INTERNAL_DBIS_NAME} from ${t}`),h=h||(u.dbisDb=u.openDB(Ma.INTERNAL_DBIS_NAME,T)),_.dbisDB=h;let O=[];for(let{key:A,value:w}of h.getRange({start:!0})){let[G,k]=A.toString().split("/");if(k===""&&(k=w.name),k){if(G!==e)continue}else k=G;if(!s.find(ge=>ge.name===k)?.indexed&&w.indexed&&!w.isPrimaryKey){Y(),S=!0,h.remove(A);let ge=_.indices[G];ge&&O.push(ge)}}Le.trace(`${e} table loading, comparing atributes`);let H=[];try{for(let A of s||[]){let w=e+"/"+(A.name||"");Object.defineProperty(A,"key",{value:w,configurable:!0});let G=h.get(w);if(A.isPrimaryKey){if(n===!0&&!_.audit){_.enableAuditing(),G||(w=e+"/",G=h.get(w));let X=Object.assign({},G,{audit:!0});S=!0,Y(),h.put(w,X)}continue}G?.attribute&&!G.name&&(G.indexed=!0);let k=!G||G.type!==A.type||G.indexed!==A.indexed||JSON.stringify(G.attributes)!==JSON.stringify(A.attributes)||JSON.stringify(G.elements)!==JSON.stringify(A.elements);if(A.indexed){let X=new wi.default(!0,!1);Le.trace(`openDB ${w} from ${t}`);let ge=u.openDB(w,X);(k||G.indexingPID&&G.indexingPID!==process.pid||G.restartNumber<Wc.workerData?.restartNumber)&&(S=!0,Y(),G=h.get(w),(k||G.indexingPID&&G.indexingPID!==process.pid||G.restartNumber<Wc.workerData?.restartNumber)&&(S=!0,A.lastIndexedKey=G?.lastIndexedKey||!1,A.indexingPID=process.pid,ge.isIndexing=!0,Object.defineProperty(A,"dbi",{value:ge}),H.push(A)),h.put(w,A)),f[A.name]=ge}else k&&(S=!0,Y(),h.put(w,A))}}finally{y&&y()}if(S&&(_.schemaVersion++,_.updatedAttributes()),Le.trace(`${e} table loading, running index`),H.length>0||O.length>0?_.indexingOperation=X9(_,H,O):S&&Fd.signalSchemaChange(new qd.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=c,S)for(let A of DT)A(_,c!=="cluster");return r&&_.setTTLExpiration(+r),Le.trace(`${e} table loaded`),_;function Y(){y||u.transactionSync(()=>({then(A){y=A}}))}o(Y,"startTxn")}async function X9(e,t,r){try{let s=e.schemaVersion;await Fd.signalSchemaChange(new qd.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,a=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:l,value:_,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(_){if(u++,n=e.primaryStore.ifVersion(l,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,T=(0,bv.getIndexedValues)(_[h]);if(T)for(let S=0,y=T.length;S<y;S++)f.dbi.put(T[S],l)}}),n.then(()=>u--,E=>{u--,Le.error(E)}),Wc.workerData&&Wc.workerData.restartNumber!==yv.restartNumber&&(i=!0),++a%100===0||i){for(let E of t)E.lastIndexedKey=l,e.dbisDB.put(E.key,E);if(i)return}u>z9?await n:u>J9&&await new Promise(E=>setImmediate(E))}for(let l of t)delete l.lastIndexedKey,delete l.indexingPID,l.dbi.isIndexing=!1,n=e.dbisDB.put(l.key,l)}await n,await Fd.signalSchemaChange(new qd.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Le.error("Error in indexing",s)}}function Z9({table:e,database:t}){let r=vo({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function Jp(e){DT.push(e)}var bt,Ma,Hd,Me,fr,va,wi,wT,Zt,Nv,CT,bv,Fd,qd,Wc,Le,yv,UT,xd,sr,Pe,Pa,DT,Gd,vn,Ba,z9,J9,de=pe(()=>{bt=D(Q()),Ma=D(xe()),Hd=require("lmdb"),Me=require("path"),fr=require("fs"),va=D(we());td();wi=D(Iu()),wT=D(Cu()),Zt=D(g()),Nv=D(require("fs-extra")),CT=require("../index"),bv=D(vt()),Fd=D(Hs()),qd=D(Fr()),Wc=require("worker_threads"),Le=D(q()),yv=D(_t());Fc();UT="data",xd=Symbol("defined-tables");(0,bt.initSync)();sr=Object.create(null),Pe=Object.create(null);(0,CT._assignPackageExport)("databases",Pe);(0,CT._assignPackageExport)("tables",sr);Pa=Symbol.for("next-table-id"),DT=[],vn=new Map;o(W9,"getTables");o(Gr,"getDatabases");o(Q9,"resetDatabases");o(Kc,"readMetaDb");o(Iv,"ensureDB");o(wv,"setTable");o(vo,"database");o(Fh,"dropDatabase");o(et,"table");z9=1e3,J9=10;o(X9,"runIndexing");o(Z9,"dropTableMeta");o(Jp,"onUpdatedTable")});var x=m((F_e,kv)=>{"use strict";var Bn=require("path"),Mv=require("fs-extra"),jt=q(),Cv=require("fs-extra"),kd=require("os"),j9=require("net"),e7=require("recursive-iterator"),Ge=g(),t7=yR(),Uv=require("papaparse"),Vd=require("moment"),{inspect:r7}=require("util"),Dv=require("is-number"),H_e=require("lodash"),s7=require("minimist"),n7=require("https"),i7=require("http"),{hdb_errors:$d}=W(),a7=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Pv=require("util").promisify(setTimeout),o7=100,c7=5,u7="",l7=4,Lv={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};kv.exports={isEmpty:hr,isEmptyOrZeroLength:gs,arrayHasEmptyValues:E7,arrayHasEmptyOrZeroLengthValues:f7,buildFolderPath:h7,isBoolean:vv,errorizeMessage:_7,stripFileExtension:S7,autoCast:p7,autoCastJSON:Bv,autoCastJSONDeep:MT,removeDir:T7,compareVersions:R7,isCompatibleDataVersion:g7,escapeRawValue:A7,unescapeValue:O7,stringifyProps:N7,timeoutPromise:y7,isClusterOperation:w7,getClusterUser:U7,checkGlobalSchemaTable:C7,getHomeDir:Fv,getPropsFilePath:b7,promisifyPapaParse:D7,removeBOM:qv,createEventPromise:L7,checkProcessRunning:M7,checkSchemaTableExist:P7,checkSchemaExists:Gv,checkTableExists:xv,getStartOfTomorrowInSeconds:v7,getLimitKey:B7,isObject:m7,isNotEmptyAndHasValue:d7,autoCasterIsNumberCheck:Hv,backtickASTSchemaItems:H7,isPortTaken:I7,createForkArgs:F7,autoCastBoolean:q7,async_set_timeout:Pv,getTableHashAttribute:G7,doesSchemaExist:x7,doesTableExist:k7,stringifyObj:V7,ms_to_time:$7,changeExtension:Y7,getEnvCliRootPath:PT,noBootFile:K7,httpRequest:W7,transformReq:Q7,convertToMS:z7,PACKAGE_ROOT:Ge.PACKAGE_ROOT};function _7(e){return e instanceof Error?e:new Error(e)}o(_7,"errorizeMessage");function hr(e){return e==null}o(hr,"isEmpty");function d7(e){return!hr(e)&&(e||e===0||e===""||vv(e))}o(d7,"isNotEmptyAndHasValue");function gs(e){return hr(e)||e.length===0||e.size===0}o(gs,"isEmptyOrZeroLength");function E7(e){if(hr(e))return!0;for(let t=0;t<e.length;t++)if(hr(e[t]))return!0;return!1}o(E7,"arrayHasEmptyValues");function f7(e){if(gs(e))return!0;for(let t=0;t<e.length;t++)if(gs(e[t]))return!0;return!1}o(f7,"arrayHasEmptyOrZeroLengthValues");function h7(...e){try{return e.join(Bn.sep)}catch{console.error(e)}}o(h7,"buildFolderPath");function vv(e){return hr(e)?!1:e===!0||e===!1}o(vv,"isBoolean");function m7(e){return hr(e)?!1:typeof e=="object"}o(m7,"isObject");function S7(e){return gs(e)?u7:e.slice(0,-l7)}o(S7,"stripFileExtension");function p7(e){return hr(e)||e===""||typeof e!="string"?e:Lv[e]!==void 0?Lv[e]:Hv(e)===!0?Number(e):a7.test(e)?new Date(e):e}o(p7,"autoCast");function Bv(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}o(Bv,"autoCastJSON");function MT(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=MT(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=MT(r);s!==r&&(e[t]=s)}return e}else return Bv(e)}o(MT,"autoCastJSONDeep");function Hv(e){if(e.startsWith("0.")&&Dv(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Dv(e))}o(Hv,"autoCasterIsNumberCheck");async function T7(e){if(gs(e))throw new Error(`Directory path: ${e} does not exist`);try{await Cv.emptyDir(e),await Cv.remove(e)}catch(t){throw jt.error(`Error removing files in ${e} -- ${t}`),t}}o(T7,"removeDir");function R7(e,t){if(gs(e)){jt.info("Invalid current version sent as parameter.");return}if(gs(t)){jt.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,a=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(a.length,c.length);for(let l=0;l<u;l++)if(r=parseInt(a[l],10)-parseInt(c[l],10),r)return r;return a.length-c.length}o(R7,"compareVersions");function g7(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}o(g7,"isCompatibleDataVersion");function A7(e){if(hr(e))return e;let t=String(e);return t==="."?Ge.UNICODE_PERIOD:t===".."?Ge.UNICODE_PERIOD+Ge.UNICODE_PERIOD:t.replace(Ge.FORWARD_SLASH_REGEX,Ge.UNICODE_FORWARD_SLASH)}o(A7,"escapeRawValue");function O7(e){if(hr(e))return e;let t=String(e);return t===Ge.UNICODE_PERIOD?".":t===Ge.UNICODE_PERIOD+Ge.UNICODE_PERIOD?"..":String(e).replace(Ge.ESCAPED_FORWARD_SLASH_REGEX,"/")}o(O7,"unescapeValue");function N7(e,t){if(hr(e))return jt.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let a of i)r+=";"+a+kd.EOL}!gs(s)&&s[0]===";"?r+=" "+s+n+kd.EOL:gs(s)||(r+=s+"="+n+kd.EOL)}catch{jt.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}o(N7,"stringifyProps");function Fv(){let e;try{e=kd.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}o(Fv,"getHomeDir");function b7(){let e=Bn.join(Fv(),Ge.HDB_HOME_DIR_NAME,Ge.BOOT_PROPS_FILE_NAME);return Mv.existsSync(e)||(e=Bn.join(__dirname,"../","hdb_boot_properties.file")),e}o(b7,"getPropsFilePath");function y7(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}o(y7,"timeoutPromise");async function I7(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=j9.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}o(I7,"isPortTaken");function w7(e){try{return Ge.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){jt.error(`Error checking operation against cluster ops ${t}`)}return!1}o(w7,"isClusterOperation");function C7(e,t){let r=(de(),re(Ne)).getDatabases();if(!r[e])return $d.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return $d.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(C7,"checkGlobalSchemaTable");function U7(e,t){if(hr(t)){jt.warn("No CLUSTERING_USER defined, clustering disabled");return}if(hr(e)||gs(e)){jt.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){jt.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){jt.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}o(U7,"getClusterUser");function D7(){Uv.parsePromise=function(e,t,r){return new Promise(function(s,n){Uv.parse(e,{header:!0,transformHeader:qv,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}o(D7,"promisifyPapaParse");function qv(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}o(qv,"removeBOM");function L7(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;jt.info(`Got cluster status event response: ${r7(n)}`);try{i.cancel()}catch{jt.error("Error trying to cancel timeout.")}s(n)})})}o(L7,"createEventPromise");async function M7(e){let t=!0,r=0;do await Pv(o7*r++),(await t7.findPs(e)).length>0&&(t=!1);while(t&&r<c7);if(t)throw new Error(`process ${e} was not started`)}o(M7,"checkProcessRunning");function P7(e,t){let r=Gv(e);if(r)return r;let s=xv(e,t);if(s)return s}o(P7,"checkSchemaTableExist");function Gv(e){let{getDatabases:t}=(de(),re(Ne));if(!t()[e])return $d.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(Gv,"checkSchemaExists");function xv(e,t){let{getDatabases:r}=(de(),re(Ne));if(!r()[e][t])return $d.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(xv,"checkTableExists");function v7(){let e=Vd().utc().add(1,Ge.MOMENT_DAYS_TAG).startOf(Ge.MOMENT_DAYS_TAG).unix(),t=Vd().utc().unix();return e-t}o(v7,"getStartOfTomorrowInSeconds");function B7(){return Vd().utc().format("DD-MM-YYYY")}o(B7,"getLimitKey");function H7(e){try{let t=new e7(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){jt.error("Got an error back ticking items."),jt.error(t)}}o(H7,"backtickASTSchemaItems");function F7(e){return[e]}o(F7,"createForkArgs");function q7(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}o(q7,"autoCastBoolean");function G7(e,t){let{getDatabases:r}=(de(),re(Ne)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}o(G7,"getTableHashAttribute");function x7(e){let{getDatabases:t}=(de(),re(Ne));return t()[e]!==void 0}o(x7,"doesSchemaExist");function k7(e,t){let{getDatabases:r}=(de(),re(Ne));return r()[e]?.[t]!==void 0}o(k7,"doesTableExist");function V7(e){try{return JSON.stringify(e)}catch{return e}}o(V7,"stringifyObj");function $7(e){let t=Vd.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}o($7,"ms_to_time");function Y7(e,t){let r=Bn.basename(e,Bn.extname(e));return Bn.join(Bn.dirname(e),r+t)}o(Y7,"changeExtension");function PT(){if(process.env[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=s7(process.argv);if(e[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}o(PT,"getEnvCliRootPath");var LT;function K7(){if(LT)return LT;let e=PT();PT()&&Mv.pathExistsSync(Bn.join(e,Ge.HDB_CONFIG_FILE))&&(LT=!0)}o(K7,"noBootFile");function W7(e,t){let r;return e.protocol==="http:"?r=i7:r=n7,new Promise((s,n)=>{let i=r.request(e,a=>{a.setEncoding("utf8");let c={body:"",headers:a.headers};a.on("data",u=>{c.body+=u}),a.on("end",()=>{s(c)})});i.on("error",a=>{n(a)}),i.write(JSON.stringify(t)),i.end()})}o(W7,"httpRequest");function Q7(e){if(!e.schema&&!e.database){e.schema=Ge.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}o(Q7,"transformReq");function z7(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}o(z7,"convertToMS")});var Q=m((G_e,Yv)=>{"use strict";var vT=require("fs-extra"),zr=require("path"),Vv=require("os"),J7=require("properties-reader"),Qc=q(),Ci=x(),ee=g(),Yd=Ar(),X7="Error initializing environment manager",Kd="BOOT_PROPS_FILE_PATH",$v=!1,Z7={[ee.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},rn={};Yv.exports={BOOT_PROPS_FILE_PATH:Kd,getHdbBasePath:j7,setHdbBasePath:eee,get:tee,initSync:see,setProperty:Ee,initTestEnvironment:nee};function j7(){return rn[ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}o(j7,"getHdbBasePath");function eee(e){rn[ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}o(eee,"setHdbBasePath");function tee(e){let t=Yd.getConfigValue(e);return t===void 0?rn[e]:t}o(tee,"get");function Ee(e,t){Z7[e]&&(rn[e]=t),Yd.updateConfigObject(e,t)}o(Ee,"setProperty");function ree(){let e;try{e=Ci.getPropsFilePath(),vT.accessSync(e,vT.constants.F_OK|vT.constants.R_OK),$v=!0;let t=J7(e);return rn[ee.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ee.HDB_SETTINGS_NAMES.INSTALL_USER),rn[ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),rn[Kd]=e,!0}catch{return Qc.trace(`Environment manager found no properties file at ${e}`),!1}}o(ree,"doesPropFileExist");function see(e=!1){try{($v||ree()||Ci.noBootFile())&&(Yd.initConfig(e),rn[ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Yd.getConfigValue(ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Qc.error(X7),Qc.error(t),console.error(t),process.exit(1)}}o(see,"initSync");function nee(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:a,local_studio_on:c}=e,u=zr.join(__dirname,"../../","unitTests");rn[Kd]=zr.join(u,"hdb_boot_properties.file"),Ee(ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,zr.join(u,"settings.test")),Ee(ee.HDB_SETTINGS_NAMES.INSTALL_USER,Vv.userInfo()?Vv.userInfo().username:void 0),Ee(ee.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,zr.join(u,"envDir","utility","keys","privateKey.pem")),Ee(ee.HDB_SETTINGS_NAMES.CERT_KEY,zr.join(u,"envDir","utility","keys","certificate.pem")),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,zr.join(u,"envDir","utility","keys","privateKey.pem")),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,zr.join(u,"envDir","utility","keys","certificate.pem")),Ee(ee.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ee(ee.HDB_SETTINGS_NAMES.LOG_PATH_KEY,zr.join(u,"envDir","log")),Ee(ee.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ee(ee.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ee(ee.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ee(ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,zr.join(u,"envDir")),Ee(ee.CONFIG_PARAMS.STORAGE_PATH,zr.join(u,"envDir")),Ee(ee.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Ci.isEmpty(n)?!0:n),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Ci.isEmpty(n)?!0:n),Ee(ee.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ee(ee.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ci.isEmpty(i)?!1:i),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Ci.isEmpty(i)?!1:i),Ee(ee.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ee(ee.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ee(ee.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ee(ee.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ee(ee.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,zr.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ee(ee.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ci.isEmpty(c)?!1:c),a&&(Ee("CORS_ACCESSLIST",a),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,a)),s&&(Ee(ee.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(Ee(ee.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(Ee(ee.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Kd}. Please check your boot props and settings files`;Qc.fatal(r),Qc.error(t)}}o(nee,"initTestEnvironment")});var rt=m((K_e,lB)=>{"use strict";var yt=Q();yt.initSync();var iee=require("fs-extra"),aee=require("semver"),Zc=require("path"),{monotonicFactory:oee}=require("ulidx"),qT=oee(),cee=require("util"),Wv=require("child_process"),uee=cee.promisify(Wv.exec),lee=Wv.spawn,_e=Be(),Re=g(),Wd=x(),Dr=q(),Qd=Ls(),_ee=Al(),zc=Ar(),{Encoder:dee,decode:GT}=require("msgpackr"),Qv=new dee,{isEmpty:Ui}=Wd,zv=Or(),Jv=12e10,Eee=48*36e11,fee=5e9,{connect:hee,StorageType:Xv,RetentionPolicy:Zv,AckPolicy:zd,DeliverPolicy:Jd,DiscardPolicy:mee,NatsConnection:k_e,JetStreamManager:V_e,JetStreamClient:$_e,StringCodec:Y_e,JSONCodec:See,createInbox:xT,headers:pee,ErrorCode:Kv}=require("nats"),{PACKAGE_ROOT:Tee}=g(),Ree=$o(),{recordAction:gee}=(Ra(),re(k_)),jv=See(),Aee="clustering",Oee=Ree.engines[_e.NATS_SERVER_NAME],Nee=Zc.join(Tee,"dependencies"),FT=Zc.join(Nee,`${process.platform}-${process.arch}`,_e.NATS_BINARY_NAME),BT,HT,Jc,Ha,Fa;lB.exports={runCommand:eB,checkNATSServerInstalled:bee,createConnection:kT,getConnection:Xd,getJetStreamManager:jc,getJetStream:tB,getNATSReferences:er,getServerList:Iee,createLocalStream:VT,listStreams:rB,deleteLocalStream:wee,getServerConfig:eu,listRemoteStreams:Cee,viewStream:Uee,viewStreamIterator:Dee,publishToStream:Lee,createWorkQueueStream:Mee,addSourceToWorkStream:nB,request:vee,removeSourceFromWorkStream:aB,reloadNATS:$T,reloadNATSHub:Bee,reloadNATSLeaf:Hee,extractServerName:iB,requestErrorHandler:Fee,updateWorkStream:qee,createLocalTableStream:cB,createTableStreams:Gee,purgeTableStream:uB,purgeSchemaTableStreams:xee,getStreamInfo:kee,updateLocalStreams:$ee,closeConnection:yee,getJsmServerName:tu,addNatsMsgHeader:sB,updateIngestStreamConsumer:Pee};async function eB(e,t=void 0){let{stdout:r,stderr:s}=await uee(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
24
|
+
`+Kp.readFileSync(o):"")};s.http2=!0,s.https=c}return s}a(G6,"getServerOptions");function x6(){let e=Wr.get(U6),t=Wr.get(D6),r;return e&&(e===!0||e.toUpperCase()===sP)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(x6,"getCORSOpts");function k6(){return Wr.get(P6)}a(k6,"getHeaderTimeoutConfig")});var Zp={};je(Zp,{disableNATS:()=>$6,setNATSReplicator:()=>Wp,start:()=>V6});function V6(){Rd.default.get(gd.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&K6()}function $6(e=!0){lP=e}function K6(){if(lP)return;let e=Gr(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];Wp(n,r,i)}}jp((r,s)=>{Wp(r.tableName,r.databaseName,r),s&&dP(r)}),!oP&&(oP=!0)}function Wp(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.Source?.isNATSReplicator)return;let s;r.sourcedFrom(class extends ht{static{a(this,"NATSReplicator")}put(o){let c;return s?.put&&(!s.put.reliesOnPrototype||s.prototype.put)&&(c=s.put(this[ae],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[ae],record:o},c)}delete(){let o;return s?.delete&&(!s.delete.reliesOnPrototype||s.prototype.delete)&&(o=s.delete(this[ae],this.getContext())),n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[ae]},o)}publish(o){let c;return s?.publish&&(!s.publish.reliesOnPrototype||s.prototype.publish)&&(c=s.publish(this[ae],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[ae],record:o},c)}invalidate(o){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[ae]})}static defineSchema(o){dP(o)}static mergeSource(o,c){return s=o,s?.get&&(!s.get.reliesOnPrototype||s.prototype.get)&&(c?.replicationSource?this.get=async(u,l)=>{let _=await s.get(u,l);return _&&n(l).addWrite(t,{operation:"put",table:e,id:u,record:_}),_}:this.get=(u,l)=>s.get(u,l)),this}static subscribe(){let o=new Jr;return(0,aP.setSubscription)(t,e,o),o}static subscribeOnThisThread(o){return o<Y6}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0});function n(i){let o=i?.transaction?.nats;return o||(i?.transaction?(i.transaction.push(o=i.transaction.nats=new Td(i.transaction,i)),o.user=i.user):o=_P),o}a(n,"getNATSTransaction")}function dP(e){let t=Rd.default.get(gd.default.CONFIG_PARAMS.CLUSTERING_NODENAME);(0,zp.publishToStream)(`${Jp.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,Xp.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var zp,Jp,Xp,aP,cP,Rd,gd,uP,lP,Y6,_P,oP,Td,Qp,EP=Se(()=>{de();Xr();zp=C(nt()),Jp=C(Be()),Xp=C(Ps());na();aP=C(eT()),cP=C(vt()),Rd=C(Q()),gd=C(A()),uP=C(x());a(V6,"start");a($6,"disableNATS");Y6=2;a(K6,"assignReplicationSource");a(Wp,"setNATSReplicator");a(dP,"publishSchema");Td=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r,s){let n=this.writes_by_db.get(t);if(n||this.writes_by_db.set(t,n=[]),s?.then)return s.then(()=>n.push(r));n.push(r)}commit(t){let r=Rd.default.get(gd.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,l;for(let _ of i){let d=_.table,E=_.operation=="put"?"upsert":_.operation;u||(uP.trace(`Sending transaction event ${E}`),l=u={operation:E,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(_.record),c.push(_.id)):l=l.next={operation:E,table:d,id:_.id,record:_.record}}s.push((0,zp.publishToStream)(`${Jp.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,Xp.createNatsTableStreamName)(n,u.table),void 0,u))}return Promise.all(s)}},Qp=class extends Td{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,cP.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit()}};_P=new Qp});async function hP({clientId:e,user:t,listener:r,clean:s}){let n;if(e&&!s){let i=await tT.getResource(e,{});n=new sT(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await tT.get(e);i&&i.delete()}n=new Od(e,t)}return n}function rT(){return Ad++,Ad>65500&&(Ad=1),Ad}var fP,Bc,tT,Ad,Od,sT,mP=Se(()=>{de();_c();fP=C(vt()),Bc=C(x());xn();tT=rt({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]});a(hP,"getSession");Ad=1;a(rT,"getNextMessageId");Od=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,omitCurrent:i,startTime:o}=t,c=n.indexOf("?"),u,l;if(c>-1?(u=n.slice(c),l=n.slice(0,c)):l=n,!l)throw new Error("No topic provided");let _=!1,d;if((l.endsWith("+")||l.endsWith("#"))&&(_=!0,l.endsWith("+")&&(d=!0),l=l.slice(0,l.length-1)),l.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");if(l.indexOf("#")>-1||l.indexOf("+")>-1)throw new Error("Only trailing wildcards are supported");let E=this.subscriptions.find(O=>O.topic===n);E&&(E.end(),this.subscriptions.splice(this.subscriptions.indexOf(E),1));let f={search:u,user:this.user,startTime:o,omitCurrent:i,isCollection:_,shallowWildcard:d,url:""},h=In.getMatch(l);if(!h)throw new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);f.url=h.relativeURL;let T=h.path,p=h.Resource,R=await Ye(f,async()=>{let O=await p.subscribe(f);if(!O)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!O[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let k of O)try{let $;if(k.type&&k.type!=="put"&&k.type!=="delete"&&k.type!=="message"||s&&!s(k))continue;r?(k.topic=n,$=this.needsAcknowledge(k)):$=rT();let U=k.id;Array.isArray(U)&&(U=fo(U)),U==null&&(U=""),this.listener(T+"/"+U,k.value,$,t)}catch($){(0,Bc.warn)($)}})(),O});return R.topic=n,R.qos=t.qos,this.subscriptions.push(R),R}resume(){}needsAcknowledge(t){return rT()}acknowledge(t){}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);r&&r.end()}async publish(t,r){let{topic:s,retain:n}=t;t.data=r,t.user=this.user;let i=In.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);t.url=i.relativeURL;let o=i.Resource;return Ye(t,()=>n?r===void 0?o.delete(t,t):o.put(t,t.data,t):o.publish(t,t.data,t))}setListener(t){this.listener=t}disconnect(){for(let t of this.subscriptions)t.end();this.subscriptions=[]}},sT=class extends Od{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=rT();return this.awaitingAcks.set(r,{topic:t.topic,timestamp:t.timestamp}),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t);let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Bc.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,fP.getNextMonotonicTime)()),(0,Bc.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),tT.put(this.sessionRecord)),t.qos}}});var oT={};je(oT,{start:()=>Q6});async function Q6({server:e,port:t,webSocket:r,securePort:s,requireAuthentication:n}){let i=e.mqtt={requireAuthentication:n};r&&e.ws((o,c,u)=>{if(o.protocol==="mqtt"){let{onMessage:l,onClose:_}=TP(o,(d,E)=>{if(o.send(d),E&&o._socket.writableNeedDrain)return new Promise(f=>this._socket.once("drain",f))},c,Promise.resolve(u).then(()=>c?.user),i);o.on("message",l),o.on("close",_),o.on("error",d=>{(0,tn.info)("WebSocket error",d)})}},{subProtocol:"mqtt"}),(t||s)&&e.socket(async o=>{let c;W6&&o.remoteAddress.includes("127.0.0.1")&&(c=await(0,RP.getSuperUser)());let{onMessage:u,onClose:l}=TP(o,_=>o.write(_),null,c,i);o.on("data",u),o.on("close",l),o.on("error",_=>{(0,tn.info)("Socket error",_)})},{port:t,securePort:s})}function TP(e,t,r,s,n){pP||(pP=!0,np(_=>{_.push({metric:"mqtt-connections",connections:nT})})),nT++;let i,o={protocolVersion:4},c=(0,Nd.parser)({protocolVersion:5});function u(_){c.parse(_)}a(u,"onMessage");function l(){nT--,i?.disconnect()}return a(l,"onClose"),c.on("packet",async _=>{s?.then&&(s=await s),i?.then&&await i;try{switch(_.cmd){case"connect":if(o.protocolVersion=_.protocolVersion,_.username)try{s=await tt.auth(_.username,_.password.toString()),(0,iT.get)(rn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&SP.notify({username:s.username,status:rn.AUTH_AUDIT_STATUS.SUCCESS,type:rn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,iT.get)(rn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&SP.error({username:s.username,status:rn.AUTH_AUDIT_STATUS.FAILURE,type:rn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),d({cmd:"connack",reasonCode:134,returnCode:134})}if(!s&&n.requireAuthentication)return d({cmd:"connack",reasonCode:134,returnCode:134});try{n.authorizeClient?.(_,s),i=hP({user:s,..._}),i=await i}catch(O){return(0,tn.error)(O),d({cmd:"connack",reasonCode:O.code||128,returnCode:O.code||128})}d({cmd:"connack",sessionPresent:i.sessionWasPresent,reasonCode:0,returnCode:0}),i.setListener((O,k,$,U)=>{try{let b=O.indexOf("/",1),P=b>0?O.slice(0,b):O;d({cmd:"publish",topic:O,payload:E(k),messageId:$||Math.floor(Math.random()*1e8),qos:U.qos},P)}catch(b){(0,tn.error)(b),i?.disconnect()}}),i.sessionWasPresent&&await i.resume();break;case"subscribe":let f=[];for(let O of _.subscriptions){let k;try{k=(await i.addSubscription(O,O.qos>=1)).qos||0}catch($){(0,tn.error)($),k=128}f.push(k)}await i.committed,d({cmd:"suback",granted:f,messageId:_.messageId});break;case"unsubscribe":for(let O of _.unsubscriptions)i.removeSubscription(O);d({cmd:"unsuback",messageId:_.messageId});break;case"pubrel":d({cmd:"pubcomp",messageId:_.messageId,reasonCode:0});return;case"publish":let h=_.qos===2?"pubrec":"puback",T=e.deserialize||(e.deserialize=Ao(r?.headers["content-type"])),p=_.payload?.length>0?T(_.payload):void 0,R;try{R=await i.publish(_,p)}catch(O){console.warn(O),_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:128},_.topic)}_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:R===!1?144:0},_.topic);break;case"pubrec":d({cmd:"pubrel",messageId:_.messageId,reasonCode:0});break;case"pubcomp":case"puback":i.acknowledge(_.messageId);break;case"pingreq":d({cmd:"pingresp"});break;case"disconnect":i?.disconnect(),e.close?e.close():e.end();break}}catch(f){console.error(f),d({cmd:"disconnect"})}function d(f,h){let T=(0,Nd.generate)(f,o);t(T),Ss(T.length,"bytes-sent",h,f.cmd,"mqtt")}a(d,"sendPacket");function E(f){return r?Ks(f,r):JSON.stringify(f)}a(E,"serialize")}),{onMessage:u,onClose:l}}var Nd,RP,iT,rn,tn,SP,W6,pP,nT,gP=Se(()=>{Nd=require("mqtt-packet");mP();RP=C(br());So();hi();es();iT=C(Q()),rn=C(A()),tn=C(x()),SP=(0,tn.loggerWithTag)("auth-event"),W6=!0;a(Q6,"start");nT=0;a(TP,"onSocket")});var DP={};je(DP,{loadComponent:()=>bd,loadComponentDirectories:()=>UP});function UP(e,t){t&&(cT=t),e&&(uT=e);let r=[];if((0,Ts.existsSync)(aT)){let n=(0,Ts.readdirSync)(aT,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Lr.join)(aT,o);r.push(bd(c,cT,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(bd(s,cT,s)),Promise.all(r).then(()=>{CP=!0})}async function bd(e,t,r,s,n){if(!OP.has(e)){OP.set(e,!0),n&&(uT=n);try{let i,o=(0,Lr.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Ts.existsSync)(o)?i=(0,NP.parseDocument)((0,Ts.readFileSync)(o,"utf8"),{simpleKeys:!0}).toJSON():i=Z6;let c=[];for(let u in i){let l=i[u];if(!l)continue;let _,d=l.package;if(d){let E=e,f;for(;!(0,Ts.existsSync)(f=(0,Lr.join)(E,"node_modules",u));)if(E=(0,Lr.dirname)(E),E.length<(0,wP.getHdbBasePath)().length){f=null;break}if(f)_=await bd(f,t,r,!1);else throw new Error(`Unable to find package ${u}:${d}`)}else _=X6[u];if(_)try{c.push(_);let E=a(p=>(p.origin=r,rt(p)),"ensureTable"),f=l.network||(l.port||l.securePort)&&l,h=f?.securePort||f?.https&&f.port,T=!f?.https&&f?.port;if(Hc.isMainThread&&(_=await _.startOnMainThread?.({server:tt,ensureTable:E,port:T,securePort:h,resources:t,...l})||_,s&&f))for(let p of[T,h])try{if(+p&&!AP.includes(p)){AP.push(p);let R=lT.get(_T.CONFIG_PARAMS.HTTP_SESSION_AFFINITY);jM(p,R)}}catch(R){console.error("Error listening on socket",p,R,u)}if(t.isWorker&&(_=await _.start?.({server:tt,ensureTable:E,port:T,securePort:h,resources:t,...l})||_),uT.set(_,!0),_.handleFile&&l.files){if(l.files.includes(".."))throw(0,IP.handleHDBError)("Can not reference parent directories");let p=(0,Lr.join)(e,l.files);for(let R of await(0,bP.default)(p,{onlyFiles:!1,objectMode:!0})){let{path:O,dirent:k}=R,$=(0,Lr.relative)(e,O),U=(0,Lr.basename)(e),b=l.path||"/";b=b.startsWith("/")?b:b.startsWith("./")?"/"+U+b.slice(2):b==="."?"/"+U:"/"+U+"/"+b,b+=(b.endsWith("/")?"":"/")+$;try{if(k.isFile()){let P=await J6(O);Hc.isMainThread&&await _.setupFile?.(P,b,O,t),t.isWorker&&await _.handleFile?.(P,b,O,t)}else Hc.isMainThread&&await _.setupDirectory?.(b,O,t),t.isWorker&&await _.handleDirectory?.(b,O,t)}catch(P){console.error(`Could not load ${k.isFile()?"file":"directory"} ${O} using ${l.module} for application ${e}`,P),t.set(l.path||"/",new Fc(P))}}}}catch(E){console.error(`Could not load component ${u} for application ${e}`,E),t.set(l.path||"/",new Fc(E),null,!0)}}if(Hc.isMainThread&&!CP&&(0,yP.watchDir)(e,async()=>UP()),i.extensionModule)return await Cu((0,Lr.join)(e,i.extensionModule))}catch(i){console.error(`Could not load application directory ${e}`,i),t.set("",new Fc(i))}}}var Ts,Lr,Hc,NP,lT,_T,bP,yP,IP,wP,z6,J6,aT,uT,CP,cT,X6,Z6,AP,OP,Fc,LP=Se(()=>{Ts=require("fs"),Lr=require("path"),Hc=require("worker_threads"),NP=require("yaml"),lT=C(Q()),_T=C(A());hg();Tg();Rg();iL();$M();QM();bP=C(require("fast-glob")),yP=C(dt());vE();es();IP=C(W());Xr();de();eP();wP=C(Q()),z6=C(iP());g_();EP();gP();({readFile:J6}=Ts.promises),aT=lT.get(_T.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),uT=new Map;a(UP,"loadComponentDirectories");X6={REST:cp,graphqlSchema:PE,jsResource:HE,fastifyRoutes:xp,login:qE,static:kp,operationsApi:z6,customFunctions:{},clustering:Zp,authentication:dc,mqtt:oT},Z6={REST:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}},AP=[],OP=new Map;a(bd,"loadComponent");Fc=class extends ht{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var FP=m((d_e,HP)=>{"use strict";var wd=require("fs-extra"),dT=require("path"),yd=x(),MP=V(),Id=A(),BP=Q(),j6=Nr();HP.exports=e9;async function e9(){let e=t9(),t=BP.get(Id.CONFIG_PARAMS.ROOTPATH),r=dT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+Id.PACKAGE_ROOT}},n=dT.join(t,"node_modules");await wd.ensureDir(n);let i,o=!0,c=!1;try{i=await wd.readJson(r)}catch(u){if(MP.isEmptyOrZeroLength(e))return;if(u.code!==Id.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!MP.isEmptyOrZeroLength(e)){for(let{name:u,package:l}of e){let _=await PP(l);s.dependencies[u]=_+l}if(!o){yd.notify("Installing components"),await vP(r,s);return}for(let{name:u,package:l}of e){let _=i.dependencies[u],d=await PP(l);if(_===void 0||_!==d+l){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(yd.notify("Removing component",u),c=!0);c&&(yd.notify("Updating components."),await vP(r,s))}a(e9,"installComponents");function t9(){let e=j6.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(t9,"getComponentsConfig");async function PP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":dT.extname(e)||await wd.pathExists(e)?"file:":"github:"}a(PP,"getPkgPrefix");async function vP(e,t){yd.trace("npm installing components package.json",t),await wd.writeFile(e,JSON.stringify(t,null," ")),await C_().installAllRootModules(BP.get(Id.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}a(vP,"installPackages")});var xP=m((f_e,GP)=>{var{isMainThread:qP}=require("worker_threads"),{getTables:r9}=(de(),re(Ne)),{loadComponentDirectories:s9,loadComponent:n9}=(LP(),re(DP)),{resetResources:i9}=(_c(),re(RU)),o9=FP(),a9=Nr(),{dirname:c9}=require("path"),{getConnection:u9}=nt(),l9=Q(),_9=A(),ET=new Map;async function d9(e=!1){!qP&&l9.get(_9.CONFIG_PARAMS.CLUSTERING_ENABLED)&&u9(),qP&&await o9();let t=i9();r9(),t.isWorker=e,await n9(c9(a9.getConfigFilePath()),t,"hdb",!0,ET),await s9(ET,t);let r=[];for(let[s]of ET)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(d9,"loadRootComponents");GP.exports.loadRootComponents=d9});var dt=m((S_e,Pn)=>{"use strict";var{Worker:E9,MessageChannel:f9,parentPort:Rs,isMainThread:pT,threadId:h9,workerData:qc}=require("worker_threads"),{PACKAGE_ROOT:m9}=A(),{join:$P,isAbsolute:S9,extname:Ud}=require("path"),{server:p9}=(es(),re(wu)),{watch:T9,readdir:R9}=require("fs/promises"),{totalmem:kP}=require("os"),TT=A(),Oi=x(),m_e=A(),{randomBytes:g9}=require("crypto"),A9=1024*1024,Mn=[],Ln=[],O9=50,YP=1e4,N9="restart",KP="request_thread_info",WP="resource_report",QP="thread_info",zP="added-port",b9="ack",fT;Pn.exports={startWorker:hT,restartWorkers:RT,shutdownWorkers:C9,workers:Mn,setMonitorListener:H9,onMessageFromWorkers:U9,onMessageByType:D9,broadcast:L9,broadcastWithAcknowledgement:P9,setChildListenerByType:w9,getWorkerIndex:XP,getTicketKeys:ZP,setMainIsWorker:y9,restartNumber:qc?.restartNumber||1};var JP;function XP(){return qc?qc.workerIndex:JP?0:void 0}a(XP,"getWorkerIndex");function y9(e){JP=e}a(y9,"setMainIsWorker");var Cd;function ZP(){return Cd||(Cd=pT?g9(48):qc.ticketKeys,Cd)}a(ZP,"getTicketKeys");Object.defineProperty(p9,"workerIndex",{get(){return XP()}});var jP={[KP](e,t){v9(t)},[WP](e,t){B9(t,e)}};function hT(e,t={}){let r=process.constrainedMemory?.()||kP();r=Math.min(r,kP());let s=Math.max(Math.floor(r/A9/(1+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>7,16),64),i=[];for(let c of Ln){let{port1:u,port2:l}=new f9;c.postMessage({type:zP,port:u},[u]),i.push(l)}Ud(e)||(e+=".js");let o=new E9(S9(e)?e:$P(m9,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:i,workerIndex:t.workerIndex,name:t.name,restartNumber:Pn.exports.restartNumber,ticketKeys:ZP()},transferList:i},t));return Ld(o,!0),o.unexpectedRestarts=t.unexpectedRestarts||0,o.startCopy=()=>{hT(e,t)},o.on("error",c=>{console.error("Worker error:",c),Oi.error("Worker error:",c)}),o.on("exit",c=>{Mn.splice(Mn.indexOf(o),1),!o.wasShutdown&&t.autoRestart!==!1&&(o.unexpectedRestarts<O9?(t.unexpectedRestarts=o.unexpectedRestarts+1,hT(e,t)):Oi.error(`Thread has been restarted ${o.restarts} times and will not be restarted`))}),o.on("message",c=>{jP[c.type]?.(c,o)}),Mn.push(o),q9(),t.onStarted&&t.onStarted(o),o.name=t.name,o}a(hT,"startWorker");var I9=[TT.THREAD_TYPES.HTTP];async function RT(e=null,t=2,r=!0){if(pT){if(r){let{loadRootComponents:n}=xP();await n()}Pn.exports.restartNumber++,t<1&&(t=t*Mn.length);let s=[];for(let n of Mn.slice(0)){if(e&&n.name!==e||n.wasShutdown)continue;n.postMessage({restartNumber:Pn.exports.restartNumber,type:TT.ITC_EVENT_TYPES.SHUTDOWN}),n.wasShutdown=!0,n.emit("shutdown",{});let i=I9.indexOf(n.name)>-1,o=new Promise(c=>{let u=setTimeout(()=>n.terminate(),YP*2).unref();n.on("exit",()=>{clearTimeout(u),s.splice(s.indexOf(o)),!i&&r&&n.startCopy(),c()})});s.push(o),i&&r&&(n.startCopy(),s.length>=t&&await Promise.race(s))}await Promise.all(s)}else Rs.postMessage({type:N9,workerType:e})}a(RT,"restartWorkers");function w9(e,t){jP[e]=t}a(w9,"setChildListenerByType");function C9(e){return RT(e,1/0,!1)}a(C9,"shutdownWorkers");var ev=[];function U9(e){ev.push(e)}a(U9,"onMessageFromWorkers");var mT=new Map;function D9(e,t){let r=mT.get(e);r||mT.set(e,r=[]),r.push(t)}a(D9,"onMessageByType");function L9(e){for(let t of Ln)try{t.postMessage(e)}catch(r){Oi.error("Unable to send message to worker",r)}}a(L9,"broadcast");var Dd=new Map,M9=1;function P9(e){return new Promise(t=>{let r=0;for(let s of Ln)try{let n=M9++,i=a(()=>{Dd.delete(n),--r===0&&t(),s!==Rs&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,Dd.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of Dd)o.port===s&&o()})),s.postMessage(e),r++}catch(n){Oi.error("Unable to send message to worker",n)}r===0&&t()})}a(P9,"broadcastWithAcknowledgement");function v9(e){e.postMessage({type:QP,workers:tv()})}a(v9,"sendThreadInfo");function tv(){let e=Date.now();return Mn.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(tv,"getChildWorkerInfo");function B9(e,t){e.resources=t,e.resources.updated=Date.now()}a(B9,"recordResourceReport");var ST;function H9(e){ST=e}a(H9,"setMonitorListener");var F9=1e3,VP=!1;function q9(){VP||(VP=!0,setInterval(()=>{for(let e of Mn){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}ST&&ST()},F9).unref())}a(q9,"startMonitoring");var G9=1e3;if(Rs){Ld(Rs);for(let e of qc.addPorts)Ld(e);setInterval(()=>{let e=process.memoryUsage();Rs.postMessage({type:WP,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},G9).unref(),fT=a(()=>new Promise((e,t)=>{Rs.on("message",r),Rs.postMessage({type:KP});function r(s){s.type===QP&&(Rs.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else fT=tv;Pn.exports.getThreadInfo=fT;function Ld(e,t){Ln.push(e),e.on("message",r=>{if(r.type===zP)Ld(r.port);else if(r.type===b9){let s=Dd.get(r.id);s&&s()}else{for(let n of ev)n(r,e);let s=mT.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){Oi.error(i)}}}).on("close",()=>{Ln.splice(Ln.indexOf(e),1)}).on("exit",()=>{Ln.splice(Ln.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(Ld,"addPort");if(pT){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await R9(s,{withFileTypes:!0}))i.isDirectory()&&r($P(s,i.name));for await(let{filename:i}of T9(s,{persistent:!1}))(Ud(i)===".ts"||Ud(i)===".js"||Ud(i)===".graphql")&&(t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await RT(),Oi.info("Reloaded HarperDB components")},100))},"watch_dir");Pn.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else Rs.on("message",async e=>{let{type:t}=e;t===TT.ITC_EVENT_TYPES.SHUTDOWN&&(Pn.exports.restartNumber=e.restartNumber,Rs.unref(),setTimeout(()=>{Oi.warn("Thread did not voluntarily terminate",h9),process.exit(0)},YP).unref())})});function bT(e){let t=e.auditStore=e.openDB(ov.AUDIT_STORE_NAME,k9);t.rootStore=e;let r=[];return t.addDeleteRemovalCallback=function(s,n){return r[s]=n,{remove(){delete r[s]}}},(0,cv.getWorkerIndex)()===0&&e.on("aftercommit",()=>{AT||(AT=setTimeout(()=>{if(AT=null,t.rootStore.status!=="closed")for(let{key:s,value:n}of t.getRange({start:[0,0],end:[Date.now()-rv,0]})){if((n[0]&15)===NT){let i=s[1];r[i]?.(s[2])}t.remove(s)}},rv/10).unref())}),t}function vd(e,t,r){let s=_v[r.type],n=3;if(t?t.length>80?(s|=Md,n=(0,sn.writeKey)(t,gs,e?14:6),gT.setUint16(2,n)):(n=(0,sn.writeKey)(t,gs,e?11:3),gs[1]=n):gs[1]=0,e){s|=lv;let i=s&Md?6:3;gT.setFloat64(i,e),t||(n=i+8)}return gs[0]=s,s&Md?gT.setUint16(4,0):gs[2]=0,r.value?Buffer.concat([gs.slice(0,n),r.value]):gs.subarray(0,n)}function vn(e,t){let r=e[0],s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)),n=r&Md,i=n?6:3,o;r&lv&&(o=s.getFloat64(i),i+=8);let c;n?c=s.getUint16(2):c=e[1];let u=r&OT?t.decoder.decode(e.subarray(c||i)):void 0;return{type:_v[r&7],value:u,lastVersion:o,get user(){return c?(0,sn.readKey)(e,i,c):void 0}}}var sn,Pd,ov,av,cv,uv,gs,gT,x9,k9,rv,AT,OT,sv,NT,nv,iv,Md,lv,_v,Gc=Se(()=>{sn=require("ordered-binary"),Pd=C(Q()),ov=C(xe()),av=C(A()),cv=C(dt()),uv=C(V());(0,Pd.initSync)();gs=Buffer.alloc(1024),gT=new DataView(gs.buffer,gs.byteOffset,1024),x9={writeKey(e,t,r){if(Array.isArray(e)){let s=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength));return s.setFloat64(r,e[0]),s.setUint32(r+8,e[1]),(0,sn.writeKey)(e[2],t,r+12)}else return(0,sn.writeKey)(e,t,r)},readKey(e,t,r){if(e[t]>40){let s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength));return[s.getFloat64(t),s.getUint32(t+8),(0,sn.readKey)(e,t+12,r)]}else return(0,sn.readKey)(e,t,r)}},k9={encoding:"binary",keyEncoder:x9},rv=(0,uv.convertToMS)((0,Pd.get)(av.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,AT=null;a(bT,"openAuditStore");OT=16,sv=1,NT=2,nv=3,iv=4,Md=128,lv=64,_v={put:sv|OT,[sv]:"put",delete:NT,[NT]:"delete",message:nv|OT,[nv]:"message",invalidate:iv,[iv]:"invalidate"};a(vd,"createAuditEntry");a(vn,"readAuditEntry")});var yT,Ni,V9,xc,Bd,dv=Se(()=>{yT=C(vt());Gc();Ni=Symbol("completion"),V9=100,xc=class{static{a(this,"DatabaseTransaction")}writes=[];hasWrittenTime;username;lmdbDb;auditStore;readTxn;constructor(t,r,s){this.lmdbDb=t,this.username=r?.username,this.auditStore=s}getReadTxn(){return this.readTxn||(this.readTxn=this.lmdbDb.useReadTransaction())}resetReadSnapshot(){this.readTxn&&(this.readTxn.done(),this.readTxn=null)}addWrite(t){this.writes.push(t)}validate(){for(let t of this.writes||[])t.validate?.()}commit(t=(0,yT.getNextMonotonicTime)(),r=!0,s=0){this.resetReadSnapshot();let n,i=[],o=0,c;this.hasWrittenTime=!1;let u=a(_=>{let d=_.commit(t,s);if(d&&(d[Ni]&&(i||(i=[]),i.push(d[Ni])),c=_.store,this.auditStore)){d.user=this.username,d.lastVersion=_.lastVersion,d.newTxnTime&&!this.hasWrittenTime&&(t=d.newTxnTime),this.hasWrittenTime=!0;let E=[t,_.store.tableId,_.key];_.invalidated&&(E.invalidated=!0),this.auditStore.put(E,vd(_.lastVersion,this.username,d))}},"doWrite"),l=a(()=>{let _=this.writes[o++];if(_)if(_.key){let d=_.store.getEntry(_.key),E=s===0&&_.lastVersion!==void 0?_.lastVersion:_.lastVersion=d?.version??null,f=_.store.ifVersion(_.key,E,l);n=n||f}else l();else for(let d of this.writes)u(d)},"nextCondition");return this.writes.length<V9>>s?l():(s=1,n=this.writes[0].store.transaction(()=>{for(let _ of this.writes)u(_);return!0})),n?.then(_=>_?(c&&i.push(c.flushed),Promise.all(i).then(()=>(this.writes=[],{txnTime:t}))):this.commit(t,r,s+1))}abort(){this.resetReadSnapshot(),this.writes=[]}},Bd=class extends xc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit(this.timestamp)}get timestamp(){return this._timestamp||(this._timestamp=(0,yT.getNextMonotonicTime)())}getReadTxn(){}}});function mv(e,t,r,s,n){let i=e.primaryStore.env.path,o=e.primaryStore.tableId;Po||((0,bi.onMessageByType)(fv,d=>{let E=d.auditIds;wT(d.path,E,d.txnId)}),(0,bi.onMessageByType)(hv,d=>{(0,As.trace)("confirming to proceed with txn",d.txnId)}),Po=Object.create(null));let c=Po[i]||(Po[i]=[]);c.auditStore=e.auditStore;let u=c[o];u||(u=c[o]=new Map,u.envs=c,u.tableId=o,u.store=e.primaryStore),t=fo(t);let l=new IT(r);l.startTime=s,n&&(l.includeDescendants=n);let _=u.get(t);return _?_.push(l):(u.set(t,_=[l]),_.tables=u,_.key=t),l.subscriptions=_,l}function wT(e,t,r,s){if(!Po)return;let n=Po[e];if(n){if(Mo&&Mo+1!==r){(0,As.trace)("Waiting to ensure latest txn id",Mo,"proceeds",r,s);let i=(async()=>{for(let[o,c]of Hd)o<r&&((0,As.trace)("Txn",r,"waiting for txn",o),await c);if(Mo+1!==r){await(0,bi.broadcastWithAcknowledgement)({type:hv,txnId:r});for(let[o,c]of Hd)o<r&&((0,As.trace)("Txn",r,"waiting for txn",o),await c)}Hd.delete(r),(0,As.trace)("Proceeding with txn id",r),Mo=r-1,wT(e,t,r,s)})();return Hd.set(r,i),i}(0,As.trace)("Notifying with txn id",r,s),Mo=r;try{n.auditStore.resetReadTxn()}catch(i){throw i.message+=" in "+e,i}e:for(let i of t){let[o,c,u]=i,l=n[c];if(!l)continue;(0,Ev.writeKey)(i,Y9,0);let _=i[3];_&&(i.length=3);let d,E=fo(u),f;do{let h=l.get(E);if(h){for(let p of h)if(!(f&&!p.includeDescendants)){if(p.startTime>=o){(0,As.info)("omitting",u,p.startTime,o);continue}try{if(p.crossThreads===!1&&!s)continue;if(d===void 0){let R=n.auditStore.get(i);if(!R||(d=vn(R,l.store),d.type!=="message"&&l.store.getEntry(i[2])?.version!==i[0])||_&&d.type!=="invalidate")continue e}p.listener(u,d,o)}catch(R){console.error(R),(0,As.info)(R)}}}if(E==null)break;let T=E.lastIndexOf?.("/",E.length-2);T>-1?E=E.slice(0,T+1):E=null,f=!0}while(!0)}}}function Sv(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u,l=[];if(t)do{if(i.flag&$9)continue;let _;i.meta&&i.meta.store===t&&(_=i.meta.key)&&(typeof _[2]=="symbol"&&(_[2]=null),_.invalidated&&(_[3]=!0),l.push(_))}while(i!=o&&(i=i.next));l.length!==0&&((0,bi.broadcast)({type:fv,path:n,auditIds:l,txnId:c,start:u}),wT(n,l,c,!0))})}}var As,bi,Ev,fv,hv,$9,Po,Y9,IT,Mo,Hd,pv=Se(()=>{As=C(x()),bi=C(dt()),Ev=require("ordered-binary");na();_c();Gc();fv="transaction",hv="transaction-await",$9=67108864,Y9=Buffer.alloc(4096);a(mv,"addSubscription");IT=class extends Jr{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}},Hd=new Map;a(wT,"notifyFromTransactionData");a(Sv,"listenToCommits")});var Np={};je(Np,{coerceType:()=>Fd,makeTable:()=>Gd,setServerUtilities:()=>J9});function Gd(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:l,dbisDB:_}=e,{expirationMS:d,audit:E,trackDeletes:f}=e,{attributes:h}=e;h||(h=[]),Sv(i,u);let T=0,p,R,O,k={},$,U,b,P;for(let Z of h)(Z.assignCreatedTime||Z.name==="__createdtime__")&&($=Z),(Z.assignUpdatedTime||Z.name==="__updatedtime__")&&(U=Z),Z.expiresAt&&(b=Z),Z.isPrimaryKey&&(k=Z);let z;E&&JT();class F extends ht{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=h;static expirationTimer;static createdTimeProperty=$;static updatedTimeProperty=U;static dbisDB=_;static schemaDefined=l;static sourcedFrom(S,N){if(N&&(this.sourceOptions=N,N.expiration&&this.setTTLExpiration(N.expiration)),this.Source)if(this.Source.mergeSource)this.Source=this.Source.mergeSource(S,this.sourceOptions);else if(S.mergeSource)this.Source=S.mergeSource(this.Source,this.sourceOptions);else throw new Error("Can not assign multiple sources to a table with no source providing a (static) mergeSource method");else this.Source=S;return R=S&&S.get&&(!S.get.reliesOnPrototype||S.prototype.get),(async()=>{let D=!1,y=a(async w=>{let v=w.value,q=w.table?Pe[c][w.table]:F;if(c===Qr.SYSTEM_SCHEMA_NAME&&(w.table===Qr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||w.table===Qr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),w.id===void 0&&(w.id=v[q.primaryKey],w.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(w));let L=await q.getResource(w.id,w,kc);switch(w.type){case"put":return L._writeUpdate(v,kc);case"delete":return L._writeDelete(kc);case"publish":return L._writePublish(v,kc);case"invalidate":return L.invalidate(kc);default:wi.error("Unknown operation",w.type,w.id)}},"writeUpdate");try{let w=S.subscribe&&(!S.subscribe.reliesOnPrototype||S.prototype.subscribe);w&&f==null&&(f=!0);let v=S.subscribeOnThisThread?S.subscribeOnThisThread((0,Ii.getWorkerIndex)()):(0,Ii.getWorkerIndex)()===0,q=w&&v&&await S.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(q)for await(let L of q)try{if(!(L.type==="transaction"?L.writes[0]:L)){console.error("Bad subscription event");continue}let X=Ye(L,()=>{if(L.type==="transaction"){let J=[];for(let Y of L.writes){Y[Ae]=L;try{J.push(y(Y))}catch(j){throw j.message+=" writing "+JSON.stringify(Y)+" of event "+JSON.stringify(L),j}}return Promise.all(J)}else if(L.type==="define_schema"){let J=this.attributes.slice(0),Y;for(let j of L.attributes)J.find(De=>De.name===j.name)||(J.push(j),Y=!0);Y&&(rt({table:n,database:c,attributes:J,origin:"cluster"}),Yc.signalSchemaChange(new Kc.SchemaEventMsg(process.pid,Qr.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return y(L)});L.onCommit&&(X?.then&&D&&Yc.signalUserChange(new Kc.UserEventMsg(process.pid)),X?.then?X.then(L.onCommit):L.onCommit())}catch(G){console.error("error in subscription handler",G)}}catch(w){console.error(w)}})(),this}static getResource(S,N,D){let y=super.getResource(S,N,D);if(S!=null)try{if(y.hasOwnProperty(ce))return y;let w=y._txnForRequest();if(typeof S=="object"&&S&&!Array.isArray(S))throw new Error(`Invalid id ${JSON.stringify(S)}`);let v,q,G={transaction:w?.getReadTxn()},X;return iu(S,N,G,y,D?.allowInvalidated,(J,Y)=>{Y?q(Y):(y[ce]=J?.value,y[Xt]=J?.version,X=!0,v?.(y))}),X?y:new Promise((J,Y)=>{v=J,q=Y})}catch(w){throw w.message.includes("Unable to serialize object")&&(w.message+=": "+JSON.stringify(S)),w}return y}static setTTLExpiration(S){(0,Ii.getWorkerIndex)()===0&&(d=S*1e3,this.expirationTimer&&clearInterval(this.expirationTimer),this.expirationTimer=setInterval(()=>{if(this.primaryStore.rootStore.status!=="open")return clearInterval(this.expirationTimer);for(let{key:N,value:D,version:y}of this.primaryStore.getRange({start:!1,versions:!0}))y<Date.now()-d&&y>0&&D?.__invalidated__==null&&F.evict(N,D,y)},d).unref())}static enableAuditing(){E=!0,JT(),F.audit=!0}static coerceId(S){return S===""?null:Fd(S,k)}static async dropTable(){if(delete Pe[c][n],c===o){for(let S in r)_.remove(F.tableName+"/"+S),r[S].drop();_.remove(F.tableName+"/"),i.drop(),await _.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Yc.signalSchemaChange(new Kc.SchemaEventMsg(process.pid,Qr.OPERATIONS_ENUM.DROP_TABLE,c,n))}static Source;static get(S,N){return S&&typeof S=="object"&&!Array.isArray(S)&&S.url===""?{recordCount:this.getRecordCount(),records:"./",name:n,database:c,attributes:h}:super.get(S,N)}get(S){if(typeof S=="string")return this.getProperty(S);if(this[Us])return this.search(S);if(S?.property)return this.getProperty(S.property);if(this.doesExist()||this[Ae]?.hasOwnProperty("returnNonexistent")&&this[Ae].returnNonexistent)return this}static allowRead(S,N){if(!S)return!1;let D=S.role.permission;if(D.super_user)return!0;if(D[n]?.read){let y=D[n].attribute_permissions;if(y){N||(N={});let w=N.select;if(w){let v=CT(y,"read");N.select=w.filter(q=>v[q])}else N.select=y.filter(v=>v.read).map(v=>v.attribute_name);return N}else return!0}}allowUpdate(S,N,D){if(!S)return!1;let y=S.role.permission;if(y.super_user)return!0;if(y[n]?.update){let w=y[n].attribute_permissions;if(w){let v=CT(w,"update");for(let q in N)if(!v[q])return!1;if(D)for(let q of w){let L=q.attribute_name;!q.update&&!(L in N)&&(N[L]=this.getProperty(L))}}else return!0}}allowCreate(S,N){return this.allowUpdate(S,{})}static allowCreate(S,N){if(!S)return!1;let D=S.role.permission;if(D.super_user)return!0;if(D[n]?.insert){let y=D[n].attribute_permissions;if(y){let w=CT(y,"insert");for(let v in N)if(!w[v])return!1}else return!0}}static allowDelete(S){if(!S)return!1;let N=S.role.permission;if(N.super_user||N[n]?.delete)return!0}update(S,N){if(!this._txnForRequest())throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;let y;if(typeof S=="object"&&S){if(N)for(let w in this[ce])S[w]===void 0&&(S[w]=void 0);y=this[ft],y&&(S=Object.assign(y,S)),this[ft]=y=S}return!this[ce]&&t&&!(y||(y=this[ft]))?.[t]&&(y||(y=this[ft]=Object.create(null)),y[t]=this[ae]),this._writeUpdate(this),this}invalidate(S){this._txnForRequest().addWrite({key:this[ae],store:i,invalidated:!0,lastVersion:this[Xt],nodeName:this[Ae]?.nodeName,commit:(D,y)=>{if(y)return;let w={__invalidated__:D};for(let G in r)w[G]=this.getProperty(G);let v=F.Source,q,L=this[ae];return S?.isNotification||v?.shouldReceiveInvalidations&&(q=v.invalidate(L,this)),i.put(this[ae],w,D),{type:E&&"invalidate",[Ni]:q}}})}static evict(S,N,D){let y=this.Source;if(y?.get&&(!y.get.reliesOnPrototype||y.prototype.get)){let w;if(!N){let v=i.getEntry(S);if(!v)return;N=v.value,D=v.version}if(N)for(let v in r)w||(w={__invalidated__:0}),w[v]=N[v];return w?i.put(S,w,D,D):i.remove(S,D)}else return i.remove(S,D)}lock(){throw new Error("Not yet implemented")}static operation(S,N){return S.table||=n,S.schema||=c,Iv.operation(S,N)}async put(S){this.update(S,!0)}_writeUpdate(S,N){let D=this._txnForRequest();if(this[ae]===void 0)throw new Error("Can not save record without an id");let y=this[ce],w,v,q=this[ae];y||(this[ce]={}),D.addWrite({key:q,store:i,lastVersion:this[Xt],nodeName:this[Ae]?.nodeName,validate:()=>{this.validate(S)},commit:(L,G)=>{let X;if(G){if(w)return;let Y=i.getEntry(q);y=Y?.value;let j=this[Ae];j&&Y?.version>(j.lastModified||0)&&(j.lastModified=Y.version)}if(!v){if(v=!0,N?.isNotification)S=oa(S);else{if(S[gv]&&(w=!Ru(S),w))return;t&&S[t]!==q&&(S[t]=q),U&&(S[U.name]=U.type==="Date"?new Date(L):U.type==="String"?new Date(L).toISOString():L),$&&(y?S[$.name]=y[$.name]:S[$.name]=$.type==="Date"?new Date(L):$.type==="String"?new Date(L).toISOString():L),S=oa(S);let Y=F.Source;Y?.put&&(!Y.put.reliesOnPrototype||Y.prototype.put)&&(X=Y.put(q,S,this))}if(S[ce])throw new Error("Can not assign a record with a record property");this[ce]=S}if(wi.trace("Checking timestamp for put",q,this[Xt]>L,this[Xt],L),this[Xt]>L)return E&&{type:"put",value:i.encoder.encode(S)};let J=i.encoder.encode(S);return i.put(this[ae],(0,vo.asBinary)(J),L),Ze(this[ae],y,S),y===null&&!G&&Fn(-1),{type:E&&"put",value:J,[Ni]:X}}})}async delete(S){return typeof S=="string"?this.deleteProperty(S):this[ce]?this._writeDelete(S):!1}_writeDelete(S){let N=this._txnForRequest(),D,y=this[ae],w;return N.addWrite({key:y,store:i,lastVersion:this[Xt],nodeName:this[Ae]?.nodeName,commit:(v,q)=>{let L=this[ce];if(q){let G=i.getEntry(y);L=G?.value;let X=this[Ae];X&&G?.version>(X.lastModified||0)&&(X.lastModified=G.version)}if(!D&&(D=!0,!S?.isNotification)){let G=F.Source;G?.delete&&(!G.delete.reliesOnPrototype||G.prototype.delete)&&(w=G.delete(y,this))}if(!(this[Xt]>v))return Ze(this[ae],L),wi.trace("Write delete entry",E||f,v),E||f?(i.put(this[ae],null,v),E||zT(),q||Fn(1)):i.remove(this[ae]),{type:E&&"delete",[Ni]:w}}}),!0}search(S){let N=this._txnForRequest();if(!S)throw new Error("No query provided");let D=S.reverse===!0,y=S.conditions;y?y.length===void 0&&(y=Array.from(y)):y=Array.isArray(S)?S:S[Symbol.iterator]?Array.from(S):[],this[ae]&&(y=[{attribute:null,comparator:"prefix",value:this[ae]}].concat(y));for(let Y of y){let j=Y[0]??Y.attribute,De=j==null?k:h.find(on=>on.name==j);if(De)De.type&&(Y[1]===void 0?Y.value=w(Y.value,De):Y[1]=w(Y[1],De));else if(j!=null)throw(0,yi.handleHDBError)(new Error,`${j} is not a defined attribute`,404)}function w(Y,j){return Array.isArray(Y)?Y.map(De=>Fd(De,j)):Fd(Y,j)}a(w,"coerceTypedValues"),y.length>1&&(y=(0,bv.sortBy)(y,Y=>{if(Y.estimated_count===void 0){let j=Y.comparator||Y.search_type;if(j===Vc.SEARCH_TYPES.EQUALS){let De=Y[0]??Y.attribute;if(De==null||De===t)Y.estimated_count=1;else{let on=r[De];Y.estimated_count=on?on.getValuesCount(Y[1]??Y.value):1/0}}else j===Vc.SEARCH_TYPES.CONTAINS||j===Vc.SEARCH_TYPES.ENDS_WITH||j==="ne"?Y.estimated_count=1/0:j===Vc.SEARCH_TYPES.STARTS_WITH||j==="prefix"?Y.estimated_count=W9:Y.estimated_count=K9}return Y.estimated_count}));let v=N.getReadTxn();v.use();let q=S.select,L=y[0],G;if(!L)G=i.getRange(D?{end:!1,reverse:!0,transaction:v,lazy:q?.length<4}:{start:!1,transaction:v,lazy:q?.length<4}).map(({value:Y})=>Y?new Promise(j=>setImmediate(()=>j(Y))):vo.SKIP);else{let Y=IE(L,v,D,F,S.allowFullScan);if(!S.operator||S.operator.toLowerCase()==="and"){let j=y.slice(1).map(wE);G=J(Y,j)}else{for(let De=1;De<y.length;De++){let on=y[De],nE=IE(on,v,D,F,S.allowFullScan);Y=Y.concat(nE)}let j=new Set;Y=Y.filter(De=>j.has(De)?!1:(j.add(De),!0)),G=J(Y)}}(S.offset||S.limit!==void 0)&&(G=G.slice(S.offset,S.limit!==void 0?(S.offset||0)+S.limit:void 0)),G.onDone=()=>{v.done()};let X=this[Ae];function J(Y,j){let De=j?.length,on={transaction:v,lazy:De>0||q?.length<4,alwaysPrefetch:!0};return Y.map(nE=>new Promise(iE=>iu(nE,X,on,null,!1,wB=>{let oE=wB?.value;if(!oE)return iE(vo.SKIP);for(let aE=0;aE<De;aE++)if(!j[aE](oE))return iE(vo.SKIP);iE(oE)})))}return a(J,"idsToRecords"),G}async subscribe(S){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||rt({table:n,database:c,schemaDefined:l,attributes:h,audit:!0});let N=mv(F,this[ae]??null,function(v,q,L){try{this.send({id:v,timestamp:L,...q})}catch(G){console.error(G)}},S.startTime,this[Us]),D=this[ae],y=S.previousCount;y>1e3&&(y=1e3);let w=S.startTime;if(this[Us]){if(w){if(y)throw new yi.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:v,value:q}of u.getRange({start:[w,Number.MAX_SAFE_INTEGER]})){let[L,G,X]=v;if(v.length>3&&(X=v.slice(2)),G!==s)continue;let J=vn(q,i);(D==null||Nv(D,X))&&N.send({id:X,timestamp:L,...J}),N.startTime=L}}else if(y){let v=[];for(let{key:q,value:L}of u.getRange({start:"z",end:!1,reverse:!0}))try{let[G,X,J]=q;if(q.length>3&&(J=q.slice(2)),X!==s)continue;if(D==null||Nv(D,J)){let Y=vn(L,i);if(v.push({id:J,timestamp:G,...Y}),--y<=0)break}}catch(G){wi.error("Error getting history entry",q,G)}for(let q=v.length;q>0;)N.send(v[--q]);v[0]&&(N.startTime=v[0].timestamp)}else if(!S.omitCurrent)for(let{key:v,value:q,version:L}of i.getRange({start:D??!1,end:D==null?void 0:[D,yv.MAXIMUM_KEY],versions:!0}))q&&N.send({id:v,timestamp:L,value:q})}else{y&&!w&&(w=0);let v=this[Xt];if(w<v){let q=[],L=v;do{let G=[L,s,D],X=u.get(G);if(X){S.omitCurrent=!0;let J=vn(X,i);q.push({id:D,timestamp:L,...J}),L=J.lastVersion}else break;y&&y--}while(L>w&&y!==0);for(let G=q.length;G>0;)N.send(q[--G]);N.startTime=v}!S.omitCurrent&&this.doesExist()&&N.send({id:D,timestamp:this[Xt],value:this})}return S.listener&&N.on("data",S.listener),N}doesExist(){return!!this[ce]}async publish(S,N){this._writePublish(S,N)}_writePublish(S,N){let D=this._txnForRequest(),y=this[ae]||null,w,v;D.addWrite({store:i,key:y,lastVersion:this[Xt],nodeName:this[Ae]?.nodeName,validate:()=>{this.validate(S)},commit:(q,L)=>{if(this.validate(S),!v&&(v=!0,!N?.isNotification)){let J=F.Source;J?.publish&&(!J.publish.reliesOnPrototype||J.prototype.publish)&&(w=J.publish(y,S,this))}let G=L>0?i.get(y):this[ce];G===void 0&&!L&&(E||f)&&(E||zT(),Fn(1));let X={type:"message",value:i.encoder.encode(S),[Ni]:w};return!D.hasWrittenTime&&this[Xt]>q&&(q=X.newTxnTime=this[Xt]+.001),i.put(y,G??null,q),X}})}_txnForRequest(){let S=this[Ae],N=S?.transaction;if(N){let D;return(D=N?.find(y=>y.lmdbDb?.path===i.path))||N.push(D=new xc(i,S.user,u)),D}else return new Bd(i,S.user,u)}validate(S){let N;for(let D=0,y=h.length;D<y;D++){let w=h[D];if(w.type){let v=S[w.name];if(v!=null)switch(w.type){case"Int":case"Float":(typeof v!="number"||w.type==="Int"&&v!==Math.floor(v))&&(N||(N=[])).push(`Property ${w.name} must be an ${w.type==="Int"?"integer":"number"}`);break;case"ID":typeof v=="string"||v?.length>0&&v.every?.(q=>typeof q=="string")||(N||(N=[])).push(`Property ${w.name} must be a string, number, or an array (of strings and numbers)`);break;case"String":typeof v!="string"&&(N||(N=[])).push(`Property ${w.name} must be a string`)}}w.required&&S[w.name]==null&&(N||(N=[])).push(`Property ${w.name} is required`)}if(N)throw new yi.ClientError(N.join(". "))}getUpdatedTime(){return this[Xt]}wasLoadedFromSource(){return R?!!this[Av]:void 0}static async addAttributes(S){let N=h.slice(0);for(let D of S){if(!D.name)throw new yi.ClientError("Attribute name is required");if(D.name.match(/[`/]/))throw new yi.ClientError("Attribute names cannot include backticks or forward slashes");N.push(D)}return rt({table:n,database:c,schemaDefined:l,attributes:N}),F.indexingOperation}static async removeAttributes(S){let N=h.filter(D=>!S.includes(D.name));return rt({table:n,database:c,schemaDefined:l,attributes:N}),F.indexingOperation}static getRecordCount(){let S=0;for(let{key:N,value:D}of i.getRange({end:!1}))S++,N[0]?.description==="deletions"&&(S+=D||0);return i.getStats().entryCount-S}static updatedAttributes(){Au(this,this)}static async deleteHistory(S=0){let N;for(let{key:D,value:y}of u.getRange({start:[0,0],end:[S,0]})){await new Promise(L=>setImmediate(L));let[w,v,q]=D;D.length>3&&(q=D.slice(2)),v===s&&(N=i.remove(q))}await N}static async*getHistory(S=0,N=1/0){for(let{key:D,value:y}of u.getRange({start:[S,0],end:[N,0]})){await new Promise(G=>setImmediate(G));let[w,v,q]=D;if(D.length>3&&(q=D.slice(2)),v!==s)continue;let L=vn(y,i);L.id=q,L.timestamp=w,yield L}}static async getHistoryOfRecord(S){let N=[],D=i.getEntry(S);if(!D)return N;let y=D.version,w=0;do{await new Promise(L=>setImmediate(L));let v=[y,s,S],q=u.get(v);if(q){let L=vn(q,i);L.timestamp=y,N.push(L),y=L.lastVersion}else break}while(w<1e3);return N.reverse()}static cleanup(){z?.remove()}}F.updatedAttributes();let Oe=F.prototype;return Oe[gv]=!0,d&&F.setTTLExpiration(d/1e3),b&&IB(),F;function Ze(Z,S,N){let D;for(let y in r){let w=r[y],v=w.isIndexing,q=N?.[y],L=S?.[y];if(q===L&&!v)continue;D=!0;let G=(0,$c.getIndexedValues)(L);if(G){Tv&&w.prefetch(G.map(X=>({key:X,value:Z})),Ov);for(let X=0,J=G.length;X<J;X++)w.remove(G[X],Z)}if(G=(0,$c.getIndexedValues)(q),G){Tv&&w.prefetch(G.map(X=>({key:X,value:Z})),Ov);for(let X=0,J=G.length;X<J;X++)w.put(G[X],Z)}}return D}a(Ze,"updateIndices");function iu(Z,S,N,D,y,w){let v=a(()=>{let q=N.transaction;if(q?.isDone)throw new Error("Invalid read transaction");let L;q&&!q.hasRunLoadRecord&&(L=!0,q.hasRunLoadRecord=!0);let G;try{G=i.getEntry(Z,N)}catch(j){throw j.message+=". The read txn is "+JSON.stringify(q)+" first loadRecord: "+L,console.error(j),console.error("reader list",i.readerList()),console.error("reader check",i.readerCheck()),console.error("reader list",i.readerList()),j}let X,J,Y;if(G?(S&&G?.version>(S.lastModified||0)&&(S.lastModified=G.version),J=G.version,X=G.value,(J<0||!X||typeof X.__invalidated__=="number"||d&&J<Date.now()-d)&&(Y=!0)):Y=!0,R&&Oo(Y,"cache-hit",n),Y&&!y&&(D&&(D[Av]=!0),R))return Vo(Z,X,J,S).then(j=>{if(j?.value?.[ce])throw new Error("Can not assign a record with a record property");S&&j?.version>(S.lastModified||0)&&(S.lastModified=j.version),w(j)},j=>{w(null,j)});if(G?.value?.[ce])throw new Error("Can not assign a record with a record property");w(G)},"whenPrefetched");if(!N.alwaysPrefetch&&(Z==null||i.cache?.get(Z)))return v();i.prefetch([Z],v)}a(iu,"loadRecord");function Li(){P=new Set,(0,Ii.onMessageByType)("transaction",Z),i.on("aftercommit",Z);function Z(){for(let S of P)S()}a(Z,"onCommit")}a(Li,"setupCommitListeners");async function Vo(Z,S=null,N,D){if(N<0){let L;return P||Li(),await new Promise(G=>{let X,J=a(()=>{if(L=i.getEntry(Z),!L||L.version>0){if(clearTimeout(X),P.delete(J),typeof L?.value?.__invalidated__=="number")return G(Vo(Z,L.value,L.version,D));G(L)}},"listener");P.add(J),X=setTimeout(()=>{P.delete(J),G(Vo(Z,L?.value,void 0,D))},1e4).unref()})}let y=S?.__invalidated__,w=-(N||1);i.put(Z,S,w,N);let v={transaction:D?.transaction,replacingRecord:S,replacingVersion:N},q=D?.responseHeaders;q&&(v.responseHeaders=q);try{let L=performance.now(),G=await F.Source.get(Z,v),X=performance.now()-L;Ss(X,"cache-resolution",n),q&&q.append("Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`);let J=v.lastModified||N;(!J||d&&J<Date.now()-d)&&(J=(0,$c.getNextMonotonicTime)());let j=Ze(Z,S,G)&&N||y>0;return G?(t&&(G[t]=Z),typeof G.toJSON=="function"&&(G=G.toJSON()),i.put(Z,G,J,w)):i.remove(Z,w),j&&E&&u.put([J,s,Z],vd(y,null,G?{type:"put",value:i.encoder.encode(G)}:{type:"delete"})),{version:J,value:G}}catch(L){throw i.put(Z,S,N,w),L}}a(Vo,"getFromSource");function Fn(Z){T||(T=i.get([Rv,UT.threadId])||0),T+=Z,O||(O=setTimeout(()=>{O=null,i.rootStore.status==="open"&&i.put([Rv,UT.threadId],T)},50))}a(Fn,"recordDeletion");function zT(){p||(p=setTimeout(()=>{if(p=null,i.rootStore.status==="open"){for(let{key:Z,value:S}of i.getRange({start:!0}))if(S===null){let N=i.getEntry(Z);N?.value===null&&i.remove(Z,N.version),Fn(-1)}}},F.getRecordCount()*100+z9).unref())}a(zT,"enqueueDeletionCleanup");function JT(){z=u?.addDeleteRemovalCallback(s,Z=>{let S=i.getEntry(Z);S?.value===null&&i.remove(Z,S.version),Fn(-1)})}a(JT,"addDeleteRemoval");function IB(){(0,Ii.getWorkerIndex)()===0&&setInterval(async()=>{try{let Z=b.name,S=r[Z];if(!S)throw new Error(`expiresAt attribute ${b} must be indexed`);for(let{value:N}of S.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let D=i.getEntry(N);D?.value?.[Z]<Date.now()&&F.evict(N,D.value,D.version),await new Promise(y=>setImmediate(y))}}catch(Z){wi.error("Error in evicting old records",Z)}},Q9).unref()}a(IB,"runRecordExpirationEviction")}function CT(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function Ov(){}function J9(e){Iv=e}function Fd(e,t){let r=t?.type;return e===null?e:r==="Int"?parseInt(e):r==="Float"?parseFloat(e):r==="Date"?(typeof e!="number"&&!X9.test(e)&&(e+="Z"),new Date(e)):r?e:(0,qd.autoCast)(e)}function Nv(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}var Qr,vo,$c,bv,UT,Vc,Wc,yi,Yc,Kc,wi,yv,Ii,qd,Iv,K9,W9,Q9,Tv,Rv,Xt,gv,G_e,Av,kc,z9,X9,nd=Se(()=>{Qr=C(A()),vo=require("lmdb"),$c=C(vt()),bv=require("lodash"),UT=require("worker_threads");Xr();dv();Vc=C(xe()),Wc=C(Q());pv();yi=C(W()),Yc=C(qs()),Kc=C(Fr());de();yu();wi=C(x());Nu();xn();yv=require("ordered-binary"),Ii=C(dt());Gc();qd=C(V());hi();K9=1e8,W9=1e7,Q9=6e4;Wc.initSync();Tv=Wc.get(Qr.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Rv=Symbol.for("deletions"),Xt=Symbol.for("version"),gv=Symbol.for("incremental-update"),G_e=Symbol("source-resource"),Av=Symbol("load-from-source"),kc={isNotification:!0,allowInvalidated:!0},z9=(0,qd.convertToMS)(Wc.get(Qr.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(Gd,"makeTable");a(CT,"attributesAsObject");a(Ov,"noop");a(J9,"setServerUtilities");X9=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(Fd,"coerceType");a(Nv,"isDescendantId")});var Ne={};je(Ne,{database:()=>Ha,databases:()=>Pe,dropDatabase:()=>xh,dropTableMeta:()=>s7,getDatabases:()=>Gr,getTables:()=>Z9,onUpdatedTable:()=>jp,readMetaDb:()=>Qc,resetDatabases:()=>j9,table:()=>rt,tables:()=>sr});function Z9(){return $d||Gr(),sr||{}}function Gr(){if($d)return Pe;$d=!0,qo=new Map;let e=(0,bt.getHdbBasePath)()&&(0,Me.join)((0,bt.getHdbBasePath)(),Zt.DATABASES_DIR_NAME),t=(0,bt.get)(Zt.CONFIG_PARAMS.SCHEMAS)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,bt.get)(Zt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,fr.existsSync)(e)?e:(0,Me.join)((0,bt.getHdbBasePath)(),Zt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,fr.existsSync)(e))for(let r of(0,fr.readdirSync)(e,{withFileTypes:!0})){let s=(0,Me.basename)(r.name,".mdb");r.isFile()&&(0,Me.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Qc((0,Me.join)(e,r.name),null,s)}if((0,fr.existsSync)((0,Fo.getBaseSchemaPath)())){for(let r of(0,fr.readdirSync)((0,Fo.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,Me.join)((0,Fo.getBaseSchemaPath)(),r.name),n=(0,Me.join)((0,Fo.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,fr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,Me.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Me.join)(n,i.name);Qc((0,Me.join)(s,i.name),(0,Me.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,fr.existsSync)(n))for(let o of(0,fr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,Me.extname)(o.name).toLowerCase()===".mdb"&&Qc((0,Me.join)(n,o.name),(0,Me.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,Me.join)(c.path,(0,Me.basename)(o+".mdb"));(0,fr.existsSync)(u)&&Qc(u,o,r,null,!0)}}for(let r in Pe){let s=qo.get(r);if(s){let n=Pe[r];r.includes("delete")&&Le.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Le.trace(`delete table class ${i}`),delete n[i])}else if(delete Pe[r],r==="data"){for(let n in sr)delete sr[n];delete sr[Yd]}}return qo=null,Pe}}function j9(){$d=!1;for(let[,e]of Bn)e.needsDeletion=!0;Gr();for(let[e,t]of Bn)t.needsDeletion&&!e.endsWith("system.mdb")&&(console.log("closing database",e),t.close().then(()=>console.log("closed database",e)),Bn.delete(e));return Pe}function Qc(e,t,r=MT,s,n){let i=new DT.default(e,!1);e.includes("delete")&&Le.trace(`reading meta data from ${e}`);try{let o=Bn.get(e);o?o.needsDeletion=!1:(o=(0,xd.open)(i),Bn.set(e,o));let c=new Ci.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(Bo.INTERNAL_DBIS_NAME,c)),l=o.auditStore;l||(s?(0,fr.existsSync)(s)&&(i.path=s,l=(0,xd.open)(i),l.isLegacy=!0):l=bT(o));let _=Dv(r),d=_[Yd],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[T,p]=f.toString().split("/");e.includes("delete")&&Le.trace(`read key ${f}`),p===""?p=h.name:p||(p=T,T=t,h.name||(h.name=p,h.indexed=!h.is_hash_attribute)),d?.add(T);let R=E.get(T);R||E.set(T,R={attributes:[]}),(p==null||h.is_hash_attribute)&&(R.primary=h),p!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:T,primary:p}=h;if(!p){for(let F of T)if(F.is_hash_attribute||F.isPrimaryKey){p=F;break}if(!p)throw new Error(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(T)}`)}let R=_[f],O={},k=[],$,U,b=typeof p.audit=="boolean"?p.audit:(0,bt.get)(Zt.CONFIG_PARAMS.LOGGING_AUDITLOG),P=p.trackDeletes,z=p.expiration;if(R)O=R.indices,k=R.attributes,R.schemaVersion++;else{$=p.tableId,$?$>=(u.get(Ho)||0)&&u.putSync(Ho,$+1):(p.tableId=$=u.get(Ho),$||($=1),u.putSync(Ho,$+1),u.putSync(p.key,p));let F=new Ci.default(!p.is_hash_attribute,p.is_hash_attribute);Le.trace(`openDB ${p.key} from ${r}`),U=o.openDB(p.key,F),U.rootStore=o,U.tableId=$}for(let F of T){F.attribute=F.name;try{if(!F.is_hash_attribute&&(F.indexed||F.attribute&&!F.name)){if(!O[F.name]){let Ze=new Ci.default(!F.is_hash_attribute,F.is_hash_attribute);Le.trace(`openDB ${F.key} from ${r}`),O[F.name]=o.openDB(F.key,Ze)}let Oe=k.find(Ze=>Ze.name===F.name);Oe?k.splice(k.indexOf(Oe),1,F):k.push(F)}}catch(Oe){Le.error("Error trying to update attribute",F,k,O,Oe)}}if(!R){Le.trace(`creating table class ${f}`,Object.keys(_)),R=Lv(_,f,Gd({primaryStore:U,auditStore:l,audit:b,expirationMS:z&&z*1e3,trackDeletes:P,tableName:f,tableId:$,primaryKey:p.name,databasePath:n?r+"/"+f:r,databaseName:r,indices:O,attributes:T,schemaDefined:p.schemaDefined,dbisDB:u})),R.schemaVersion=1;for(let F of PT)F(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Dv(e){let t=Pe[e];if(t||(e==="data"?t=Pe[e]=sr:e==="system"?Object.defineProperty(Pe,"system",{value:t=Object.create(null),configurable:!0}):t=Pe[e]=Object.create(null)),qo&&!qo.has(e)){let r=new Set;t[Yd]=r,qo.set(e,r)}return t}function Lv(e,t,r){return e[t]=r,r}function Ha({database:e,table:t}){e||(e=MT),Gr();let r=Dv(e),s=(0,Me.join)((0,bt.getHdbBasePath)(),Zt.DATABASES_DIR_NAME),n=t&&(0,bt.get)(Zt.CONFIG_PARAMS.SCHEMAS)?.[e]?.tables?.[t]?.path;s=n||(0,bt.get)(Zt.CONFIG_PARAMS.SCHEMAS)?.[e]?.path||process.env.STORAGE_PATH||(0,bt.get)(Zt.CONFIG_PARAMS.STORAGE_PATH)||((0,fr.existsSync)(s)?s:(0,Me.join)((0,bt.getHdbBasePath)(),Zt.LEGACY_DATABASES_DIR_NAME));let i=(0,Me.join)(s,(n?t:e)+".mdb"),o=Bn.get(i);if(!o){let c=new DT.default(i,!1);o=(0,xd.open)(c),Bn.set(i,o)}return o}async function xh(e){if(!Pe[e])throw new Error("Schema does not exist");let t=Pe[e];for(let r in t){let n=t[r].primaryStore.rootStore;Bn.delete(n.path),n.status==="open"&&(await n.close(),await wv.remove(n.path))}if(e==="data"){for(let r in sr)delete sr[r];delete sr[Yd]}delete Pe[e]}function rt({table:e,database:t,expiration:r,attributes:s,audit:n,trackDeletes:i,schemaDefined:o,origin:c}){t||(t=MT);let u=Ha({database:t,table:e}),l=Pe[t],_=l?.[e];if(u.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let d,E,f,h;o==null&&(o=!0);let T=new Ci.default(!1);for(let U of s)U.attribute?(U.name=U.attribute,U.indexed=!0):U.attribute=U.name,U.expiresAt&&(U.indexed=!0);let p,R;if(_){if(Le.trace(`${e} table already exists`),d=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);_.attributes.splice(0,_.attributes.length,...s)}else{let U=u.auditStore;U||(U=bT(u)),E=s.find(F=>F.isPrimaryKey)||{},d=E.name,E.is_hash_attribute=!0,E.schemaDefined=o,i&&(E.trackDeletes=!0),n=E.audit=typeof n=="boolean"?n:(0,bt.get)(Zt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(E.expiration=r),c&&(E.origins?E.origins.includes(c)||E.origins.push(c):E.origins=[c]),Le.trace(`${e} table loading, opening primary store`);let b=new Ci.default(!1,!0),P=e+"/";Le.trace(`openDB ${P} from ${t}`);let z=u.openDB(P,b);z.rootStore=u,Le.trace(`openDB ${Bo.INTERNAL_DBIS_NAME} from ${t}`),h=u.dbisDb=u.openDB(Bo.INTERNAL_DBIS_NAME,T),z.tableId=h.get(Ho),z.tableId||(z.tableId=1),h.putSync(Ho,z.tableId+1),E.tableId=z.tableId,_=Lv(l,e,Gd({primaryStore:z,auditStore:U,audit:n,trackDeletes:i,expirationMS:r&&r*1e3,primaryKey:d,tableName:e,tableId:z.tableId,databasePath:t,databaseName:t,indices:{},attributes:s,schemaDefined:o,dbisDB:h})),_.schemaVersion=1,p=!0,$(),h.put(P,E)}Le.trace(`${e} table loading, getting stored attributes`),f=_.indices,h||Le.trace(`openDB ${Bo.INTERNAL_DBIS_NAME} from ${t}`),h=h||(u.dbisDb=u.openDB(Bo.INTERNAL_DBIS_NAME,T)),_.dbisDB=h;let O=[];for(let{key:U,value:b}of h.getRange({start:!0})){let[P,z]=U.toString().split("/");if(z===""&&(z=b.name),z){if(P!==e)continue}else z=P;if(!s.find(Oe=>Oe.name===z)?.indexed&&b.indexed&&!b.isPrimaryKey){$(),p=!0,h.remove(U);let Oe=_.indices[P];Oe&&O.push(Oe)}}Le.trace(`${e} table loading, comparing atributes`);let k=[];try{for(let U of s||[]){let b=e+"/"+(U.name||"");Object.defineProperty(U,"key",{value:b,configurable:!0});let P=h.get(b);if(U.isPrimaryKey){if(n===!0&&!_.audit){_.enableAuditing(),P||(b=e+"/",P=h.get(b));let F=Object.assign({},P,{audit:!0});p=!0,$(),h.put(b,F)}continue}P?.attribute&&!P.name&&(P.indexed=!0);let z=!P||P.type!==U.type||P.indexed!==U.indexed||JSON.stringify(P.attributes)!==JSON.stringify(U.attributes)||JSON.stringify(P.elements)!==JSON.stringify(U.elements);if(U.indexed){let F=new Ci.default(!0,!1);Le.trace(`openDB ${b} from ${t}`);let Oe=u.openDB(b,F);(z||P.indexingPID&&P.indexingPID!==process.pid||P.restartNumber<zc.workerData?.restartNumber)&&(p=!0,$(),P=h.get(b),(z||P.indexingPID&&P.indexingPID!==process.pid||P.restartNumber<zc.workerData?.restartNumber)&&(p=!0,U.lastIndexedKey=P?.lastIndexedKey||!1,U.indexingPID=process.pid,Oe.isIndexing=!0,Object.defineProperty(U,"dbi",{value:Oe}),k.push(U)),h.put(b,U)),f[U.name]=Oe}else z&&(p=!0,$(),h.put(b,U))}}finally{R&&R()}if(p&&(_.schemaVersion++,_.updatedAttributes()),Le.trace(`${e} table loading, running index`),k.length>0||O.length>0?_.indexingOperation=r7(_,k,O):p&&kd.signalSchemaChange(new Vd.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=c,p)for(let U of PT)U(_,c!=="cluster");return r&&_.setTTLExpiration(+r),Le.trace(`${e} table loaded`),_;function $(){R||u.transactionSync(()=>({then(U){R=U}}))}a($,"startTxn")}async function r7(e,t,r){try{let s=e.schemaVersion;await kd.signalSchemaChange(new Vd.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:l,value:_,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(_){if(u++,n=e.primaryStore.ifVersion(l,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,T=(0,Cv.getIndexedValues)(_[h]);if(T)for(let p=0,R=T.length;p<R;p++)f.dbi.put(T[p],l)}}),n.then(()=>u--,E=>{u--,Le.error(E)}),zc.workerData&&zc.workerData.restartNumber!==Uv.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=l,e.dbisDB.put(E.key,E);if(i)return}u>e7?await n:u>t7&&await new Promise(E=>setImmediate(E))}for(let l of t)delete l.lastIndexedKey,delete l.indexingPID,l.dbi.isIndexing=!1,n=e.dbisDB.put(l.key,l)}await n,await kd.signalSchemaChange(new Vd.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Le.error("Error in indexing",s)}}function s7({table:e,database:t}){let r=Ha({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function jp(e){PT.push(e)}var bt,Bo,xd,Me,fr,Fo,Ci,DT,Zt,wv,LT,Cv,kd,Vd,zc,Le,Uv,MT,Yd,sr,Pe,Ho,PT,$d,Bn,qo,e7,t7,de=Se(()=>{bt=C(Q()),Bo=C(xe()),xd=require("lmdb"),Me=require("path"),fr=require("fs"),Fo=C(we());nd();Ci=C(Du()),DT=C(Mu()),Zt=C(A()),wv=C(require("fs-extra")),LT=require("../index"),Cv=C(vt()),kd=C(qs()),Vd=C(Fr()),zc=require("worker_threads"),Le=C(x()),Uv=C(dt());Gc();MT="data",Yd=Symbol("defined-tables");(0,bt.initSync)();sr=Object.create(null),Pe=Object.create(null);(0,LT._assignPackageExport)("databases",Pe);(0,LT._assignPackageExport)("tables",sr);Ho=Symbol.for("next-table-id"),PT=[],Bn=new Map;a(Z9,"getTables");a(Gr,"getDatabases");a(j9,"resetDatabases");a(Qc,"readMetaDb");a(Dv,"ensureDB");a(Lv,"setTable");a(Ha,"database");a(xh,"dropDatabase");a(rt,"table");e7=1e3,t7=10;a(r7,"runIndexing");a(s7,"dropTableMeta");a(jp,"onUpdatedTable")});var V=m((z_e,Kv)=>{"use strict";var Hn=require("path"),Hv=require("fs-extra"),jt=x(),Mv=require("fs-extra"),Kd=require("os"),n7=require("net"),i7=require("recursive-iterator"),Ge=A(),o7=CR(),Pv=require("papaparse"),Wd=require("moment"),{inspect:a7}=require("util"),vv=require("is-number"),Q_e=require("lodash"),c7=require("minimist"),u7=require("https"),l7=require("http"),{hdb_errors:Qd}=W(),_7=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Fv=require("util").promisify(setTimeout),d7=100,E7=5,f7="",h7=4,Bv={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};Kv.exports={isEmpty:hr,isEmptyOrZeroLength:Os,arrayHasEmptyValues:p7,arrayHasEmptyOrZeroLengthValues:T7,buildFolderPath:R7,isBoolean:qv,errorizeMessage:m7,stripFileExtension:A7,autoCast:O7,autoCastJSON:Gv,autoCastJSONDeep:BT,removeDir:N7,compareVersions:b7,isCompatibleDataVersion:y7,escapeRawValue:I7,unescapeValue:w7,stringifyProps:C7,timeoutPromise:D7,isClusterOperation:M7,getClusterUser:v7,checkGlobalSchemaTable:P7,getHomeDir:kv,getPropsFilePath:U7,promisifyPapaParse:B7,removeBOM:Vv,createEventPromise:H7,checkProcessRunning:F7,checkSchemaTableExist:q7,checkSchemaExists:$v,checkTableExists:Yv,getStartOfTomorrowInSeconds:G7,getLimitKey:x7,isObject:g7,isNotEmptyAndHasValue:S7,autoCasterIsNumberCheck:xv,backtickASTSchemaItems:k7,isPortTaken:L7,createForkArgs:V7,autoCastBoolean:$7,async_set_timeout:Fv,getTableHashAttribute:Y7,doesSchemaExist:K7,doesTableExist:W7,stringifyObj:Q7,ms_to_time:z7,changeExtension:J7,getEnvCliRootPath:HT,noBootFile:X7,httpRequest:Z7,transformReq:j7,convertToMS:eee,PACKAGE_ROOT:Ge.PACKAGE_ROOT};function m7(e){return e instanceof Error?e:new Error(e)}a(m7,"errorizeMessage");function hr(e){return e==null}a(hr,"isEmpty");function S7(e){return!hr(e)&&(e||e===0||e===""||qv(e))}a(S7,"isNotEmptyAndHasValue");function Os(e){return hr(e)||e.length===0||e.size===0}a(Os,"isEmptyOrZeroLength");function p7(e){if(hr(e))return!0;for(let t=0;t<e.length;t++)if(hr(e[t]))return!0;return!1}a(p7,"arrayHasEmptyValues");function T7(e){if(Os(e))return!0;for(let t=0;t<e.length;t++)if(Os(e[t]))return!0;return!1}a(T7,"arrayHasEmptyOrZeroLengthValues");function R7(...e){try{return e.join(Hn.sep)}catch{console.error(e)}}a(R7,"buildFolderPath");function qv(e){return hr(e)?!1:e===!0||e===!1}a(qv,"isBoolean");function g7(e){return hr(e)?!1:typeof e=="object"}a(g7,"isObject");function A7(e){return Os(e)?f7:e.slice(0,-h7)}a(A7,"stripFileExtension");function O7(e){return hr(e)||e===""||typeof e!="string"?e:Bv[e]!==void 0?Bv[e]:xv(e)===!0?Number(e):_7.test(e)?new Date(e):e}a(O7,"autoCast");function Gv(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Gv,"autoCastJSON");function BT(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=BT(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=BT(r);s!==r&&(e[t]=s)}return e}else return Gv(e)}a(BT,"autoCastJSONDeep");function xv(e){if(e.startsWith("0.")&&vv(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&vv(e))}a(xv,"autoCasterIsNumberCheck");async function N7(e){if(Os(e))throw new Error(`Directory path: ${e} does not exist`);try{await Mv.emptyDir(e),await Mv.remove(e)}catch(t){throw jt.error(`Error removing files in ${e} -- ${t}`),t}}a(N7,"removeDir");function b7(e,t){if(Os(e)){jt.info("Invalid current version sent as parameter.");return}if(Os(t)){jt.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(o.length,c.length);for(let l=0;l<u;l++)if(r=parseInt(o[l],10)-parseInt(c[l],10),r)return r;return o.length-c.length}a(b7,"compareVersions");function y7(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(y7,"isCompatibleDataVersion");function I7(e){if(hr(e))return e;let t=String(e);return t==="."?Ge.UNICODE_PERIOD:t===".."?Ge.UNICODE_PERIOD+Ge.UNICODE_PERIOD:t.replace(Ge.FORWARD_SLASH_REGEX,Ge.UNICODE_FORWARD_SLASH)}a(I7,"escapeRawValue");function w7(e){if(hr(e))return e;let t=String(e);return t===Ge.UNICODE_PERIOD?".":t===Ge.UNICODE_PERIOD+Ge.UNICODE_PERIOD?"..":String(e).replace(Ge.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(w7,"unescapeValue");function C7(e,t){if(hr(e))return jt.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+Kd.EOL}!Os(s)&&s[0]===";"?r+=" "+s+n+Kd.EOL:Os(s)||(r+=s+"="+n+Kd.EOL)}catch{jt.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(C7,"stringifyProps");function kv(){let e;try{e=Kd.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(kv,"getHomeDir");function U7(){let e=Hn.join(kv(),Ge.HDB_HOME_DIR_NAME,Ge.BOOT_PROPS_FILE_NAME);return Hv.existsSync(e)||(e=Hn.join(__dirname,"../","hdb_boot_properties.file")),e}a(U7,"getPropsFilePath");function D7(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(D7,"timeoutPromise");async function L7(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=n7.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(L7,"isPortTaken");function M7(e){try{return Ge.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){jt.error(`Error checking operation against cluster ops ${t}`)}return!1}a(M7,"isClusterOperation");function P7(e,t){let r=(de(),re(Ne)).getDatabases();if(!r[e])return Qd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return Qd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(P7,"checkGlobalSchemaTable");function v7(e,t){if(hr(t)){jt.warn("No CLUSTERING_USER defined, clustering disabled");return}if(hr(e)||Os(e)){jt.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){jt.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){jt.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(v7,"getClusterUser");function B7(){Pv.parsePromise=function(e,t,r){return new Promise(function(s,n){Pv.parse(e,{header:!0,transformHeader:Vv,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(B7,"promisifyPapaParse");function Vv(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Vv,"removeBOM");function H7(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;jt.info(`Got cluster status event response: ${a7(n)}`);try{i.cancel()}catch{jt.error("Error trying to cancel timeout.")}s(n)})})}a(H7,"createEventPromise");async function F7(e){let t=!0,r=0;do await Fv(d7*r++),(await o7.findPs(e)).length>0&&(t=!1);while(t&&r<E7);if(t)throw new Error(`process ${e} was not started`)}a(F7,"checkProcessRunning");function q7(e,t){let r=$v(e);if(r)return r;let s=Yv(e,t);if(s)return s}a(q7,"checkSchemaTableExist");function $v(e){let{getDatabases:t}=(de(),re(Ne));if(!t()[e])return Qd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a($v,"checkSchemaExists");function Yv(e,t){let{getDatabases:r}=(de(),re(Ne));if(!r()[e][t])return Qd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Yv,"checkTableExists");function G7(){let e=Wd().utc().add(1,Ge.MOMENT_DAYS_TAG).startOf(Ge.MOMENT_DAYS_TAG).unix(),t=Wd().utc().unix();return e-t}a(G7,"getStartOfTomorrowInSeconds");function x7(){return Wd().utc().format("DD-MM-YYYY")}a(x7,"getLimitKey");function k7(e){try{let t=new i7(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){jt.error("Got an error back ticking items."),jt.error(t)}}a(k7,"backtickASTSchemaItems");function V7(e){return[e]}a(V7,"createForkArgs");function $7(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a($7,"autoCastBoolean");function Y7(e,t){let{getDatabases:r}=(de(),re(Ne)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(Y7,"getTableHashAttribute");function K7(e){let{getDatabases:t}=(de(),re(Ne));return t()[e]!==void 0}a(K7,"doesSchemaExist");function W7(e,t){let{getDatabases:r}=(de(),re(Ne));return r()[e]?.[t]!==void 0}a(W7,"doesTableExist");function Q7(e){try{return JSON.stringify(e)}catch{return e}}a(Q7,"stringifyObj");function z7(e){let t=Wd.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(z7,"ms_to_time");function J7(e,t){let r=Hn.basename(e,Hn.extname(e));return Hn.join(Hn.dirname(e),r+t)}a(J7,"changeExtension");function HT(){if(process.env[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=c7(process.argv);if(e[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(HT,"getEnvCliRootPath");var vT;function X7(){if(vT)return vT;let e=HT();HT()&&Hv.pathExistsSync(Hn.join(e,Ge.HDB_CONFIG_FILE))&&(vT=!0)}a(X7,"noBootFile");function Z7(e,t){let r;return e.protocol==="http:"?r=l7:r=u7,new Promise((s,n)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(Z7,"httpRequest");function j7(e){if(!e.schema&&!e.database){e.schema=Ge.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(j7,"transformReq");function eee(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(eee,"convertToMS")});var Q=m((X_e,zv)=>{"use strict";var FT=require("fs-extra"),zr=require("path"),Wv=require("os"),tee=require("properties-reader"),Jc=x(),Ui=V(),te=A(),zd=Nr(),ree="Error initializing environment manager",Jd="BOOT_PROPS_FILE_PATH",Qv=!1,see={[te.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[te.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[te.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},nn={};zv.exports={BOOT_PROPS_FILE_PATH:Jd,getHdbBasePath:nee,setHdbBasePath:iee,get:oee,initSync:cee,setProperty:Ee,initTestEnvironment:uee};function nee(){return nn[te.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(nee,"getHdbBasePath");function iee(e){nn[te.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(iee,"setHdbBasePath");function oee(e){let t=zd.getConfigValue(e);return t===void 0?nn[e]:t}a(oee,"get");function Ee(e,t){see[e]&&(nn[e]=t),zd.updateConfigObject(e,t)}a(Ee,"setProperty");function aee(){let e;try{e=Ui.getPropsFilePath(),FT.accessSync(e,FT.constants.F_OK|FT.constants.R_OK),Qv=!0;let t=tee(e);return nn[te.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(te.HDB_SETTINGS_NAMES.INSTALL_USER),nn[te.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(te.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),nn[Jd]=e,!0}catch{return Jc.trace(`Environment manager found no properties file at ${e}`),!1}}a(aee,"doesPropFileExist");function cee(e=!1){try{(Qv||aee()||Ui.noBootFile())&&(zd.initConfig(e),nn[te.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=zd.getConfigValue(te.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Jc.error(ree),Jc.error(t),console.error(t),process.exit(1)}}a(cee,"initSync");function uee(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=zr.join(__dirname,"../../","unitTests");nn[Jd]=zr.join(u,"hdb_boot_properties.file"),Ee(te.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,zr.join(u,"settings.test")),Ee(te.HDB_SETTINGS_NAMES.INSTALL_USER,Wv.userInfo()?Wv.userInfo().username:void 0),Ee(te.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,zr.join(u,"envDir","utility","keys","privateKey.pem")),Ee(te.HDB_SETTINGS_NAMES.CERT_KEY,zr.join(u,"envDir","utility","keys","certificate.pem")),Ee(te.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,zr.join(u,"envDir","utility","keys","privateKey.pem")),Ee(te.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,zr.join(u,"envDir","utility","keys","certificate.pem")),Ee(te.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ee(te.HDB_SETTINGS_NAMES.LOG_PATH_KEY,zr.join(u,"envDir","log")),Ee(te.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ee(te.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ee(te.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ee(te.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,zr.join(u,"envDir")),Ee(te.CONFIG_PARAMS.STORAGE_PATH,zr.join(u,"envDir")),Ee(te.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Ui.isEmpty(n)?!0:n),Ee(te.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Ui.isEmpty(n)?!0:n),Ee(te.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ee(te.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ui.isEmpty(i)?!1:i),Ee(te.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Ui.isEmpty(i)?!1:i),Ee(te.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ee(te.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ee(te.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ee(te.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ee(te.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,zr.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ee(te.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ui.isEmpty(c)?!1:c),o&&(Ee("CORS_ACCESSLIST",o),Ee(te.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(Ee(te.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ee(te.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(Ee(te.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ee(te.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(Ee(te.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ee(te.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Jd}. Please check your boot props and settings files`;Jc.fatal(r),Jc.error(t)}}a(uee,"initTestEnvironment")});var nt=m((sde,fB)=>{"use strict";var yt=Q();yt.initSync();var lee=require("fs-extra"),_ee=require("semver"),eu=require("path"),{monotonicFactory:dee}=require("ulidx"),kT=dee(),Eee=require("util"),Xv=require("child_process"),fee=Eee.promisify(Xv.exec),hee=Xv.spawn,_e=Be(),Re=A(),Xd=V(),Mr=x(),Zd=Ps(),mee=yl(),Xc=Nr(),{Encoder:See,decode:VT}=require("msgpackr"),Zv=new See,{isEmpty:Di}=Xd,jv=br(),eB=12e10,pee=48*36e11,Tee=5e9,{connect:Ree,StorageType:tB,RetentionPolicy:rB,AckPolicy:jd,DeliverPolicy:eE,DiscardPolicy:gee,NatsConnection:j_e,JetStreamManager:ede,JetStreamClient:tde,StringCodec:rde,JSONCodec:Aee,createInbox:$T,headers:Oee,ErrorCode:Jv}=require("nats"),{PACKAGE_ROOT:Nee}=A(),bee=Ka(),{recordAction:yee}=(hi(),re(Y_)),sB=Aee(),Iee="clustering",wee=bee.engines[_e.NATS_SERVER_NAME],Cee=eu.join(Nee,"dependencies"),xT=eu.join(Cee,`${process.platform}-${process.arch}`,_e.NATS_BINARY_NAME),qT,GT,Zc,Go,xo;fB.exports={runCommand:nB,checkNATSServerInstalled:Uee,createConnection:YT,getConnection:tE,getJetStreamManager:tu,getJetStream:iB,getNATSReferences:er,getServerList:Lee,createLocalStream:KT,listStreams:oB,deleteLocalStream:Mee,getServerConfig:ru,listRemoteStreams:Pee,viewStream:vee,viewStreamIterator:Bee,publishToStream:Hee,createWorkQueueStream:Fee,addSourceToWorkStream:cB,request:Gee,removeSourceFromWorkStream:lB,reloadNATS:WT,reloadNATSHub:xee,reloadNATSLeaf:kee,extractServerName:uB,requestErrorHandler:Vee,updateWorkStream:$ee,createLocalTableStream:dB,createTableStreams:Yee,purgeTableStream:EB,purgeSchemaTableStreams:Kee,getStreamInfo:Wee,updateLocalStreams:zee,closeConnection:Dee,getJsmServerName:su,addNatsMsgHeader:aB,updateIngestStreamConsumer:qee};async function nB(e,t=void 0){let{stdout:r,stderr:s}=await fee(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
25
25
|
`,""));return r.replace(`
|
|
26
|
-
`,"")}o(eB,"runCommand");async function bee(){try{await iee.access(FT)}catch{return!1}let e=await eB(`${FT} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return aee.eq(t,Oee)}o(bee,"checkNATSServerInstalled");async function kT(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let a=await zv.getClusterUser();if(Ui(a))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=a.username,r=a.decrypt_hash}Dr.trace("create nats connection called");let i=await hee({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:3e4,tls:{keyFile:yt.get(Re.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:yt.get(Re.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:yt.get(Re.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return Dr.trace("create connection established a nats client connection with id",i?.info?.client_id),i}o(kT,"createConnection");async function yee(){As&&(await As.drain(),As=void 0,Ha=void 0,Fa=void 0,Xc=void 0)}o(yee,"closeConnection");var As,Xc;async function Xd(){return Xc||(Xc=kT(yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),As=await Xc),As||Xc}o(Xd,"getConnection");async function jc(){if(Ha)return Ha;Ui(As)&&await Xd();let{domain:e}=eu(Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Ui(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ha=await As.jetstreamManager({domain:e}),Ha}o(jc,"getJetStreamManager");async function tB(){if(Fa)return Fa;Ui(As)&&await Xd();let{domain:e}=eu(Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Ui(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Fa=As.jetstream({domain:e}),Fa}o(tB,"getJetStream");async function er(){let e=As||await Xd(),t=Ha||await jc(),r=Fa||await tB();return{connection:e,jsm:t,js:r}}o(er,"getNATSReferences");async function Iee(e){let t=yt.get(Re.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await zv.getClusterUser(),n=await kT(t,r,s),i=xT(),a=n.subscribe(i),c=[],u,l=(async()=>{for await(let _ of a){let d=jv.decode(_.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await n.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await n.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await n.flush(),await Wd.async_set_timeout(e),await a.drain(),await n.close(),await l,c}o(Iee,"getServerList");async function VT(e,t){let{jsm:r}=await er(),s=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:Xv.File,retention:Zv.Limits,subjects:t,discard:mee.Old,duplicate_window:Jv,max_msgs:n,max_bytes:i,max_age:s})}o(VT,"createLocalStream");async function rB(){let{jsm:e}=await er(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}o(rB,"listStreams");async function wee(e){let{jsm:t}=await er();await t.streams.delete(e)}o(wee,"deleteLocalStream");async function Cee(e){let{connection:t}=await er(),r=[],s=xT(),n=t.subscribe(s),i=(async()=>{for await(let a of n)r.push(jv.decode(a.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}o(Cee,"listRemoteStreams");async function Uee(e,t=void 0,r=void 0){let{jsm:s,js:n}=await er(),i=qT(),a={durable_name:i,ack_policy:zd.Explicit};t&&(a.deliver_policy=Jd.StartTime,a.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,a);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let l=[];for await(let _ of u){let d=GT(_.data),E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};if(_.headers&&(E.origin=_.headers.get(_e.MSG_HEADERS.ORIGIN),E.nats_msg_id=_.headers.get(_e.MSG_HEADERS.NATS_MSG_ID)),l.push(E),_.ack(),_.info.pending===0)break}return await c.delete(),l}o(Uee,"viewStream");async function*Dee(e,t=void 0,r=void 0){let{jsm:s,js:n}=await er(),i=qT(),a={durable_name:i,ack_policy:zd.Explicit};t&&(a.deliver_policy=Jd.StartTime,a.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,a);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let l of u){let _=GT(l.data);_[0]||(_=[_]);for(let d of _){let E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};l.headers&&(E.origin=l.headers.get(_e.MSG_HEADERS.ORIGIN),E.nats_msg_id=l.headers.get(_e.MSG_HEADERS.NATS_MSG_ID)),yield E}if(l.ack(),l.info.pending===0)break}await c.delete()}o(Dee,"viewStreamIterator");async function Lee(e,t,r,s){Dr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=sB(s,r);let{js:n}=await er(),i=await tu(),a=`${e}.${i}`,c=s instanceof Uint8Array?s:Qv.encode(s);try{Dr.trace(`publishToStream publishing to subject: ${a}`),gee(c.length,"bytes-sent",e,s.operation,"replication"),await n.publish(a,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return oB(async()=>{try{await n.publish(a,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Dr.trace(`publishToStream creating stream: ${t}`);let _=a.split(".");_[2]="*",await VT(t,[a]),await n.publish(a,c,{headers:r})}else throw u}});throw u}}o(Lee,"publishToStream");function sB(e,t){t===void 0&&(t=pee());let r=yt.get(Re.CONFIG_PARAMS.CLUSTERING_NODENAME);if(!t.has(_e.MSG_HEADERS.NATS_MSG_ID)){let s=Wd.getTableHashAttribute(e.schema,e.table),n=e.action?e.action:e.operation,i=`${r}.${e.schema}.${e.table}.${n}.${s}.${Date.now()}.${qT()}`;t.append(_e.MSG_HEADERS.NATS_MSG_ID,i)}return t.has(_e.MSG_HEADERS.ORIGIN)||t.append(_e.MSG_HEADERS.ORIGIN,r),t}o(sB,"addNatsMsgHeader");function eu(e){e=e.toLowerCase();let t=Zc.join(yt.get(Re.CONFIG_PARAMS.ROOTPATH),Aee);if(e===Re.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return Ui(HT)&&(HT={port:zc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:zc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.HUB,config_file:_e.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:Zc.join(t,_e.PID_FILES.HUB),hdb_nats_path:t}),HT;if(e===Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return Ui(BT)&&(BT={port:zc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:zc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.LEAF,config_file:_e.NATS_CONFIG_FILES.LEAF_SERVER,domain:zc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.LEAF,pid_file_path:Zc.join(t,_e.PID_FILES.LEAF),hdb_nats_path:t}),BT;Dr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}o(eu,"getServerConfig");async function Mee(e){let{jsm:t}=await er(),r=await tu();try{await t.streams.add({name:e.stream_name,storage:Xv.File,retention:Zv.Limits,duplicate_window:Jv,max_age:Eee,max_bytes:fee,subjects:[`${_e.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:zd.Explicit,durable_name:e.durable_name,deliver_policy:Jd.All,max_ack_pending:1e4});else throw s}}o(Mee,"createWorkQueueStream");async function Pee(){let{jsm:e}=await er();(await e.consumers.info(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,_e.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Dr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,_e.WORK_QUEUE_CONSUMER_NAMES.durable_name),Dr.info("Adding pull consumer to ingest stream"),await e.consumers.add(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:zd.Explicit,durable_name:_e.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:Jd.All,max_ack_pending:1e4}))}o(Pee,"updateIngestStreamConsumer");async function nB(e,t,r){let{jsm:s}=await er(),n=await s.streams.info(t),i=iB(s.prefix),a=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,l=Qd.createNatsTableStreamName(c,u),_=i===e,d,E,f=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let T=0,S=n.config.sources.length;T<S;T++)if(d=n.config.sources[T],E=T,_&&d.name===l||!_&&d.name===l&&d.external&&d.external.api===`$JS.${e}.API`){f=!0;break}if(f===!0){if(d.opt_start_time===a)return;n.config.sources.splice(E,1),await s.streams.update(t,n.config)}let h={name:l,opt_start_time:a,filter_subject:`${_e.SUBJECT_PREFIXES.TXN}.>`};_||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}o(nB,"addSourceToWorkStream");function iB(e){return e.split(".")[1]}o(iB,"extractServerName");async function aB(e,t,r){let{schema:s,table:n}=r,i=Qd.createNatsTableStreamName(s,n),{jsm:a}=await er(),c=await a.streams.info(t);if(!Array.isArray(c.config.sources)||c.config.sources.length===0)return;let u=c.config.sources.length,l;for(;u--;)if(l=c.config.sources[u],l.name===i&&l.external.api===`$JS.${e}.API`){c.config.sources.splice(u,1);break}await a.streams.update(t,c.config)}o(aB,"removeSourceFromWorkStream");async function vee(e,t,r=2e4,s=xT()){if(!Wd.isObject(t))throw new Error("data param must be an object");let n=Qv.encode(t),{connection:i}=await er(),a={timeout:r};s&&(a.reply=s,a.noMux=!0);let c=await i.request(e,n,a);return GT(c.data)}o(vee,"request");function $T(e){return new Promise(async(t,r)=>{let s=lee(FT,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",a=>{r(a)}),s.stdout.on("data",a=>{i+=a.toString()}),s.stderr.on("data",a=>{n+=a.toString()}),s.stderr.on("close",a=>{n&&r(n),t(i)})})}o($T,"reloadNATS");async function Bee(){let{pid_file_path:e}=eu(Re.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await $T(e)}o(Bee,"reloadNATSHub");async function Hee(){let{pid_file_path:e}=eu(Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await $T(e)}o(Hee,"reloadNATSLeaf");function Fee(e,t,r){let s;switch(e.code){case Kv.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case Kv.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}o(Fee,"requestErrorHandler");async function qee(e,t){let r=t+_e.SERVER_SUFFIX.LEAF;await oB(async()=>{e.subscribe===!0?await nB(r,_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await aB(r,_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}o(qee,"updateWorkStream");function oB(e){return _ee.writeTransaction(Re.SYSTEM_SCHEMA_NAME,Re.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}o(oB,"exclusiveLock");async function cB(e,t){let r=Qd.createNatsTableStreamName(e,t),s=await tu(),n=Vee(e,t,s);await VT(r,[n])}o(cB,"createLocalTableStream");async function Gee(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await cB(s,n)}}o(Gee,"createTableStreams");async function uB(e,t){if(yt.get(Re.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=Qd.createNatsTableStreamName(e,t),{jsm:s}=await er();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")Dr.warn(r);else throw r}}o(uB,"purgeTableStream");async function xee(e,t){if(yt.get(Re.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await uB(e,t[r])}o(xee,"purgeSchemaTableStreams");async function kee(e){return(await jc()).streams.info(e)}o(kee,"getStreamInfo");function Vee(e,t,r){return`${_e.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}o(Vee,"createSubjectName");async function tu(){if(Jc)return Jc;if(Jc=(await jc())?.nc?.info?.server_name,Jc===void 0)throw new Error("Unable to get jetstream manager server name");return Jc}o(tu,"getJsmServerName");async function $ee(){let e=await jc(),t=await tu(),r=await rB();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let a=Yee(s),c=i.split(".");if(!(c[c.length-1]===t&&!a)){if(n.name===_e.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let l=`${_e.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Dr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}else if(n.name===_e.WORK_QUEUE_CONSUMER_NAMES.stream_name){let l=`${_e.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Dr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}else{let l=i.split(".");l[l.length-1]=t;let _=l.join(".");Dr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}await e.streams.update(n.name,n)}}}o($ee,"updateLocalStreams");function Yee(e){let{config:t}=e,r=!1;if(t.name===_e.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===_e.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}o(Yee,"updateStreamLimits")});var Xp=m((J_e,gB)=>{"use strict";var{decode:Kee}=require("msgpackr"),{isMainThread:Wee,parentPort:Qee,threadId:Q_e}=require("worker_threads"),YT=rt(),qa=Be(),zee=g(),ru=q(),_B=Q(),fB=g();_t();var Jee=Ls(),{recordAction:Xee,recordActionBinary:Zee}=(Ra(),re(k_)),{publishToStream:jee}=YT,z_e={durable:qa.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:qa.WORK_QUEUE_CONSUMER_NAMES.deliver_group},ete,tte,rte,hB,mB;gB.exports={initialize:SB,workQueueListener:RB,setSubscription:ste,setIgnoreOrigin:ite,getDatabaseSubscriptions:nte};async function SB(){mB=!0,ru.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await YT.getNATSReferences();ete=e,tte=e.info.server_name,rte=t,hB=r}o(SB,"initialize");var jd=new Map;function ste(e,t,r){let s=jd.get(e);s||jd.set(e,s=new Map),s.set(t,r),mB||SB().then(RB)}o(ste,"setSubscription");function nte(){return jd}o(nte,"getDatabaseSubscriptions");var pB;function ite(e){pB=e}o(ite,"setIgnoreOrigin");var TB=100,dB=new Array(TB),Zd=0;async function RB(){let t=await(await hB.consumers.get(qa.WORK_QUEUE_CONSUMER_NAMES.stream_name,qa.WORK_QUEUE_CONSUMER_NAMES.durable_name)).consume();for await(let r of t)await dB[Zd],dB[Zd]=ate(r).catch(s=>{ru.error(s)}),++Zd>=TB&&(Zd=0)}o(RB,"workQueueListener");Wee||Qee.on("message",async e=>{let{type:t}=e;t===fB.ITC_EVENT_TYPES.SHUTDOWN&&YT.closeConnection()});async function ate(e){let t=Kee(e.data);Xee(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let n=e.headers.get(qa.MSG_HEADERS.ORIGIN)===_B.get(zee.CONFIG_PARAMS.CLUSTERING_NODENAME)&&!pB;if(Zee(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}try{let{operation:i,schema:a,next:c,table:u,records:l,hash_values:_,__origin:d}=t;ru.trace("processing message:",i,a,u,(l?"records: "+l.map(y=>y.id):"")+(_?"ids: "+_:""),"with sequence:",e.seq),ru.trace(`messageProcessor nats msg id: ${e.headers.get(qa.MSG_HEADERS.NATS_MSG_ID)}`);let E;l||(l=_);let{timestamp:f,user:h,node_name:T}=d||{},S=jd.get(a)?.get(u);if(!S)throw new Error("Missing table for replication message",u);if(i==="define_schema")t.type=i,S.send(t);else if(l.length===1&&!c)S.send({type:EB(i),value:l[0],id:_?.[0],timestamp:f,table:u,onCommit:E,user:h,nodeName:T});else{let y=l.map((O,H)=>({type:EB(i),value:O,id:_?.[H],table:u}));for(;c;)y.push({type:c.operation,value:c.record,id:c.id,table:c.table}),c=c.next;S.send({type:"transaction",writes:y,table:u,timestamp:f,onCommit:E,user:h,nodeName:T})}_B.get(fB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&jee(e.subject.split(".").slice(0,-1).join("."),Jee.createNatsTableStreamName(a,u),e.headers,e.data)}catch(i){ru.error(i)}e.ack()}o(ate,"messageProcessor");function EB(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}o(EB,"convertOperation")});var AB=Xp();(async()=>{try{await AB.initialize(),await AB.workQueueListener()}catch(e){console.error("Error launching Nats ingest service."),console.error(e)}})();
|
|
26
|
+
`,"")}a(nB,"runCommand");async function Uee(){try{await lee.access(xT)}catch{return!1}let e=await nB(`${xT} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return _ee.eq(t,wee)}a(Uee,"checkNATSServerInstalled");async function YT(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await jv.getClusterUser();if(Di(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Mr.trace("create nats connection called");let i=await Ree({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:3e4,tls:{keyFile:yt.get(Re.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:yt.get(Re.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:yt.get(Re.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return Mr.trace("create connection established a nats client connection with id",i?.info?.client_id),i}a(YT,"createConnection");async function Dee(){Ns&&(await Ns.drain(),Ns=void 0,Go=void 0,xo=void 0,jc=void 0)}a(Dee,"closeConnection");var Ns,jc;async function tE(){return jc||(jc=YT(yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Ns=await jc),Ns||jc}a(tE,"getConnection");async function tu(){if(Go)return Go;Di(Ns)&&await tE();let{domain:e}=ru(Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Di(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Go=await Ns.jetstreamManager({domain:e}),Go}a(tu,"getJetStreamManager");async function iB(){if(xo)return xo;Di(Ns)&&await tE();let{domain:e}=ru(Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Di(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return xo=Ns.jetstream({domain:e}),xo}a(iB,"getJetStream");async function er(){let e=Ns||await tE(),t=Go||await tu(),r=xo||await iB();return{connection:e,jsm:t,js:r}}a(er,"getNATSReferences");async function Lee(e){let t=yt.get(Re.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await jv.getClusterUser(),n=await YT(t,r,s),i=$T(),o=n.subscribe(i),c=[],u,l=(async()=>{for await(let _ of o){let d=sB.decode(_.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await n.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await n.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await n.flush(),await Xd.async_set_timeout(e),await o.drain(),await n.close(),await l,c}a(Lee,"getServerList");async function KT(e,t){let{jsm:r}=await er(),s=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:tB.File,retention:rB.Limits,subjects:t,discard:gee.Old,duplicate_window:eB,max_msgs:n,max_bytes:i,max_age:s})}a(KT,"createLocalStream");async function oB(){let{jsm:e}=await er(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(oB,"listStreams");async function Mee(e){let{jsm:t}=await er();await t.streams.delete(e)}a(Mee,"deleteLocalStream");async function Pee(e){let{connection:t}=await er(),r=[],s=$T(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(sB.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(Pee,"listRemoteStreams");async function vee(e,t=void 0,r=void 0){let{jsm:s,js:n}=await er(),i=kT(),o={durable_name:i,ack_policy:jd.Explicit};t&&(o.deliver_policy=eE.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let l=[];for await(let _ of u){let d=VT(_.data),E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};if(_.headers&&(E.origin=_.headers.get(_e.MSG_HEADERS.ORIGIN),E.nats_msg_id=_.headers.get(_e.MSG_HEADERS.NATS_MSG_ID)),l.push(E),_.ack(),_.info.pending===0)break}return await c.delete(),l}a(vee,"viewStream");async function*Bee(e,t=void 0,r=void 0){let{jsm:s,js:n}=await er(),i=kT(),o={durable_name:i,ack_policy:jd.Explicit};t&&(o.deliver_policy=eE.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let l of u){let _=VT(l.data);_[0]||(_=[_]);for(let d of _){let E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};l.headers&&(E.origin=l.headers.get(_e.MSG_HEADERS.ORIGIN),E.nats_msg_id=l.headers.get(_e.MSG_HEADERS.NATS_MSG_ID)),yield E}if(l.ack(),l.info.pending===0)break}await c.delete()}a(Bee,"viewStreamIterator");async function Hee(e,t,r,s){Mr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=aB(s,r);let{js:n}=await er(),i=await su(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:Zv.encode(s);try{Mr.trace(`publishToStream publishing to subject: ${o}`),yee(c.length,"bytes-sent",e,s.operation,"replication"),await n.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return _B(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Mr.trace(`publishToStream creating stream: ${t}`);let _=o.split(".");_[2]="*",await KT(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(Hee,"publishToStream");function aB(e,t){t===void 0&&(t=Oee());let r=yt.get(Re.CONFIG_PARAMS.CLUSTERING_NODENAME);if(!t.has(_e.MSG_HEADERS.NATS_MSG_ID)){let s=Xd.getTableHashAttribute(e.schema,e.table),n=e.action?e.action:e.operation,i=`${r}.${e.schema}.${e.table}.${n}.${s}.${Date.now()}.${kT()}`;t.append(_e.MSG_HEADERS.NATS_MSG_ID,i)}return t.has(_e.MSG_HEADERS.ORIGIN)||t.append(_e.MSG_HEADERS.ORIGIN,r),t}a(aB,"addNatsMsgHeader");function ru(e){e=e.toLowerCase();let t=eu.join(yt.get(Re.CONFIG_PARAMS.ROOTPATH),Iee);if(e===Re.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return Di(GT)&&(GT={port:Xc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Xc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.HUB,config_file:_e.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:eu.join(t,_e.PID_FILES.HUB),hdb_nats_path:t}),GT;if(e===Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return Di(qT)&&(qT={port:Xc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Xc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.LEAF,config_file:_e.NATS_CONFIG_FILES.LEAF_SERVER,domain:Xc.getConfigFromFile(Re.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.LEAF,pid_file_path:eu.join(t,_e.PID_FILES.LEAF),hdb_nats_path:t}),qT;Mr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(ru,"getServerConfig");async function Fee(e){let{jsm:t}=await er(),r=await su();try{await t.streams.add({name:e.stream_name,storage:tB.File,retention:rB.Limits,duplicate_window:eB,max_age:pee,max_bytes:Tee,subjects:[`${_e.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:jd.Explicit,durable_name:e.durable_name,deliver_policy:eE.All,max_ack_pending:1e4});else throw s}}a(Fee,"createWorkQueueStream");async function qee(){let{jsm:e}=await er();(await e.consumers.info(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,_e.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Mr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,_e.WORK_QUEUE_CONSUMER_NAMES.durable_name),Mr.info("Adding pull consumer to ingest stream"),await e.consumers.add(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:jd.Explicit,durable_name:_e.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:eE.All,max_ack_pending:1e4}))}a(qee,"updateIngestStreamConsumer");async function cB(e,t,r){let{jsm:s}=await er(),n=await s.streams.info(t),i=uB(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,l=Zd.createNatsTableStreamName(c,u),_=i===e,d,E,f=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let T=0,p=n.config.sources.length;T<p;T++)if(d=n.config.sources[T],E=T,_&&d.name===l||!_&&d.name===l&&d.external&&d.external.api===`$JS.${e}.API`){f=!0;break}if(f===!0){if(d.opt_start_time===o)return;n.config.sources.splice(E,1),await s.streams.update(t,n.config)}let h={name:l,opt_start_time:o,filter_subject:`${_e.SUBJECT_PREFIXES.TXN}.>`};_||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(cB,"addSourceToWorkStream");function uB(e){return e.split(".")[1]}a(uB,"extractServerName");async function lB(e,t,r){let{schema:s,table:n}=r,i=Zd.createNatsTableStreamName(s,n),{jsm:o}=await er(),c=await o.streams.info(t);if(!Array.isArray(c.config.sources)||c.config.sources.length===0)return;let u=c.config.sources.length,l;for(;u--;)if(l=c.config.sources[u],l.name===i&&l.external.api===`$JS.${e}.API`){c.config.sources.splice(u,1);break}await o.streams.update(t,c.config)}a(lB,"removeSourceFromWorkStream");async function Gee(e,t,r=2e4,s=$T()){if(!Xd.isObject(t))throw new Error("data param must be an object");let n=Zv.encode(t),{connection:i}=await er(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return VT(c.data)}a(Gee,"request");function WT(e){return new Promise(async(t,r)=>{let s=hee(xT,["--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(WT,"reloadNATS");async function xee(){let{pid_file_path:e}=ru(Re.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await WT(e)}a(xee,"reloadNATSHub");async function kee(){let{pid_file_path:e}=ru(Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await WT(e)}a(kee,"reloadNATSLeaf");function Vee(e,t,r){let s;switch(e.code){case Jv.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case Jv.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(Vee,"requestErrorHandler");async function $ee(e,t){let r=t+_e.SERVER_SUFFIX.LEAF;await _B(async()=>{e.subscribe===!0?await cB(r,_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await lB(r,_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a($ee,"updateWorkStream");function _B(e){return mee.writeTransaction(Re.SYSTEM_SCHEMA_NAME,Re.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(_B,"exclusiveLock");async function dB(e,t){let r=Zd.createNatsTableStreamName(e,t),s=await su(),n=Qee(e,t,s);await KT(r,[n])}a(dB,"createLocalTableStream");async function Yee(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await dB(s,n)}}a(Yee,"createTableStreams");async function EB(e,t){if(yt.get(Re.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=Zd.createNatsTableStreamName(e,t),{jsm:s}=await er();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")Mr.warn(r);else throw r}}a(EB,"purgeTableStream");async function Kee(e,t){if(yt.get(Re.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await EB(e,t[r])}a(Kee,"purgeSchemaTableStreams");async function Wee(e){return(await tu()).streams.info(e)}a(Wee,"getStreamInfo");function Qee(e,t,r){return`${_e.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Qee,"createSubjectName");async function su(){if(Zc)return Zc;if(Zc=(await tu())?.nc?.info?.server_name,Zc===void 0)throw new Error("Unable to get jetstream manager server name");return Zc}a(su,"getJsmServerName");async function zee(){let e=await tu(),t=await su(),r=await oB();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=Jee(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===_e.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let l=`${_e.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Mr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}else if(n.name===_e.WORK_QUEUE_CONSUMER_NAMES.stream_name){let l=`${_e.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Mr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}else{let l=i.split(".");l[l.length-1]=t;let _=l.join(".");Mr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}await e.streams.update(n.name,n)}}}a(zee,"updateLocalStreams");function Jee(e){let{config:t}=e,r=!1;if(t.name===_e.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===_e.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=yt.get(Re.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(Jee,"updateStreamLimits")});var eT=m((ade,bB)=>{"use strict";var{decode:Xee}=require("msgpackr"),{isMainThread:Zee,parentPort:jee,threadId:ide}=require("worker_threads"),QT=nt(),ko=Be(),ete=A(),nu=x(),hB=Q(),pB=A();dt();var tte=Ps(),{recordAction:rte,recordActionBinary:ste}=(hi(),re(Y_)),{publishToStream:nte}=QT,ode={durable:ko.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:ko.WORK_QUEUE_CONSUMER_NAMES.deliver_group},ite,ote,ate,TB,RB;bB.exports={initialize:gB,workQueueListener:NB,setSubscription:cte,setIgnoreOrigin:lte,getDatabaseSubscriptions:ute};async function gB(){RB=!0,nu.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await QT.getNATSReferences();ite=e,ote=e.info.server_name,ate=t,TB=r}a(gB,"initialize");var sE=new Map;function cte(e,t,r){let s=sE.get(e);s||sE.set(e,s=new Map),s.set(t,r),RB||gB().then(NB)}a(cte,"setSubscription");function ute(){return sE}a(ute,"getDatabaseSubscriptions");var AB;function lte(e){AB=e}a(lte,"setIgnoreOrigin");var OB=100,mB=new Array(OB),rE=0;async function NB(){let t=await(await TB.consumers.get(ko.WORK_QUEUE_CONSUMER_NAMES.stream_name,ko.WORK_QUEUE_CONSUMER_NAMES.durable_name)).consume();for await(let r of t)await mB[rE],mB[rE]=_te(r).catch(s=>{nu.error(s)}),++rE>=OB&&(rE=0)}a(NB,"workQueueListener");Zee||jee.on("message",async e=>{let{type:t}=e;t===pB.ITC_EVENT_TYPES.SHUTDOWN&&QT.closeConnection()});async function _te(e){let t=Xee(e.data);rte(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let n=e.headers.get(ko.MSG_HEADERS.ORIGIN)===hB.get(ete.CONFIG_PARAMS.CLUSTERING_NODENAME)&&!AB;if(ste(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}try{let{operation:i,schema:o,next:c,table:u,records:l,hash_values:_,__origin:d}=t;nu.trace("processing message:",i,o,u,(l?"records: "+l.map(R=>R.id):"")+(_?"ids: "+_:""),"with sequence:",e.seq),nu.trace(`messageProcessor nats msg id: ${e.headers.get(ko.MSG_HEADERS.NATS_MSG_ID)}`);let E;l||(l=_);let{timestamp:f,user:h,node_name:T}=d||{},p=sE.get(o)?.get(u);if(!p)throw new Error("Missing table for replication message",u);if(i==="define_schema")t.type=i,p.send(t);else if(l.length===1&&!c)p.send({type:SB(i),value:l[0],id:_?.[0],timestamp:f,table:u,onCommit:E,user:h,nodeName:T});else{let R=l.map((O,k)=>({type:SB(i),value:O,id:_?.[k],table:u}));for(;c;)R.push({type:c.operation,value:c.record,id:c.id,table:c.table}),c=c.next;p.send({type:"transaction",writes:R,table:u,timestamp:f,onCommit:E,user:h,nodeName:T})}hB.get(pB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&nte(e.subject.split(".").slice(0,-1).join("."),tte.createNatsTableStreamName(o,u),e.headers,e.data)}catch(i){nu.error(i)}e.ack()}a(_te,"messageProcessor");function SB(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(SB,"convertOperation")});var yB=eT();(async()=>{try{await yB.initialize(),await yB.workQueueListener()}catch(e){console.error("Error launching Nats ingest service."),console.error(e)}})();
|