harperdb 4.3.0-alpha.1 → 4.3.0-beta.1

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/bin/lite.js CHANGED
@@ -1,27 +1,27 @@
1
- var Lx=Object.create;var za=Object.defineProperty;var Dx=Object.getOwnPropertyDescriptor;var Mx=Object.getOwnPropertyNames;var Ux=Object.getPrototypeOf,Px=Object.prototype.hasOwnProperty;var a=(e,t)=>za(e,"name",{value:t,configurable:!0});var ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$e=(e,t)=>{for(var r in t)za(e,r,{get:t[r],enumerable:!0})},dA=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Mx(t))!Px.call(e,n)&&n!==r&&za(e,n,{get:()=>t[n],enumerable:!(s=Dx(t,n))||s.enumerable});return e};var U=(e,t,r)=>(r=e!=null?Lx(Ux(e)):{},dA(t||!e||!e.__esModule?za(r,"default",{value:e,enumerable:!0}):r,e)),ee=e=>dA(za({},"__esModule",{value:!0}),e);var w=T((iie,yA)=>{"use strict";var es=require("path"),vx=require("fs"),{relative:sie,join:nie}=es,{existsSync:Bx}=vx;function Hx(){let e=__dirname;for(;!Bx(es.join(e,"package.json"));){let t=es.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Hx,"getHDBPackageRoot");var Qn=Hx(),fA="js",Bl=fA,xx="harperdb-config.yaml",Fx="defaultConfig.yaml",Gx="hdb",EA=`harperdb.${Bl}`,hA=`customFunctionsServer.${Bl}`,qx=`restartHdb.${Bl}`,WE="HarperDB",vl="Custom Functions",Hl="Clustering Hub",xl="Clustering Leaf",kx="Clustering Ingest Service",Vx="Clustering Reply Service",$x="foreground.pid",Yx="hdb.pid",Kx="data",Wx={HDB:WE,CLUSTERING_HUB:Hl,CLUSTERING_LEAF:xl,CLUSTERING_INGEST_SERVICE:kx,CLUSTERING_REPLY_SERVICE:Vx,CUSTOM_FUNCTIONS:vl,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"},Qx={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},zx={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Jx={harperdb:WE,"clustering hub":Hl,"clustering leaf":xl,"custom functions":vl,custom_functions:vl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},Xx={CLUSTERING_HUB_PROC_DESCRIPTOR:Hl,CLUSTERING_LEAF_PROC_DESCRIPTOR:xl},KE={HDB:es.join(Qn,"server/harperdb"),CUSTOM_FUNCTIONS:es.join(Qn,"server/customFunctions"),CLUSTERING_HUB:es.join(Qn,"server/nats"),CLUSTERING_LEAF:es.join(Qn,"server/nats")},jx={HDB:es.join(KE.HDB,EA),CUSTOM_FUNCTIONS:es.join(KE.CUSTOM_FUNCTIONS,hA)},Zx={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:es.join(Qn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:es.join(Qn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:es.join(Qn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},eF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},mA="support@harperdb.io",tF="customer-success@harperdb.io",pA=1,rF=4141,SA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",sF="https://www.harperdb.io/product",nF=`For support, please submit a request at ${SA} or contact ${mA}`,TA=`For license support, please contact ${tF}`,iF="None of the specified records were found.",oF="hash attribute not found",aF=`Your current license only supports ${pA} role. ${TA}`,cF="Your current license only supports 3 connections to a node.",uF="127.0.0.1",lF=1,_F=/^\.$/,dF=/^\.\.$/,fF="U+002E",EF=/\//g,hF="U+002F",mF=/U\+002F/g,pF=/^U\+002E$/,SF=/^U\+002EU\+002E$/,TF="d",gF=999999,RF="*",AF="--max-old-space-size=",OF="system",bF="__hdb_hash",NF=".harperdb",yF=".hdb",IF="keys",wF="hdb_boot_properties.file",CF=".updateConfig.json",LF="SIGTSTP",DF=24,MF=6e4,UF=448,PF="blob",vF="trash",BF="database",HF="schema",xF="transactions",FF=".count",GF="id",qF="PROCESS_NAME",gA={SETTINGS_PATH_KEY:"settings_path"},RA=require("lodash"),kF={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",HDB_CONFIG:"HDB_CONFIG",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},VF={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},$F={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},YF={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"},KF={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"},Ir="hdb_internal:",WF={CREATE_SCHEMA:Ir+"create_schema",CREATE_TABLE:Ir+"create_table",CREATE_ATTRIBUTE:Ir+"create_attribute",ADD_USER:Ir+"add_user",ALTER_USER:Ir+"alter_user",DROP_USER:Ir+"drop_user",HDB_NODES:Ir+"hdb_nodes",HDB_USERS:Ir+"hdb_users",HDB_WORKERS:Ir+"hdb_workers",CATCHUP:Ir+"catchup",SCHEMA_CATCHUP:Ir+"schema_catchup",WORKER_ROOM:Ir+"cluster_workers"},QF={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"},zF="060493.ks",JF=".license",XF={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},J={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",SET_NODE_REPLICATION:"set_node_replication",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"},jF={CSV:".csv",JSON:".json"},ZF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},eG={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Ja={};Ja[J.INSERT]=J.INSERT;Ja[J.UPDATE]=J.UPDATE;Ja[J.UPSERT]=J.UPSERT;Ja[J.DELETE]=J.DELETE;var ve=Object.create(null);ve[J.DESCRIBE_ALL]=J.DESCRIBE_ALL;ve[J.DESCRIBE_TABLE]=J.DESCRIBE_TABLE;ve[J.DESCRIBE_SCHEMA]=J.DESCRIBE_SCHEMA;ve[J.READ_LOG]=J.READ_LOG;ve[J.ADD_NODE]=J.ADD_NODE;ve[J.LIST_USERS]=J.LIST_USERS;ve[J.LIST_ROLES]=J.LIST_ROLES;ve[J.USER_INFO]=J.USER_INFO;ve[J.SQL]=J.SQL;ve[J.GET_JOB]=J.GET_JOB;ve[J.SEARCH_JOBS_BY_START_DATE]=J.SEARCH_JOBS_BY_START_DATE;ve[J.DELETE_FILES_BEFORE]=J.DELETE_FILES_BEFORE;ve[J.EXPORT_LOCAL]=J.EXPORT_LOCAL;ve[J.EXPORT_TO_S3]=J.EXPORT_TO_S3;ve[J.CLUSTER_STATUS]=J.CLUSTER_STATUS;ve[J.REMOVE_NODE]=J.REMOVE_NODE;ve[J.RESTART]=J.RESTART;ve[J.CUSTOM_FUNCTIONS_STATUS]=J.CUSTOM_FUNCTIONS_STATUS;ve[J.GET_CUSTOM_FUNCTIONS]=J.GET_CUSTOM_FUNCTIONS;ve[J.GET_CUSTOM_FUNCTION]=J.GET_CUSTOM_FUNCTION;ve[J.SET_CUSTOM_FUNCTION]=J.SET_CUSTOM_FUNCTION;ve[J.DROP_CUSTOM_FUNCTION]=J.DROP_CUSTOM_FUNCTION;ve[J.ADD_CUSTOM_FUNCTION_PROJECT]=J.ADD_CUSTOM_FUNCTION_PROJECT;ve[J.DROP_CUSTOM_FUNCTION_PROJECT]=J.DROP_CUSTOM_FUNCTION_PROJECT;ve[J.PACKAGE_CUSTOM_FUNCTION_PROJECT]=J.PACKAGE_CUSTOM_FUNCTION_PROJECT;ve[J.DEPLOY_CUSTOM_FUNCTION_PROJECT]=J.DEPLOY_CUSTOM_FUNCTION_PROJECT;var tG={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},rG={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},AA={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"},sG=RA.invert(AA),nG={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"},y={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_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",MAXHEAPMEMORY:"maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",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_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_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",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",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},OA={settings_path:gA.SETTINGS_PATH_KEY,hdb_root_key:y.ROOTPATH,hdb_root:y.ROOTPATH,rootpath:y.ROOTPATH,server_port_key:y.OPERATIONSAPI_NETWORK_PORT,server_port:y.OPERATIONSAPI_NETWORK_PORT,cert_key:y.TLS_CERTIFICATE,certificate:y.TLS_CERTIFICATE,private_key_key:y.TLS_PRIVATEKEY,private_key:y.TLS_PRIVATEKEY,http_secure_enabled_key:y.OPERATIONSAPI_NETWORK_HTTPS,https_on:y.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:y.OPERATIONSAPI_NETWORK_CORS,cors_on:y.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:y.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:y.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:y.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:y.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:y.LOGGING_LEVEL,log_level:y.LOGGING_LEVEL,log_path_key:y.LOGGING_ROOT,log_path:y.LOGGING_ROOT,clustering_node_name_key:y.CLUSTERING_NODENAME,node_name:y.CLUSTERING_NODENAME,clustering_enabled_key:y.CLUSTERING_ENABLED,clustering:y.CLUSTERING_ENABLED,max_http_threads:y.THREADS,max_hdb_processes:y.THREADS,server_timeout_key:y.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:y.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:y.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:y.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:y.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:y.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:y.LOGGING_AUDITLOG,disable_transaction_log:y.LOGGING_AUDITLOG,operation_token_timeout_key:y.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:y.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:y.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:y.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:y.HTTP_PORT,custom_functions_port:y.HTTP_PORT,custom_functions_directory_key:y.COMPONENTSROOT,custom_functions_directory:y.COMPONENTSROOT,max_custom_function_processes:y.THREADS,log_to_file:y.LOGGING_FILE,log_to_stdstreams:y.LOGGING_STDSTREAMS,local_studio_on:y.LOCALSTUDIO_ENABLED,clustering_port:y.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:y.CLUSTERING_USER,clustering_enabled:y.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:y.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:y.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:y.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:y.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:y.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:y.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:y.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:y.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:y.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:y.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:y.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:y.CLUSTERING_NODENAME,clustering_tls_certificate:y.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:y.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:y.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:y.CLUSTERING_TLS_INSECURE,clustering_tls_verify:y.CLUSTERING_TLS_VERIFY,clustering_loglevel:y.CLUSTERING_LOGLEVEL,clustering_republishmessages:y.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:y.CLUSTERING_DATABASELEVEL,customfunctions_network_port:y.HTTP_PORT,customfunctions_tls_certificate:y.TLS_CERTIFICATE,customfunctions_network_cors:y.HTTP_CORS,customfunctions_network_corsaccesslist:y.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:y.HTTP_HEADERSTIMEOUT,customfunctions_network_https:y.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:y.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:y.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:y.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:y.HTTP_TIMEOUT,http_threads:y.THREADS,threads:y.THREADS,maxheapmemory:y.MAXHEAPMEMORY,http_session_affinity:y.HTTP_SESSIONAFFINITY,http_compressionthreshold:y.HTTP_COMPRESSIONTHRESHOLD,http_cors:y.HTTP_CORS,http_corsaccesslist:y.HTTP_CORSACCESSLIST,http_headerstimeout:y.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:y.HTTP_KEEPALIVETIMEOUT,http_timeout:y.HTTP_TIMEOUT,http_port:y.HTTP_PORT,http_secureport:y.HTTP_SECUREPORT,customfunctions_processes:y.THREADS,customfunctions_root:y.COMPONENTSROOT,localstudio_enabled:y.LOCALSTUDIO_ENABLED,logging_file:y.LOGGING_FILE,logging_level:y.LOGGING_LEVEL,logging_root:y.LOGGING_ROOT,logging_rotation_enabled:y.LOGGING_ROTATION_ENABLED,logging_rotation_compress:y.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:y.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:y.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:y.LOGGING_ROTATION_PATH,logging_stdstreams:y.LOGGING_STDSTREAMS,logging_auditlog:y.LOGGING_AUDITLOG,logging_auditretention:y.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:y.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:y.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:y.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:y.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:y.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:y.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:y.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:y.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:y.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:y.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:y.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:y.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:y.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:y.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:y.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:y.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:y.ROOTPATH,databases:y.DATABASES,storage_path:y.STORAGE_PATH,ignorescripts:y.IGNORE_SCRIPTS,mqtt_network_port:y.MQTT_NETWORK_PORT,mqtt_websocket:y.MQTT_WEBSOCKET,mqtt_network_secureport:y.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:y.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:y.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:y.MQTT_NETWORK_MTLS_USER,mqtt_requireauthentication:y.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:y.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:y.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:y.AUTHENTICATION_CACHETTL,authentication_enablesessions:y.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:y.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:y.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:y.COMPONENTSROOT,tls_certificate:y.TLS_CERTIFICATE,tls_privatekey:y.TLS_PRIVATEKEY,tls_certificateauthority:y.TLS_CERTIFICATEAUTHORITY,tls_ciphers:y.TLS_CIPHERS};for(let e in y){let t=y[e];OA[t.toLowerCase()]=t}var iG={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},oG={csv_file_load:"csv_file_load",csv_data_load:J.CSV_DATA_LOAD,csv_url_load:J.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"},aG={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"},cG={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},uG={VERSION_DEFAULT:"2.2.0"},lG={DEVELOPMENT:8192,DEFAULT:512},_G={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"},dG={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"},fG={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},bA={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},EG=Symbol("metadata"),hG="__clustering__",mG=Object.values(bA),pG=15984864e5,NA={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},SG=RA.invert(NA),TG={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"},gG=111,RG=`\r
2
- `,AG={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},OG=["*","%"],bG="unauthorized_access",NG="func_val",yG={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},IG={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},wG={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"},CG={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},LG={HTTP:"http"},DG={STOPPED:"stopped",ONLINE:"online"},MG="3.x.x",UG={SUCCESS:"success",FAILURE:"failure"},PG={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};yA.exports={LOCAL_HARPERDB_OPERATIONS:ve,HDB_SUPPORT_ADDRESS:mA,HDB_SUPPORT_URL:SA,HDB_PRICING_URL:sF,SUPPORT_HELP_MSG:nF,LICENSE_HELP_MSG:TA,HDB_PROC_NAME:EA,HDB_PROC_DESCRIPTOR:WE,CLUSTERING_LEAF_PROC_DESCRIPTOR:xl,CLUSTERING_HUB_PROC_DESCRIPTOR:Hl,SYSTEM_SCHEMA_NAME:OF,HASH_FOLDER_NAME:bF,HDB_HOME_DIR_NAME:NF,UPDATE_FILE_NAME:CF,LICENSE_KEY_DIR_NAME:IF,BOOT_PROPS_FILE_NAME:wF,JOB_TYPE_ENUM:oG,JOB_STATUS_ENUM:XF,SYSTEM_TABLE_NAMES:YF,SYSTEM_TABLE_HASH_ATTRIBUTES:KF,OPERATIONS_ENUM:J,VALID_S3_FILE_TYPES:jF,S3_BUCKET_AUTH_KEYS:ZF,VALID_SQL_OPS_ENUM:eG,GEO_CONVERSION_ENUM:rG,HDB_SETTINGS_NAMES:AA,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:sG,SERVICE_ACTIONS_ENUM:tG,CLUSTER_MESSAGE_TYPE_ENUM:aG,CLUSTER_CONNECTION_DIRECTION_ENUM:cG,CLUSTER_EVENTS_DEFS_ENUM:_G,PERIOD_REGEX:_F,DOUBLE_PERIOD_REGEX:dF,UNICODE_PERIOD:fF,FORWARD_SLASH_REGEX:EF,UNICODE_FORWARD_SLASH:hF,ESCAPED_FORWARD_SLASH_REGEX:mF,ESCAPED_PERIOD_REGEX:pF,ESCAPED_DOUBLE_PERIOD_REGEX:SF,REG_KEY_FILE_NAME:zF,RESTART_TIMEOUT_MS:MF,HDB_FILE_PERMISSIONS:UF,DATABASES_DIR_NAME:BF,LEGACY_DATABASES_DIR_NAME:HF,TRANSACTIONS_DIR_NAME:xF,LIMIT_COUNT_NAME:FF,ID_ATTRIBUTE_STRING:GF,INSERT_MODULE_ENUM:VF,UPGRADE_JSON_FIELD_NAMES_ENUM:$F,RESTART_CODE:LF,RESTART_CODE_NUM:DF,CLUSTER_OPERATIONS:Ja,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:QF,HDB_INTERNAL_SC_CHANNEL_PREFIX:Ir,INTERNAL_SC_CHANNELS:WF,CLUSTERING_MESSAGE_TYPES:TG,HDB_FILE_SUFFIX:yF,BLOB_FOLDER_NAME:PF,HDB_TRASH_DIR:vF,ORIGINATOR_SET_VALUE:gG,LICENSE_VALUES:uG,RAM_ALLOCATION_ENUM:lG,TIME_STAMP_NAMES_ENUM:bA,TIME_STAMP_NAMES:mG,PERMS_UPDATE_RELEASE_TIMESTAMP:pG,SEARCH_NOT_FOUND_MESSAGE:iF,SEARCH_ATTRIBUTE_NOT_FOUND:oF,LICENSE_ROLE_DENIED_RESPONSE:aF,LICENSE_MAX_CONNS_REACHED:cF,BASIC_LICENSE_MAX_NON_CU_ROLES:pA,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:rF,VALUE_SEARCH_COMPARATORS:NA,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:SG,LICENSE_FILE_NAME:JF,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:dG,NEW_LINE:RG,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:lF,MOMENT_DAYS_TAG:TF,API_TURNOVER_SEC:gF,LOOPBACK:uF,CODE_EXTENSION:Bl,WILDCARD_SEARCH_VALUE:RF,NODE_ERROR_CODES:fG,JAVASCRIPT_EXTENSION:fA,PERMS_CRUD_ENUM:AG,UNAUTHORIZED_PERMISSION_NAME:bG,SEARCH_WILDCARDS:OG,FUNC_VAL:NG,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:yG,JWT_ENUM:IG,CLUSTERING_FLAG:hG,ITC_EVENT_TYPES:wG,CUSTOM_FUNCTION_PROC_NAME:hA,CUSTOM_FUNCTION_PROC_DESCRIPTOR:vl,SERVICES:CG,THREAD_TYPES:LG,MEM_SETTING_KEY:AF,HDB_RESTART_SCRIPT:qx,PROCESS_DESCRIPTORS:Wx,SERVICE_SERVERS:jx,SERVICE_SERVERS_CWD:KE,PROCESS_DESCRIPTORS_VALIDATE:Jx,LAUNCH_SERVICE_SCRIPTS:Zx,LOG_LEVELS:zx,PROCESS_NAME_ENV_PROP:qF,LOG_NAMES:Qx,PM2_PROCESS_STATUSES:DG,CONFIG_PARAM_MAP:OA,CONFIG_PARAMS:y,HDB_CONFIG_FILE:xx,HDB_DEFAULT_CONFIG_FILE:Fx,ROLE_TYPES_ENUM:eF,BOOT_PROP_PARAMS:gA,INSTALL_PROMPTS:kF,HDB_ROOT_DIR_NAME:Gx,CLUSTERING_PROCESSES:Xx,FOREGROUND_PID_FILE:$x,PACKAGE_ROOT:Qn,PRE_4_0_0_VERSION:MG,DATABASES_PARAM_CONFIG:iG,METADATA_PROPERTY:EG,AUTH_AUDIT_STATUS:UG,AUTH_AUDIT_TYPES:PG,HDB_PID_FILE:Yx,DEFAULT_DATABASE_NAME:Kx,LEGACY_CONFIG_PARAMS:nG};QE()});var QE=T((cie,wA)=>{var vG=require("fast-glob"),{statSync:zE,existsSync:JE,readFileSync:BG,writeFileSync:HG}=require("fs"),{spawnSync:xG,spawn:FG,execFileSync:aie}=require("child_process"),{isMainThread:GG}=require("worker_threads"),{join:zn,relative:IA}=require("path"),{PACKAGE_ROOT:Ns}=w(),{tmpdir:qG,platform:kG}=require("os");require("source-map-support").install();var VG=["resources","server","dataLayer","components"],Xa="ts-build",XE,$G=__filename.endsWith("tsBuild.js");if($G){if(GG){let r;try{zE(zn(Ns,Xa)),r=!0}catch{}if(r)for(let s of vG.sync(VG.map(n=>n+"/**/*.ts"),{cwd:Ns})){let n=0,i=0;try{n=zE(zn(Ns,s)).mtimeMs-5e3,i=zE(zn(Ns,Xa,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."),XE=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),XE=!0;if(XE){let s=zn(Ns,"node_modules/.bin/tsc");kG()==="win32"&&(s+=".cmd");let n=xG(s,{cwd:Ns});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=zn(qG(),"harperdb-tsc.pid"),o;if(JE(i))try{process.kill(+BG(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=FG(s,["--watch"],{cwd:Ns,detached:!0,stdio:"ignore"});HG(i,c.pid.toString()),c.unref()}}}}let e=wA.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(Ns)&&!s[0].includes("node_modules")){let i=IA(Ns,s[0]),o;i.startsWith(Xa)?o=zn(Ns,IA(Xa,i)):o=zn(Ns,Xa,i);let c=zn(o,r),u=c+".js";if(JE(u))return u;if(c.includes(".")&&JE(c))return c}return t(r,s,n)}}});var Ci={};$e(Ci,{server:()=>At});var CA,At,wr=ge(()=>{CA=require("../index"),At={};(0,CA._assignPackageExport)("server",At)});var jE=T((uie,MA)=>{"use strict";var LA=require("minimist");MA.exports=YG;function YG(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=DA(process.env),s=DA(LA(process.argv))):(r=process.env,s=LA(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(YG,"assignCMDENVVariables");function DA(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(DA,"objKeysToLowerCase")});var q=T((_ie,ih)=>{"use strict";var Li=require("fs-extra"),{workerData:KG,threadId:WG}=require("worker_threads"),Tn=require("path"),vA=require("yaml"),BA=require("properties-reader"),Ot=w(),UA=jE(),QG=require("os"),{PACKAGE_ROOT:eh}=w(),{_assignPackageExport:zG}=require("../index"),Za={};for(let e in console)Za[e]||(Za[e]=console[e]);var sr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},HA={STDOUT:"stdOut",STDERR:"stdErr"},JG=Tn.join(eh,"logs"),XG=Tn.join(eh,"config/yaml/",Ot.HDB_DEFAULT_CONFIG_FILE),jG=1e4,Sn,Ys,rr,Fl,Gl,ec,Do,ja;ja===void 0&&xA();ih.exports={notify:qA,fatal:kA,error:tc,warn:nh,info:ql,debug:sh,trace:rh,setLogLevel:iq,log_level:rr,loggerWithTag:ZG,suppressLogging:eq,initLogSettings:xA,setupConsoleLogging:FA,logCustomLevel:sq,closeLogFile:th,getLogFilePath:()=>ec,OUTPUTS:HA,AuthAuditLog:cq};zG("logger",ih.exports);function xA(e=!1){try{if(ja===void 0||e){th();let t=nq(),r=UA(["ROOTPATH"]);try{ja=BA(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!Li.pathExistsSync(Tn.join(r.ROOTPATH,Ot.HDB_CONFIG_FILE)))throw s}({level:rr,config_log_path:Gl,to_file:Sn,to_stream:Ys}=oq(r.ROOTPATH?Tn.join(r.ROOTPATH,Ot.HDB_CONFIG_FILE):ja.get("settings_path"))),Fl=Ot.LOG_NAMES.HDB,ec=Tn.join(Gl,Fl)}}catch(t){if(ja=void 0,t.code===Ot.NODE_ERROR_CODES.ENOENT){let r=UA(Object.keys(Ot.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Ot.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Ot.CONFIG_PARAMS.LOGGING_LEVEL){rr=u;continue}if(c===Ot.CONFIG_PARAMS.LOGGING_STDSTREAMS){Ys=u;continue}c===Ot.CONFIG_PARAMS.LOGGING_FILE&&(Sn=c)}let{default_level:s,default_to_file:n,default_to_stream:i}=aq();Sn=Sn===void 0?n:Sn,Sn=PA(Sn),Ys=Ys===void 0?i:Ys,Ys=PA(Ys),rr=rr===void 0?s:rr,Gl=JG,Fl=Ot.LOG_NAMES.INSTALL,ec=Tn.join(Gl,Fl);return}throw tc("Error initializing log settings"),tc(t),t}process.env.DEV_MODE&&(Ys=!0),FA()}a(xA,"initLogSettings");var ZE=!0;function FA(){Lo("error",tc),Lo("warn",nh),Lo("log",ql),Lo("info",ql),Lo("debug",sh),Lo("trace",rh)}a(FA,"setupConsoleLogging");function Lo(e,t){console[e]=function(...r){if(ZE&&t(...r),!/PM2 log:|App \[/.test(r[0]))return Za[e](...r)}}a(Lo,"logConsole");function ZG(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(qA),fatal:r(kA),error:r(tc),warn:r(nh),info:r(ql),debug:r(sh),trace:r(rh)};function r(s){return function(...n){return s(t,...n)}}}a(ZG,"loggerWithTag");function eq(e){try{ZE=!1,e()}finally{ZE=!0}}a(eq,"suppressLogging");var tq=KG?.name?.replace(/ /g,"-")||"main";function gn(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||tq+"/"+WG);c<n;c++){let _=t[c];_ instanceof Error&&_.stack?s+=_.stack:typeof _=="object"?s+=JSON.stringify(_):s+=_,c<i&&(s+=" ")}return`${r} [${o.join("] [")}]: ${s}
3
- `}a(gn,"createLogRecord");function rc(e){Sn&&GA(e),Ys&&process.stdout.write(e)}a(rc,"logStdOut");function kl(e){Sn&&GA(e),Ys&&process.stderr.write(e)}a(kl,"logStdErr");function GA(e){rq(),Do?Li.appendFileSync(Do,e):Za.log(e)}a(GA,"logToFile");function th(){try{Li.closeSync(Do)}catch{}Do=null}a(th,"closeLogFile");function rq(){if(!Do){try{if(!ec)debugger;Do=Li.openSync(ec,"a")}catch(e){Za.error(e)}setTimeout(()=>{th()},jG).unref()}}a(rq,"openLogFile");function ql(...e){sr[rr]<=sr.info&&rc(gn("info",e))}a(ql,"info");function rh(...e){sr[rr]<=sr.trace&&rc(gn("trace",e))}a(rh,"trace");function tc(...e){sr[rr]<=sr.error&&kl(gn("error",e))}a(tc,"error");function sh(...e){sr[rr]<=sr.debug&&rc(gn("debug",e))}a(sh,"debug");function qA(...e){sr[rr]<=sr.notify&&rc(gn("notify",e))}a(qA,"notify");function kA(...e){sr[rr]<=sr.fatal&&kl(gn("fatal",e))}a(kA,"fatal");function nh(...e){sr[rr]<=sr.warn&&kl(gn("warn",e))}a(nh,"warn");function sq(e,t,...r){t===HA.STDERR?kl(gn(e,r)):rc(gn(e,r))}a(sq,"logCustomLevel");function nq(){let e;try{e=QG.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=Tn.join(e,Ot.HDB_HOME_DIR_NAME,Ot.BOOT_PROPS_FILE_NAME);return Li.existsSync(t)||(t=Tn.join(eh,"utility/hdb_boot_properties.file")),t}a(nq,"getPropsFilePath");function iq(e){rr=e}a(iq,"setLogLevel");function PA(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(PA,"autoCastBoolean");function oq(e){try{if(e.includes("config/settings.js")){let o=BA(e);return{level:o.get(Ot.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:Tn.dirname(o.get(Ot.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Ot.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Ot.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=vA.parseDocument(Li.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===Ot.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(oq,"getLogConfig");function aq(){try{let e=vA.parseDocument(Li.readFileSync(XG,"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(aq,"getDefaultConfig");function cq(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(cq,"AuthAuditLog")});var $A=T((fie,VA)=>{"use strict";var uq=require("util"),lq=require("path"),_q=require("child_process"),dq=uq.promisify(_q.execFile),fq=1e3*1e3*10;VA.exports={findPs:Eq};async function Eq(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await dq("ps",["wwxo",`pid,${r}`],{maxBuffer:fq});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:lq.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(Eq,"findPs")});var Et=T((hie,KA)=>{"use strict";var hq="__dbis__",mq="__txns__",pq="__environment_name__",Sq="__dbi_defintion__",Tq={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"},gq=["__createdtime__","__updatedtime__"],Rq="\uFFFF",YA={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},Aq=Object.values(YA);KA.exports={AUDIT_STORE_NAME:mq,INTERNAL_DBIS_NAME:hq,DBI_DEFINITION_NAME:Sq,SEARCH_TYPES:Tq,TIMESTAMP_NAMES:gq,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:pq,TRANSACTIONS_DBI_NAMES_ENUM:YA,TRANSACTIONS_DBIS:Aq,OVERFLOW_MARKER:Rq}});var Cr=T((mie,tO)=>{"use strict";var WA=w(),QA=Et(),zA={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},JA=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),XA={500:JA("There was an error processing your request."),400:"Invalid request"},Oq=XA[zA.INTERNAL_SERVER_ERROR],bq={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.`},Nq={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},yq={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"},Iq={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 ${QA.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${QA.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"},wq={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${WA.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 ${WA.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"},jA={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"},Cq={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."},Lq={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`},Dq={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"},Mq={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Uq={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`},ZA={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.`},eO={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}`},Pq={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."},vq={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},Bq={...jA,...yq,...bq,...Cq,...Lq,...Dq,...Mq,...Uq,...wq,...ZA,...eO,...Pq,...vq,...Nq};tO.exports={CHECK_LOGS_WRAPPER:JA,HDB_ERROR_MSGS:Bq,DEFAULT_ERROR_MSGS:XA,DEFAULT_ERROR_RESP:Oq,HTTP_STATUS_CODES:zA,LMDB_ERRORS_ENUM:Iq,AUTHENTICATION_ERROR_MSGS:jA,VALIDATION_ERROR_MSGS:ZA,ITC_ERRORS:eO}});var Z=T((Sie,nO)=>{"use strict";var Mo=Cr(),Hq=q(),xq=w(),Vl=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,rO),this.statusCode=s||Mo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Mo.DEFAULT_ERROR_MSGS[s]?Mo.DEFAULT_ERROR_MSGS[s]:Mo.DEFAULT_ERROR_MSGS[Mo.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&&Hq[n](i)}},oh=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}},ah=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function rO(e,t,r,s=xq.LOG_LEVELS.ERROR,n=null,i=!1){if(sO(e))return e;let o=new Vl(e,t,r,s,n);return i&&delete o.stack,o}a(rO,"handleHDBError");function sO(e){return e.__proto__.constructor.name===Vl.name}a(sO,"isHDBError");nO.exports={isHDBError:sO,handleHDBError:rO,ClientError:oh,ServerError:ah,hdb_errors:Mo}});var We=T((gie,_O)=>{"use strict";var ac=w(),Fq=z(),nr=j(),cc=require("path"),Gq=require("minimist"),iO=require("fs-extra"),oO=require("lodash");nr.initSync();var{CONFIG_PARAMS:Jn,DATABASES_PARAM_CONFIG:sc,SYSTEM_SCHEMA_NAME:$l}=ac,nc,ic,oc;function aO(){if(nc!==void 0)return nc;if(nr.getHdbBasePath()!==void 0)return nc=nr.get(Jn.STORAGE_PATH)||cc.join(nr.getHdbBasePath(),ac.DATABASES_DIR_NAME),nc}a(aO,"getBaseSchemaPath");function cO(){if(ic!==void 0)return ic;if(nr.getHdbBasePath()!==void 0)return ic=lO($l),ic}a(cO,"getSystemSchemaPath");function uO(){if(oc!==void 0)return oc;if(nr.getHdbBasePath()!==void 0)return oc=nr.get(ac.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cc.join(nr.getHdbBasePath(),ac.TRANSACTIONS_DIR_NAME),oc}a(uO,"getTransactionAuditStoreBasePath");function qq(e,t){let r=nr.get(Jn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cc.join(uO(),e.toString())}a(qq,"getTransactionAuditStorePath");function lO(e,t){e=e.toString(),t=t&&t.toString();let r=nr.get(ac.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cc.join(aO(),e)}a(lO,"getSchemaPath");function kq(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,Gq(process.argv));let s=r[Jn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!Fq.isObject(s))throw o;i=s}for(let o of i){let c=o[$l];if(!c)continue;let u=nr.get(Jn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[sc.PATH];if(_)return oO.set(u,[$l,sc.TABLES,t,sc.PATH],_),nr.setProperty(Jn.DATABASES,u),_;let l=c?.[sc.PATH];if(l)return oO.set(u,[$l,sc.PATH],l),nr.setProperty(Jn.DATABASES,u),l}}let n=r[Jn.STORAGE_PATH.toUpperCase()];if(n){if(!iO.pathExistsSync(n))throw new Error(n+" does not exist");let i=cc.join(n,e);return iO.mkdirsSync(i),nr.setProperty(Jn.STORAGE_PATH,n),i}return cO()}a(kq,"initSystemSchemaPaths");function Vq(){nc=void 0,ic=void 0,oc=void 0}a(Vq,"resetPaths");_O.exports={getBaseSchemaPath:aO,getSystemSchemaPath:cO,getTransactionAuditStorePath:qq,getTransactionAuditStoreBasePath:uO,getSchemaPath:lO,initSystemSchemaPaths:kq,resetPaths:Vq}});var Lr=T((bie,mO)=>{"use strict";var $q=Cr().LMDB_ERRORS_ENUM,Aie=require("lmdb"),Yq=Et(),Oie=require("buffer").Buffer,{OVERFLOW_MARKER:dO,MAX_SEARCH_KEY_LENGTH:Yl}=Yq,fO=["number","string","symbol","boolean","bigint"];function Kq(e){if(e=e?.primaryStore||e,!e)throw new Error($q.ENV_REQUIRED)}a(Kq,"validateEnv");function Wq(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(Wq,"stringifyData");function Qq(e){return e instanceof Date?e.valueOf():e}a(Qq,"convertKeyValueToWrite");function zq(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(fO.includes(typeof e))return e.length>Yl?[e.slice(0,Yl)+dO]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if(fO.includes(typeof i))i.length>Yl?r.push(i.slice(0,Yl)+dO):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(zq,"getIndexedValues");var Kl=0,EO=0;function hO(){EO=Date.now()-performance.now()}a(hO,"adjustStartTime");hO();var Jq=6e4;setInterval(hO,Jq).unref();function Xq(){let e=performance.now()+EO;return e>Kl?(Kl=e,e):(Kl+=488e-6,Kl)}a(Xq,"getNextMonotonicTime");mO.exports={validateEnv:Kq,stringifyData:Wq,convertKeyValueToWrite:Qq,getNextMonotonicTime:Xq,getIndexedValues:zq}});var pO,ys,ch,uc=ge(()=>{pO=require("events"),ys=class extends pO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new ch;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)}},ch=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 Dr(e){return e[Qt]||(e[Qt]=Object.create(null))}function Jl(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[me])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new ts.ClientError(`${c} must be a string, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new ts.ClientError(`${c} must be a string, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new ts.ClientError(`${c} must be a number, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new ts.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new ts.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new ts.ClientError(`${c} must be a number, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new ts.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new ts.ClientError(`${c} must be a Date, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new ts.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Dr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new ts.ClientError(`${c} must be an object, attempt to assign ${l}`);Dr(this)[c]=l},"set")}_={get(){let l=this[Qt];if(l&&c in l)return l[c];let d=this[ye]?.[c];if(d&&typeof d=="object"){let f=SO(d,o);if(f)return l||(l=this[Qt]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,s[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Qt];return u?.[o]!==void 0?u[o]:this[ye]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new ts.ClientError("Can not add a property to a sealed table schema");Dr(this)[o]=c}),i("deleteProperty",function(o){Dr(this)[o]=void 0}),i("toJSON",function(){let o=this[Qt],c;for(let _ in o)c||(c=Object.assign({},this[ye])),c[_]=o[_];return Object.keys(this).length>0&&(c||(c=Object.assign({},this[ye])),Object.assign(c,this)),c||this[ye]}),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 SO(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[ye]=n}},Jl(r,t)),new r(e)):new Wl(e);case Array:let s=new zl(e.length);s[ye]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=SO(o,t?.elements)),s[n]=o}return s}}function Xl(e){let t=e[Qt],r;for(let n in t){r||(r=Object.assign({},e[ye]));let i=t[n];i&&typeof i=="object"&&(i=Xl(i)),r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[ye])),Object.assign(r,e)),r||e[ye]}function lc(e){let t;if(e[ye]&&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=lc(i);o!==i&&t===e&&(t=e.slice(0)),i=o}t[s]=i}return Object.freeze(t)}let r=e[Qt];for(let s in r){t||(t=Object.assign({},e[ye]));let n=r[s];n&&typeof n=="object"&&(n=lc(n)),t[s]=n}return t?Object.freeze(t):e[ye]||(e.buffer?e:Object.freeze(e))}function Ql(e){let t=e[ye];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Di]||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?.[ye]===n){if(Ql(i))return!0}else return!0}}else{let r=e[Qt];if(r&&!t)return!0;for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[ye]===i){if(Ql(n))return!0}else return!0}else return!0}}return!1}var ts,Qt,Wl,Di,zl,jl=ge(()=>{Is();ts=U(Z()),Qt=Symbol("own-data");a(Dr,"getChanges");a(Jl,"assignTrackedAccessors");a(SO,"trackObject");Wl=class{static{a(this,"GenericTrackedObject")}constructor(t){this[ye]=t}};Jl(Wl,{});a(Xl,"collapseData");a(lc,"deepFreeze");a(Ql,"hasChanges");Di=Symbol.for("has-array-changes"),zl=class extends Array{static{a(this,"TrackedArray")}[Di];constructor(t){super(t)}splice(...t){return this[Di]=!0,super.splice(...t)}push(...t){return this[Di]=!0,super.push(...t)}pop(){return this[Di]=!0,super.pop()}unshift(...t){return this[Di]=!0,super.unshift(...t)}shift(){return this[Di]=!0,super.shift()}};zl.prototype.constructor=Array});function tk(){ek=setInterval(function(){for(let e of uh)if(e.stale){let t=e[me]?.url;TO.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},Zq).unref()}var lh,TO,jq,uh,Mi,Zl,Zq,ek,_h=ge(()=>{lh=U(Lr()),TO=U(q());Is();jq=100,uh=new Set,Mi=class{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=!0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn;if(!this.open)throw new Error("Can not start a read on a transaction that is no longer open");return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),uh.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(uh.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(!this.open&&!this.autoCommitMode)throw new Error("Can not use a transaction that is no longer open");this.writes.push(t),this.autoCommitMode&&this.commit()}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,lh.getNextMonotonicTime)());let s=t.retries||0;if(this.validated<this.writes.length){let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let R=S();E?E.push?E.push(R):E=[E,R]:E=R}}E&&await(E.push?Promise.all(E):E)}return this.commit(t)})()}s||this.doneReadTxn(),t?.prepared?.(),this.open=!1;let n,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,s)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){s>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);n=n||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<jq>>s?u():n=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),n)return n.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=s+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(t){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=!1,this.writes=[]}},Zl=class extends Mi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,lh.getNextMonotonicTime)())}getReadTxn(){}},Zq=3e4;a(tk,"startMonitoringTxns");tk()});function Qe(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let s=e.transaction=new Mi;e.timestamp&&(s.timestamp=e.timestamp),s[me]=e,e.resourceCache||(e.resourceCache=[]);let n;try{if(n=t(s),n?.then)return n.then(i,o)}catch(c){o(c)}return i(n);function i(c){let u=s.commit(r?.resetTransaction?{prepared(){s.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw s.abort({}),c}}var gO,Ui=ge(()=>{gO=require("../index");Is();_h();a(Qe,"transaction");(0,gO._assignPackageExport)("transaction",Qe);Qe.commit=function(e){let t=(e[me]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Qe.abort=function(e){let t=(e[me]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function dc(e,t,r,s,n,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],O=Rn(s.attributes,R);if(O.relationship){if(o.length<2)throw new Pi.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let b=O.definition?.tableClass||O.elements?.definition?.tableClass,P=new Map,$=dc({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,b,n,P);if(O.relationship.to){i[o[0]]=P;let x=!!Rn(b.attributes,O.relationship.to)?.elements;$=ik($,O,b.primaryStore,x,P)}if(O.relationship.from){let x=a(D=>dc({attribute:O.relationship.from,value:D},t,r,s,n,P),"searchEntry");O.elements?(i[o[0]]=P,$=ok($,O,b.primaryStore,P,x)):$=$.flatMap(x)}return $}else if(o.length===1)o=o[0];else throw new Pi.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(AO[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=Ws.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case Xe.SEARCH_TYPES.EQUALS:case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"contains":case"ends_with":E=!0;break;default:throw new Pi.ClientError(`Unknown query comparator "${u}"`)}if(r){let R=_;_=l,l=R,R=!f,f=!d,d=R}let h=o===s.primaryKey||o==null,p=h?s.primaryStore:s.indices[o];if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(!n)throw new Pi.ClientError(`"${o}" is not indexed${c===null&&!p.indexNulls?" for nulls, index needs to be rebuilt to search for nulls":p?.isIndexing?" yet":""}, can not search for this attribute`,404);let R=fc(e);if(!R)throw new Pi.ClientError(`Unknown search operator ${e.comparator}`);return s.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:O,value:b})=>new Promise((P,$)=>setImmediate(()=>{try{P(b&&R(b)?O:dh.SKIP)}catch(x){$(x)}})))}let S={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(S).map(O=>O.value==null?dh.SKIP:O);return R.hasEntries=!0,R}else return p.getRange(S).map(({value:R})=>R)}function Rn(e,t){if(Array.isArray(t))if(t.length>1){let r=Rn(e,t[0]),s=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return s?Rn(s,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function ik(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i,o;return{next(){if(!i){let u=t.relationship.to;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=jn(d),o=!0);let h=n.get(E);h?h.push(f):n.set(E,h=[f]),d!==E&&(h.key=d)},"add_entry"),l=0;for await(let d of e){let f=d.value??r.get(d.key??d),E=f?.[u];if(E!=null&&!n.filters?.some(h=>!h(f))){if(s)for(let h=0;h<E.length;h++)_(E[h],d);else _(E,d);l++>100&&(await new Promise(setImmediate),l=0)}}return i=(o?n:n.keys())[Symbol.iterator](),this.next()})()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function ok(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i,o;return{next(){let c;if(o&&(c=o.next(),!c.done))return c;if(!i)return(async()=>{let u=new Map;s.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>u.has(jn(d)));let _=0;for await(let l of e){if(s.filters){let d=r.get(l);if(s.filters.some(f=>!f(d)))continue}u.set(jn(l),l),_++>100&&(await new Promise(setImmediate),_=0)}return i=u.values()[Symbol.iterator](),this.next()})();do{let u=i.next();return u.done?u:(o=n(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function fc(e,t,r,s){if(e.conditions){let c=e.conditions.map(fc);return e.operator==="or"?u=>c.some(_=>_(u)):u=>c.every(_=>_(u))}let n=e.comparator,i=e[0]??e.attribute,o=e[1]??e.value;if(Array.isArray(i)){if(i.length===0)return()=>!0;if(i.length===1)i=i[0];else if(i.length>1){let c=i[0],u=Rn(t.attributes,c),_=u.definition?.tableClass||u.elements.definition?.tableClass,l=s?.[c],d=fc({attribute:i.length>2?i.slice(1):i[1],value:o,comparator:n},t,r,l?.[c]?.joined);if(!d)return;if(l){l.filters||(l.filters=[]),l.filters.push(d);return}let f=t.propertyResolvers?.[c];return(E,h)=>{let p,S;return f?(S=f(E,r,h),p=S?.value):p=E[c],p?Array.isArray(p)?p.some(d):d(p,S):!1}}}switch(o instanceof Date&&(o=o.getTime()),AO[n]||n){case Xe.SEARCH_TYPES.EQUALS:case void 0:return Ks(i,c=>c===o);case Xe.SEARCH_TYPES.CONTAINS:return Ks(i,c=>c?.toString().includes(o));case Xe.SEARCH_TYPES.ENDS_WITH:case Xe.SEARCH_TYPES._ENDS_WITH:return Ks(i,c=>c?.toString().endsWith(o));case Xe.SEARCH_TYPES.STARTS_WITH:case Xe.SEARCH_TYPES._STARTS_WITH:return Ks(i,c=>typeof c=="string"&&c.startsWith(o));case Xe.SEARCH_TYPES.BETWEEN:return o[0]instanceof Date&&(o[0]=o[0].getTime()),o[1]instanceof Date&&(o[1]=o[1].getTime()),Ks(i,c=>(0,Ws.compareKeys)(c,o[0])>=0&&(0,Ws.compareKeys)(c,o[1])<=0);case"gt":case Xe.SEARCH_TYPES.GREATER_THAN:case Xe.SEARCH_TYPES._GREATER_THAN:return Ks(i,c=>(0,Ws.compareKeys)(c,o)>0);case"ge":case Xe.SEARCH_TYPES.GREATER_THAN_EQUAL:case Xe.SEARCH_TYPES._GREATER_THAN_EQUAL:return Ks(i,c=>(0,Ws.compareKeys)(c,o)>=0);case Xe.SEARCH_TYPES.LESS_THAN:case"lt":case Xe.SEARCH_TYPES._LESS_THAN:return Ks(i,c=>(0,Ws.compareKeys)(c,o)<0);case"le":case Xe.SEARCH_TYPES.LESS_THAN_EQUAL:case Xe.SEARCH_TYPES._LESS_THAN_EQUAL:return Ks(i,c=>(0,Ws.compareKeys)(c,o)<=0);case"ne":return Ks(i,c=>(0,Ws.compareKeys)(c,o)!==0);default:throw new Pi.ClientError(`Unknown query comparator "${n}"`)}}function Ks(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 fh(e){return t=>{if(t.estimated_count===void 0){if(t.conditions){let s;if(t.operator==="or"){s=0;for(let n of t.conditions)s+=n.estimated_count}else{s=1/0;for(let n of t.conditions)s=1/(1/s+1/n.estimated_count)}return t.estimated_count=s,t.estimated_count}let r=t.comparator||t.search_type;if(r===Xe.SEARCH_TYPES.EQUALS){let s=t[0]??t.attribute;if(s==null||s===e.primaryKey)t.estimated_count=1;else if(Array.isArray(s)){let n=Rn(e.attributes,s[0]),i=n.definition?.tableClass||n.elements.definition?.tableClass,o=fh(i)({value:t.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"});t.estimated_count=o*4*(e.indices[n.relationship.from]||e.primaryStore).getStats().entryCount/(i.primaryStore.getStats().entryCount||1)}else{let n=e.indices[s];t.estimated_count=n?n.getValuesCount(t[1]??t.value):1/0}}else r===Xe.SEARCH_TYPES.CONTAINS||r===Xe.SEARCH_TYPES.ENDS_WITH||r==="ne"?t.value===null&&r==="ne"?t.estimated_count=RO:t.estimated_count=1/0:r===Xe.SEARCH_TYPES.STARTS_WITH||r==="prefix"?t.estimated_count=RO:r===Xe.SEARCH_TYPES.BETWEEN?t.estimated_count=sk:t.estimated_count=rk;typeof t.descending=="boolean"&&(t.estimated_count/=4)}return t.estimated_count}}function e_(e){if(e)if(Xn=e,Uo.lastIndex=0,ak.test(e))try{let t=_c(new vo,"");if(ir!==Xn.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${ir} in '${Xn}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function _c(e,t){let r=Uo,s,n,i,o,c;for(;s=r.exec(Xn);){ir=r.lastIndex;let[,u,_]=s;if(o){if(u)throw new SyntaxError(`expected operator, but encountered '${u}'`);o=!1,c=!1}else c=!0;let l;switch(_){case"=":if(n)u.length<=2&&(i=u);else{if(i="equals",!u)throw new SyntaxError("attribute must be specified before equality comparator");n=Po(u)}break;case"!=":case"<":case"<=":case">":case">=":if(i=nk[_],!u)throw new SyntaxError(`attribute must be specified before comparator ${_}`);n=Po(u);break;case"=*":i="ends_with",n=Po(u);break;case"*":o=!0;case"*&":e.conditions?e.conditions.push({comparator:i==="ends_with"?"contains":"starts_with",attribute:n,value:decodeURIComponent(u)}):e.push(u+_),n=null;break;case"|":e.operator="or";case"":case void 0:case"&":if(n==null){if(n===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${_[0]?"'"+_[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${_?"'"+_+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.conditions.push({comparator:i,attribute:n,value:decodeURIComponent(u)})}n=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(Po(u)),n=void 0;break;case"(":Uo.lastIndex=ir;let d=_c(u?[]:new vo,")");switch(u){case"":e.conditions.push(d);break;case"limit":switch(d.length){case 1:e.limit=+d[0];break;case 2:e.offset=+d[0],e.limit=d[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(d[0])&&d.length===1&&!d[0].name?(e.select=d[0],e.select.asArray=!0):d.length===1?e.select=d[0]:d.length===2&&d[1]===""?e.select=d.slice(0,1):e.select=d;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=OO(d);break;default:throw new SyntaxError(`unknown query function call ${u}`)}Xn[ir]===","?r.lastIndex=++ir:o=!0,n=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!u)throw new SyntaxError("property sets must have a defined parent property name");Uo.lastIndex=ir,l=_c([],"}"),l.name=u,e.push(l),Xn[ir]===","?r.lastIndex=++ir:o=!0;break;case"[":Uo.lastIndex=ir,u?(l=_c(new vo,"]"),l.name=u):l=_c(e.conditions?new vo:[],"]"),e.conditions?(e.conditions.push(l),n=null):e.push(l),Xn[ir]===","?r.lastIndex=++ir:o=!0;break;case")":case"]":case"}":if(t===_[0]){if(e.conditions){if(n)e.conditions.push({comparator:i||"equals",attribute:n,value:decodeURIComponent(u)});else if(u)throw new SyntaxError("no attribute or comparison specified")}else(u||e.length>0&&c)&&e.push(Po(u));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${_[0]}'`):new SyntaxError(`unexpected token '${_[0]}'`);default:throw new SyntaxError(`unexpected operator '${_}'`)}if(t!==")"&&(r=n?ck:Uo,r.lastIndex=ir),ir===Xn.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Po(e){return e.indexOf(".")>-1?e.split(".").map(Po):decodeURIComponent(e)}function OO(e){let t=bO(e[0]);return e.length>1&&(t.next=OO(e.slice(1))),t}function bO(e){if(Array.isArray(e)){let t=bO(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function jn(e){return Array.isArray(e)?e.join("\0"):e}var Pi,Xe,Ws,dh,rk,sk,RO,nk,AO,ak,Uo,ck,ir,Xn,vo,t_=ge(()=>{Pi=U(Z()),Xe=U(Et()),Ws=require("ordered-binary"),dh=require("lmdb"),rk=1e8,sk=15e6,RO=1e7,nk={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne"};a(dc,"searchByIndex");a(Rn,"findAttribute");a(ik,"joinTo");a(ok,"joinFrom");AO={greater_than:"gt",greater_than_equal:"ge",less_than:"lt",less_than_equal:"le",not_equal:"ne",equal:"equals",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(fc,"filterByType");a(Ks,"attributeComparator");a(fh,"estimateCondition");ak=/[()[\]*|!<>.]|(=\w+=)/,Uo=/([^?&|=<>!([{}\])*,]*)([([{}\])|,&]|[=<>!*]*)/g,ck=/([^&|*=[\]{}]+)([[\]{}]|[&|*=]*)/g;a(e_,"parseQuery");a(_c,"parseBlock");a(Po,"decodeProperty");a(OO,"toSortObject");a(bO,"toSortEntry");vo=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}}};a(jn,"flattenKey")});var mh={};$e(mh,{CONTEXT:()=>me,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>ns,RECORD_PROPERTY:()=>ye,Resource:()=>Ft,SAVE_UPDATES_PROPERTY:()=>CO,snake_case:()=>lk,transformForSelect:()=>s_});function lk(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function NO(e,t){if(Ec=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Ec=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),s=new hh;for(let n=0;n<r.length;n++){let i=r[n];if(!i&&n===r.length-1){Ec=!0;break}s[n]=t.coerceId(decodeURIComponent(i))}return s}function rs(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[me]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[me]||i):l=i:(l=n,c=l[Le]??l[this.primaryKey]??null):i?o=i[me]||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=[],_=!0;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,_=!1)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=n.id??null,c==null&&(_=!0))}else c=n??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return d.resetTransaction=!0,Qe(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(t.type==="read"&&(E[CO]=!1),o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new r_(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new r_(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function ss(e,t){let r=new wO.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 Eh(e,t,r){let s=e[ye];if(s){let n=e[Qt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:n&&i in n?n[i]:(c=t?.[i])?c(e,r):s[i]}}else return t?n=>{let i=t[n];return i?i(e,r):e[n]}:n=>e[n]}function s_(e,t){let r=t?.propertyResolvers,s=t[me],n;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):Eh(c,r,s)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(Eh(u,r,s));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(Eh(u,r,s)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){n||(n={});let u=n[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=n[c.name]=s_(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var yO,IO,wO,me,Le,ns,CO,ye,uk,Ft,r_,Ec,hh,Is=ge(()=>{yO=require("crypto");uc();IO=require("../index"),wO=U(Z());jl();Ui();t_();me=Symbol.for("context"),Le=Symbol.for("primary-key"),ns=Symbol("is-collection"),CO=Symbol("save-updates"),ye=Symbol("stored-record"),uk={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Ft=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let s=r?.[me];this[me]=s!==void 0?s:r||null}static get=rs(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&&!c.selectApplied){let _=s_(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",resetTransaction:!0,ensureLoaded:!0,async:!0});static put=rs(function(t,r,s,n){if(Array.isArray(n)&&t[ns]){let i=[],o=s.authorize;for(let c of n){let u=t.constructor,_=u.getResource(c[u.primaryKey],s,{async:!0});_.then?i.push(_.then(l=>l.put(c,s))):i.push(_.put(c,s))}return Promise.all(i)}return t.put?t.put(n,r):ss(t,"put")},{hasContent:!0,type:"update"});static delete=rs(function(t,r,s,n){return t.delete?t.delete(r):ss(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,yO.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),Qe(s,()=>{let i=new this(n,s),o=i.update?i.update(r):ss(i,"update");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=rs(function(t,r,s,n){return t.invalidate?t.invalidate(r):ss(t,"delete")},{hasContent:!1,type:"update"});static post=rs(function(t,r,s,n){return t[Le]!=null&&t.update?.(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=rs(function(t,r,s,n){return t.connect?t.connect(n,r):ss(t,"connect")},{hasContent:!0,type:"read"});static subscribe=rs(function(t,r,s,n){return t.subscribe?t.subscribe(r):ss(t,"subscribe")},{type:"read"});static publish=rs(function(t,r,s,n){return t[Le]!=null&&t.update?.(),t.publish?t.publish(n,r):ss(t,"publish")},{hasContent:!0,type:"create"});static search=rs(function(t,r,s,n){let i=t.search?t.search(r):ss(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=s_(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=rs(function(t,r,s,n){return t.search?t.search(n,r):ss(t,"search")},{hasContent:!0,type:"read"});static copy=rs(function(t,r,s,n){return t.copy?t.copy(n,r):ss(t,"copy")},{type:"create"});static move=rs(function(t,r,s,n){return t.move?t.move(n,r):ss(t,"move")},{type:"delete"});post(t){if(this[ns])return this.constructor.create(this[Le],t,this[me]);ss(this,"post")}static isCollection(t){return t?.[ns]}static coerceId(t){return t}static parseQuery(t){return e_(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let o=t.slice(n+1);t=t.slice(0,n);let c=r?.headers&&uk[o];if(c)r.headers.set("accept",c);else if(s)s.property=o;else return{query:{property:o},id:NO(t,this),isCollection:Ec}}let i=NO(t,this);return Ec?{id:i,isCollection:!0}:i}static getResource(t,r,s){let n,i=r[me],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=s?.isCollection;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 _=u.asMap.get(t);if(n=_?.find(l=>l.constructor===c),n)return n;_||u.asMap.set(t,_=[]),_.push(n=new c(t,i))}else{if(n=u.find(_=>_[Le]===t&&_.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Le],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else n=new c(t,i);return o&&(n[ns]=!0),n}subscribe(t){return new ys}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new ys}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[Le]}getContext(){return this[me]}};Ft.prototype[me]=null;(0,IO._assignPackageExport)("Resource",Ft);a(lk,"snake_case");r_=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(NO,"pathToId");hh=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(rs,"transactional");a(ss,"missingMethod");a(Eh,"selectFromObject");a(s_,"transformForSelect")});var LO={};$e(LO,{Resources:()=>n_,keyArrayToString:()=>Bo,resetResources:()=>_k,resources:()=>Zn});function _k(){return Zn=new n_}function Bo(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var n_,Zn,hc=ge(()=>{Ui();n_=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 _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=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&&(t[0]!=="/"&&(t="/"+t),n.relativeURL=t)),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 Qe(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(_k,"resetResources");a(Bo,"keyArrayToString")});var BO={};$e(BO,{HAS_EXPIRATION:()=>Oh,LAST_TIMESTAMP_PLACEHOLDER:()=>pc,LOCAL_TIMESTAMP:()=>dk,METADATA:()=>mc,NO_TIMESTAMP:()=>ph,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Ah,RecordEncoder:()=>Rh,TIMESTAMP_ASSIGN_LAST:()=>Ek,TIMESTAMP_ASSIGN_NEW:()=>UO,TIMESTAMP_ASSIGN_PREVIOUS:()=>PO,TIMESTAMP_PLACEHOLDER:()=>i_,TIMESTAMP_RECORD_PREVIOUS:()=>Sh,getUpdateRecord:()=>bh,handleLocalTimeForGets:()=>u_});function vO(){return xo[0]=xo[0]^64,fk.getFloat64(0)}function u_(e){let t=e.getEntry;e.readCount=0,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[mc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[mc]>=0?c.value:c};let s=e.getRange;e.getRange=function(i){let o=s.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[mc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})},e.env.metadataRetriever||(e.env.metadataRetriever=!0,e.on("aftercommit",({next:i,last:o})=>{do{let c=i.meta,u=c&&c.store;if(u&&!(i.flag&67108864)){let _=u.cache;if(c.key){let l=hk.call(_,c.key);if(l&&l.timestampBytes){let d=l.timestampOffset;l.timestampBytes[d]===2&&(l.timestampBytes.copy(xo,0,d),l.timestampBytes=null,l.localTime=vO())}}}}while(i!=o&&(i=i.next))}));let n=e.useReadTransaction();if(n.done(),!n.done.isTracked){let i=n.constructor,o=n.use,c=n.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,vi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<vi.length;u++){let _=vi[u].deref();(!_||_===this||_.isDone||_.isCommitted)&&vi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function bh(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Ho=i?.localTime?Sh|PO:ph:Ho=u?i?.localTime?Sh|16384:UO|16384:ph,l>0&&(c|=Oh),a_=c,gh=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Ho>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(s,n,h);if(e.cache&&S.result!==!1){let R=e.cache.get(s);R&&(c>=0?R.metadataFlags=c:R.metadataFlags>=0&&(R.metadataFlags=void 0),(l||!R.expiresAt)&&(R.expiresAt=l),h.instructedWrite&&(R.localTime||(R.localTime=1),R.timestampBytes=Th,R.timestampOffset=Th.start||0))}if(u){let R=_?.user?.username;if(E&&(o_=e.encoder.encode(E)),f&&i?.localTime){let O=i?.localTime,b=r.get(O);if(b){let P=Mr(b).previousLocalTime;return r.put(O,c_(o,t,s,P,R,d,o_),{ifVersion:p}),S}}r.put(pc,c_(o,t,s,i?.localTime?1:0,R,d,o_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+s+" options: "+h,S}}}var DO,MO,i_,pc,Ah,dk,mc,xo,fk,ph,UO,Ek,PO,Sh,Oh,Th,o_,Ho,a_,gh,Rh,hk,vi,Sc=ge(()=>{DO=require("msgpackr");Fo();MO=U(q()),i_=new Uint8Array([1,1,1,1,4,64,0,0]),pc=new Uint8Array([1,1,1,1,1,0,0,0]),Ah=new Uint8Array([1,1,1,1,3,64,0,0]),dk=Symbol("local-timestamp"),mc=Symbol("metadata"),xo=new Uint8Array(8),fk=new DataView(xo.buffer,0,8),ph=0,UO=0,Ek=1,PO=3,Sh=4,Oh=16,Ho=0,a_=-1,gh=0,Rh=class extends DO.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,n){if(Ho||a_>=0){let i=0,o=Ho;o&&(i+=8,Ho=0);let c=a_,u=gh;c>=0&&(i+=2,a_=-1,u&&(i+=8,gh=0));let _=Th=r.call(this,s,n|2048|i);o_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(i_[4]=o,i_[5]=o>>8,_.set(i_,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,s,n)}}decode(t,r){let s=r?.start||0,n=r>-1?r:r?.end||t.length,i=t[s],o=0;try{if(i<32&&n>2){let c=s,u;if(i===2){if(t.copy)t.copy(xo,0,c),c+=8;else for(let d=0;d<8;d++)xo[d]=t[c++];u=vO(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Oh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,n),n-c);return{localTime:u,value:l,[mc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(vO,"getTimestamp");hk=Map.prototype.get;a(u_,"handleLocalTimeForGets");vi=[];setInterval(()=>{for(let e=0;e<vi.length;e++){let t=vi[e].deref();!t||t.isDone||t.isCommitted?vi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&MO.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t),t.openTimer++):t.openTimer=1)}},15e3).unref();a(bh,"getUpdateRecord")});var QO={};$e(QO,{AUDIT_STORE_OPTIONS:()=>KO,createAuditEntry:()=>c_,openAuditStore:()=>__,readAuditEntry:()=>Mr,setAuditRetention:()=>mk,transactionKeyEncoder:()=>YO});function __(e){let t=e.auditStore=e.openDB(qO.AUDIT_STORE_NAME,KO);t.rootStore=e;let r=[];return t.addDeleteRemovalCallback=function(s,n){return r[s]=n,{remove(){delete r[s]}}},(0,VO.getWorkerIndex)()===0&&e.on("aftercommit",()=>{Tc||(Tc=setTimeout(()=>{if(Tc=null,t.rootStore.status!=="closed")for(let{key:s,value:n}of t.getRange({start:0,end:Date.now()-Nh})){if((n[0]&15)===Ih){let i=Mr(n),o=i.tableId;r[o]?.(i.recordId)}t.remove(s)}},Nh/10).unref())}),t}function mk(e){clearTimeout(Tc),Tc=null,Nh=e}function c_(e,t,r,s,n,i,o){let c=WO[i],u=1;s&&(s>1?Go.setFloat64(0,s):is.set(Ah),u=9),f(0),f(t),d(r),Go.setFloat64(u,e),u+=8,n?d(n):is[u++]=0,is[s?8:0]=c;let l=is.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,qo.writeKey)(E,is,u);let p=u-h-1;p>127?p>16383?(Ch.error("Key or username was too large for audit entry",E),u=h+1,is[h]=0):(is.copyWithin(h+2,h+1,u),Go.setUint16(h,p|32768),u++):is[h]=p}function f(E){E<128?is[u++]=E:E<16384?(Go.setUint16(u,E|32768),u+=2):E<1056964608?(Go.setUint32(u,E|3221225472),u+=4):(is[u]=255,Go.setUint32(u+1,E),u+=5)}}function Mr(e){try{let t=e.dataView||(e.dataView=new wh(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let s=t.readInt(),n=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:WO[s&7],tableId:i,get recordId(){return GO(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?GO(e,l,d):void 0},getValue(f){return s&yh?f.decoder.decode(e.subarray(t.position)):void 0}}}catch{return Ch.error("Reading audit entry error",e),{}}}function GO(e,t,r){let s=e.subarray(t,r);return(0,qo.readKey)(s,0,r-t)}var qo,l_,qO,kO,VO,$O,Ch,is,Go,YO,KO,Nh,Tc,yh,HO,Ih,xO,FO,WO,wh,Fo=ge(()=>{qo=require("ordered-binary"),l_=U(j()),qO=U(Et()),kO=U(w()),VO=U(Ze()),$O=U(z());Sc();Ch=U(q());(0,l_.initSync)();is=Buffer.alloc(1024),Go=new DataView(is.buffer,is.byteOffset,1024),YO={writeKey(e,t,r){return e===pc?(t.set(pc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,qo.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,qo.readKey)(e,t,r)}},KO={encoding:"binary",keyEncoder:YO},Nh=(0,$O.convertToMS)((0,l_.get)(kO.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Tc=null;a(__,"openAuditStore");a(mk,"setAuditRetention");yh=16,HO=1,Ih=2,xO=3,FO=4,WO={put:HO|yh,[HO]:"put",delete:Ih,[Ih]:"delete",message:xO|yh,[xO]:"message",invalidate:FO,[FO]:"invalidate"};a(c_,"createAuditEntry");a(Mr,"readAuditEntry");wh=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(GO,"readKeySafely")});function JO(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;ko||((0,Rc.onMessageByType)(zO,l=>{XO(l.path)}),(0,Rc.onMessageByType)(pk,l=>{(0,gc.trace)("confirming to proceed with txn",l.txnId)}),ko=Object.create(null));let o=ko[n]||(ko[n]=[]);o.auditStore=e.auditStore;let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Bo(t);let u=new Dh(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function XO(e,t){if(!ko)return;let r=ko[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(n){throw n.message+=" in "+e,n}let s;for(let{key:n,value:i}of r.auditStore.getRange({start:Lh,exclusiveStart:!0})){Lh=n;let o=Mr(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Bo(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=n){(0,gc.info)("omitting",u,h.startTime,n);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(s?s.push(h):s=[h]),h.txnInProgress=o.version),h.listener(u,o,n,p)}catch(p){console.error(p),(0,gc.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(s)for(let n of s)n.txnInProgress=null,n.listener(null,{type:"end_txn"},Lh,!0)}function jO(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",()=>{(0,Rc.broadcast)({type:zO,path:n}),XO(n,!0)})}}var gc,Rc,zO,pk,ko,ioe,Dh,Lh,ZO=ge(()=>{gc=U(q()),Rc=U(Ze());uc();hc();Fo();zO="transaction",pk="transaction-await",ioe=Buffer.alloc(4096);a(JO,"addSubscription");Dh=class extends ys{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}},Lh=Date.now();a(XO,"notifyFromTransactionData");a(jO,"listenToCommits")});var tb=T((coe,eb)=>{"use strict";var Mh=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};eb.exports=Mh});var sb=T((loe,rb)=>{"use strict";var Uh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};rb.exports=Uh});var d_=T((doe,nb)=>{"use strict";var vh=j(),Bh=w(),{RecordEncoder:Sk}=(Sc(),ee(BO));vh.initSync();var Tk=vh.get(Bh.CONFIG_PARAMS.STORAGE_COMPRESSION),gk=vh.get(Bh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,Rk=Bh.UPDATES_PROPERTY,Ph=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=Tk&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=gk&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:Sk},this.alwaysLazyProperty=s=>s===Rk)}};nb.exports=Ph});var E_=T((Eoe,ob)=>{"use strict";var Vo=j(),Ac=w();Vo.initSync();var Ak=Vo.get(Ac.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Vo.get(Ac.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Vo.get(Ac.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",ib=Vo.get(Ac.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),Ok=Vo.get(Ac.CONFIG_PARAMS.STORAGE_NOREADAHEAD),f_=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=Ak,this.noFSAccess=!0,ib!==void 0&&(this.overlappingSync=ib),this.noReadAhead=Ok}};ob.exports=f_;f_.MAX_DBS=1e4});var Ye=T((moe,mb)=>{"use strict";var xh=require("lmdb"),ws=require("fs-extra"),Ur=require("path"),h_=Lr(),ub=q(),or=Cr().LMDB_ERRORS_ENUM,m_=sb(),Fh=d_(),lb=E_(),ei=Et(),ab=w(),{table:bk,resetDatabases:Nk}=(pe(),ee(Ge)),cb=j(),Cs=ei.INTERNAL_DBIS_NAME,_b=ei.DBI_DEFINITION_NAME,yk="data.mdb",Ik="lock.mdb",Oc=".mdb",wk="-lock",Hh=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=os(t,r),this.key_type=this.dbi[ei.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ei.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new xh.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function p_(e,t){if(e===void 0)throw new Error(or.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(or.ENV_NAME_REQUIRED)}a(p_,"pathEnvNameValidation");async function Gh(e,t,r=!0){try{await ws.access(e)}catch(s){throw s.code==="ENOENT"?new Error(or.INVALID_BASE_PATH):s}try{let s=Ur.join(e,t+Oc);return await ws.access(s,ws.constants.R_OK|ws.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await ws.access(Ur.join(e,t,yk),ws.constants.R_OK|ws.constants.F_OK),Ur.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(or.INVALID_ENVIRONMENT)}else throw new Error(or.INVALID_ENVIRONMENT);throw s}}a(Gh,"validateEnvironmentPath");function S_(e,t){if(h_.validateEnv(e),t===void 0)throw new Error(or.DBI_NAME_REQUIRED)}a(S_,"validateEnvDBIName");async function Ck(e,t,r=!1,s=!1){p_(e,t);let n=Ur.basename(e);t=t.toString();let i=cb.get(ab.CONFIG_PARAMS.DATABASES);i||cb.setProperty(ab.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await Gh(e,t,s),db(e,t,r)}catch(o){if(o.message===or.INVALID_ENVIRONMENT){let c=Ur.join(e,t);await ws.mkdirp(s?c:e);let u=new lb(s?c:c+Oc,!1),_=xh.open(u);_.dbis=Object.create(null);let l=new Fh(!1);_.openDB(Cs,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=qh(e,t,r);return _[ei.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(Ck,"createEnvironment");async function Lk(e,t,r,s=!0){p_(e,t),t=t.toString();let n=Ur.join(e,t);return bk({table:t,database:Ur.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(Lk,"copyEnvironment");async function db(e,t,r=!1){p_(e,t),t=t.toString();let s=qh(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 Gh(e,t),i=Ur.join(e,t+Oc),o=n!=i,c=new lb(n,o),u=xh.open(c);u.dbis=Object.create(null);let _=Eb(u);for(let l=0;l<_.length;l++)os(u,_[l]);return u[ei.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(db,"openEnvironment");async function Dk(e,t,r=!1){p_(e,t),t=t.toString();let s=Ur.join(e,t+Oc),n=await Gh(e,t);if(global.lmdb_map!==void 0){let i=qh(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await fb(o),delete global.lmdb_map[i]}}await ws.remove(n),await ws.remove(n===s?n+wk:Ur.join(Ur.dirname(n),Ik))}a(Dk,"deleteEnvironment");async function fb(e){h_.validateEnv(e);let t=e[ei.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(fb,"closeEnvironment");function qh(e,t,r=!1){let n=`${Ur.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(qh,"getCachedEnvironmentName");function Mk(e){h_.validateEnv(e);let t=Object.create(null),r=os(e,Cs);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==Cs)try{t[s]=Object.assign(new m_,n)}catch{ub.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(Mk,"listDBIDefinitions");function Eb(e){h_.validateEnv(e);let t=[],r=os(e,Cs);for(let{key:s}of r.getRange({start:!1}))s!==Cs&&t.push(s);return t}a(Eb,"listDBIs");function Uk(e,t){let s=os(e,Cs).getEntry(t),n=new m_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{ub.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(Uk,"getDBIDefinition");function hb(e,t,r,s=!r){if(S_(e,t),t=t.toString(),t===Cs)throw new Error(or.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return os(e,t)}catch(n){if(n.message===or.DBI_DOES_NOT_EXIST){let i=new Fh(r,s===!0),o=e.openDB(t,i),c=new m_(r===!0,s);return o[_b]=c,os(e,Cs).putSync(t,c),e.dbis[t]=o,o}throw n}}a(hb,"createDBI");function os(e,t){if(S_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Cs?r=Uk(e,t):r=new m_,r===void 0)throw new Error(or.DBI_DOES_NOT_EXIST);let s;try{let n=new Fh(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(or.DBI_DOES_NOT_EXIST):n}return s[_b]=r,e.dbis[t]=s,s}a(os,"openDBI");function Pk(e,t){S_(e,t),t=t.toString();let r=os(e,t),s=r.getStats();return r[ei.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(Pk,"statDBI");async function vk(e,t){try{let r=Ur.join(e,t+Oc);return(await ws.stat(r)).size}catch{throw new Error(or.INVALID_ENVIRONMENT)}}a(vk,"environmentDataSize");function Bk(e,t){if(S_(e,t),t=t.toString(),t===Cs)throw new Error(or.CANNOT_DROP_INTERNAL_DBIS_NAME);os(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],os(e,Cs).removeSync(t)}a(Bk,"dropDBI");function Hk(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{os(e,i)}catch(o){if(o.message===or.DBI_DOES_NOT_EXIST)hb(e,i,i!==t,i===t),s=!0;else throw o}}s&&Nk()}a(Hk,"initializeDBIs");mb.exports={openDBI:os,openEnvironment:db,createEnvironment:Ck,listDBIs:Eb,listDBIDefinitions:Mk,createDBI:hb,dropDBI:Bk,statDBI:Pk,deleteEnvironment:Dk,initializeDBIs:Hk,TransactionCursor:Hh,environmentDataSize:vk,copyEnvironment:Lk,closeEnvironment:fb}});var Tb=T((Soe,Sb)=>{"use strict";var kh=Ye(),xk=q(),pb=Cr().LMDB_ERRORS_ENUM;Sb.exports=Fk;async function Fk(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 kh.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==pb.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await kh.closeEnvironment(global.lmdb_map[s]),await kh.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==pb.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){xk.error(t)}}a(Fk,"cleanLMDBMap")});var Bi=T((goe,Gk)=>{Gk.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",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var Mb=T((Aoe,Db)=>{"use strict";var Vh=require("recursive-iterator"),qk=require("alasql"),$h=require("clone"),gb=z(),{handleHDBError:Rb,hdb_errors:kk}=Z(),{HDB_ERROR_MSGS:Ab,HTTP_STATUS_CODES:Ob}=kk,{getDatabases:Vk}=(pe(),ee(Ge)),$k=["DISTINCT_ARRAY"],bb=Symbol("validateTables"),Yh=Symbol("validateTable"),Roe=Symbol("getAllColumns"),Nb=Symbol("validateAllColumns"),T_=Symbol("findColumn"),yb=Symbol("validateOrderBy"),bc=Symbol("validateSegment"),Kh=Symbol("validateColumn"),Ib=Symbol("setColumnsForTable"),wb=Symbol("checkColumnsForAsterisk"),Cb=Symbol("validateGroupBy"),Lb=Symbol("hasColumns"),Wh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[bb](),this[wb](),this[Nb]()}[bb](){if(this[Lb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Yh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Yh](t.table)})}}[Lb](){let t=!1,r=new Vh(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Yh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=Vk();if(!r[t.databaseid])throw Rb(new Error,Ab.SCHEMA_NOT_FOUND(t.databaseid),Ob.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Rb(new Error,Ab.TABLE_NOT_FOUND(t.databaseid,t.tableid),Ob.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=$h(n);i.table=$h(t),this.attributes.push(i)})}[T_](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)}[wb](){let t=new Vh(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[Ib](r.tableid)}[Ib](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new qk.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Nb](){this[bc](this.statement.columns,!1),this[bc](this.statement.joins,!1),this[bc](this.statement.where,!1),this[Cb](this.statement.group,!1),this[bc](this.statement.order,!0)}[bc](t,r){if(!t)return;let s=new Vh(t),n=[];for(let{node:i,path:o}of s)!gb.isEmpty(i)&&!gb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[yb](i):n.push(this[Kh](i)));return n}[Cb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&$k.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=$h(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[T_](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[T_](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`}[yb](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[Kh](t)}[Kh](t){let r=this[T_](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]}};Db.exports=Wh});var Pb=T((boe,Ub)=>{"use strict";var Qh=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")}};Ub.exports=Qh});var Bb=T((yoe,vb)=>{"use strict";var zh=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};vb.exports=zh});var xb=T((woe,Hb)=>{"use strict";var Jh=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}};Hb.exports=Jh});var Gb=T((Loe,Fb)=>{"use strict";var Xh=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};Fb.exports=Xh});var $o=T((voe,Vb)=>{"use strict";var Yk=Ye(),Kk=Bb(),Wk=xb(),Qk=Gb(),Qs=Lr(),Nc=Cr().LMDB_ERRORS_ENUM,zk=Et(),An=w(),Jk=z(),Xk=require("uuid"),Moe=require("lmdb"),{handleHDBError:jk,hdb_errors:Zk}=Z(),{OVERFLOW_MARKER:Uoe,MAX_SEARCH_KEY_LENGTH:Poe}=zk,qb=j();qb.initSync();var g_=qb.get(An.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),jh=An.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Hi=An.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function eV(e,t,r,s,n=Qs.getNextMonotonicTime()){rm(e,t,r,s),Zh(e,t,r);let i=new Kk,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];kb(_,!0,n);let l=tV(e,t,r,_),d=_[t];o.push(l),c.push(d)}return em(o,c,s,i,n)}a(eV,"insertRecords");function tV(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 l=c([[{}]]);Array.isArray(l)&&(c=l[0][An.FUNC_VAL],s[o]=c)}let u=Qs.getIndexedValues(c),_=e.dbis[o];if(u){g_&&_.prefetch(u.map(l=>({key:l,value:n})),R_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],n)}}g_&&e.dbis[t].prefetch([n],R_),e.dbis[t].put(n,s,s[Hi])})}a(tV,"insertRecord");function rV(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(rV,"removeSkippedRecords");function kb(e,t,r){let s=r>0;(s||!Number.isInteger(e[Hi]))&&(e[Hi]=r||(r=Qs.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[jh]))&&(e[jh]=r||Qs.getNextMonotonicTime()):delete e[jh]}a(kb,"setTimestamps");function Zh(e,t,r){r.indexOf(An.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(An.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(An.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(An.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),Yk.initializeDBIs(e,t,r)}a(Zh,"initializeTransaction");async function sV(e,t,r,s,n=Qs.getNextMonotonicTime()){rm(e,t,r,s),Zh(e,t,r);let i=new Wk,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=tm(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return em(c,u,s,i,n,o)}a(sV,"updateRecords");async function nV(e,t,r,s,n=Qs.getNextMonotonicTime()){try{rm(e,t,r,s)}catch(u){throw jk(u,u.message,Zk.HTTP_STATUS_CODES.BAD_REQUEST)}Zh(e,t,r);let i=new Qk,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;Jk.isEmpty(_[t])?(l=Xk.v4(),_[t]=l):l=_[t];let d=tm(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return em(o,c,s,i,n)}a(nV,"upsertRecords");async function em(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||Qs.getNextMonotonicTime(),rV(r,i),s}a(em,"finalizeWrite");function tm(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(kb(r,!l,o),Number.isInteger(r[Hi])&&_[Hi]>r[Hi])return!1;l&&n.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let R=_[h];if(typeof p=="function"){let b=p([[_]]);Array.isArray(b)&&(p=b[0][An.FUNC_VAL],r[h]=p)}if(p===R)continue;let O=Qs.getIndexedValues(R);if(O){g_&&S.prefetch(O.map(b=>({key:b,value:s})),R_);for(let b=0,P=O.length;b<P;b++)S.remove(O[b],s)}if(O=Qs.getIndexedValues(p),O){g_&&S.prefetch(O.map(b=>({key:b,value:s})),R_);for(let b=0,P=O.length;b<P;b++)S.put(O[b],s)}}let E=Object.assign({},_,r);c.put(s,E,E[Hi])},"do_put");return u?d=c.ifVersion(s,u.version,f):d=c.ifNoExists(s,f),d.then(E=>E?!0:tm(e,t,r,s,n,i,o))}a(tm,"updateUpsertRecord");function iV(e,t,r){if(Qs.validateEnv(e),t===void 0)throw new Error(Nc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Nc.WRITE_ATTRIBUTES_REQUIRED):new Error(Nc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(iV,"validateBasic");function rm(e,t,r,s){if(iV(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Nc.RECORDS_REQUIRED):new Error(Nc.RECORDS_MUST_BE_ARRAY)}a(rm,"validateWrite");function R_(){}a(R_,"noop");Vb.exports={insertRecords:eV,updateRecords:sV,upsertRecords:nV}});var Js=T((Hoe,Kb)=>{"use strict";var Yb=z(),$b=w(),Yo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,zs=require("joi"),ti={schema_format:{pattern:Yo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},oV=zs.alternatives(zs.string().min(1).max(ti.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),zs.number(),zs.array()).required(),aV=zs.alternatives(zs.string().min(1).max(ti.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),zs.number()),cV=zs.alternatives(zs.string().min(1).max(ti.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),zs.number()).required();function uV(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ti.schema_length.maximum?`'${e}' maximum of 250 characters`:Yo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(uV,"checkValidTable");function lV(e,t){return Yb.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(lV,"validateSchemaExists");function _V(e,t){let r=t.state.ancestors[0].schema;return Yb.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(_V,"validateTableExists");function dV(e,t){return e.toLowerCase()===$b.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${$b.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(dV,"validateSchemaName");Kb.exports={common_validators:ti,schema_regex:Yo,hdb_schema_table:oV,validateSchemaExists:lV,validateTableExists:_V,validateSchemaName:dV,checkValidTable:uV,hdb_database:aV,hdb_table:cV}});var et=T((Foe,Wb)=>{"use strict";var ar=require("validate.js");ar.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||ar.validators.type.checks[t](e)?null:` must be a '${t}' value`};ar.validators.type.checks={Object:function(e){return ar.isObject(e)&&!ar.isArray(e)},Array:ar.isArray,Integer:ar.isInteger,Number:ar.isNumber,String:ar.isString,Date:ar.isDate,Boolean:function(e){return typeof e=="boolean"}};ar.validators.hasValidFileExt=function(e,t){return ar.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};Wb.exports={validateObject:fV,validateObjectAsync:EV,validateBySchema:hV};function fV(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=ar(e,t,{format:"flat"});return r?new Error(r):null}a(fV,"validateObject");async function EV(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await ar.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(EV,"validateObjectAsync");function hV(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(hV,"validateBySchema")});var A_=T((qoe,Qb)=>{var{common_validators:Xs}=Js(),Ic=et(),yc="is required",ht={database:{presence:!1,format:Xs.schema_format,length:Xs.schema_length},schema:{presence:!1,format:Xs.schema_format,length:Xs.schema_length},table:{presence:!0,format:Xs.schema_format,length:Xs.schema_length},attribute:{presence:!0,format:Xs.schema_format,length:Xs.schema_length},hash_attribute:{presence:!0,format:Xs.schema_format,length:Xs.schema_length}};function wc(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(wc,"makeAttributesStrings");function mV(e){return e=wc(e),ht.table.presence=!1,ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Ic.validateObject(e,ht)}a(mV,"schema_object");function pV(e){return e=wc(e),ht.table.presence={message:yc},ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Ic.validateObject(e,ht)}a(pV,"table_object");function SV(e){return e=wc(e),ht.table.presence={message:yc},ht.attribute.presence=!1,Ic.validateObject(e,ht)}a(SV,"create_table_object");function TV(e){return e=wc(e),ht.table.presence={message:yc},ht.attribute.presence={message:yc},ht.hash_attribute.presence=!1,Ic.validateObject(e,ht)}a(TV,"attribute_object");function gV(e){return e=wc(e),ht.table.presence={message:yc},ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Ic.validateObject(e,ht)}a(gV,"describe_table");function RV(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(RV,"validateTableResidence");Qb.exports={schema_object:mV,create_table_object:SV,table_object:pV,attribute_object:TV,describe_table:gV,validateTableResidence:RV}});var Jb=T((Voe,zb)=>{"use strict";var AV=require("uuid"),sm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||AV.v4(),this.schema_table=`${this.schema}.${this.table}`}};zb.exports=sm});var O_=T((Yoe,Xb)=>{"use strict";var OV=Jb(),nm=class extends OV{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}};Xb.exports=nm});var Zb=T((Woe,jb)=>{"use strict";jb.exports=NV;var bV="inserted";function NV(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===bV?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(NV,"returnObject")});var b_=T((zoe,nN)=>{"use strict";var yV=w(),im=Ye(),IV=$o(),{getSystemSchemaPath:wV,getSchemaPath:CV}=We(),LV=Bi(),DV=A_(),MV=O_(),UV=Zb(),{handleHDBError:eN,hdb_errors:rN}=Z(),tN=z(),{HTTP_STATUS_CODES:PV}=rN,om=LV.hdb_attribute,sN=[];for(let e=0;e<om.attributes.length;e++)sN.push(om.attributes[e].attribute);var vV="inserted";nN.exports=BV;async function BV(e){let t=DV.attribute_object(e);if(t)throw eN(new Error,t.message,rN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&tN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw eN(new Error,r,PV.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=tN.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 MV(e.schema,e.table,e.attribute,e.id);try{let i=await im.openEnvironment(CV(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}`);im.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await im.openEnvironment(wV(),yV.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await IV.insertRecords(o,om.hash_attribute,sN,[n]);return UV(vV,c,{records:[n]},u)}catch(i){throw i}}a(BV,"lmdbCreateAttribute")});var cm=T((Xoe,oN)=>{var{hdb_table:HV,hdb_database:iN}=Js(),xV=et(),am=require("joi"),FV={undefined:"undefined",null:"null"},GV=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||FV[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"),qV=am.object({database:iN,schema:iN,table:HV,records:am.array().items(am.object().custom(GV)).required()});oN.exports=function(e){return xV.validateBySchema(e,qV)}});var Cc=T((eae,cN)=>{"use strict";var On=z(),aN=q(),Zoe=cm(),{getDatabases:kV}=(pe(),ee(Ge)),{ClientError:xi}=Z();cN.exports=VV;function VV(e){if(On.isEmpty(e))throw new xi("invalid update parameters defined.");if(On.isEmptyOrZeroLength(e.schema))throw new xi("invalid schema specified.");if(On.isEmptyOrZeroLength(e.table))throw new xi("invalid table specified.");if(!Array.isArray(e.records))throw new xi("records must be an array");let t=kV()[e.schema]?.[e.table];if(On.isEmpty(t))throw new xi(`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&&On.isEmptyOrZeroLength(o[r]))throw aN.error("a valid hash attribute must be provided with update record:",o),new xi("a valid hash attribute must be provided with update record, check log for more info");if(!On.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw aN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new xi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!On.isEmpty(o[r])&&o[r]!==""&&s.has(On.autoCast(o[r]))&&(o.skip=!0),s.add(On.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(VV,"insertUpdateValidate")});var Lc=T((rae,uN)=>{"use strict";var $V=w().OPERATIONS_ENUM,um=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=$V.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};uN.exports=um});var Pc=T((iae,lN)=>{"use strict";var nae=Lc(),N_=w(),_m=z(),lm=q(),YV=require("uuid"),{handleHDBError:Dc,hdb_errors:KV}=Z(),{HDB_ERROR_MSGS:Mc,HTTP_STATUS_CODES:Uc}=KV;lN.exports=WV;function WV(e,t,r){for(let n=0;n<t.length;n++)QV(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];zV(i,r,e.operation)}}a(WV,"processRows");function QV(e){if(Buffer.byteLength(String(e))>N_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Dc(new Error,Mc.ATTR_NAME_LENGTH_ERR(e),Uc.BAD_REQUEST,void 0,void 0,!0);if(_m.isEmptyOrZeroLength(e)||_m.isEmpty(e.trim()))throw Dc(new Error,Mc.ATTR_NAME_NULLISH_ERR,Uc.BAD_REQUEST,void 0,void 0,!0)}a(QV,"validateAttribute");function zV(e,t,r){if(!e.hasOwnProperty(t)||_m.isEmptyOrZeroLength(e[t])){if(r===N_.OPERATIONS_ENUM.INSERT||r===N_.OPERATIONS_ENUM.UPSERT){e[t]=YV.v4();return}throw lm.error("Update transaction aborted due to record with no hash value:",e),Dc(new Error,Mc.RECORD_MISSING_HASH_ERR,Uc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>N_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw lm.error(e),Dc(new Error,Mc.HASH_VAL_LENGTH_ERR,Uc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw lm.error(e),Dc(new Error,Mc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Uc.BAD_REQUEST,void 0,void 0,!0)}a(zV,"validateHash")});var y_=T((aae,dN)=>{"use strict";var _N=z(),JV=w(),XV=q(),jV=b_(),ZV=O_(),e$=bn(),{SchemaEventMsg:t$}=Ls(),r$="already exists in";dN.exports=s$;async function s$(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 n$(e,t.schema,t.name,i)})),n}a(s$,"lmdbCheckForNewAttributes");async function n$(e,t,r,s){let n=new ZV(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await i$(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(r$))XV.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(n$,"createNewAttribute");async function i$(e){let t;return t=await jV(e),e$.signalSchemaChange(new t$(process.pid,JV.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(i$,"createAttribute")});var Ko=T((uae,fN)=>{"use strict";var dm=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}};fN.exports=dm});var hN=T((_ae,EN)=>{"use strict";var o$=Ko(),a$=w().OPERATIONS_ENUM,fm=class extends o${static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(a$.INSERT,r,s,n,i),this.records=t}};EN.exports=fm});var pN=T((fae,mN)=>{"use strict";var c$=Ko(),u$=w().OPERATIONS_ENUM,Em=class extends c${static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(u$.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};mN.exports=Em});var TN=T((hae,SN)=>{"use strict";var l$=Ko(),_$=w().OPERATIONS_ENUM,hm=class extends l${static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(_$.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};SN.exports=hm});var RN=T((pae,gN)=>{"use strict";var d$=Ko(),f$=w().OPERATIONS_ENUM,mm=class extends d${static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(f$.DELETE,s,n,t,i),this.original_records=r}};gN.exports=mm});var vc=T((gae,NN)=>{"use strict";var Tae=require("path"),AN=Ye(),E$=hN(),h$=pN(),m$=TN(),p$=RN(),Wo=Et(),ON=z(),{CONFIG_PARAMS:S$}=w(),bN=j();bN.initSync();var I_=w().OPERATIONS_ENUM,{getTransactionAuditStorePath:T$}=We();NN.exports=g$;async function g$(e,t){if(bN.get(S$.LOGGING_AUDITLOG)===!1)return;let r=T$(e.schema,e.table),s=await AN.openEnvironment(r,e.table,!0),n=R$(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){AN.initializeDBIs(s,Wo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Wo.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[Wo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[Wo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),ON.isEmpty(n.user_name)||s.dbis[Wo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[Wo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(g$,"writeTransaction");function R$(e,t){let r=ON.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===I_.INSERT)return new E$(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===I_.UPDATE)return new h$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===I_.UPSERT)return new m$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===I_.DELETE)return new p$(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(R$,"createTransactionObject")});var pm=T((Oae,yN)=>{"use strict";var A$=Cc(),Aae=Lc(),Bc=w(),O$=Pc(),b$=$o().insertRecords,N$=Ye(),y$=q(),I$=y_(),{getSchemaPath:w$}=We(),C$=vc();yN.exports=L$;async function L$(e){try{let{schema_table:t,attributes:r}=A$(e);O$(e,r,t.hash_attribute),e.schema!==Bc.SYSTEM_SCHEMA_NAME&&(r.includes(Bc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Bc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Bc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Bc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await I$(e.hdb_auth_header,t,r),n=w$(e.schema,e.table),i=await N$.openEnvironment(n,e.table),o=await b$(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await C$(e,o)}catch(c){y$.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(L$,"lmdbCreateRecords")});var CN=T((Nae,wN)=>{"use strict";var IN=w(),D$=pm(),M$=Lc(),U$=require("fs-extra"),{getSchemaPath:P$}=We();wN.exports=v$;async function v$(e){let t=[{name:e.schema,createddate:Date.now()}],r=new M$(IN.SYSTEM_SCHEMA_NAME,IN.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await D$(r),await U$.mkdirp(P$(e.schema))}a(v$,"lmdbCreateSchema")});var DN=T((Iae,LN)=>{"use strict";var Sm=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}};LN.exports=Sm});var vN=T((Mae,PN)=>{"use strict";var MN=Ye(),Tm=Lr(),gm=Cr().LMDB_ERRORS_ENUM,B$=Et(),UN=q(),Cae=z(),H$=require("lmdb"),x$=DN(),F$=w(),{OVERFLOW_MARKER:Lae,MAX_SEARCH_KEY_LENGTH:Dae}=B$,G$=F$.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function q$(e,t,r,s){if(Tm.validateEnv(e),t===void 0)throw new Error(gm.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(gm.IDS_REQUIRED):new Error(gm.IDS_MUST_BE_ITERABLE);try{let n=MN.listDBIs(e);MN.initializeDBIs(e,t,n);let i=new x$,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||s&&h[G$]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,H$.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let R=n[S];if(!h.hasOwnProperty(R)||R===t)continue;let O=e.dbis[R],b=h[R];if(b!=null)try{let P=Tm.getIndexedValues(b);if(P)for(let $=0,x=P.length;$<x;$++)O.remove(P[$],o)}catch{UN.warn(`cannot delete from attribute: ${R}, ${b}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){UN.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=Tm.getNextMonotonicTime(),i}catch(n){throw n}}a(q$,"deleteRecords");PN.exports={deleteRecords:q$}});var Hc=T((Pae,HN)=>{"use strict";var Qo=z(),k$=vN(),V$=Ye(),{getSchemaPath:$$}=We(),Y$=vc(),K$=q();HN.exports=W$;async function W$(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Qo.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Qo.isEmptyOrZeroLength(e.hash_values)&&!Qo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Qo.isEmpty(u)||e.hash_values.push(u)}}if(Qo.isEmptyOrZeroLength(e.hash_values))return BN([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Qo.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=$$(e.schema,e.table),i=await V$.openEnvironment(n,e.table),o=await k$.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await Y$(e,o)}catch(c){K$.error(`unable to write transaction due to ${c.message}`)}return BN(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(W$,"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}}a(BN,"createDeleteResponse")});var Am=T((Hae,xN)=>{"use strict";var Q$=w(),Bae=Lr();function Rm(e,t){let r=Object.create(null);if(t.length===1&&Q$.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(Rm,"parseRow");function z$(e,t,r,s){let n=Rm(r,e);s.push(n)}a(z$,"searchAll");function J$(e,t,r,s){let n=Rm(r,e);s[t]=n}a(J$,"searchAllToMap");function X$(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(X$,"iterateDBI");function Fi(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(Fi,"pushResults");function j$(e,t,r,s,n,i){t.toString().endsWith(e)&&Fi(t,r,s,n,i)}a(j$,"endsWith");function Z$(e,t,r,s,n,i){t.toString().includes(e)&&Fi(t,r,s,n,i)}a(Z$,"contains");function e1(e,t,r,s,n,i){t>e&&Fi(t,r,s,n,i)}a(e1,"greaterThanCompare");function t1(e,t,r,s,n,i){t>=e&&Fi(t,r,s,n,i)}a(t1,"greaterThanEqualCompare");function r1(e,t,r,s,n,i){t<e&&Fi(t,r,s,n,i)}a(r1,"lessThanCompare");function s1(e,t,r,s,n,i){t<=e&&Fi(t,r,s,n,i)}a(s1,"lessThanEqualCompare");xN.exports={parseRow:Rm,searchAll:z$,searchAllToMap:J$,iterateDBI:X$,endsWith:j$,contains:Z$,greaterThanCompare:e1,greaterThanEqualCompare:t1,lessThanCompare:r1,lessThanEqualCompare:s1,pushResults:Fi}});var zo=T((kae,YN)=>{"use strict";var ri=Ye(),Fae=q(),Pr=Lr(),w_=Et(),ut=Cr().LMDB_ERRORS_ENUM,Gae=z(),n1=w(),C_=Am(),{parseRow:i1}=C_,qae=require("lmdb"),{OVERFLOW_MARKER:FN,MAX_SEARCH_KEY_LENGTH:o1}=w_;function GN(e,t,r,s=!1,n=void 0,i=void 0){return Gi(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(GN,"iterateFullIndex");function xc(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Gi(e,t,r,(l,d,f,E)=>{let O={transaction:l,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(O.values=!1,d.getRange(O).map(b=>({value:b}))):d.getRange(O)})}a(xc,"iterateRangeBetween");function Gi(e,t,r,s){let n=e.database||e,i=ri.openDBI(n,r);i[w_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ri.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(Gi,"setupTransaction");function qN(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(FN)){if(!n)if(r)n=ri.openDBI(e,r);else{let u=ri.listDBIs(e);for(let _=0,l=u.length;_<l&&(n=ri.openDBI(e,u[_]),!n[w_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(qN,"getOverflowCheck");function a1(e,t,r,s=!1,n=void 0,i=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);return Gi(e,t,t,(o,c,u)=>(L_(r),r=Fc(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(_=>i1(_.value,r))))}a(a1,"searchAll");function c1(e,t,r,s=!1,n=void 0,i=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);L_(r),r=Fc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of GN(e,t,t,s,n,i))o.set(c,C_.parseRow(u,r));return o}a(c1,"searchAllToMap");function u1(e,t,r=!1,s=void 0,n=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=GN(e,void 0,t,r,s,n),c=o.transaction,u=qN(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(u1,"iterateDBI");function l1(e,t){if(Pr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);return ri.statDBI(e,t).entryCount}a(l1,"countAll");function _1(e,t,r,s,n=!1,i=void 0,o=void 0){return si(e,r,s),Gi(e,t,r,(c,u,_,l)=>(s=Pr.convertKeyValueToWrite(s),l===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(_1,"equals");function d1(e,t,r){return si(e,t,r),ri.openDBI(e,t).getValuesCount(r)}a(d1,"count");function f1(e,t,r,s,n=!1,i=void 0,o=void 0){return si(e,r,s),Gi(e,null,r,(c,u)=>{s=Pr.convertKeyValueToWrite(s);let _=!0;typeof s=="number"&&(_=!1);let l;if(n===!0){let d;for(let f of u.getKeys({transaction:c,start:s}))if(!f.startsWith(s)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(s))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(f1,"startsWith");function E1(e,t,r,s,n=!1,i=void 0,o=void 0){return kN(e,t,r,s,n,i,o,!0)}a(E1,"endsWith");function kN(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return si(e,r,s),Gi(e,null,r,(u,_,l,d)=>{let f=qN(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(E=>{let h=E.toString();return h.endsWith(FN)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(s):S.includes(s))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(s):h.includes(s))?_[w_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(p=>({key:E,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(kN,"contains");function h1(e,t,r,s,n=!1,i=void 0,o=void 0){si(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),xc(e,t,r,s,u,n,i,o,!0,!1)}a(h1,"greaterThan");function m1(e,t,r,s,n=!1,i=void 0,o=void 0){si(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),xc(e,t,r,s,u,n,i,o,!1,!1)}a(m1,"greaterThanEqual");function p1(e,t,r,s,n=!1,i=void 0,o=void 0){si(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),xc(e,t,r,u,s,n,i,o,!1,!0)}a(p1,"lessThan");function S1(e,t,r,s,n=!1,i=void 0,o=void 0){si(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),xc(e,t,r,u,s,n,i,o,!1,!1)}a(S1,"lessThanEqual");function T1(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(Pr.validateEnv(e),r===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ut.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ut.END_VALUE_REQUIRED);if(s=Pr.convertKeyValueToWrite(s),n=Pr.convertKeyValueToWrite(n),s>n)throw new Error(ut.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return xc(e,t,r,s,n,i,o,c)}a(T1,"between");function g1(e,t,r,s){Pr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(L_(r),r=Fc(n,r),s===void 0)throw new Error(ut.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=C_.parseRow(c,r)),o}a(g1,"searchByHash");function R1(e,t,r){Pr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ut.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(R1,"checkHashExists");function A1(e,t,r,s,n=[]){return $N(e,t,r,s,n),VN(e,t,r,s,n).map(i=>i[1])}a(A1,"batchSearchByHash");function O1(e,t,r,s,n=[]){$N(e,t,r,s,n);let i=new Map;for(let[o,c]of VN(e,t,r,s,n))i.set(o,c);return i}a(O1,"batchSearchByHashToMap");function VN(e,t,r,s,n=[]){return Gi(e,t,t,(i,o,c)=>{r=Fc(c,r);let u=r.length<3;return s.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,C_.parseRow(l,r)];n.push(_)}).filter(_=>_)})}a(VN,"batchHashSearch");function $N(e,t,r,s,n){if(Pr.validateEnv(e),t===void 0)throw new Error(ut.HASH_ATTRIBUTE_REQUIRED);if(L_(r),s==null)throw new Error(ut.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ut.IDS_MUST_BE_ITERABLE)}a($N,"initializeBatchSearchByHash");function L_(e){if(!Array.isArray(e))throw e===void 0?new Error(ut.FETCH_ATTRIBUTES_REQUIRED):new Error(ut.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(L_,"validateFetchAttributes");function si(e,t,r){if(Pr.validateEnv(e),t===void 0)throw new Error(ut.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ut.SEARCH_VALUE_REQUIRED);if(r?.length>o1)throw new Error(ut.SEARCH_VALUE_TOO_LARGE)}a(si,"validateComparisonFunctions");function Fc(e,t){return t.length===1&&n1.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ri.listDBIs(e)),t}a(Fc,"setGetWholeRowAttributes");YN.exports={searchAll:a1,searchAllToMap:c1,count:d1,countAll:l1,equals:_1,startsWith:f1,endsWith:E1,contains:kN,searchByHash:g1,setGetWholeRowAttributes:Fc,batchSearchByHash:A1,batchSearchByHashToMap:O1,checkHashExists:R1,iterateDBI:u1,greaterThan:h1,greaterThanEqual:m1,lessThan:p1,lessThanEqual:S1,between:T1}});var Jo=T(($ae,JN)=>{var KN=require("lodash"),WN=et(),ue=require("joi"),b1=z(),{hdb_schema_table:Gc,checkValidTable:QN,hdb_table:zN,hdb_database:D_}=Js(),{handleHDBError:N1,hdb_errors:y1}=Z(),{getDatabases:I1}=(pe(),ee(Ge)),{HTTP_STATUS_CODES:w1}=y1,C1=ue.object({database:D_,schema:D_,table:zN,search_attribute:Gc,search_value:ue.any().required(),get_attributes:ue.array().min(1).items(ue.alternatives(Gc,ue.object())).optional(),desc:ue.bool(),limit:ue.number().integer().min(1),offset:ue.number().integer().min(0)}),L1=ue.object({database:D_,schema:D_,table:zN,operator:ue.string().valid("and","or").default("and").lowercase(),offset:ue.number().integer().min(0),limit:ue.number().integer().min(1),get_attributes:ue.array().min(1).items(ue.alternatives(Gc,ue.object())).optional(),sort:ue.object({attribute:ue.alternatives(Gc,ue.array().min(1)),descending:ue.bool().optional()}).optional(),conditions:ue.array().min(1).items(ue.alternatives(ue.object({operator:ue.string().valid("and","or").default("and").lowercase(),conditions:ue.array()}),ue.object({search_attribute:ue.alternatives(Gc,ue.array().min(1)),search_type:ue.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:ue.when("search_type",{switch:[{is:"equals",then:ue.any()},{is:"between",then:ue.array().items(ue.alternatives([ue.string(),ue.number()])).length(2)}],otherwise:ue.alternatives(ue.string(),ue.number())}).required()}))).required()});JN.exports=function(e,t){let r=null;switch(t){case"value":r=WN.validateBySchema(e,C1);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(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(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=WN.validateBySchema(e,L1);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=b1.checkGlobalSchemaTable(e.schema,e.table);if(n)return N1(new Error,n,w1.NOT_FOUND);let o=I1()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=KN.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!KN.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Om=T((Kae,XN)=>{"use strict";var D1=Ye(),M1=Jo(),{getSchemaPath:U1}=We();XN.exports=P1;function P1(e){let t=M1(e,"hashes");if(t)throw t;let r=U1(e.schema,e.table);return D1.openEnvironment(r,e.table)}a(P1,"initialize")});var bm=T((Qae,jN)=>{"use strict";var v1=zo(),B1=Om();jN.exports=H1;async function H1(e){let t=await B1(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return v1.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(H1,"lmdbGetDataByHash")});var Xo=T((Jae,ZN)=>{"use strict";var Nm=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};ZN.exports=Nm});var ty=T((Zae,ey)=>{"use strict";var jae=Xo(),x1=zo(),F1=Om();ey.exports=G1;async function G1(e){let t=await F1(e),r=global.hdb_schema[e.schema][e.table];return x1.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(G1,"lmdbSearchByHash")});var js=T((tce,ry)=>{"use strict";var ym=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};ry.exports=ym});var M_=T((sce,cy)=>{"use strict";var zt=zo(),q1=Ye(),k1=z(),le=Et(),qi=w(),V1=Bi(),sy=Cr().LMDB_ERRORS_ENUM,{getSchemaPath:$1}=We(),Nn=qi.SEARCH_WILDCARDS;async function Y1(e,t,r){let s;e.schema===qi.SYSTEM_SCHEMA_NAME?s=V1[e.table]:s=global.hdb_schema[e.schema][e.table];let n=ay(e,s.hash_attribute,r,t);return iy(e,n,s.hash_attribute,r)}a(Y1,"prepSearch");async function iy(e,t,r,s){let n=$1(e.schema,e.table),i=await q1.openEnvironment(n,e.table),o=oy(i,e,t,r),c=o.transaction||i;if([le.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,le.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,le.SEARCH_TYPES.SEARCH_ALL,le.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(K1(e,r)===!1){let l=e.search_attribute;if(l===r)return s?ny(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?ny(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?zt.batchSearchByHashToMap(c,r,e.get_attributes,_):zt.batchSearchByHash(c,r,e.get_attributes,_)}a(iy,"executeSearch");function oy(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 le.SEARCH_TYPES.EQUALS:n=zt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case le.SEARCH_TYPES.CONTAINS:n=zt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case le.SEARCH_TYPES.ENDS_WITH:case le.SEARCH_TYPES._ENDS_WITH:n=zt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case le.SEARCH_TYPES.STARTS_WITH:case le.SEARCH_TYPES._STARTS_WITH:n=zt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case le.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return zt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case le.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return zt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case le.SEARCH_TYPES.SEARCH_ALL:return zt.searchAll(e,s,t.get_attributes,o,c,u);case le.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return zt.searchAllToMap(e,s,t.get_attributes,o,c,u);case le.SEARCH_TYPES.BETWEEN:n=zt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case le.SEARCH_TYPES.GREATER_THAN:case le.SEARCH_TYPES._GREATER_THAN:n=zt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case le.SEARCH_TYPES.GREATER_THAN_EQUAL:case le.SEARCH_TYPES._GREATER_THAN_EQUAL:n=zt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case le.SEARCH_TYPES.LESS_THAN:case le.SEARCH_TYPES._LESS_THAN:n=zt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case le.SEARCH_TYPES.LESS_THAN_EQUAL:case le.SEARCH_TYPES._LESS_THAN_EQUAL:n=zt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(oy,"searchByType");function ny(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(ny,"createMapFromIterable");function K1(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(K1,"checkToFetchMore");function ay(e,t,r,s){if(k1.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),Nn.indexOf(n)>-1)return r===!0?le.SEARCH_TYPES.SEARCH_ALL_TO_MAP:le.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(Nn[0])<0&&n.indexOf(Nn[1])<0)return c===!0?r===!0?le.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:le.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:le.SEARCH_TYPES.EQUALS;if(Nn.indexOf(i)>=0&&Nn.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),le.SEARCH_TYPES.CONTAINS;if(Nn.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),le.SEARCH_TYPES.ENDS_WITH;if(Nn.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),le.SEARCH_TYPES.STARTS_WITH;if(n.includes(Nn[0])||n.includes(Nn[1]))return le.SEARCH_TYPES.EQUALS;throw new Error(sy.UNKNOWN_SEARCH_TYPE)}else switch(s){case qi.VALUE_SEARCH_COMPARATORS.BETWEEN:return le.SEARCH_TYPES.BETWEEN;case qi.VALUE_SEARCH_COMPARATORS.GREATER:return le.SEARCH_TYPES.GREATER_THAN;case qi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return le.SEARCH_TYPES.GREATER_THAN_EQUAL;case qi.VALUE_SEARCH_COMPARATORS.LESS:return le.SEARCH_TYPES.LESS_THAN;case qi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return le.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(sy.UNKNOWN_SEARCH_TYPE)}}a(ay,"createSearchTypeFromSearchObject");cy.exports={executeSearch:iy,createSearchTypeFromSearchObject:ay,prepSearch:Y1,searchByType:oy}});var ly=T((oce,uy)=>{"use strict";var ice=js(),W1=Jo(),Q1=z(),z1=w(),J1=M_();uy.exports=X1;function X1(e,t){if(!Q1.isEmpty(t)&&z1.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=W1(e,"value");if(s)throw s;let n=!0;return J1.prepSearch(e,t,n)}a(X1,"lmdbGetDataByValue")});var qc=T((uce,_y)=>{"use strict";var cce=js(),j1=Jo(),Z1=z(),eY=w(),tY=M_();_y.exports=rY;async function rY(e,t){if(!Z1.isEmpty(t)&&eY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=j1(e,"value");if(s)throw s;return tY.prepSearch(e,t,!1)}a(rY,"lmdbSearchByValue")});var fy=T((dce,dy)=>{"use strict";var _ce=Et(),Im=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}},wm=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Cm=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};dy.exports={SearchByConditionsObject:Im,SearchCondition:wm,SortAttribute:Cm}});var Sy=T((mce,py)=>{"use strict";var Ece=fy().SearchByConditionsObject,sY=js(),nY=Jo(),Lm=zo(),U_=Et(),{Resource:hce}=(Is(),ee(mh)),my=M_(),iY=Am(),oY=require("lodash"),{getSchemaPath:aY}=We(),Ey=Ye(),{handleHDBError:cY,hdb_errors:uY}=Z(),{HTTP_STATUS_CODES:lY}=uY,_Y=1e8;py.exports=dY;async function dY(e){let t=nY(e,"conditions");if(t)throw cY(t,t.message,lY.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=aY(e.schema,e.table),s=await Ey.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Ey.openDBI(s,_.search_attribute);let i=oY.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===U_.SEARCH_TYPES.EQUALS?_.estimated_count=Lm.count(s,_.search_attribute,_.search_value):l===U_.SEARCH_TYPES.CONTAINS||l===U_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=_Y}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await hy(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=s.dbis[n.hash_attribute],l=i.slice(1).map(my.filterByType),d=l.length,f=Lm.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))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(E=>iY.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await hy(o,e,f,n.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Lm.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(dY,"lmdbSearchByConditions");async function hy(e,t,r,s){let n=new sY(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===U_.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,my.searchByType(e,n,i,s).map(o=>o.value)}a(hy,"executeConditionSearch")});var kc=T((Sce,Ty)=>{"use strict";var fY=w().OPERATIONS_ENUM,Dm=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=fY.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};Ty.exports=Dm});var Mm=T((gce,Iy)=>{"use strict";var Oy=js(),by=kc(),Ny=qc(),yy=Hc(),cr=w(),gy=z(),Ry=Ye(),{getTransactionAuditStorePath:EY,getSchemaPath:hY}=We(),Ay=q();Iy.exports=mY;async function mY(e){try{if(gy.isEmpty(global.hdb_schema[e.schema])||gy.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await pY(e),await SY(e);let t=hY(e.schema,e.table);try{await Ry.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Ay.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=EY(e.schema,e.table);await Ry.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Ay.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(mY,"lmdbDropTable");async function pY(e){let t=new Oy(cr.SYSTEM_SCHEMA_NAME,cr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,cr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[cr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Ny(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 by(cr.SYSTEM_SCHEMA_NAME,cr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await yy(n)}a(pY,"deleteAttributesFromSystem");async function SY(e){let t=new Oy(cr.SYSTEM_SCHEMA_NAME,cr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,cr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[cr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,cr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,cr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await Ny(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 by(cr.SYSTEM_SCHEMA_NAME,cr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await yy(n)}catch(i){throw i}}a(SY,"dropTableFromSystem")});var Cy=T((Ace,wy)=>{"use strict";var TY=require("fs-extra"),gY=js(),RY=Xo(),AY=kc(),OY=Mm(),bY=Hc(),NY=bm(),yY=qc(),yn=w(),{getSchemaPath:IY}=We(),{handleHDBError:wY,hdb_errors:CY}=Z(),{HDB_ERROR_MSGS:LY,HTTP_STATUS_CODES:DY}=CY;wy.exports=MY;async function MY(e){let t;try{t=await UY(e.schema);let r=new gY(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,yn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[yn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await yY(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await OY(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new AY(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await bY(n);let i=IY(t);await TY.remove(i)}catch(r){throw r}}a(MY,"lmdbDropSchema");async function UY(e){let t=new RY(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[yn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await NY(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw wY(new Error,LY.SCHEMA_NOT_FOUND(e),DY.NOT_FOUND,void 0,void 0,!0);return s}a(UY,"validateDropSchema")});var Pm=T((bce,Ly)=>{"use strict";var Um=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};Ly.exports=Um});var My=T((Ice,Dy)=>{"use strict";var PY=require("fs-extra"),P_=Ye(),{getTransactionAuditStorePath:vY}=We(),vm=Et(),yce=Pm();Dy.exports=BY;async function BY(e){let t;try{let r=vY(e.schema,e.table);await PY.mkdirp(r),t=await P_.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{P_.createDBI(t,vm.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),P_.createDBI(t,vm.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),P_.createDBI(t,vm.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(BY,"createTransactionsAuditEnvironment")});var By=T((Cce,vy)=>{"use strict";var Bm=w(),Uy=Ye(),HY=$o(),{getSystemSchemaPath:xY,getSchemaPath:FY}=We(),GY=Bi(),qY=b_(),Hm=O_(),kY=q(),VY=My(),Fm=GY.hdb_table,Py=[];for(let e=0;e<Fm.attributes.length;e++)Py.push(Fm.attributes[e].attribute);vy.exports=$Y;async function $Y(e,t){let r=FY(t.schema,t.table),s=new Hm(t.schema,t.table,Bm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Hm(t.schema,t.table,Bm.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Hm(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Uy.createEnvironment(r,t.table),e!==void 0){let o=await Uy.openEnvironment(xY(),Bm.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await HY.insertRecords(o,Fm.hash_attribute,Py,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await xm(s),await xm(n),await xm(i)}await VY(t)}catch(o){throw o}}a($Y,"lmdbCreateTable");async function xm(e){try{await qY(e)}catch(t){kY.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(xm,"createAttribute")});var xy=T((Dce,Hy)=>{"use strict";var YY=Cc(),KY=Pc(),WY=y_(),Vc=w(),QY=$o().updateRecords,zY=Ye(),{getSchemaPath:JY}=We(),XY=vc(),jY=q();Hy.exports=ZY;async function ZY(e){try{let{schema_table:t,attributes:r}=YY(e);KY(e,r,t.hash_attribute),e.schema!==Vc.SYSTEM_SCHEMA_NAME&&(r.includes(Vc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Vc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Vc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Vc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await WY(e.hdb_auth_header,t,r),n=JY(e.schema,e.table),i=await zY.openEnvironment(n,e.table),o=await QY(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await XY(e,o)}catch(c){jY.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(ZY,"lmdbUpdateRecords")});var Gy=T((Uce,Fy)=>{"use strict";var eK=w().OPERATIONS_ENUM,Gm=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=eK.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};Fy.exports=Gm});var ky=T((Bce,qy)=>{"use strict";var vce=Gy(),tK=Cc(),rK=Pc(),sK=y_(),$c=w(),nK=$o().upsertRecords,iK=Ye(),{getSchemaPath:oK}=We(),aK=vc(),cK=q(),{handleHDBError:uK,hdb_errors:lK}=Z();qy.exports=_K;async function _K(e){let t;try{t=tK(e)}catch(u){throw uK(u,u.message,lK.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;rK(e,s,r.hash_attribute),e.schema!==$c.SYSTEM_SCHEMA_NAME&&(s.includes($c.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push($c.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes($c.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push($c.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await sK(e.hdb_auth_header,r,s),i=oK(e.schema,e.table),o=await iK.openEnvironment(i,e.table),c=await nK(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await aK(e,c)}catch(u){cK.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(_K,"lmdbUpsertRecords")});var $y=T((xce,Vy)=>{"use strict";var qm=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};Vy.exports=qm});var Ky=T((Gce,Yy)=>{"use strict";var km=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}};Yy.exports=km});var zy=T((Vce,Qy)=>{"use strict";var Vm=Ye(),{getTransactionAuditStorePath:dK}=We(),kce=$y(),Yc=Et(),fK=z(),Wy=Ky(),EK=require("util").promisify,hK=EK(setTimeout),mK=1e4,pK=100;Qy.exports=SK;async function SK(e){let t=dK(e.schema,e.table),r=await Vm.openEnvironment(t,e.table,!0),s=Vm.listDBIs(r);Vm.initializeDBIs(r,Yc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new Wy;do n=await TK(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 hK(pK);while(n.transactions_deleted>0);return i}a(SK,"deleteAuditLogsBefore");async function TK(e,t){let r=new Wy;try{let s=e.dbis[Yc.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[Yc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];fK.isEmpty(c)||(n=e.dbis[Yc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Yc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>mK)break}return await n,r}catch(s){throw s}}a(TK,"deleteTransactions")});var Xy=T((Yce,Jy)=>{"use strict";var $m=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};Jy.exports=$m});var Zy=T((Qce,jy)=>{"use strict";var gK=js(),RK=kc(),Wce=Xy(),Zs=w(),AK=z(),Ym=Ye(),OK=Bi(),bK=qc(),NK=Hc(),{getSchemaPath:yK}=We();jy.exports=IK;async function IK(e,t=!0){let r;e.schema===Zs.SYSTEM_SCHEMA_NAME?r=OK[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await CK(e),n=yK(e.schema,e.table),i=await Ym.openEnvironment(n,e.table);return t===!0&&await wK(e,i,r.hash_attribute),Ym.dropDBI(i,e.attribute),s}a(IK,"lmdbDropAttribute");async function wK(e,t,r){let s=Ym.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);n=t.dbis[r].put(o,_,u)}await n}a(wK,"removeAttributeFromAllObjects");async function CK(e){let t=new gK(Zs.SYSTEM_SCHEMA_NAME,Zs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Zs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Zs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,Zs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await bK(t)).filter(o=>o[Zs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(AK.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[Zs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new RK(Zs.SYSTEM_SCHEMA_NAME,Zs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return NK(i)}a(CK,"dropAttributeFromSystem")});var iI=T((Xce,nI)=>{"use strict";var Km=Ye(),jo=Et(),Jce=Lr(),Wm=w(),eI=z(),{getTransactionAuditStorePath:LK}=We(),DK=zo(),v_=Ko(),MK=q();nI.exports=UK;async function UK(e){let t=LK(e.schema,e.table),r=await Km.openEnvironment(t,e.table,!0),s=Km.listDBIs(r);Km.initializeDBIs(r,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Wm.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return tI(r,e.search_values);case Wm.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,vK(r,e.search_values,n);case Wm.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return PK(r,e.search_values);default:return tI(r)}}a(UK,"readAuditLog");function tI(e,t=[0,Date.now()]){eI.isEmpty(t[0])&&(t[0]=0),eI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[jo.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 v_,n))}a(tI,"searchTransactionsByTimestamp");function PK(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[jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,sI(e,i))}return Object.fromEntries(r)}a(PK,"searchTransactionsByUsername");function vK(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=DK.equals(e,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);s.has(f)?s.get(f).push(_.toString()):s.set(f,[_.toString()])}}let n=Array.from(s.keys()),i=sI(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);rI(u,"records",r,l,o),rI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(vK,"searchTransactionsByHashValues");function rI(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 _=n.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new v_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new v_(e.operation,e.user_name,i,void 0);_[t]=[c],n.set(u,[_])}}}a(rI,"loopRecords");function sI(e,t){let r=[];try{let s=e.dbis[jo.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 v_,i);r.push(o)}}catch(i){MK.warn(i)}return r}catch(s){throw s}}a(sI,"batchSearchTransactions")});var aI=T((tue,oI)=>{"use strict";var{getSchemaPath:Zce}=We(),eue=Ye(),{database:BK}=(pe(),ee(Ge));oI.exports={writeTransaction:HK};async function HK(e,t,r){return BK({database:e,table:t}).transaction(r)}a(HK,"writeTransaction")});var _I=T((sue,lI)=>{"use strict";var{getSchemaPath:cI}=We(),uI=Ye();lI.exports={flush:xK,resetReadTxn:FK};async function xK(e,t){return(await uI.openEnvironment(cI(e,t),t.toString())).flushed}a(xK,"flush");async function FK(e,t){try{(await uI.openEnvironment(cI(e,t),t.toString())).resetReadTxn()}catch{}}a(FK,"resetReadTxn")});var hI=T((iue,EI)=>{"use strict";var{Readable:GK}=require("stream"),{getDatabases:qK}=(pe(),ee(Ge)),{readSync:kK,openSync:VK,createReadStream:dI}=require("fs"),{open:$K}=require("lmdb"),fI=d_(),YK=E_(),{AUDIT_STORE_OPTIONS:KK}=(Fo(),ee(QO)),{INTERNAL_DBIS_NAME:WK,AUDIT_STORE_NAME:QK}=Et();EI.exports=JK;var Qm=32768,zK=100;async function JK(e){let t=e.database||e.schema||"data",r=qK()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let _=r[n[0]];if(!_)throw new Error(`Can not find table ${n[0]}`);let l=_.dbisDB,d=$K({noSync:!0,maxDbs:YK.MAX_DBS}),f,E=d.openDB(WK,new fI(!1)),h=l.useReadTransaction(),p=0,S=a(async function(O,b){b.encoding="binary",b.encoder=void 0;let P=d.openDB(O,b),$=l.openDB(O,b);for(let{key:x,version:D,value:Y}of $.getRange({transaction:h,versions:$.useVersions}))f=P.put(x,Y,D),p++%zK===0&&(await new Promise(V=>setTimeout(V,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:O,value:b}of l.getRange({transaction:h,start:!1}))if(n.some(P=>O.startsWith?.(P+"/"))){E.put(O,b);let[,P]=O.split("/"),$=!P,x=new fI(!$,$);await S(O,x)}e.include_audit&&await S(QK,Object.assign({},KK)),await f;let R=dI(d.path);return R.headers=u(),R.on("close",()=>{h.done(),d.close()}),R}let o=r[Object.keys(r)[0]].primaryStore,c=VK(o.path);return o.transaction(()=>{let _=Buffer.alloc(Qm);kK(c,_,0,Qm),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=dI(null,{fd:c,start:Qm}),f=new GK.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",s),_}}a(JK,"getBackup")});var SI=T((aue,pI)=>{"use strict";var XK=q(),{handleHDBError:jK}=Z(),ZK=Pb(),eW=b_(),tW=pm(),rW=CN(),sW=Hc(),nW=bm(),iW=ty(),oW=ly(),aW=qc(),cW=Sy(),uW=Cy(),lW=By(),_W=xy(),dW=ky(),fW=zy(),EW=Mm(),hW=Zy(),mW=iI(),pW=aI(),mI=_I(),SW=hI(),zm=class extends ZK{static{a(this,"LMDBBridge")}async searchByConditions(t){return cW(t)}async getDataByHash(t){return await nW(t)}async searchByHash(t){return await iW(t)}async getDataByValue(t,r){return await oW(t,r)}async searchByValue(t){return await aW(t)}async createSchema(t){return await rW(t)}async dropSchema(t){return await uW(t)}async createTable(t,r){return await lW(t,r)}async dropTable(t){return await EW(t)}async createAttribute(t){return await eW(t)}async createRecords(t){return await tW(t)}async updateRecords(t){return await _W(t)}async upsertRecords(t){try{return await dW(t)}catch(r){throw jK(r,null,null,XK.ERR,r)}}async deleteRecords(t){return await sW(t)}async dropAttribute(t){return await hW(t)}async deleteAuditLogsBefore(t){return await fW(t)}async readAuditLog(t){return await mW(t)}writeTransaction(t,r,s){return pW.writeTransaction(t,r,s)}flush(t,r){return mI.flush(t,r)}resetReadTxn(t,r){return mI.resetReadTxn(t,r)}getBackup(t){return SW(t)}};pI.exports=zm});var II={};$e(II,{ResourceBridge:()=>jm});function Zm({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 gI(e,t){let r=en(e),s=Zm(e,r);if(!r)throw new Ds.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},o;Qe(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:n,select:s},i);return l=l&&Xl(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function en(e){let t=e.database||e.schema||gW,r=Ms()[t];if(!r)throw(0,Ds.handleHDBError)(new Error,TW.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function RI(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*AI(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,version: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 OI,B_,Ds,bI,NI,Us,Jm,Xm,yI,TW,gW,RW,AW,TI,jm,wI=ge(()=>{"use strict";OI=U(SI()),B_=U(Jo()),Ds=U(Z());pe();bI=U(Cc()),NI=U(Pc()),Us=U(w()),Jm=U(bn()),Xm=U(Ls()),yI=U(z());Ui();jl();({HDB_ERROR_MSGS:TW}=Ds.hdb_errors),gW="data",RW=1e4,AW=10,jm=class extends OI.default{static{a(this,"ResourceBridge")}constructor(t){super(t),TI=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,B_.default)(t,"conditions");if(r)throw(0,Ds.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=en(t);if(!s)throw new Ds.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Zm(t,s),sort:t.sort,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 Ds.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}]}lt({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await en(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=en(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(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,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(_=>setImmediate(_));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){en(t).dropTable()}createSchema(t){return Kc({database:t.schema,table:null}),Jm.signalSchemaChange(new Xm.SchemaEventMsg(process.pid,Us.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await ep(t.schema),Jm.signalSchemaChange(new Xm.SchemaEventMsg(process.pid,Us.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,TI.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,bI.default)(t);(0,NI.default)(t,s,r.primaryKey);let n,i=Ms()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Qe(o,async c=>{if(!i.schemaDefined){n=[];for(let l of s)i.attributes.find(f=>f.name==l)||n.push(l);n.length>0&&await i.addAttributes(n.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=Xl(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:_}})}async deleteRecords(t){let r=Ms()[t.schema][t.table],s={user:t.hdb_user};return Qe(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 RI(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Ms()[t.schema][t.table];if(!r.createdTimeProperty)throw new Ds.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:Us.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,yI.async_set_timeout)(AW),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%RW===0&&await _();return u.length>0&&await _(),n?RI(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,B_.default)(t,"hashes");if(r)throw r;return gI(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of gI(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&Us.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let s=(0,B_.default)(t,"value");if(s)throw s;let n=en(t);if(!n)throw new Ds.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===Us.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:Zm(t,n)})}async getDataByValue(t,r){let s=new Map,n=en(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){en({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return en(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=en(t),s={};switch(t.search_type){case Us.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,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case Us.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of AI(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return AI(r,t.search_values?.[0],t.search_values?.[1])}}};a(Zm,"getSelect");a(gI,"getRecords");a(en,"getTable");a(RI,"createDeleteResponse");a(AI,"groupRecordsInHistory")});var Ps=T((fue,CI)=>{"use strict";var{ResourceBridge:OW}=(wI(),ee(II)),bW=j();bW.initSync();var H_;function NW(){return H_||(H_=new OW,H_)}a(NW,"getBridge");CI.exports=NW()});var UI=T((hue,MI)=>{"use strict";var LI=require("lodash"),Wc=require("mathjs"),yW=require("jsonata"),DI=z();MI.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?LI.uniqWith(e,LI.isEqual):e,searchJSON:IW,mad:Qc.bind(null,Wc.mad),mean:Qc.bind(null,Wc.mean),mode:Qc.bind(null,Wc.mode),prod:Qc.bind(null,Wc.prod),median:Qc.bind(null,Wc.median)};function Qc(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(Qc,"aggregateFunction");function IW(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(DI.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),DI.isEmpty(this.__ala__.res[r])){let s=yW(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(IW,"searchJSON")});var vI=T((pue,PI)=>{"use strict";var mt=require("moment"),tp="YYYY-MM-DDTHH:mm:ss.SSSZZ";mt.suppressDeprecationWarnings=!0;PI.exports={current_date:()=>mt().utc().format("YYYY-MM-DD"),current_time:()=>mt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return mt(e).utc().format("YYYY");case"month":return mt(e).utc().format("MM");case"day":return mt(e).utc().format("DD");case"hour":return mt(e).utc().format("HH");case"minute":return mt(e).utc().format("mm");case"second":return mt(e).utc().format("ss");case"millisecond":return mt(e).utc().format("SSS");default:break}},date:e=>mt(e).utc().format(tp),date_format:(e,t)=>mt(e).utc().format(t),date_add:(e,t,r)=>mt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>mt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=mt(e).utc(),n=mt(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>mt().utc().valueOf(),get_server_time:()=>mt().format(tp),offset_utc:(e,t)=>mt(e).utc().utcOffset(t).format(tp)}});var FI=T((Sue,xI)=>{"use strict";var wW=require("@turf/area"),CW=require("@turf/length"),LW=require("@turf/circle"),DW=require("@turf/difference"),MW=require("@turf/distance"),UW=require("@turf/boolean-contains"),PW=require("@turf/boolean-equal"),vW=require("@turf/boolean-disjoint"),BW=require("@turf/helpers"),BI=w(),de=z(),In=q();xI.exports={geoArea:HW,geoLength:xW,geoCircle:FW,geoDifference:GW,geoDistance:HI,geoNear:qW,geoContains:kW,geoEqual:VW,geoCrosses:$W,geoConvert:YW};function HW(e){if(de.isEmpty(e))return NaN;typeof e=="string"&&(e=de.autoCastJSON(e));try{return wW.default(e)}catch(t){return In.trace(t,e),NaN}}a(HW,"geoArea");function xW(e,t){if(de.isEmpty(e))return NaN;typeof e=="string"&&(e=de.autoCastJSON(e));try{return CW.default(e,{units:t||"kilometers"})}catch(r){return In.trace(r,e),NaN}}a(xW,"geoLength");function FW(e,t,r){if(de.isEmpty(e))return NaN;if(de.isEmpty(t))return NaN;typeof e=="string"&&(e=de.autoCastJSON(e));try{return LW.default(e,t,{units:r||"kilometers"})}catch(s){return In.trace(s,e,t),NaN}}a(FW,"geoCircle");function GW(e,t){if(de.isEmpty(e))return NaN;if(de.isEmpty(t))return NaN;typeof e=="string"&&(e=de.autoCastJSON(e)),typeof t=="string"&&(t=de.autoCastJSON(t));try{return DW(e,t)}catch(r){return In.trace(r,e,t),NaN}}a(GW,"geoDifference");function HI(e,t,r){if(de.isEmpty(e))return NaN;if(de.isEmpty(t))return NaN;typeof e=="string"&&(e=de.autoCastJSON(e)),typeof t=="string"&&(t=de.autoCastJSON(t));try{return MW.default(e,t,{units:r||"kilometers"})}catch(s){return In.trace(s,e,t),NaN}}a(HI,"geoDistance");function qW(e,t,r,s){if(de.isEmpty(e)||de.isEmpty(t))return!1;if(de.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=de.autoCastJSON(e)),typeof t=="string"&&(t=de.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return HI(e,t,s)<=r}catch(n){return In.trace(n,e,t),!1}}a(qW,"geoNear");function kW(e,t){if(de.isEmpty(e)||de.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=de.autoCastJSON(e)),typeof t=="string"&&(t=de.autoCastJSON(t));try{return UW.default(e,t)}catch(r){return In.trace(r,e,t),!1}}a(kW,"geoContains");function VW(e,t){if(de.isEmpty(e)||de.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=de.autoCastJSON(e)),typeof t=="string"&&(t=de.autoCastJSON(t));try{return PW.default(e,t)}catch(r){return In.trace(r,e,t),!1}}a(VW,"geoEqual");function $W(e,t){if(de.isEmpty(e)||de.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=de.autoCastJSON(e)),typeof t=="string"&&(t=de.autoCastJSON(t));try{return!vW.default(e,t)}catch(r){return In.trace(r,e,t),!1}}a($W,"geoCrosses");function YW(e,t,r){if(de.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(de.isEmpty(t))throw new Error("geo_type is required");if(de.isEmpty(BI.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(BI.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=de.autoCastJSON(e)),BW[t](e,r)}a(YW,"geoConvert")});var x_=T((gue,GI)=>{var ki=UI(),vr=vI(),tn=FI();GI.exports=e=>{e.aggr.mad=e.aggr.MAD=ki.mad,e.aggr.mean=e.aggr.MEAN=ki.mean,e.aggr.mode=e.aggr.MODE=ki.mode,e.aggr.prod=e.aggr.PROD=ki.prod,e.aggr.median=e.aggr.MEDIAN=ki.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ki.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ki.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=vr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=vr.current_time,e.fn.extract=e.fn.EXTRACT=vr.extract,e.fn.date=e.fn.DATE=vr.date,e.fn.date_format=e.fn.DATE_FORMAT=vr.date_format,e.fn.date_add=e.fn.DATE_ADD=vr.date_add,e.fn.date_sub=e.fn.DATE_SUB=vr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=vr.date_diff,e.fn.now=e.fn.NOW=vr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=vr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=vr.get_server_time,e.fn.getdate=e.fn.GETDATE=vr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=vr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=tn.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=tn.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=tn.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=tn.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=tn.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=tn.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=tn.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=tn.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=tn.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=tn.geoNear}});var $I=T((Rue,VI)=>{"use strict";var zc=require("lodash"),ur=require("alasql");ur.options.cache=!1;var KW=x_(),qI=require("clone"),F_=require("recursive-iterator"),oe=q(),Ie=z(),Zo=Ps(),WW=w(),{hdb_errors:QW}=Z(),{getDatabases:kI}=(pe(),ee(Ge)),zW="IS NULL",vs="There was a problem performing this search. Please check the logs and try again.";KW(ur);var rp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ie.isEmpty(t))throw oe.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(),Ie.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!Ie.isEmptyOrZeroLength(s))return oe.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw oe.error("Error thrown from checkEmptySQL in SQLSearch class method search."),oe.error(s),new Error(vs)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw oe.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),oe.error(s),new Error(vs)}if(Object.keys(this.data).length===0)return oe.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw oe.error("Error thrown from processJoins in SQLSearch class method search."),oe.error(s),new Error(vs)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw oe.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),oe.error(s),new Error(vs)}try{return t=await this._finalSQL(),t}catch(s){throw oe.error("Error thrown from finalSQL in SQLSearch class method search."),oe.error(s),new Error(vs)}}_getColumns(){let t=new F_(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(qI(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=zc.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=kI()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ie.isEmpty(this.statement.where)){oe.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new F_(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ie.isEmpty(r)&&r.right)if(Ie.isNotEmptyAndHasValue(r.right.value)){let s=Ie.autoCast(r.right.value);[!0,!1].indexOf(s)>=0&&(r.right=new ur.yy.LogicValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=Ie.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new ur.yy.LogicValue({value:i}):s instanceof ur.yy.StringValue&&Ie.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new ur.yy.NumValue({value:i}))});if(t){oe.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new F_(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(!Ie.isEmpty(WW.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ie.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ie.isEmptyOrZeroLength(r.left.columnid)||Ie.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(Ie.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"=":!Ie.isEmpty(r.right.value)||!Ie.isEmpty(r.left.value)?s.add(Ie.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 _=0;_<u.length;_++)if(u[_].value)s.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(Ie.isEmptyOrZeroLength(this.all_table_attributes)&&Ie.isEmptyOrZeroLength(this.statement.from)&&Ie.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&&zc.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(Ie.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);Ie.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(Ie.isEmptyOrZeroLength(this.all_table_attributes)&&!Ie.isEmptyOrZeroLength(this.columns.columns))return t;if(Ie.isEmptyOrZeroLength(this.all_table_attributes)&&Ie.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await ur.promise(r)}catch(r){throw oe.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),oe.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(qI(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(Ie.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(zW)>-1&&this.tables.forEach(n=>{let i={columnid:kI()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=zc.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,_=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!Ie.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ie.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await Zo.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(l){throw oe.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),oe.error(l),new Error(vs)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await Zo.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw oe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),oe.error(l),new Error(vs)}else if(!Ie.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ie.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await Zo.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...s[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]):(this.data[i].__merged_data[p]=[...s[i]],this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw oe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),oe.error(l),new Error(vs)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await Zo.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw oe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),oe.error(l),new Error(vs)}}}_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 ur.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 ur.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new ur.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 ur.yy.FuncValue:new ur.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(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,n);f=await ur.promise(h,t),t=null}catch(E){throw oe.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),oe.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let p=f[E];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),p=zc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,R=p.length;S<R;S++){let O=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[O]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new F_(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=zc.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 oe.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),oe.error(i),new Error(vs)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await Zo.getDataByHash(c),_=n.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=n.columns[h],S=E[p]===void 0?null:E[p];this.data[s].__merged_data[f].push(S)}}}}catch(r){throw oe.error("Error thrown from getDataByHash function in SQLSearch class method getData."),oe.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&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let s;try{let n=this._buildSQL();oe.trace(`Final SQL: ${n}`),s=await ur.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),oe.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw oe.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),oe.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 oe.error(QW.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),oe.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),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],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${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"),_=`[${c}]`;s=s.replace(u,_)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await Zo.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 oe.error("There was an error when processing this SQL operation. Check your logs"),oe.error(o),new Error(vs)}}return Object.values(Object.values(this.data)[0].__merged_data)}};VI.exports=rp});var as=T((Oue,YI)=>{"use strict";var JW=Mb();YI.exports={searchByConditions:jW,searchByHash:ZW,searchByValue:eQ,search:tQ};var sp=Ps(),{transformReq:np}=z(),XW=$I();async function jW(e){return np(e),sp.searchByConditions(e)}a(jW,"searchByConditions");async function ZW(e){np(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of sp.searchByHash(e))r&&t.push(r);return t}a(ZW,"searchByHash");async function eQ(e){np(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of sp.searchByValue(e))t.push(r);return t}a(eQ,"searchByValue");function tQ(e,t){try{let r=new JW(e);r.validate(),new XW(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(tQ,"search")});var wn=T((Nue,zI)=>{"use strict";var Jc=require("crypto"),rQ=j(),{CONFIG_PARAMS:sQ}=w(),WI="aes-256-cbc",nQ=32,iQ=16,ip=64,QI=32,oQ=ip+QI,KI=new Map;zI.exports={encrypt:aQ,decrypt:cQ,createNatsTableStreamName:uQ};function aQ(e){let t=Jc.randomBytes(nQ),r=Jc.randomBytes(iQ),s=Jc.createCipheriv(WI,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(aQ,"encrypt");function cQ(e){let t=e.substr(0,ip),r=e.substr(ip,QI),s=e.substr(oQ,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Jc.createDecipheriv(WI,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(cQ,"decrypt");function uQ(e,t){let r=rQ.get(sQ.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=KI.get(r);return s||(s=Jc.createHash("md5").update(r).digest("hex"),KI.set(r,s)),s}a(uQ,"createNatsTableStreamName")});var Vi=T((wue,XI)=>{"use strict";var Iue=as(),G_=q(),JI=A_(),lQ=wn(),q_=z(),{handleHDBError:k_,hdb_errors:_Q}=Z(),{HDB_ERROR_MSGS:V_,HTTP_STATUS_CODES:op}=_Q,dQ=j();dQ.initSync();var{getDatabases:ap}=(pe(),ee(Ge));XI.exports={describeAll:fQ,describeTable:$_,describeSchema:EQ};async function fQ(e){try{let t=q_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=ap(),i={},o={},c=[],u=e?.exact_count;for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let d=n[l];for(let f in d)try{let E;if(t||s)E=await $_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await $_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){G_.error(E)}}let _={};for(let l in c)t||s?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return G_.error("Got an error in describeAll"),G_.error(t),k_(new Error,V_.DESCRIBE_ALL_ERR)}}a(fQ,"describeAll");async function $_(e,t){q_.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=JI.describe_table(e);if(i)throw i;let c=ap()[r];if(!c)throw k_(new Error,V_.SCHEMA_NOT_FOUND(e.schema),op.NOT_FOUND);let u=c[s];if(!u)throw k_(new Error,V_.TABLE_NOT_FOUND(e.schema,e.table),op.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(n){let f={};n.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=lQ.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){G_.warn(`unable to stat table dbi due to ${f}`)}return d}a($_,"descTable");async function EQ(e){q_.transformReq(e);let t=JI.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=ap()[s];if(!i)throw k_(new Error,V_.SCHEMA_NOT_FOUND(e.schema),op.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),q_.isEmpty(u)||u.describe){let _=await $_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(EQ,"describeSchema")});var ni=T((Mue,rw)=>{var hQ=Bi(),{callbackify:ZI,promisify:mQ}=require("util"),{getDatabases:ew}=(pe(),ee(Ge));rw.exports={setSchemaDataToGlobal:jI,getTableSchema:pQ,getSystemSchema:SQ,setSchemaDataToGlobalAsync:mQ(jI)};var tw=Vi(),Lue=ZI(tw.describeAll),Due=ZI(tw.describeTable);function jI(e){global.hdb_schema=ew(),e&&e()}a(jI,"setSchemaDataToGlobal");function pQ(e,t,r){let s=ew()[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(pQ,"getTableSchema");function SQ(){return hQ}a(SQ,"getSystemSchema")});var cs=T((Pue,ow)=>{"use strict";var K_=cm(),Gt=z(),TQ=require("util"),W_=Ps(),gQ=ni(),sw=q(),{handleHDBError:$i,hdb_errors:RQ}=Z(),{HTTP_STATUS_CODES:Yi}=RQ,AQ=TQ.promisify(gQ.getTableSchema),OQ="updated",nw="inserted",iw="upserted";ow.exports={insert:NQ,update:yQ,upsert:IQ,validation:bQ,flush:wQ};async function bQ(e){if(Gt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Gt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Gt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await AQ(e.schema,e.table),r=K_(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&&Gt.isEmptyOrZeroLength(c[s]))throw sw.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(!Gt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw sw.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!Gt.isEmpty(c[s])&&c[s]!==""&&n.has(Gt.autoCast(c[s]))&&(c.skip=!0),n.add(Gt.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(bQ,"validation");async function NQ(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=K_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Gt.transformReq(e);let r=Gt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let s=await W_.createRecords(e);return Y_(nw,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(NQ,"insertData");async function yQ(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=K_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Gt.transformReq(e);let r=Gt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let s=await W_.updateRecords(e);return Gt.isEmpty(s.existing_rows)?Y_(OQ,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):Y_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(yQ,"updateData");async function IQ(e){if(e.operation!=="upsert")throw $i(new Error,"invalid operation, must be upsert",Yi.INTERNAL_SERVER_ERROR);let t=K_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);Gt.transformReq(e);let r=Gt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let s=await W_.upsertRecords(e);return Y_(iw,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(IQ,"upsertData");function Y_(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===nw?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===iw?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(Y_,"returnObject");function wQ(e){return Gt.transformReq(e),W_.flush(e.schema,e.table)}a(wQ,"flush")});var up=T((Bue,uw)=>{var CQ=et(),cp=require("joi"),{hdb_table:LQ,hdb_database:aw}=Js(),cw={schema:aw,database:aw,table:LQ},DQ={date:cp.date().iso().required()},MQ={timestamp:cp.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};uw.exports=function(e,t){let r=t==="timestamp"?{...cw,...MQ}:{...cw,...DQ},s=cp.object(r);return CQ.validateBySchema(e,s)}});var dw=T((Hue,_w)=>{var UQ=et(),lp=require("joi"),{hdb_table:PQ,hdb_database:lw}=Js(),vQ=lp.object({schema:lw,database:lw,table:PQ,hash_values:lp.array().required(),ids:lp.array()});_w.exports=function(e){return UQ.validateBySchema(e,vQ)}});var Ew=T((xue,fw)=>{"use strict";var _p=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}},dp=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}},fp=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};fw.exports={InsertObject:_p,NoSQLSeachObject:dp,DeleteResponseObject:fp}});var Qi=T((Gue,Tw)=>{"use strict";var mw=up(),BQ=dw(),Ki=z(),hw=require("moment"),pw=q(),{promisify:HQ,callbackify:xQ}=require("util"),Wi=w(),FQ=ni(),Ep=HQ(FQ.getTableSchema),hp=Ps(),{DeleteResponseObject:GQ}=Ew(),{handleHDBError:ii,hdb_errors:qQ}=Z(),{HDB_ERROR_MSGS:Q_,HTTP_STATUS_CODES:oi}=qQ,kQ="records successfully deleted",VQ=xQ(Sw);Tw.exports={delete:VQ,deleteRecord:Sw,deleteFilesBefore:$Q,deleteAuditLogsBefore:YQ};async function $Q(e){let t=mw(e,"date");if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),!hw(e.date,hw.ISO_8601).isValid())throw ii(new Error,Q_.INVALID_DATE,oi.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,Q_.INVALID_DATE,!0);let s=Ki.checkSchemaTableExist(e.schema,e.table);if(s)throw ii(new Error,s,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,s,!0);let n=await hp.deleteRecordsBefore(e);if(await Ep(e.schema,e.table),pw.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a($Q,"deleteFilesBefore");async function YQ(e){let t=mw(e,"timestamp");if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),isNaN(e.timestamp))throw ii(new Error,Q_.INVALID_VALUE("Timestamp"),oi.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,Q_.INVALID_VALUE("Timestamp"),!0);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ii(new Error,r,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);let s=await hp.deleteAuditLogsBefore(e);return await Ep(e.schema,e.table),pw.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(YQ,"deleteAuditLogsBefore");async function Sw(e){e.ids&&(e.hash_values=e.ids);let t=BQ(e);if(t)throw ii(t,t.message,oi.BAD_REQUEST,void 0,void 0,!0);Ki.transformReq(e);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ii(new Error,r,oi.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);try{await Ep(e.schema,e.table);let s=await hp.deleteRecords(e);return Ki.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${kQ}`),s}catch(s){if(s.message===Wi.SEARCH_NOT_FOUND_MESSAGE){let n=new GQ;return n.message=Wi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(Sw,"deleteRecord")});var z_=T((kue,Aw)=>{var KQ=require("crypto"),gw=9;function WQ(e){let t=zQ(gw),r=Rw(e+t);return t+r}a(WQ,"createHash");function QQ(e,t){let r=e?.substr(0,gw),s=r+Rw(t+r);return e===s}a(QQ,"validateHash");function zQ(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(zQ,"generateSalt");function Rw(e){return KQ.createHash("md5").update(e).digest("hex")}a(Rw,"md5");Aw.exports={hash:WQ,validate:QQ}});var bw=T(($ue,Ow)=>{var mp=et(),Jt={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 JQ(e){return Jt.password.presence=!0,Jt.username.presence=!0,Jt.role.presence=!0,Jt.active.presence=!0,mp.validateObject(e,Jt)}a(JQ,"addUserValidation");function XQ(e){return Jt.password.presence=!1,Jt.username.presence=!0,Jt.role.presence=!1,Jt.active.presence=!1,mp.validateObject(e,Jt)}a(XQ,"alterUserValidation");function jQ(e){return Jt.password.presence=!1,Jt.username.presence=!0,Jt.role.presence=!1,Jt.active.presence=!1,mp.validateObject(e,Jt)}a(jQ,"dropUserValidation");Ow.exports={addUserValidation:JQ,alterUserValidation:XQ,dropUserValidation:jQ}});var tt=T((Wue,yw)=>{"use strict";var{platform:Kue}=require("os"),ZQ="nats-server.zip",pp="nats-server",ez=process.platform==="win32"?`${pp}.exe`:pp,Sp="HDB",tz=/^[^\s.,*>]+$/,Nw="__request__",rz=a(e=>`${e}.${Nw}`,"REQUEST_SUBJECT"),sz={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},nz={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},iz={HUB:"hub.pid",LEAF:"leaf.pid"},oz={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},az={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Sp,deliver_subject:"__HDB__.WORKQUEUE"},cz={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Sp,deliver_subject:"HDB.SCHEMAQUEUE"},uz={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Sp,deliver_subject:"HDB.USERQUEUE"},lz={SUCCESS:"success",ERROR:"error"},_z={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},dz={TXN:"txn",MSGID:"msgid"},ea={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},fz={[ea.ERR]:1,[ea.WRN]:2,[ea.INF]:3,[ea.DBG]:4,[ea.TRC]:5},Ez={debug:"-D",trace:"-DVV"};yw.exports={NATS_SERVER_ZIP:ZQ,NATS_SERVER_NAME:pp,NATS_BINARY_NAME:ez,PID_FILES:iz,NATS_CONFIG_FILES:nz,SERVER_SUFFIX:oz,WORK_QUEUE_CONSUMER_NAMES:az,SCHEMA_QUEUE_CONSUMER_NAMES:cz,USER_QUEUE_CONSUMER_NAMES:uz,NATS_TERM_CONSTRAINTS_RX:tz,REQUEST_SUFFIX:Nw,UPDATE_REMOTE_RESPONSE_STATUSES:lz,CLUSTER_STATUS_STATUSES:_z,REQUEST_SUBJECT:rz,SUBJECT_PREFIXES:dz,MSG_HEADERS:sz,LOG_LEVELS:ea,LOG_LEVEL_FLAGS:Ez,LOG_LEVEL_HIERARCHY:fz}});var ww=T((zue,Iw)=>{"use strict";var hz={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,`\r
1
+ var Zx=Object.create;var za=Object.defineProperty;var eF=Object.getOwnPropertyDescriptor;var tF=Object.getOwnPropertyNames;var rF=Object.getPrototypeOf,nF=Object.prototype.hasOwnProperty;var a=(e,t)=>za(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qe=(e,t)=>{for(var r in t)za(e,r,{get:t[r],enumerable:!0})},bA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of tF(t))!nF.call(e,s)&&s!==r&&za(e,s,{get:()=>t[s],enumerable:!(n=eF(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Zx(rF(e)):{},bA(t||!e||!e.__esModule?za(r,"default",{value:e,enumerable:!0}):r,e)),ee=e=>bA(za({},"__esModule",{value:!0}),e);var M=T((Bie,xA)=>{"use strict";var Zr=require("path"),sF=require("fs"),{relative:Pie,join:vie}=Zr,{existsSync:iF}=sF;function oF(){let e=__dirname;for(;!iF(Zr.join(e,"package.json"));){let t=Zr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(oF,"getHDBPackageRoot");var Ys=oF(),NA="js",Ml=NA,aF="harperdb-config.yaml",cF="defaultConfig.yaml",uF="hdb",yA=`harperdb.${Ml}`,IA=`customFunctionsServer.${Ml}`,lF=`restartHdb.${Ml}`,eh="HarperDB",Ll="Custom Functions",Ul="Clustering Hub",Pl="Clustering Leaf",_F="Clustering Ingest Service",dF="Clustering Reply Service",fF="foreground.pid",EF="hdb.pid",hF="data",mF={HDB:eh,CLUSTERING_HUB:Ul,CLUSTERING_LEAF:Pl,CLUSTERING_INGEST_SERVICE:_F,CLUSTERING_REPLY_SERVICE:dF,CUSTOM_FUNCTIONS:Ll,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"},pF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},SF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},TF={harperdb:eh,"clustering hub":Ul,"clustering leaf":Pl,"custom functions":Ll,custom_functions:Ll,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},gF={CLUSTERING_HUB_PROC_DESCRIPTOR:Ul,CLUSTERING_LEAF_PROC_DESCRIPTOR:Pl},ZE={HDB:Zr.join(Ys,"server/harperdb"),CUSTOM_FUNCTIONS:Zr.join(Ys,"server/customFunctions"),CLUSTERING_HUB:Zr.join(Ys,"server/nats"),CLUSTERING_LEAF:Zr.join(Ys,"server/nats")},RF={HDB:Zr.join(ZE.HDB,yA),CUSTOM_FUNCTIONS:Zr.join(ZE.CUSTOM_FUNCTIONS,IA)},AF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Zr.join(Ys,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Zr.join(Ys,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Zr.join(Ys,"launchServiceScripts/launchUpdateNodes4-0-0.js")},OF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},wA="support@harperdb.io",bF="customer-success@harperdb.io",CA=1,NF=4141,DA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",yF="https://www.harperdb.io/product",IF=`For support, please submit a request at ${DA} or contact ${wA}`,LA=`For license support, please contact ${bF}`,wF="None of the specified records were found.",CF="hash attribute not found",DF=`Your current license only supports ${CA} role. ${LA}`,LF="Your current license only supports 3 connections to a node.",MF="127.0.0.1",UF=1,PF=/^\.$/,vF=/^\.\.$/,BF="U+002E",HF=/\//g,xF="U+002F",FF=/U\+002F/g,qF=/^U\+002E$/,GF=/^U\+002EU\+002E$/,kF="d",VF=999999,$F="*",YF="--max-old-space-size=",KF="system",WF="__hdb_hash",QF=".harperdb",zF=".hdb",JF="keys",XF="hdb_boot_properties.file",jF=".updateConfig.json",ZF="SIGTSTP",eq=24,tq=6e4,rq=448,nq="blob",sq="trash",iq="database",oq="schema",aq="transactions",cq=".count",uq="id",lq="PROCESS_NAME",MA={SETTINGS_PATH_KEY:"settings_path"},UA=require("lodash"),_q={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",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},dq={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},fq={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},Eq={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"},hq={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"},Ir="hdb_internal:",mq={CREATE_SCHEMA:Ir+"create_schema",CREATE_TABLE:Ir+"create_table",CREATE_ATTRIBUTE:Ir+"create_attribute",ADD_USER:Ir+"add_user",ALTER_USER:Ir+"alter_user",DROP_USER:Ir+"drop_user",HDB_NODES:Ir+"hdb_nodes",HDB_USERS:Ir+"hdb_users",HDB_WORKERS:Ir+"hdb_workers",CATCHUP:Ir+"catchup",SCHEMA_CATCHUP:Ir+"schema_catchup",WORKER_ROOM:Ir+"cluster_workers"},pq={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"},Sq="060493.ks",Tq=".license",gq={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},X={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",SET_NODE_REPLICATION:"set_node_replication",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"},Rq={CSV:".csv",JSON:".json"},Aq={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},Oq={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Ja={};Ja[X.INSERT]=X.INSERT;Ja[X.UPDATE]=X.UPDATE;Ja[X.UPSERT]=X.UPSERT;Ja[X.DELETE]=X.DELETE;var He=Object.create(null);He[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;He[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;He[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;He[X.READ_LOG]=X.READ_LOG;He[X.ADD_NODE]=X.ADD_NODE;He[X.LIST_USERS]=X.LIST_USERS;He[X.LIST_ROLES]=X.LIST_ROLES;He[X.USER_INFO]=X.USER_INFO;He[X.SQL]=X.SQL;He[X.GET_JOB]=X.GET_JOB;He[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;He[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;He[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;He[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;He[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;He[X.REMOVE_NODE]=X.REMOVE_NODE;He[X.RESTART]=X.RESTART;He[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;He[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;He[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;He[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;He[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;He[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;He[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;He[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var bq={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},Nq={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},PA={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"},yq=UA.invert(PA),Iq={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"},C={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_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",MAXHEAPMEMORY:"maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",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_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_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",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",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},vA={settings_path:MA.SETTINGS_PATH_KEY,hdb_root_key:C.ROOTPATH,hdb_root:C.ROOTPATH,rootpath:C.ROOTPATH,server_port_key:C.OPERATIONSAPI_NETWORK_PORT,server_port:C.OPERATIONSAPI_NETWORK_PORT,cert_key:C.TLS_CERTIFICATE,certificate:C.TLS_CERTIFICATE,private_key_key:C.TLS_PRIVATEKEY,private_key:C.TLS_PRIVATEKEY,http_secure_enabled_key:C.OPERATIONSAPI_NETWORK_HTTPS,https_on:C.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:C.OPERATIONSAPI_NETWORK_CORS,cors_on:C.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:C.LOGGING_LEVEL,log_level:C.LOGGING_LEVEL,log_path_key:C.LOGGING_ROOT,log_path:C.LOGGING_ROOT,clustering_node_name_key:C.CLUSTERING_NODENAME,node_name:C.CLUSTERING_NODENAME,clustering_enabled_key:C.CLUSTERING_ENABLED,clustering:C.CLUSTERING_ENABLED,max_http_threads:C.THREADS,max_hdb_processes:C.THREADS,server_timeout_key:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:C.LOGGING_AUDITLOG,disable_transaction_log:C.LOGGING_AUDITLOG,operation_token_timeout_key:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:C.HTTP_PORT,custom_functions_port:C.HTTP_PORT,custom_functions_directory_key:C.COMPONENTSROOT,custom_functions_directory:C.COMPONENTSROOT,max_custom_function_processes:C.THREADS,log_to_file:C.LOGGING_FILE,log_to_stdstreams:C.LOGGING_STDSTREAMS,local_studio_on:C.LOCALSTUDIO_ENABLED,clustering_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:C.CLUSTERING_USER,clustering_enabled:C.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:C.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:C.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:C.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:C.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:C.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:C.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:C.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:C.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:C.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:C.CLUSTERING_NODENAME,clustering_tls_certificate:C.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:C.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:C.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:C.CLUSTERING_TLS_INSECURE,clustering_tls_verify:C.CLUSTERING_TLS_VERIFY,clustering_loglevel:C.CLUSTERING_LOGLEVEL,clustering_republishmessages:C.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:C.CLUSTERING_DATABASELEVEL,customfunctions_network_port:C.HTTP_PORT,customfunctions_tls_certificate:C.TLS_CERTIFICATE,customfunctions_network_cors:C.HTTP_CORS,customfunctions_network_corsaccesslist:C.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:C.HTTP_HEADERSTIMEOUT,customfunctions_network_https:C.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:C.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:C.HTTP_TIMEOUT,http_threads:C.THREADS,threads:C.THREADS,maxheapmemory:C.MAXHEAPMEMORY,http_session_affinity:C.HTTP_SESSIONAFFINITY,http_compressionthreshold:C.HTTP_COMPRESSIONTHRESHOLD,http_cors:C.HTTP_CORS,http_corsaccesslist:C.HTTP_CORSACCESSLIST,http_headerstimeout:C.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,http_timeout:C.HTTP_TIMEOUT,http_port:C.HTTP_PORT,http_secureport:C.HTTP_SECUREPORT,customfunctions_processes:C.THREADS,customfunctions_root:C.COMPONENTSROOT,localstudio_enabled:C.LOCALSTUDIO_ENABLED,logging_file:C.LOGGING_FILE,logging_level:C.LOGGING_LEVEL,logging_root:C.LOGGING_ROOT,logging_rotation_enabled:C.LOGGING_ROTATION_ENABLED,logging_rotation_compress:C.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:C.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:C.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:C.LOGGING_ROTATION_PATH,logging_stdstreams:C.LOGGING_STDSTREAMS,logging_auditlog:C.LOGGING_AUDITLOG,logging_auditretention:C.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:C.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:C.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:C.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:C.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:C.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:C.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:C.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:C.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:C.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:C.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:C.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:C.ROOTPATH,databases:C.DATABASES,storage_path:C.STORAGE_PATH,ignorescripts:C.IGNORE_SCRIPTS,mqtt_network_port:C.MQTT_NETWORK_PORT,mqtt_websocket:C.MQTT_WEBSOCKET,mqtt_network_secureport:C.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:C.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:C.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:C.MQTT_NETWORK_MTLS_USER,mqtt_requireauthentication:C.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:C.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:C.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:C.AUTHENTICATION_CACHETTL,authentication_enablesessions:C.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:C.COMPONENTSROOT,tls_certificate:C.TLS_CERTIFICATE,tls_privatekey:C.TLS_PRIVATEKEY,tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,tls_ciphers:C.TLS_CIPHERS};for(let e in C){let t=C[e];vA[t.toLowerCase()]=t}var wq={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},Cq={csv_file_load:"csv_file_load",csv_data_load:X.CSV_DATA_LOAD,csv_url_load:X.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"},Dq={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"},Lq={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Mq={VERSION_DEFAULT:"2.2.0"},Uq={DEVELOPMENT:8192,DEFAULT:512},Pq={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"},vq={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"},Bq={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},BA={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Hq=Symbol("metadata"),xq="__clustering__",Fq=Object.values(BA),qq=15984864e5,HA={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Gq=UA.invert(HA),kq={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"},Vq=111,$q=`\r
2
+ `,Yq={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Kq=["*","%"],Wq="unauthorized_access",Qq="func_val",zq={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Jq={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Xq={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"},jq={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Zq={HTTP:"http"},eG={STOPPED:"stopped",ONLINE:"online"},tG="3.x.x",rG={SUCCESS:"success",FAILURE:"failure"},nG={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};xA.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:wA,HDB_SUPPORT_URL:DA,HDB_PRICING_URL:yF,SUPPORT_HELP_MSG:IF,LICENSE_HELP_MSG:LA,HDB_PROC_NAME:yA,HDB_PROC_DESCRIPTOR:eh,CLUSTERING_LEAF_PROC_DESCRIPTOR:Pl,CLUSTERING_HUB_PROC_DESCRIPTOR:Ul,SYSTEM_SCHEMA_NAME:KF,HASH_FOLDER_NAME:WF,HDB_HOME_DIR_NAME:QF,UPDATE_FILE_NAME:jF,LICENSE_KEY_DIR_NAME:JF,BOOT_PROPS_FILE_NAME:XF,JOB_TYPE_ENUM:Cq,JOB_STATUS_ENUM:gq,SYSTEM_TABLE_NAMES:Eq,SYSTEM_TABLE_HASH_ATTRIBUTES:hq,OPERATIONS_ENUM:X,VALID_S3_FILE_TYPES:Rq,S3_BUCKET_AUTH_KEYS:Aq,VALID_SQL_OPS_ENUM:Oq,GEO_CONVERSION_ENUM:Nq,HDB_SETTINGS_NAMES:PA,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:yq,SERVICE_ACTIONS_ENUM:bq,CLUSTER_MESSAGE_TYPE_ENUM:Dq,CLUSTER_CONNECTION_DIRECTION_ENUM:Lq,CLUSTER_EVENTS_DEFS_ENUM:Pq,PERIOD_REGEX:PF,DOUBLE_PERIOD_REGEX:vF,UNICODE_PERIOD:BF,FORWARD_SLASH_REGEX:HF,UNICODE_FORWARD_SLASH:xF,ESCAPED_FORWARD_SLASH_REGEX:FF,ESCAPED_PERIOD_REGEX:qF,ESCAPED_DOUBLE_PERIOD_REGEX:GF,REG_KEY_FILE_NAME:Sq,RESTART_TIMEOUT_MS:tq,HDB_FILE_PERMISSIONS:rq,DATABASES_DIR_NAME:iq,LEGACY_DATABASES_DIR_NAME:oq,TRANSACTIONS_DIR_NAME:aq,LIMIT_COUNT_NAME:cq,ID_ATTRIBUTE_STRING:uq,INSERT_MODULE_ENUM:dq,UPGRADE_JSON_FIELD_NAMES_ENUM:fq,RESTART_CODE:ZF,RESTART_CODE_NUM:eq,CLUSTER_OPERATIONS:Ja,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:pq,HDB_INTERNAL_SC_CHANNEL_PREFIX:Ir,INTERNAL_SC_CHANNELS:mq,CLUSTERING_MESSAGE_TYPES:kq,HDB_FILE_SUFFIX:zF,BLOB_FOLDER_NAME:nq,HDB_TRASH_DIR:sq,ORIGINATOR_SET_VALUE:Vq,LICENSE_VALUES:Mq,RAM_ALLOCATION_ENUM:Uq,TIME_STAMP_NAMES_ENUM:BA,TIME_STAMP_NAMES:Fq,PERMS_UPDATE_RELEASE_TIMESTAMP:qq,SEARCH_NOT_FOUND_MESSAGE:wF,SEARCH_ATTRIBUTE_NOT_FOUND:CF,LICENSE_ROLE_DENIED_RESPONSE:DF,LICENSE_MAX_CONNS_REACHED:LF,BASIC_LICENSE_MAX_NON_CU_ROLES:CA,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:NF,VALUE_SEARCH_COMPARATORS:HA,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Gq,LICENSE_FILE_NAME:Tq,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:vq,NEW_LINE:$q,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:UF,MOMENT_DAYS_TAG:kF,API_TURNOVER_SEC:VF,LOOPBACK:MF,CODE_EXTENSION:Ml,WILDCARD_SEARCH_VALUE:$F,NODE_ERROR_CODES:Bq,JAVASCRIPT_EXTENSION:NA,PERMS_CRUD_ENUM:Yq,UNAUTHORIZED_PERMISSION_NAME:Wq,SEARCH_WILDCARDS:Kq,FUNC_VAL:Qq,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:zq,JWT_ENUM:Jq,CLUSTERING_FLAG:xq,ITC_EVENT_TYPES:Xq,CUSTOM_FUNCTION_PROC_NAME:IA,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Ll,SERVICES:jq,THREAD_TYPES:Zq,MEM_SETTING_KEY:YF,HDB_RESTART_SCRIPT:lF,PROCESS_DESCRIPTORS:mF,SERVICE_SERVERS:RF,SERVICE_SERVERS_CWD:ZE,PROCESS_DESCRIPTORS_VALIDATE:TF,LAUNCH_SERVICE_SCRIPTS:AF,LOG_LEVELS:SF,PROCESS_NAME_ENV_PROP:lq,LOG_NAMES:pF,PM2_PROCESS_STATUSES:eG,CONFIG_PARAM_MAP:vA,CONFIG_PARAMS:C,HDB_CONFIG_FILE:aF,HDB_DEFAULT_CONFIG_FILE:cF,ROLE_TYPES_ENUM:OF,BOOT_PROP_PARAMS:MA,INSTALL_PROMPTS:_q,HDB_ROOT_DIR_NAME:uF,CLUSTERING_PROCESSES:gF,FOREGROUND_PID_FILE:fF,PACKAGE_ROOT:Ys,PRE_4_0_0_VERSION:tG,DATABASES_PARAM_CONFIG:wq,METADATA_PROPERTY:Hq,AUTH_AUDIT_STATUS:rG,AUTH_AUDIT_TYPES:nG,HDB_PID_FILE:EF,DEFAULT_DATABASE_NAME:hF,LEGACY_CONFIG_PARAMS:Iq};th()});var th=T((Fie,qA)=>{var sG=require("fast-glob"),{statSync:rh,existsSync:nh,readFileSync:iG,writeFileSync:oG}=require("fs"),{spawnSync:aG,spawn:cG,execFileSync:xie}=require("child_process"),{isMainThread:uG}=require("worker_threads"),{join:Ks,relative:FA}=require("path"),{PACKAGE_ROOT:Rn}=M(),{tmpdir:lG,platform:_G}=require("os");require("source-map-support").install();var dG=["resources","server","dataLayer","components"],Xa="ts-build",sh,fG=__filename.endsWith("tsBuild.js");if(fG){if(uG){let r;try{rh(Ks(Rn,Xa)),r=!0}catch{}if(r)for(let n of sG.sync(dG.map(s=>s+"/**/*.ts"),{cwd:Rn})){let s=0,i=0;try{s=rh(Ks(Rn,n)).mtimeMs-5e3,i=rh(Ks(Rn,Xa,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),sh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),sh=!0;if(sh){let n=Ks(Rn,"node_modules/.bin/tsc");_G()==="win32"&&(n+=".cmd");let s=aG(n,{cwd:Rn});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=Ks(lG(),"harperdb-tsc.pid"),o;if(nh(i))try{process.kill(+iG(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=cG(n,["--watch"],{cwd:Rn,detached:!0,stdio:"ignore"});oG(i,c.pid.toString()),c.unref()}}}}let e=qA.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(Rn)&&!n[0].includes("node_modules")){let i=FA(Rn,n[0]),o;i.startsWith(Xa)?o=Ks(Rn,FA(Xa,i)):o=Ks(Rn,Xa,i);let c=Ks(o,r),u=c+".js";if(nh(u))return u;if(c.includes(".")&&nh(c))return c}return t(r,n,s)}}});var yi={};qe(yi,{server:()=>ut});var GA,ut,Zt=Re(()=>{GA=require("../index"),ut={};(0,GA._assignPackageExport)("server",ut)});var ih=T((qie,$A)=>{"use strict";var kA=require("minimist");$A.exports=EG;function EG(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=VA(process.env),n=VA(kA(process.argv))):(r=process.env,n=kA(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(EG,"assignCMDENVVariables");function VA(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(VA,"objKeysToLowerCase")});var Y=T((kie,dh)=>{"use strict";var Ii=require("fs-extra"),{workerData:hG,threadId:mG}=require("worker_threads"),Es=require("path"),WA=require("yaml"),QA=require("properties-reader"),At=M(),YA=ih(),pG=require("os"),{PACKAGE_ROOT:ah}=M(),{_assignPackageExport:SG}=require("../index"),Za={};for(let e in console)Za[e]||(Za[e]=console[e]);var tr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},zA={STDOUT:"stdOut",STDERR:"stdErr"},TG=Es.join(ah,"logs"),gG=Es.join(ah,"config/yaml/",At.HDB_DEFAULT_CONFIG_FILE),RG=1e4,ds,Gn,er,vl,Bl,ec,Uo,ja;ja===void 0&&JA();dh.exports={notify:ZA,fatal:eO,error:tc,warn:_h,info:Hl,debug:lh,trace:uh,setLogLevel:wG,log_level:er,loggerWithTag:AG,suppressLogging:OG,initLogSettings:JA,setupConsoleLogging:XA,logCustomLevel:yG,closeLogFile:ch,getLogFilePath:()=>ec,OUTPUTS:zA,AuthAuditLog:LG};SG("logger",dh.exports);function JA(e=!1){try{if(ja===void 0||e){ch();let t=IG(),r=YA(["ROOTPATH"]);try{ja=QA(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Ii.pathExistsSync(Es.join(r.ROOTPATH,At.HDB_CONFIG_FILE)))throw n}({level:er,config_log_path:Bl,to_file:ds,to_stream:Gn}=CG(r.ROOTPATH?Es.join(r.ROOTPATH,At.HDB_CONFIG_FILE):ja.get("settings_path"))),vl=At.LOG_NAMES.HDB,ec=Es.join(Bl,vl)}}catch(t){if(ja=void 0,t.code===At.NODE_ERROR_CODES.ENOENT){let r=YA(Object.keys(At.CONFIG_PARAM_MAP),!0);for(let o in r){let c=At.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===At.CONFIG_PARAMS.LOGGING_LEVEL){er=u;continue}if(c===At.CONFIG_PARAMS.LOGGING_STDSTREAMS){Gn=u;continue}c===At.CONFIG_PARAMS.LOGGING_FILE&&(ds=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=DG();ds=ds===void 0?s:ds,ds=KA(ds),Gn=Gn===void 0?i:Gn,Gn=KA(Gn),er=er===void 0?n:er,Bl=TG,vl=At.LOG_NAMES.INSTALL,ec=Es.join(Bl,vl);return}throw tc("Error initializing log settings"),tc(t),t}process.env.DEV_MODE&&(Gn=!0),XA()}a(JA,"initLogSettings");var oh=!0;function XA(){Mo("error",tc),Mo("warn",_h),Mo("log",Hl),Mo("info",Hl),Mo("debug",lh),Mo("trace",uh)}a(XA,"setupConsoleLogging");function Mo(e,t){console[e]=function(...r){if(oh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return Za[e](...r)}}a(Mo,"logConsole");function AG(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(ZA),fatal:r(eO),error:r(tc),warn:r(_h),info:r(Hl),debug:r(lh),trace:r(uh)};function r(n){return function(...s){return n(t,...s)}}}a(AG,"loggerWithTag");function OG(e){try{oh=!1,e()}finally{oh=!0}}a(OG,"suppressLogging");var bG=hG?.name?.replace(/ /g,"-")||"main";function hs(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-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||bG+"/"+mG);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
3
+ `}a(hs,"createLogRecord");function rc(e){ds&&jA(e),Gn&&process.stdout.write(e)}a(rc,"logStdOut");function xl(e){ds&&jA(e),Gn&&process.stderr.write(e)}a(xl,"logStdErr");function jA(e){NG(),Uo?Ii.appendFileSync(Uo,e):Za.log(e)}a(jA,"logToFile");function ch(){try{Ii.closeSync(Uo)}catch{}Uo=null}a(ch,"closeLogFile");function NG(){if(!Uo){try{if(!ec)debugger;Uo=Ii.openSync(ec,"a")}catch(e){Za.error(e)}setTimeout(()=>{ch()},RG).unref()}}a(NG,"openLogFile");function Hl(...e){tr[er]<=tr.info&&rc(hs("info",e))}a(Hl,"info");function uh(...e){tr[er]<=tr.trace&&rc(hs("trace",e))}a(uh,"trace");function tc(...e){tr[er]<=tr.error&&xl(hs("error",e))}a(tc,"error");function lh(...e){tr[er]<=tr.debug&&rc(hs("debug",e))}a(lh,"debug");function ZA(...e){tr[er]<=tr.notify&&rc(hs("notify",e))}a(ZA,"notify");function eO(...e){tr[er]<=tr.fatal&&xl(hs("fatal",e))}a(eO,"fatal");function _h(...e){tr[er]<=tr.warn&&xl(hs("warn",e))}a(_h,"warn");function yG(e,t,...r){t===zA.STDERR?xl(hs(e,r)):rc(hs(e,r))}a(yG,"logCustomLevel");function IG(){let e;try{e=pG.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=Es.join(e,At.HDB_HOME_DIR_NAME,At.BOOT_PROPS_FILE_NAME);return Ii.existsSync(t)||(t=Es.join(ah,"utility/hdb_boot_properties.file")),t}a(IG,"getPropsFilePath");function wG(e){er=e}a(wG,"setLogLevel");function KA(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(KA,"autoCastBoolean");function CG(e){try{if(e.includes("config/settings.js")){let o=QA(e);return{level:o.get(At.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:Es.dirname(o.get(At.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(At.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(At.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=WA.parseDocument(Ii.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===At.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(CG,"getLogConfig");function DG(){try{let e=WA.parseDocument(Ii.readFileSync(gG,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(DG,"getDefaultConfig");function LG(e,t,r,n,s,i){this.username=e,this.status=t,this.type=r,this.originating_ip=n,this.request_method=s,this.path=i}a(LG,"AuthAuditLog")});var rO=T(($ie,tO)=>{"use strict";var MG=require("util"),UG=require("path"),PG=require("child_process"),vG=MG.promisify(PG.execFile),BG=1e3*1e3*10;tO.exports={findPs:HG};async function HG(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await vG("ps",["wwxo",`pid,${r}`],{maxBuffer:BG});for(let s of n.trim().split(`
4
+ `).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.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,n])=>({pid:Number.parseInt(r,10),name:UG.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(HG,"findPs")});var Et=T((Kie,sO)=>{"use strict";var xG="__dbis__",FG="__txns__",qG="__environment_name__",GG="__dbi_defintion__",kG={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"},VG=["__createdtime__","__updatedtime__"],$G="\uFFFF",nO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},YG=Object.values(nO);sO.exports={AUDIT_STORE_NAME:FG,INTERNAL_DBIS_NAME:xG,DBI_DEFINITION_NAME:GG,SEARCH_TYPES:kG,TIMESTAMP_NAMES:VG,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:qG,TRANSACTIONS_DBI_NAMES_ENUM:nO,TRANSACTIONS_DBIS:YG,OVERFLOW_MARKER:$G}});var wr=T((Wie,fO)=>{"use strict";var iO=M(),oO=Et(),aO={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},cO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),uO={500:cO("There was an error processing your request."),400:"Invalid request"},KG=uO[aO.INTERNAL_SERVER_ERROR],WG={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.`},QG={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},zG={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"},JG={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 ${oO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${oO.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"},XG={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${iO.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 ${iO.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"},lO={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"},jG={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."},ZG={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`},ek={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"},tk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},rk={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`},_O={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.`},dO={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}`},nk={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."},sk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},ik={...lO,...zG,...WG,...jG,...ZG,...ek,...tk,...rk,...XG,..._O,...dO,...nk,...sk,...QG};fO.exports={CHECK_LOGS_WRAPPER:cO,HDB_ERROR_MSGS:ik,DEFAULT_ERROR_MSGS:uO,DEFAULT_ERROR_RESP:KG,HTTP_STATUS_CODES:aO,LMDB_ERRORS_ENUM:JG,AUTHENTICATION_ERROR_MSGS:lO,VALIDATION_ERROR_MSGS:_O,ITC_ERRORS:dO}});var Z=T((zie,mO)=>{"use strict";var Po=wr(),ok=Y(),ak=M(),Fl=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,EO),this.statusCode=n||Po.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Po.DEFAULT_ERROR_MSGS[n]?Po.DEFAULT_ERROR_MSGS[n]:Po.DEFAULT_ERROR_MSGS[Po.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&ok[s](i)}},fh=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}},Eh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function EO(e,t,r,n=ak.LOG_LEVELS.ERROR,s=null,i=!1){if(hO(e))return e;let o=new Fl(e,t,r,n,s);return i&&delete o.stack,o}a(EO,"handleHDBError");function hO(e){return e.__proto__.constructor.name===Fl.name}a(hO,"isHDBError");mO.exports={isHDBError:hO,handleHDBError:EO,ClientError:fh,ServerError:Eh,hdb_errors:Po}});var Je=T((Xie,OO)=>{"use strict";var ac=M(),ck=J(),rr=j(),cc=require("path"),uk=require("minimist"),pO=require("fs-extra"),SO=require("lodash");rr.initSync();var{CONFIG_PARAMS:Ws,DATABASES_PARAM_CONFIG:nc,SYSTEM_SCHEMA_NAME:ql}=ac,sc,ic,oc;function TO(){if(sc!==void 0)return sc;if(rr.getHdbBasePath()!==void 0)return sc=rr.get(Ws.STORAGE_PATH)||cc.join(rr.getHdbBasePath(),ac.DATABASES_DIR_NAME),sc}a(TO,"getBaseSchemaPath");function gO(){if(ic!==void 0)return ic;if(rr.getHdbBasePath()!==void 0)return ic=AO(ql),ic}a(gO,"getSystemSchemaPath");function RO(){if(oc!==void 0)return oc;if(rr.getHdbBasePath()!==void 0)return oc=rr.get(ac.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cc.join(rr.getHdbBasePath(),ac.TRANSACTIONS_DIR_NAME),oc}a(RO,"getTransactionAuditStoreBasePath");function lk(e,t){let r=rr.get(Ws.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cc.join(RO(),e.toString())}a(lk,"getTransactionAuditStorePath");function AO(e,t){e=e.toString(),t=t&&t.toString();let r=rr.get(ac.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cc.join(TO(),e)}a(AO,"getSchemaPath");function _k(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,uk(process.argv));let n=r[Ws.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!ck.isObject(n))throw o;i=n}for(let o of i){let c=o[ql];if(!c)continue;let u=rr.get(Ws.DATABASES);u=u??{};let _=c?.tables?.[t]?.[nc.PATH];if(_)return SO.set(u,[ql,nc.TABLES,t,nc.PATH],_),rr.setProperty(Ws.DATABASES,u),_;let l=c?.[nc.PATH];if(l)return SO.set(u,[ql,nc.PATH],l),rr.setProperty(Ws.DATABASES,u),l}}let s=r[Ws.STORAGE_PATH.toUpperCase()];if(s){if(!pO.pathExistsSync(s))throw new Error(s+" does not exist");let i=cc.join(s,e);return pO.mkdirsSync(i),rr.setProperty(Ws.STORAGE_PATH,s),i}return gO()}a(_k,"initSystemSchemaPaths");function dk(){sc=void 0,ic=void 0,oc=void 0}a(dk,"resetPaths");OO.exports={getBaseSchemaPath:TO,getSystemSchemaPath:gO,getTransactionAuditStorePath:lk,getTransactionAuditStoreBasePath:RO,getSchemaPath:AO,initSystemSchemaPaths:_k,resetPaths:dk}});var Cr=T((toe,wO)=>{"use strict";var fk=wr().LMDB_ERRORS_ENUM,Zie=require("lmdb"),Ek=Et(),eoe=require("buffer").Buffer,{OVERFLOW_MARKER:bO,MAX_SEARCH_KEY_LENGTH:Gl}=Ek,NO=["number","string","symbol","boolean","bigint"];function hk(e){if(e=e?.primaryStore||e,!e)throw new Error(fk.ENV_REQUIRED)}a(hk,"validateEnv");function mk(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(mk,"stringifyData");function pk(e){return e instanceof Date?e.valueOf():e}a(pk,"convertKeyValueToWrite");function Sk(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(NO.includes(typeof e))return e.length>Gl?[e.slice(0,Gl)+bO]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(NO.includes(typeof i))i.length>Gl?r.push(i.slice(0,Gl)+bO):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(Sk,"getIndexedValues");var kl=0,yO=0;function IO(){yO=Date.now()-performance.now()}a(IO,"adjustStartTime");IO();var Tk=6e4;setInterval(IO,Tk).unref();function gk(){let e=performance.now()+yO;return e>kl?(kl=e,e):(kl+=488e-6,kl)}a(gk,"getNextMonotonicTime");wO.exports={validateEnv:hk,stringifyData:mk,convertKeyValueToWrite:pk,getNextMonotonicTime:gk,getIndexedValues:Sk}});var CO,An,hh,uc=Re(()=>{CO=require("events"),An=class extends CO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new hh;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)}},hh=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}}}});var UO={};qe(UO,{HAS_EXPIRATION:()=>Oh,LAST_TIMESTAMP_PLACEHOLDER:()=>dc,LOCAL_TIMESTAMP:()=>Rk,METADATA:()=>lc,NO_TIMESTAMP:()=>ph,PENDING_LOCAL_TIME:()=>bh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Ah,RecordEncoder:()=>gh,TIMESTAMP_ASSIGN_LAST:()=>Ok,TIMESTAMP_ASSIGN_NEW:()=>LO,TIMESTAMP_ASSIGN_PREVIOUS:()=>MO,TIMESTAMP_PLACEHOLDER:()=>Vl,TIMESTAMP_RECORD_PREVIOUS:()=>Sh,fromResource:()=>Wl,getUpdateRecord:()=>Nh,handleLocalTimeForGets:()=>Ql});function Nk(){return _c[0]=_c[0]^64,Ak.getFloat64(0)}function Wl(e){Rh=!0;try{return e()}finally{Rh=!1}}function Ql(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[lc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[lc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[lc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,wi.push(new WeakRef(this))),!Rh)try{throw new Error("Read transaction used outside of resource")}catch(u){this.readStack=u.stack}o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<wi.length;u++){let _=wi[u].deref();(!_||_.isDone||_.isCommitted)&&wi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Nh(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?vo=i?.localTime?Sh|MO:ph:vo=u?i?.localTime?Sh|16384:LO|16384:ph,l>0&&(c|=Oh),Yl=c,Th=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:vo>0},S;try{f&&(h.ifVersion=S=i?.version??null);let p=e.put(n,s,h);if(u){let g=_?.user?.username;if(E&&($l=e.encoder.encode(E)),f&&i?.localTime){let A=i?.localTime,b=r.get(A);if(b){let v=Ut(b).previousLocalTime;return r.put(A,Kl(o,t,n,v,g,d,$l),{ifVersion:S}),p}}r.put(dc,Kl(o,t,n,i?.localTime?1:0,g,d,$l),{append:d!=="invalidate",instructedWrite:!0,ifVersion:S})}return p}catch(p){throw p.message+=" id: "+n+" options: "+h,p}}}var DO,mh,Vl,dc,Ah,Rk,lc,_c,Ak,ph,LO,Ok,MO,Sh,Oh,bh,bk,$l,vo,Yl,Th,gh,ooe,Rh,wi,Bo=Re(()=>{DO=require("msgpackr");Ci();mh=B(Y()),Vl=new Uint8Array([1,1,1,1,4,64,0,0]),dc=new Uint8Array([1,1,1,1,1,0,0,0]),Ah=new Uint8Array([1,1,1,1,3,64,0,0]),Rk=Symbol("local-timestamp"),lc=Symbol("metadata"),_c=new Uint8Array(8),Ak=new DataView(_c.buffer,0,8),ph=0,LO=0,Ok=1,MO=3,Sh=4,Oh=16,bh=1,vo=0,Yl=-1,Th=0,gh=class extends DO.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(vo||Yl>=0){let i=0,o=vo;o&&(i+=8,vo=0);let c=Yl,u=Th;c>=0&&(i+=2,Yl=-1,u&&(i+=8,Th=0));let _=bk=r.call(this,n,s|2048|i);$l=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(Vl[4]=o,Vl[5]=o>>8,_.set(Vl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(_c,0,c),c+=8;else for(let d=0;d<8;d++)_c[d]=t[c++];u=Nk(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Oh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[lc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(Nk,"getTimestamp");ooe=Map.prototype.get;a(Wl,"fromResource");a(Ql,"handleLocalTimeForGets");wi=[];setInterval(()=>{for(let e=0;e<wi.length;e++){let t=wi[e].deref();!t||t.isDone||t.isCommitted?wi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(mh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):mh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(Nh,"getUpdateRecord")});var YO={};qe(YO,{AUDIT_STORE_OPTIONS:()=>VO,createAuditEntry:()=>Kl,openAuditStore:()=>jl,readAuditEntry:()=>Ut,setAuditRetention:()=>Ik,transactionKeyEncoder:()=>kO});function jl(e){let t=e.auditStore=e.openDB(FO.AUDIT_STORE_NAME,VO);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=zl){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-yh})){if((_[0]&15)===Ch){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=yk){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,yh/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,Xl.getWorkerIndex)()===(0,Xl.getWorkerCount)()-1&&s(zl),t}function Ik(e,t=zl){yh=e,zl=t}function Kl(e,t,r,n,s,i,o){let c=$O[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?Ho.setFloat64(0,n):en.set(Ah),u=9),f(0),f(t),d(r),Ho.setFloat64(u,e),u+=8,s?d(s):en[u++]=0,en[n?8:0]=c;let l=en.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,xo.writeKey)(E,en,u);let S=u-h-1;S>127?S>16383?(Lh.error("Key or username was too large for audit entry",E),u=h+1,en[h]=0):(en.copyWithin(h+2,h+1,u),Ho.setUint16(h,S|32768),u++):en[h]=S}function f(E){E<128?en[u++]=E:E<16384?(Ho.setUint16(u,E|32768),u+=2):E<1056964608?(Ho.setUint32(u,E|3221225472),u+=4):(en[u]=255,Ho.setUint32(u+1,E),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new Dh(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:$O[n&7],tableId:i,get recordId(){return xO(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?xO(e,l,d):void 0},getValue(f,E,h){if(n&Ih||n&wh&&!E)return f.decoder.decode(e.subarray(t.position));if(n&wh&&h)return Mh(f.getEntry(this.recordId),h,f)}}}catch{return Lh.error("Reading audit entry error",e),{}}}function xO(e,t,r){let n=e.subarray(t,r);return(0,xo.readKey)(n,0,r-t)}var xo,Jl,FO,qO,Xl,GO,Lh,en,Ho,kO,VO,yh,yk,zl,Ih,wh,PO,Ch,vO,BO,HO,$O,Dh,Ci=Re(()=>{xo=require("ordered-binary"),Jl=B(j()),FO=B(Et()),qO=B(M()),Xl=B(tt()),GO=B(J());Bo();Lh=B(Y());Zl();(0,Jl.initSync)();en=Buffer.alloc(1024),Ho=new DataView(en.buffer,en.byteOffset,1024),kO={writeKey(e,t,r){return e===dc?(t.set(dc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,xo.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,xo.readKey)(e,t,r)}},VO={encoding:"binary",keyEncoder:kO},yh=(0,GO.convertToMS)((0,Jl.get)(qO.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,yk=1e3,zl=1e4;a(jl,"openAuditStore");a(Ik,"setAuditRetention");Ih=16,wh=32,PO=1,Ch=2,vO=3,BO=4,HO=5,$O={put:PO|Ih,[PO]:"put",delete:Ch,[Ch]:"delete",message:vO|Ih,[vO]:"message",invalidate:BO,[BO]:"invalidate",patch:HO|wh,[HO]:"patch"};a(Kl,"createAuditEntry");a(Ut,"readAuditEntry");Dh=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(xO,"readKeySafely")});var Uh={};qe(Uh,{add:()=>e_,applyReverse:()=>KO,getRecordAtTime:()=>Mh,rebuildUpdateBefore:()=>t_});function e_(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function t_(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,e_(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function KO(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=wk[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=WO}}function Mh(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Ut(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":KO(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===WO&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Ut(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var wk,WO,Zl=Re(()=>{Ci();a(e_,"add");e_.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};wk={add:e_};a(t_,"rebuildUpdateBefore");a(KO,"applyReverse");WO={};a(Mh,"getRecordAtTime")});function Dr(e){return e[Ot]||(e[Ot]=Object.create(null))}function o_(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Ae])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a string, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a string, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a number, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new tn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new tn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new tn.ClientError(`${c} must be a number, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new tn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Dr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be an object, attempt to assign ${l}`);Dr(this)[c]=l},"set")}_={get(){let l=this[Ot];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[be]?.[c];return f.update(E)}return f}let d=this[be]?.[c];if(d&&typeof d=="object"){let f=QO(d,o);if(f)return l||(l=this[Ot]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Ot];return u?.[o]!==void 0?u[o]:this[be]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new tn.ClientError("Can not add a property to a sealed table schema");Dr(this)[o]=c}),i("deleteProperty",function(o){Dr(this)[o]=void 0}),i("toJSON",function(){let o=this[Ot],c;for(let _ in o){c||(c=Object.assign({},this[be]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[be])),Object.assign(c,this)),c||this[be]}),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 QO(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){this[be]=s}},o_(r,t)),new r(e)):new r_(e);case Array:let n=new s_(e.length);n[be]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=QO(o,t?.elements)),n[s]=o}return n;default:return e}}function a_(e){let t=e[Ot],r;for(let s in t){r||(r=Object.assign({},e[be]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=a_(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[be])),Object.assign(r,e)),r||e[be]}function Li(e,t=e[Ot]){let r;if(e[be]&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Li(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[be]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=Uh[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Li(s);r[n]=s}return r?Object.freeze(r):e[be]||e}function n_(e){let t=e[be];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Di]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[be]===s){if(n_(i))return!0}else return!0}}else{let r=e[Ot];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[be]===i){if(n_(s))return!0}else return!0}else return!0}}return!1}var tn,Ot,r_,Di,s_,i_,c_=Re(()=>{On();tn=B(Z());Zl();Ot=Symbol("own-data");a(Dr,"getChanges");a(o_,"assignTrackedAccessors");a(QO,"trackObject");r_=class{static{a(this,"GenericTrackedObject")}constructor(t){this[be]=t}};o_(r_,{});a(a_,"collapseData");a(Li,"deepFreeze");a(n_,"hasChanges");Di=Symbol.for("has-array-changes"),s_=class extends Array{static{a(this,"TrackedArray")}[Di];constructor(t){super(t)}splice(...t){return this[Di]=!0,super.splice(...t)}push(...t){return this[Di]=!0,super.push(...t)}pop(){return this[Di]=!0,super.pop()}unshift(...t){return this[Di]=!0,super.unshift(...t)}shift(){return this[Di]=!0,super.shift()}};s_.prototype.constructor=Array;i_=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});function Mk(){Lk=setInterval(function(){for(let e of Ph)if(e.stale){let t=e[Ae]?.url;zO.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},Dk).unref()}var vh,zO,Ck,Ph,Mi,u_,Dk,Lk,Bh=Re(()=>{vh=B(Cr()),zO=B(Y());On();Bo();Ck=100,Ph=new Set,Mi=class{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=!0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(!this.open)throw new Error("Can not start a read on a transaction that is no longer open");return this.readTxnsUsed=1,Wl(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),Ph.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),Wl(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Ph.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(!this.open&&!this.autoCommitMode)throw new Error("Can not use a transaction that is no longer open");this.writes.push(t),this.autoCommitMode&&this.commit()}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,vh.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let S=this.writes[h];if(!S)continue;let p=S[f===0?"before":"beforeIntermediate"];if(p){let g=p();E?E.push?E.push(g):E=[E,g]:E=g}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),t?.prepared?.(),this.open=!1;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<Ck>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=!1,this.writes=[]}},u_=class extends Mi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,vh.getNextMonotonicTime)())}getReadTxn(){}},Dk=3e4;a(Mk,"startMonitoringTxns");Mk()});function Xe(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new Mi;e.timestamp&&(n.timestamp=e.timestamp),n[Ae]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit(r?.resetTransaction?{prepared(){n.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var JO,Ui=Re(()=>{JO=require("../index");On();Bh();a(Xe,"transaction");(0,JO._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function Go(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let g=o[0],A=ps(n.attributes,g);if(A.relationship){if(o.length<2)throw new ms.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let b=A.definition?.tableClass||A.elements?.definition?.tableClass,v=new Map,G=Go({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,b,s,v);if(A.relationship.to){i[o[0]]=v;let H=!!ps(b.attributes,A.relationship.to)?.elements;G=Hk(G,A,b.primaryStore,H,v)}if(A.relationship.from){let H=a(P=>Go({attribute:A.relationship.from,value:P},t,r,n,s,v),"searchEntry");A.elements?(i[o[0]]=v,G=xk(G,A,b.primaryStore,v,H)):G=G.flatMap(H)}return G}else if(o.length===1)o=o[0];else throw new ms.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(qh[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=kn.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"contains":case"ends_with":E=!0;break;default:throw new ms.ClientError(`Unknown query comparator "${u}"`)}if(r){let g=_;_=l,l=g,g=!f,f=!d,d=g}let h=o===n.primaryKey||o==null,S=h?n.primaryStore:n.indices[o];if(!S||S.isIndexing||E||c===null&&!S.indexNulls){if(!s)throw new ms.ClientError(`"${o}" is not indexed${c===null&&!S.indexNulls?" for nulls, index needs to be rebuilt to search for nulls":S?.isIndexing?" yet":""}, can not search for this attribute`,404);let g=hc(e);if(!g)throw new ms.ClientError(`Unknown search operator ${e.comparator}`);return n.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:A,value:b})=>new Promise((v,G)=>setImmediate(()=>{try{v(b&&g(b)?A:Hh.SKIP)}catch(H){G(H)}})))}let p={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let g=S.getRange(p).map(A=>A.value==null?Hh.SKIP:A);return g.hasEntries=!0,g}else return S.getRange(p).map(({value:g})=>g)}function ps(e,t){if(Array.isArray(t))if(t.length>1){let r=ps(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?ps(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function Hk(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=bn(d),o=!0);let h=s.get(E);h?h.push(f):s.set(E,h=[f]),d!==E&&(h.key=d)},"add_entry"),l=0;for await(let d of e){let f=d.value??r.get(d.key??d),E=f?.[u];if(E!=null&&!s.filters?.some(h=>!h(f))){if(n)for(let h=0;h<E.length;h++)_(E[h],d);else _(E,d);l++>100&&(await new Promise(setImmediate),l=0)}}return i=(o?s:s.keys())[Symbol.iterator](),this.next()})()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function xk(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=bn(u.value);if(!c.has(_))return c.add(_),u}if(!i)return(async()=>{let _=new Map;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>_.has(bn(f)));let l=0;for await(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(E=>!E(f)))continue}_.set(bn(d),d),l++>100&&(await new Promise(setImmediate),l=0)}return i=_.values()[Symbol.iterator](),this.next()})();do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function hc(e,t,r,n,s,i){if(e.conditions){let l=e.conditions.map(hc);return e.operator==="or"?d=>l.some(f=>f(d)):d=>l.every(f=>f(d))}let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=ps(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=hc({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},f,r,E?.[l]?.joined,c[1]===f.primaryKey,i);if(!h)return;if(E){E.filters||(E.filters=[]),E.filters.push(h);return}let S=t.propertyResolvers?.[l],p,g=a((A,b)=>{let v,G;if(S){if(S.from&&h.idFilter){if(!p)if(h.idFilter.idSet?.size===1){for(let P of h.idFilter.idSet)e={attribute:S.from,value:P};p=_(S.from,h.idFilter,!0)}else p=_(S.from,h.idFilter,!1);let H=p(A);return p.idFilter&&(g.idFilter=p.idFilter),H}G=S(A,r,b),v=G?.value}else v=A[l];return v?Array.isArray(v)?v.some(h):h(v,G):!1},"recordFilter");return g}}switch(u instanceof Date&&(u=u.getTime()),qh[o]||o){case xh.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,f=u.length;d<f;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,kn.compareKeys)(l,u[0])>=0&&(0,kn.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,kn.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,kn.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,kn.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,kn.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,kn.compareKeys)(l,u)!==0);default:throw new ms.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f){let E;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&l_(t)(e),E=e.estimated_count>>4,(isNaN(E)||E>=i)&&(f=!1));let h=0,S=3;function p(g){let A=g[l],b;if(typeof A!="object"||!A?b=d(A):Array.isArray(A)?b=A.some(d):A instanceof Date&&(b=d(A.getTime())),f&&(S++,!b&&!p.idFilter&&++h/S*(i-S)>E)){let v=Go(e,r.transaction,!1,t).map(bn),G=new Set(v);p.idFilter=H=>G.has(bn(H)),p.idFilter.idSet=G}return b}return a(p,"recordFilter"),s&&(p.idFilter=d),p}a(_,"attributeComparator")}function l_(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Qs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=qh[n]||n,n===xh.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=ps(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=l_(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"});r.estimated_count=c*Qs(e.indices[i.relationship.from]||e.primaryStore)/(Qs(o.primaryStore)||1)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Qs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=vk*Qs(e.primaryStore)+1:n==="between"?r.estimated_count=Pk*Qs(e.primaryStore)+1:r.estimated_count=Uk*Qs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=4)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function __(e){if(e)if(zs=e,Fo.lastIndex=0,Fk.test(e))try{let t=fc(new qo,"");if(nr!==zs.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${nr} in '${zs}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function fc(e,t){let r=Fo,n,s,i,o,c,u=decodeURIComponent;for(;n=r.exec(zs);){nr=r.lastIndex;let[,_,l]=n;if(o){if(_)throw new SyntaxError(`expected operator, but encountered '${_}'`);o=!1,c=!1}else c=!0;let d;switch(l){case"=":if(s){if(_.length<=2)i=_;else throw new SyntaxError(`invalid FIQL operator ${_}`);u=XO}else{if(u=decodeURIComponent,i="equals",!_)throw new SyntaxError("attribute must be specified before equality comparator");s=Ec(_)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Bk[l],u=Fh[i]?XO:decodeURIComponent,!_)throw new SyntaxError(`attribute must be specified before comparator ${l}`);s=Ec(_);break;case"|":e.operator="or";case"":case void 0:case"&":if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${l[0]?"'"+l[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${l?"'"+l+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let E={comparator:i,attribute:s,value:u(_)};i==="eq"&&jO(E,_),e.conditions.push(E)}s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(Ec(_)),s=void 0;break;case"(":Fo.lastIndex=nr;let f=fc(_?[]:new qo,")");switch(_){case"":e.conditions.push(f);break;case"limit":switch(f.length){case 1:e.limit=+f[0];break;case 2:e.offset=+f[0],e.limit=f[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(f[0])&&f.length===1&&!f[0].name?(e.select=f[0],e.select.asArray=!0):f.length===1?e.select=f[0]:f.length===2&&f[1]===""?e.select=f.slice(0,1):e.select=f;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=ZO(f);break;default:throw new SyntaxError(`unknown query function call ${_}`)}zs[nr]===","?r.lastIndex=++nr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!_)throw new SyntaxError("property sets must have a defined parent property name");Fo.lastIndex=nr,d=fc([],"}"),d.name=_,e.push(d),zs[nr]===","?r.lastIndex=++nr:o=!0;break;case"[":Fo.lastIndex=nr,_?(d=fc(new qo,"]"),d.name=_):d=fc(e.conditions?new qo:[],"]"),e.conditions?(e.conditions.push(d),s=null):e.push(d),zs[nr]===","?r.lastIndex=++nr:o=!0;break;case")":case"]":case"}":if(t===l[0]){if(e.conditions){if(s){let E={comparator:i||"equals",attribute:s,value:u(_)};i==="eq"&&jO(E,_),e.conditions.push(E)}else if(_)throw new SyntaxError("no attribute or comparison specified")}else(_||e.length>0&&c)&&e.push(Ec(_));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${l[0]}'`):new SyntaxError(`unexpected token '${l[0]}'`);default:throw new SyntaxError(`unexpected operator '${l}'`)}if(t!==")"&&(r=s?qk:Fo,r.lastIndex=nr),nr===zs.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Ec(e){return e.indexOf(".")>-1?e.split(".").map(Ec):decodeURIComponent(e)}function XO(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new ms.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function jO(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new ms.ClientError("wildcard can only be used at the end of a string")}function ZO(e){let t=eb(e[0]);return e.length>1&&(t.next=ZO(e.slice(1))),t}function eb(e){if(Array.isArray(e)){let t=eb(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function bn(e){return Array.isArray(e)?e.join("\0"):e}function Qs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function tb(e,t,r){return t*r/Qs(e)}var ms,xh,kn,Hh,Uk,Pk,vk,Bk,Fh,qh,Fk,Fo,qk,nr,zs,qo,d_=Re(()=>{ms=B(Z()),xh=B(Et()),kn=require("ordered-binary"),Hh=require("lmdb"),Uk=.3,Pk=.1,vk=.05,Bk={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Fh={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Go,"searchByIndex");a(ps,"findAttribute");a(Hk,"joinTo");a(xk,"joinFrom");qh={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(hc,"filterByType");a(l_,"estimateCondition");Fk=/[()[\]|!<>.]|(=\w*=)/,Fo=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,qk=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(__,"parseQuery");a(fc,"parseBlock");a(Ec,"decodeProperty");a(XO,"typedDecoding");a(jO,"wildcardDecoding");a(ZO,"toSortObject");a(eb,"toSortEntry");qo=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 n=this.conditions[r];if(n.attribute===t)return n.value}}};a(bn,"flattenKey");a(Qs,"estimatedEntryCount");a(tb,"intersectionEstimate")});var Vh={};qe(Vh,{CONTEXT:()=>Ae,ID_PROPERTY:()=>Ce,IS_COLLECTION:()=>rn,RECORD_PROPERTY:()=>be,Resource:()=>Ft,snake_case:()=>kk,transformForSelect:()=>E_});function kk(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function rb(e,t){if(mc=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(mc=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new kh;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){mc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function Lr(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Ae]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[Ae]||i):l=i:(l=s,c=l[Ce]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ae]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let E of s){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,_=!1)))}else{if(typeof(c=s.url)=="string"){let E=c.indexOf("?");if(E>-1){let S=this.parseQuery(c.slice(E+1));u?u=Object.assign(S,u):u=S,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return d.resetTransaction=!0,Xe(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(S=>{if(!S)throw new f_(o.user);return typeof l?.then=="function"?l.then(p=>e(E,u,o,p)):e(E,u,o,l)});if(!h)throw new f_(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Mr(e,t){let r=new ib.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function Gh(e,t,r){let n=e[be];if(n){let s=e[Ot];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function E_(e,t){let r=t?.propertyResolvers,n=t[Ae],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):Gh(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(Gh(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(Gh(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=E_(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var nb,sb,ib,Ae,Ce,rn,be,Gk,Ft,f_,mc,kh,On=Re(()=>{nb=require("crypto");uc();sb=require("../index"),ib=B(Z());c_();Ui();d_();Ae=Symbol.for("context"),Ce=Symbol.for("primary-key"),rn=Symbol("is-collection"),be=Symbol("stored-record"),Gk={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Ft=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ce]=t;let n=r?.[Ae];this[Ae]=n!==void 0?n:r||null}static get=Lr(function(t,r,n,s){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&&!c.selectApplied){let _=E_(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",resetTransaction:!0,ensureLoaded:!0,async:!0});static put=Lr(function(t,r,n,s){if(Array.isArray(s)&&t[rn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Mr(t,"put")},{hasContent:!0,type:"update"});static patch=Lr(function(t,r,n,s){return t.patch?t.patch(s,r):Mr(t,"patch")},{hasContent:!0,type:"update"});static delete=Lr(function(t,r,n,s){return t.delete?t.delete(r):Mr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,nb.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),Xe(n,()=>{let i=new this(s,n),o=i.update?i.update(r):Mr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=Lr(function(t,r,n,s){return t.invalidate?t.invalidate(r):Mr(t,"delete")},{hasContent:!1,type:"update"});static post=Lr(function(t,r,n,s){return t[Ce]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Lr(function(t,r,n,s){return t.connect?t.connect(s,r):Mr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Lr(function(t,r,n,s){return t.subscribe?t.subscribe(r):Mr(t,"subscribe")},{type:"read"});static publish=Lr(function(t,r,n,s){return t[Ce]!=null&&t.update?.(),t.publish?t.publish(s,r):Mr(t,"publish")},{hasContent:!0,type:"create"});static search=Lr(function(t,r,n,s){let i=t.search?t.search(r):Mr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=E_(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Lr(function(t,r,n,s){return t.search?t.search(s,r):Mr(t,"search")},{hasContent:!0,type:"read"});static copy=Lr(function(t,r,n,s){return t.copy?t.copy(s,r):Mr(t,"copy")},{type:"create"});static move=Lr(function(t,r,n,s){return t.move?t.move(s,r):Mr(t,"move")},{type:"delete"});post(t){if(this[rn])return this.constructor.create(this[Ce],t,this[Ae]);Mr(this,"post")}static isCollection(t){return t?.[rn]}static coerceId(t){return t}static parseQuery(t){return __(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&Gk[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:rb(t,this),isCollection:mc}}let i=rb(t,this);return mc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Ae],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;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 _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Ce]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Ce],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[rn]=!0),s}subscribe(t){return new An}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new An}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[Ce]}getContext(){return this[Ae]}};Ft.prototype[Ae]=null;(0,sb._assignPackageExport)("Resource",Ft);a(kk,"snake_case");f_=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(rb,"pathToId");kh=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Lr,"transactional");a(Mr,"missingMethod");a(Gh,"selectFromObject");a(E_,"transformForSelect")});var ob={};qe(ob,{Resources:()=>h_,keyArrayToString:()=>ko,resetResources:()=>Vk,resources:()=>Js});function Vk(){return Js=new h_}function ko(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var h_,Js,pc=Re(()=>{Ui();h_=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Xe(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(Vk,"resetResources");a(ko,"keyArrayToString")});function cb(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;Vo||((0,m_.onMessageByType)(ab,l=>{ub(l.path)}),Vo=Object.create(null));let o=Vo[s]||(Vo[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=ko(t);let u=new Yh(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function ub(e,t){if(!Vo)return;let r=Vo[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Ut(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=ko(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,$h.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let S;h.supportsTransactions&&h.txnInProgress!==o.version&&(S=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,S)}catch(S){console.error(S),(0,$h.info)(S)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function lb(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,m_.broadcast)({type:ab,path:s}),ub(s,!0)})}}var $h,m_,ab,Vo,koe,Yh,_b=Re(()=>{$h=B(Y()),m_=B(tt());uc();pc();Ci();ab="transaction",koe=Buffer.alloc(4096);a(cb,"addSubscription");Yh=class extends An{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 n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(ub,"notifyFromTransactionData");a(lb,"listenToCommits")});var fb=T((Yoe,db)=>{"use strict";var Kh=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};db.exports=Kh});var hb=T((Woe,Eb)=>{"use strict";var Wh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Eb.exports=Wh});var p_=T((zoe,mb)=>{"use strict";var zh=j(),Jh=M(),{RecordEncoder:$k}=(Bo(),ee(UO));zh.initSync();var Yk=zh.get(Jh.CONFIG_PARAMS.STORAGE_COMPRESSION),Kk=zh.get(Jh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,Wk=Jh.UPDATES_PROPERTY,Qh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=Yk&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=Kk&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:$k},this.alwaysLazyProperty=n=>n===Wk)}};mb.exports=Qh});var T_=T((Xoe,Sb)=>{"use strict";var $o=j(),Sc=M();$o.initSync();var Qk=$o.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||$o.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||$o.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",pb=$o.get(Sc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),zk=$o.get(Sc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),S_=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=Qk,this.noFSAccess=!0,pb!==void 0&&(this.overlappingSync=pb),this.noReadAhead=zk}};Sb.exports=S_;S_.MAX_DBS=1e4});var We=T((Zoe,wb)=>{"use strict";var jh=require("lmdb"),Nn=require("fs-extra"),Ur=require("path"),g_=Cr(),Rb=Y(),sr=wr().LMDB_ERRORS_ENUM,R_=hb(),Zh=p_(),Ab=T_(),Xs=Et(),Tb=M(),{table:Jk,resetDatabases:Xk}=(Oe(),ee(Ge)),gb=j(),yn=Xs.INTERNAL_DBIS_NAME,Ob=Xs.DBI_DEFINITION_NAME,jk="data.mdb",Zk="lock.mdb",Tc=".mdb",eV="-lock",Xh=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=nn(t,r),this.key_type=this.dbi[Xs.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Xs.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new jh.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function A_(e,t){if(e===void 0)throw new Error(sr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(sr.ENV_NAME_REQUIRED)}a(A_,"pathEnvNameValidation");async function em(e,t,r=!0){try{await Nn.access(e)}catch(n){throw n.code==="ENOENT"?new Error(sr.INVALID_BASE_PATH):n}try{let n=Ur.join(e,t+Tc);return await Nn.access(n,Nn.constants.R_OK|Nn.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await Nn.access(Ur.join(e,t,jk),Nn.constants.R_OK|Nn.constants.F_OK),Ur.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(sr.INVALID_ENVIRONMENT)}else throw new Error(sr.INVALID_ENVIRONMENT);throw n}}a(em,"validateEnvironmentPath");function O_(e,t){if(g_.validateEnv(e),t===void 0)throw new Error(sr.DBI_NAME_REQUIRED)}a(O_,"validateEnvDBIName");async function tV(e,t,r=!1,n=!1){A_(e,t);let s=Ur.basename(e);t=t.toString();let i=gb.get(Tb.CONFIG_PARAMS.DATABASES);i||gb.setProperty(Tb.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await em(e,t,n),bb(e,t,r)}catch(o){if(o.message===sr.INVALID_ENVIRONMENT){let c=Ur.join(e,t);await Nn.mkdirp(n?c:e);let u=new Ab(n?c:c+Tc,!1),_=jh.open(u);_.dbis=Object.create(null);let l=new Zh(!1);_.openDB(yn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=tm(e,t,r);return _[Xs.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(tV,"createEnvironment");async function rV(e,t,r,n=!0){A_(e,t),t=t.toString();let s=Ur.join(e,t);return Jk({table:t,database:Ur.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(rV,"copyEnvironment");async function bb(e,t,r=!1){A_(e,t),t=t.toString();let n=tm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await em(e,t),i=Ur.join(e,t+Tc),o=s!=i,c=new Ab(s,o),u=jh.open(c);u.dbis=Object.create(null);let _=yb(u);for(let l=0;l<_.length;l++)nn(u,_[l]);return u[Xs.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(bb,"openEnvironment");async function nV(e,t,r=!1){A_(e,t),t=t.toString();let n=Ur.join(e,t+Tc),s=await em(e,t);if(global.lmdb_map!==void 0){let i=tm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Nb(o),delete global.lmdb_map[i]}}await Nn.remove(s),await Nn.remove(s===n?s+eV:Ur.join(Ur.dirname(s),Zk))}a(nV,"deleteEnvironment");async function Nb(e){g_.validateEnv(e);let t=e[Xs.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Nb,"closeEnvironment");function tm(e,t,r=!1){let s=`${Ur.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(tm,"getCachedEnvironmentName");function sV(e){g_.validateEnv(e);let t=Object.create(null),r=nn(e,yn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==yn)try{t[n]=Object.assign(new R_,s)}catch{Rb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(sV,"listDBIDefinitions");function yb(e){g_.validateEnv(e);let t=[],r=nn(e,yn);for(let{key:n}of r.getRange({start:!1}))n!==yn&&t.push(n);return t}a(yb,"listDBIs");function iV(e,t){let n=nn(e,yn).getEntry(t),s=new R_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{Rb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(iV,"getDBIDefinition");function Ib(e,t,r,n=!r){if(O_(e,t),t=t.toString(),t===yn)throw new Error(sr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return nn(e,t)}catch(s){if(s.message===sr.DBI_DOES_NOT_EXIST){let i=new Zh(r,n===!0),o=e.openDB(t,i),c=new R_(r===!0,n);return o[Ob]=c,nn(e,yn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(Ib,"createDBI");function nn(e,t){if(O_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==yn?r=iV(e,t):r=new R_,r===void 0)throw new Error(sr.DBI_DOES_NOT_EXIST);let n;try{let s=new Zh(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(sr.DBI_DOES_NOT_EXIST):s}return n[Ob]=r,e.dbis[t]=n,n}a(nn,"openDBI");function oV(e,t){O_(e,t),t=t.toString();let r=nn(e,t),n=r.getStats();return r[Xs.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(oV,"statDBI");async function aV(e,t){try{let r=Ur.join(e,t+Tc);return(await Nn.stat(r)).size}catch{throw new Error(sr.INVALID_ENVIRONMENT)}}a(aV,"environmentDataSize");function cV(e,t){if(O_(e,t),t=t.toString(),t===yn)throw new Error(sr.CANNOT_DROP_INTERNAL_DBIS_NAME);nn(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],nn(e,yn).removeSync(t)}a(cV,"dropDBI");function uV(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{nn(e,i)}catch(o){if(o.message===sr.DBI_DOES_NOT_EXIST)Ib(e,i,i!==t,i===t),n=!0;else throw o}}n&&Xk()}a(uV,"initializeDBIs");wb.exports={openDBI:nn,openEnvironment:bb,createEnvironment:tV,listDBIs:yb,listDBIDefinitions:sV,createDBI:Ib,dropDBI:cV,statDBI:oV,deleteEnvironment:nV,initializeDBIs:uV,TransactionCursor:Xh,environmentDataSize:aV,copyEnvironment:rV,closeEnvironment:Nb}});var Lb=T((tae,Db)=>{"use strict";var rm=We(),lV=Y(),Cb=wr().LMDB_ERRORS_ENUM;Db.exports=_V;async function _V(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 rm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Cb.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await rm.closeEnvironment(global.lmdb_map[n]),await rm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Cb.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){lV.error(t)}}a(_V,"cleanLMDBMap")});var Pi=T((nae,dV)=>{dV.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",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var $b=T((iae,Vb)=>{"use strict";var nm=require("recursive-iterator"),fV=require("alasql"),sm=require("clone"),Mb=J(),{handleHDBError:Ub,hdb_errors:EV}=Z(),{HDB_ERROR_MSGS:Pb,HTTP_STATUS_CODES:vb}=EV,{getDatabases:hV}=(Oe(),ee(Ge)),mV=["DISTINCT_ARRAY"],Bb=Symbol("validateTables"),im=Symbol("validateTable"),sae=Symbol("getAllColumns"),Hb=Symbol("validateAllColumns"),b_=Symbol("findColumn"),xb=Symbol("validateOrderBy"),gc=Symbol("validateSegment"),om=Symbol("validateColumn"),Fb=Symbol("setColumnsForTable"),qb=Symbol("checkColumnsForAsterisk"),Gb=Symbol("validateGroupBy"),kb=Symbol("hasColumns"),am=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Bb](),this[qb](),this[Hb]()}[Bb](){if(this[kb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[im](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[im](t.table)})}}[kb](){let t=!1,r=new nm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[im](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=hV();if(!r[t.databaseid])throw Ub(new Error,Pb.SCHEMA_NOT_FOUND(t.databaseid),vb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Ub(new Error,Pb.TABLE_NOT_FOUND(t.databaseid,t.tableid),vb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=sm(s);i.table=sm(t),this.attributes.push(i)})}[b_](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)}[qb](){let t=new nm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Fb](r.tableid)}[Fb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new fV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Hb](){this[gc](this.statement.columns,!1),this[gc](this.statement.joins,!1),this[gc](this.statement.where,!1),this[Gb](this.statement.group,!1),this[gc](this.statement.order,!0)}[gc](t,r){if(!t)return;let n=new nm(t),s=[];for(let{node:i,path:o}of n)!Mb.isEmpty(i)&&!Mb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[xb](i):s.push(this[om](i)));return s}[Gb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&mV.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=sm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[b_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[b_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.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`}[xb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[om](t)}[om](t){let r=this[b_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Vb.exports=am});var Kb=T((aae,Yb)=>{"use strict";var cm=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")}};Yb.exports=cm});var Qb=T((uae,Wb)=>{"use strict";var um=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Wb.exports=um});var Jb=T((_ae,zb)=>{"use strict";var lm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};zb.exports=lm});var jb=T((fae,Xb)=>{"use strict";var _m=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Xb.exports=_m});var Yo=T((Sae,tN)=>{"use strict";var pV=We(),SV=Qb(),TV=Jb(),gV=jb(),Vn=Cr(),Rc=wr().LMDB_ERRORS_ENUM,RV=Et(),Ss=M(),AV=J(),OV=require("uuid"),hae=require("lmdb"),{handleHDBError:bV,hdb_errors:NV}=Z(),{OVERFLOW_MARKER:mae,MAX_SEARCH_KEY_LENGTH:pae}=RV,Zb=j();Zb.initSync();var N_=Zb.get(Ss.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),dm=Ss.TIME_STAMP_NAMES_ENUM.CREATED_TIME,vi=Ss.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function yV(e,t,r,n,s=Vn.getNextMonotonicTime()){mm(e,t,r,n),fm(e,t,r);let i=new SV,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];eN(_,!0,s);let l=IV(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Em(o,c,n,i,s)}a(yV,"insertRecords");function IV(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Ss.FUNC_VAL],n[o]=c)}let u=Vn.getIndexedValues(c),_=e.dbis[o];if(u){N_&&_.prefetch(u.map(l=>({key:l,value:s})),y_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}N_&&e.dbis[t].prefetch([s],y_),e.dbis[t].put(s,n,n[vi])})}a(IV,"insertRecord");function wV(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(wV,"removeSkippedRecords");function eN(e,t,r){let n=r>0;(n||!Number.isInteger(e[vi]))&&(e[vi]=r||(r=Vn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[dm]))&&(e[dm]=r||Vn.getNextMonotonicTime()):delete e[dm]}a(eN,"setTimestamps");function fm(e,t,r){r.indexOf(Ss.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ss.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ss.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ss.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),pV.initializeDBIs(e,t,r)}a(fm,"initializeTransaction");async function CV(e,t,r,n,s=Vn.getNextMonotonicTime()){mm(e,t,r,n),fm(e,t,r);let i=new TV,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=hm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return Em(c,u,n,i,s,o)}a(CV,"updateRecords");async function DV(e,t,r,n,s=Vn.getNextMonotonicTime()){try{mm(e,t,r,n)}catch(u){throw bV(u,u.message,NV.HTTP_STATUS_CODES.BAD_REQUEST)}fm(e,t,r);let i=new gV,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;AV.isEmpty(_[t])?(l=OV.v4(),_[t]=l):l=_[t];let d=hm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Em(o,c,n,i,s)}a(DV,"upsertRecords");async function Em(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Vn.getNextMonotonicTime(),wV(r,i),n}a(Em,"finalizeWrite");function hm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(eN(r,!l,o),Number.isInteger(r[vi])&&_[vi]>r[vi])return!1;l&&s.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let S=r[h],p=e.dbis[h];if(p===void 0)continue;let g=_[h];if(typeof S=="function"){let b=S([[_]]);Array.isArray(b)&&(S=b[0][Ss.FUNC_VAL],r[h]=S)}if(S===g)continue;let A=Vn.getIndexedValues(g);if(A){N_&&p.prefetch(A.map(b=>({key:b,value:n})),y_);for(let b=0,v=A.length;b<v;b++)p.remove(A[b],n)}if(A=Vn.getIndexedValues(S),A){N_&&p.prefetch(A.map(b=>({key:b,value:n})),y_);for(let b=0,v=A.length;b<v;b++)p.put(A[b],n)}}let E=Object.assign({},_,r);c.put(n,E,E[vi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:hm(e,t,r,n,s,i,o))}a(hm,"updateUpsertRecord");function LV(e,t,r){if(Vn.validateEnv(e),t===void 0)throw new Error(Rc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Rc.WRITE_ATTRIBUTES_REQUIRED):new Error(Rc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(LV,"validateBasic");function mm(e,t,r,n){if(LV(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Rc.RECORDS_REQUIRED):new Error(Rc.RECORDS_MUST_BE_ARRAY)}a(mm,"validateWrite");function y_(){}a(y_,"noop");tN.exports={insertRecords:yV,updateRecords:CV,upsertRecords:DV}});var Yn=T((gae,sN)=>{"use strict";var nN=J(),rN=M(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,$n=require("joi"),js={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},MV=$n.alternatives($n.string().min(1).max(js.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+js.schema_format.message}),$n.number(),$n.array()).required(),UV=$n.alternatives($n.string().min(1).max(js.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+js.schema_format.message}),$n.number()),PV=$n.alternatives($n.string().min(1).max(js.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+js.schema_format.message}),$n.number()).required();function vV(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>js.schema_length.maximum?`'${e}' maximum of 250 characters`:Ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(vV,"checkValidTable");function BV(e,t){return nN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(BV,"validateSchemaExists");function HV(e,t){let r=t.state.ancestors[0].schema;return nN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(HV,"validateTableExists");function xV(e,t){return e.toLowerCase()===rN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${rN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(xV,"validateSchemaName");sN.exports={common_validators:js,schema_regex:Ko,hdb_schema_table:MV,validateSchemaExists:BV,validateTableExists:HV,validateSchemaName:xV,checkValidTable:vV,hdb_database:UV,hdb_table:PV}});var rt=T((Aae,iN)=>{"use strict";var ir=require("validate.js");ir.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||ir.validators.type.checks[t](e)?null:` must be a '${t}' value`};ir.validators.type.checks={Object:function(e){return ir.isObject(e)&&!ir.isArray(e)},Array:ir.isArray,Integer:ir.isInteger,Number:ir.isNumber,String:ir.isString,Date:ir.isDate,Boolean:function(e){return typeof e=="boolean"}};ir.validators.hasValidFileExt=function(e,t){return ir.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};iN.exports={validateObject:FV,validateObjectAsync:qV,validateBySchema:GV};function FV(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=ir(e,t,{format:"flat"});return r?new Error(r):null}a(FV,"validateObject");async function qV(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await ir.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(qV,"validateObjectAsync");function GV(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(GV,"validateBySchema")});var I_=T((bae,oN)=>{var{common_validators:Kn}=Yn(),Oc=rt(),Ac="is required",ht={database:{presence:!1,format:Kn.schema_format,length:Kn.schema_length},schema:{presence:!1,format:Kn.schema_format,length:Kn.schema_length},table:{presence:!0,format:Kn.schema_format,length:Kn.schema_length},attribute:{presence:!0,format:Kn.schema_format,length:Kn.schema_length},hash_attribute:{presence:!0,format:Kn.schema_format,length:Kn.schema_length}};function bc(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(bc,"makeAttributesStrings");function kV(e){return e=bc(e),ht.table.presence=!1,ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Oc.validateObject(e,ht)}a(kV,"schema_object");function VV(e){return e=bc(e),ht.table.presence={message:Ac},ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Oc.validateObject(e,ht)}a(VV,"table_object");function $V(e){return e=bc(e),ht.table.presence={message:Ac},ht.attribute.presence=!1,Oc.validateObject(e,ht)}a($V,"create_table_object");function YV(e){return e=bc(e),ht.table.presence={message:Ac},ht.attribute.presence={message:Ac},ht.hash_attribute.presence=!1,Oc.validateObject(e,ht)}a(YV,"attribute_object");function KV(e){return e=bc(e),ht.table.presence={message:Ac},ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Oc.validateObject(e,ht)}a(KV,"describe_table");function WV(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(WV,"validateTableResidence");oN.exports={schema_object:kV,create_table_object:$V,table_object:VV,attribute_object:YV,describe_table:KV,validateTableResidence:WV}});var cN=T((yae,aN)=>{"use strict";var QV=require("uuid"),pm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||QV.v4(),this.schema_table=`${this.schema}.${this.table}`}};aN.exports=pm});var w_=T((wae,uN)=>{"use strict";var zV=cN(),Sm=class extends zV{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};uN.exports=Sm});var _N=T((Dae,lN)=>{"use strict";lN.exports=XV;var JV="inserted";function XV(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===JV?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(XV,"returnObject")});var C_=T((Mae,mN)=>{"use strict";var jV=M(),Tm=We(),ZV=Yo(),{getSystemSchemaPath:e$,getSchemaPath:t$}=Je(),r$=Pi(),n$=I_(),s$=w_(),i$=_N(),{handleHDBError:dN,hdb_errors:EN}=Z(),fN=J(),{HTTP_STATUS_CODES:o$}=EN,gm=r$.hdb_attribute,hN=[];for(let e=0;e<gm.attributes.length;e++)hN.push(gm.attributes[e].attribute);var a$="inserted";mN.exports=c$;async function c$(e){let t=n$.attribute_object(e);if(t)throw dN(new Error,t.message,EN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&fN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw dN(new Error,r,o$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=fN.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new s$(e.schema,e.table,e.attribute,e.id);try{let i=await Tm.openEnvironment(t$(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}`);Tm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Tm.openEnvironment(e$(),jV.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await ZV.insertRecords(o,gm.hash_attribute,hN,[s]);return i$(a$,c,{records:[s]},u)}catch(i){throw i}}a(c$,"lmdbCreateAttribute")});var Am=T((Pae,SN)=>{var{hdb_table:u$,hdb_database:pN}=Yn(),l$=rt(),Rm=require("joi"),_$={undefined:"undefined",null:"null"},d$=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||_$[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),f$=Rm.object({database:pN,schema:pN,table:u$,records:Rm.array().items(Rm.object().custom(d$)).required()});SN.exports=function(e){return l$.validateBySchema(e,f$)}});var Nc=T((Hae,gN)=>{"use strict";var Ts=J(),TN=Y(),Bae=Am(),{getDatabases:E$}=(Oe(),ee(Ge)),{ClientError:Bi}=Z();gN.exports=h$;function h$(e){if(Ts.isEmpty(e))throw new Bi("invalid update parameters defined.");if(Ts.isEmptyOrZeroLength(e.schema))throw new Bi("invalid schema specified.");if(Ts.isEmptyOrZeroLength(e.table))throw new Bi("invalid table specified.");if(!Array.isArray(e.records))throw new Bi("records must be an array");let t=E$()[e.schema]?.[e.table];if(Ts.isEmpty(t))throw new Bi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Ts.isEmptyOrZeroLength(o[r]))throw TN.error("a valid hash attribute must be provided with update record:",o),new Bi("a valid hash attribute must be provided with update record, check log for more info");if(!Ts.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw TN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Bi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Ts.isEmpty(o[r])&&o[r]!==""&&n.has(Ts.autoCast(o[r]))&&(o.skip=!0),n.add(Ts.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(h$,"insertUpdateValidate")});var yc=T((Fae,RN)=>{"use strict";var m$=M().OPERATIONS_ENUM,Om=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=m$.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};RN.exports=Om});var Dc=T((kae,AN)=>{"use strict";var Gae=yc(),D_=M(),Nm=J(),bm=Y(),p$=require("uuid"),{handleHDBError:Ic,hdb_errors:S$}=Z(),{HDB_ERROR_MSGS:wc,HTTP_STATUS_CODES:Cc}=S$;AN.exports=T$;function T$(e,t,r){for(let s=0;s<t.length;s++)g$(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];R$(i,r,e.operation)}}a(T$,"processRows");function g$(e){if(Buffer.byteLength(String(e))>D_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Ic(new Error,wc.ATTR_NAME_LENGTH_ERR(e),Cc.BAD_REQUEST,void 0,void 0,!0);if(Nm.isEmptyOrZeroLength(e)||Nm.isEmpty(e.trim()))throw Ic(new Error,wc.ATTR_NAME_NULLISH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}a(g$,"validateAttribute");function R$(e,t,r){if(!e.hasOwnProperty(t)||Nm.isEmptyOrZeroLength(e[t])){if(r===D_.OPERATIONS_ENUM.INSERT||r===D_.OPERATIONS_ENUM.UPSERT){e[t]=p$.v4();return}throw bm.error("Update transaction aborted due to record with no hash value:",e),Ic(new Error,wc.RECORD_MISSING_HASH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>D_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw bm.error(e),Ic(new Error,wc.HASH_VAL_LENGTH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw bm.error(e),Ic(new Error,wc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}a(R$,"validateHash")});var L_=T(($ae,bN)=>{"use strict";var ON=J(),A$=M(),O$=Y(),b$=C_(),N$=w_(),y$=gs(),{SchemaEventMsg:I$}=In(),w$="already exists in";bN.exports=C$;async function C$(e,t,r){if(ON.isEmptyOrZeroLength(r))return r;let n=[];ON.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await D$(e,t.schema,t.name,i)})),s}a(C$,"lmdbCheckForNewAttributes");async function D$(e,t,r,n){let s=new N$(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await L$(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(w$))O$.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(D$,"createNewAttribute");async function L$(e){let t;return t=await b$(e),y$.signalSchemaChange(new I$(process.pid,A$.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(L$,"createAttribute")});var Wo=T((Kae,NN)=>{"use strict";var ym=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};NN.exports=ym});var IN=T((Qae,yN)=>{"use strict";var M$=Wo(),U$=M().OPERATIONS_ENUM,Im=class extends M${static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(U$.INSERT,r,n,s,i),this.records=t}};yN.exports=Im});var CN=T((Jae,wN)=>{"use strict";var P$=Wo(),v$=M().OPERATIONS_ENUM,wm=class extends P${static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(v$.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};wN.exports=wm});var LN=T((jae,DN)=>{"use strict";var B$=Wo(),H$=M().OPERATIONS_ENUM,Cm=class extends B${static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(H$.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};DN.exports=Cm});var UN=T((ece,MN)=>{"use strict";var x$=Wo(),F$=M().OPERATIONS_ENUM,Dm=class extends x${static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(F$.DELETE,n,s,t,i),this.original_records=r}};MN.exports=Dm});var Lc=T((nce,HN)=>{"use strict";var rce=require("path"),PN=We(),q$=IN(),G$=CN(),k$=LN(),V$=UN(),Qo=Et(),vN=J(),{CONFIG_PARAMS:$$}=M(),BN=j();BN.initSync();var M_=M().OPERATIONS_ENUM,{getTransactionAuditStorePath:Y$}=Je();HN.exports=K$;async function K$(e,t){if(BN.get($$.LOGGING_AUDITLOG)===!1)return;let r=Y$(e.schema,e.table),n=await PN.openEnvironment(r,e.table,!0),s=W$(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){PN.initializeDBIs(n,Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Qo.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),vN.isEmpty(s.user_name)||n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(K$,"writeTransaction");function W$(e,t){let r=vN.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===M_.INSERT)return new q$(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===M_.UPDATE)return new G$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===M_.UPSERT)return new k$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===M_.DELETE)return new V$(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(W$,"createTransactionObject")});var Lm=T((oce,xN)=>{"use strict";var Q$=Nc(),ice=yc(),Mc=M(),z$=Dc(),J$=Yo().insertRecords,X$=We(),j$=Y(),Z$=L_(),{getSchemaPath:e1}=Je(),t1=Lc();xN.exports=r1;async function r1(e){try{let{schema_table:t,attributes:r}=Q$(e);z$(e,r,t.hash_attribute),e.schema!==Mc.SYSTEM_SCHEMA_NAME&&(r.includes(Mc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Mc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Mc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Mc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Z$(e.hdb_auth_header,t,r),s=e1(e.schema,e.table),i=await X$.openEnvironment(s,e.table),o=await J$(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await t1(e,o)}catch(c){j$.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:n,txn_time:o.txn_time}}catch(t){throw t}}a(r1,"lmdbCreateRecords")});var GN=T((cce,qN)=>{"use strict";var FN=M(),n1=Lm(),s1=yc(),i1=require("fs-extra"),{getSchemaPath:o1}=Je();qN.exports=a1;async function a1(e){let t=[{name:e.schema,createddate:Date.now()}],r=new s1(FN.SYSTEM_SCHEMA_NAME,FN.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await n1(r),await i1.mkdirp(o1(e.schema))}a(a1,"lmdbCreateSchema")});var VN=T((lce,kN)=>{"use strict";var Mm=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};kN.exports=Mm});var WN=T((hce,KN)=>{"use strict";var $N=We(),Um=Cr(),Pm=wr().LMDB_ERRORS_ENUM,c1=Et(),YN=Y(),dce=J(),u1=require("lmdb"),l1=VN(),_1=M(),{OVERFLOW_MARKER:fce,MAX_SEARCH_KEY_LENGTH:Ece}=c1,d1=_1.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function f1(e,t,r,n){if(Um.validateEnv(e),t===void 0)throw new Error(Pm.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Pm.IDS_REQUIRED):new Error(Pm.IDS_MUST_BE_ITERABLE);try{let s=$N.listDBIs(e);$N.initializeDBIs(e,t,s);let i=new l1,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||n&&h[d1]>n){i.skipped.push(o);continue}let S=e.dbis[t].ifVersion(o,u1.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let p=0;p<s.length;p++){let g=s[p];if(!h.hasOwnProperty(g)||g===t)continue;let A=e.dbis[g],b=h[g];if(b!=null)try{let v=Um.getIndexedValues(b);if(v)for(let G=0,H=v.length;G<H;G++)A.remove(v[G],o)}catch{YN.warn(`cannot delete from attribute: ${g}, ${b}:${o}`)}}});c.push(S),u.push(o),i.original_records.push(h)}catch(h){YN.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=Um.getNextMonotonicTime(),i}catch(s){throw s}}a(f1,"deleteRecords");KN.exports={deleteRecords:f1}});var Uc=T((pce,zN)=>{"use strict";var zo=J(),E1=WN(),h1=We(),{getSchemaPath:m1}=Je(),p1=Lc(),S1=Y();zN.exports=T1;async function T1(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(zo.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(zo.isEmptyOrZeroLength(e.hash_values)&&!zo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];zo.isEmpty(u)||e.hash_values.push(u)}}if(zo.isEmptyOrZeroLength(e.hash_values))return QN([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(zo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=m1(e.schema,e.table),i=await h1.openEnvironment(s,e.table),o=await E1.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await p1(e,o)}catch(c){S1.error(`unable to write transaction due to ${c.message}`)}return QN(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(T1,"lmdbDeleteRecords");function QN(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(QN,"createDeleteResponse")});var Bm=T((gce,JN)=>{"use strict";var g1=M(),Tce=Cr();function vm(e,t){let r=Object.create(null);if(t.length===1&&g1.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(vm,"parseRow");function R1(e,t,r,n){let s=vm(r,e);n.push(s)}a(R1,"searchAll");function A1(e,t,r,n){let s=vm(r,e);n[t]=s}a(A1,"searchAllToMap");function O1(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(O1,"iterateDBI");function Hi(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Hi,"pushResults");function b1(e,t,r,n,s,i){t.toString().endsWith(e)&&Hi(t,r,n,s,i)}a(b1,"endsWith");function N1(e,t,r,n,s,i){t.toString().includes(e)&&Hi(t,r,n,s,i)}a(N1,"contains");function y1(e,t,r,n,s,i){t>e&&Hi(t,r,n,s,i)}a(y1,"greaterThanCompare");function I1(e,t,r,n,s,i){t>=e&&Hi(t,r,n,s,i)}a(I1,"greaterThanEqualCompare");function w1(e,t,r,n,s,i){t<e&&Hi(t,r,n,s,i)}a(w1,"lessThanCompare");function C1(e,t,r,n,s,i){t<=e&&Hi(t,r,n,s,i)}a(C1,"lessThanEqualCompare");JN.exports={parseRow:vm,searchAll:R1,searchAllToMap:A1,iterateDBI:O1,endsWith:b1,contains:N1,greaterThanCompare:y1,greaterThanEqualCompare:I1,lessThanCompare:w1,lessThanEqualCompare:C1,pushResults:Hi}});var Jo=T((Nce,ny)=>{"use strict";var Zs=We(),Ace=Y(),Pr=Cr(),U_=Et(),lt=wr().LMDB_ERRORS_ENUM,Oce=J(),D1=M(),P_=Bm(),{parseRow:L1}=P_,bce=require("lmdb"),{OVERFLOW_MARKER:XN,MAX_SEARCH_KEY_LENGTH:M1}=U_;function jN(e,t,r,n=!1,s=void 0,i=void 0){return xi(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(jN,"iterateFullIndex");function Pc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return xi(e,t,r,(l,d,f,E)=>{let A={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(A.values=!1,d.getRange(A).map(b=>({value:b}))):d.getRange(A)})}a(Pc,"iterateRangeBetween");function xi(e,t,r,n){let s=e.database||e,i=Zs.openDBI(s,r);i[U_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&Zs.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(xi,"setupTransaction");function ZN(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(XN)){if(!s)if(r)s=Zs.openDBI(e,r);else{let u=Zs.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=Zs.openDBI(e,u[_]),!s[U_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(ZN,"getOverflowCheck");function U1(e,t,r,n=!1,s=void 0,i=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return xi(e,t,t,(o,c,u)=>(v_(r),r=vc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>L1(_.value,r))))}a(U1,"searchAll");function P1(e,t,r,n=!1,s=void 0,i=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);v_(r),r=vc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of jN(e,t,t,n,s,i))o.set(c,P_.parseRow(u,r));return o}a(P1,"searchAllToMap");function v1(e,t,r=!1,n=void 0,s=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=jN(e,void 0,t,r,n,s),c=o.transaction,u=ZN(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(v1,"iterateDBI");function B1(e,t){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return Zs.statDBI(e,t).entryCount}a(B1,"countAll");function H1(e,t,r,n,s=!1,i=void 0,o=void 0){return ei(e,r,n),xi(e,t,r,(c,u,_,l)=>(n=Pr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(H1,"equals");function x1(e,t,r){return ei(e,t,r),Zs.openDBI(e,t).getValuesCount(r)}a(x1,"count");function F1(e,t,r,n,s=!1,i=void 0,o=void 0){return ei(e,r,n),xi(e,null,r,(c,u)=>{n=Pr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let f of u.getKeys({transaction:c,start:n}))if(!f.startsWith(n)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(n))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(F1,"startsWith");function q1(e,t,r,n,s=!1,i=void 0,o=void 0){return ey(e,t,r,n,s,i,o,!0)}a(q1,"endsWith");function ey(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ei(e,r,n),xi(e,null,r,(u,_,l,d)=>{let f=ZN(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(XN)?_.getValues(E,{transaction:u}).map(S=>{let p=f(E,S);if(c?p.endsWith(n):p.includes(n))return{key:p,value:S}}).filter(S=>S):(c?h.endsWith(n):h.includes(n))?_[U_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(S=>({key:E,value:S})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(ey,"contains");function G1(e,t,r,n,s=!1,i=void 0,o=void 0){ei(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Pc(e,t,r,n,u,s,i,o,!0,!1)}a(G1,"greaterThan");function k1(e,t,r,n,s=!1,i=void 0,o=void 0){ei(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Pc(e,t,r,n,u,s,i,o,!1,!1)}a(k1,"greaterThanEqual");function V1(e,t,r,n,s=!1,i=void 0,o=void 0){ei(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Pc(e,t,r,u,n,s,i,o,!1,!0)}a(V1,"lessThan");function $1(e,t,r,n,s=!1,i=void 0,o=void 0){ei(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Pc(e,t,r,u,n,s,i,o,!1,!1)}a($1,"lessThanEqual");function Y1(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Pr.validateEnv(e),r===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(lt.START_VALUE_REQUIRED);if(s===void 0)throw new Error(lt.END_VALUE_REQUIRED);if(n=Pr.convertKeyValueToWrite(n),s=Pr.convertKeyValueToWrite(s),n>s)throw new Error(lt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Pc(e,t,r,n,s,i,o,c)}a(Y1,"between");function K1(e,t,r,n){Pr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(v_(r),r=vc(s,r),n===void 0)throw new Error(lt.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=P_.parseRow(c,r)),o}a(K1,"searchByHash");function W1(e,t,r){Pr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(W1,"checkHashExists");function Q1(e,t,r,n,s=[]){return ry(e,t,r,n,s),ty(e,t,r,n,s).map(i=>i[1])}a(Q1,"batchSearchByHash");function z1(e,t,r,n,s=[]){ry(e,t,r,n,s);let i=new Map;for(let[o,c]of ty(e,t,r,n,s))i.set(o,c);return i}a(z1,"batchSearchByHashToMap");function ty(e,t,r,n,s=[]){return xi(e,t,t,(i,o,c)=>{r=vc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,P_.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(ty,"batchHashSearch");function ry(e,t,r,n,s){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(v_(r),n==null)throw new Error(lt.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(lt.IDS_MUST_BE_ITERABLE)}a(ry,"initializeBatchSearchByHash");function v_(e){if(!Array.isArray(e))throw e===void 0?new Error(lt.FETCH_ATTRIBUTES_REQUIRED):new Error(lt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(v_,"validateFetchAttributes");function ei(e,t,r){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.SEARCH_VALUE_REQUIRED);if(r?.length>M1)throw new Error(lt.SEARCH_VALUE_TOO_LARGE)}a(ei,"validateComparisonFunctions");function vc(e,t){return t.length===1&&D1.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Zs.listDBIs(e)),t}a(vc,"setGetWholeRowAttributes");ny.exports={searchAll:U1,searchAllToMap:P1,count:x1,countAll:B1,equals:H1,startsWith:F1,endsWith:q1,contains:ey,searchByHash:K1,setGetWholeRowAttributes:vc,batchSearchByHash:Q1,batchSearchByHashToMap:z1,checkHashExists:W1,iterateDBI:v1,greaterThan:G1,greaterThanEqual:k1,lessThan:V1,lessThanEqual:$1,between:Y1}});var Xo=T((Ice,cy)=>{var sy=require("lodash"),iy=rt(),Ee=require("joi"),J1=J(),{hdb_schema_table:Bc,checkValidTable:oy,hdb_table:ay,hdb_database:B_}=Yn(),{handleHDBError:X1,hdb_errors:j1}=Z(),{getDatabases:Z1}=(Oe(),ee(Ge)),{HTTP_STATUS_CODES:eY}=j1,tY=Ee.object({database:B_,schema:B_,table:ay,search_attribute:Bc,search_value:Ee.any().required(),get_attributes:Ee.array().min(1).items(Ee.alternatives(Bc,Ee.object())).optional(),desc:Ee.bool(),limit:Ee.number().integer().min(1),offset:Ee.number().integer().min(0)}),rY=Ee.object({database:B_,schema:B_,table:ay,operator:Ee.string().valid("and","or").default("and").lowercase(),offset:Ee.number().integer().min(0),limit:Ee.number().integer().min(1),get_attributes:Ee.array().min(1).items(Ee.alternatives(Bc,Ee.object())).optional(),sort:Ee.object({attribute:Ee.alternatives(Bc,Ee.array().min(1)),descending:Ee.bool().optional()}).optional(),conditions:Ee.array().min(1).items(Ee.alternatives(Ee.object({operator:Ee.string().valid("and","or").default("and").lowercase(),conditions:Ee.array()}),Ee.object({search_attribute:Ee.alternatives(Bc,Ee.array().min(1)),search_type:Ee.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:Ee.when("search_type",{switch:[{is:"equals",then:Ee.any()},{is:"between",then:Ee.array().items(Ee.alternatives([Ee.string(),Ee.number()])).length(2)}],otherwise:Ee.alternatives(Ee.string(),Ee.number())}).required()}))).required()});cy.exports=function(e,t){let r=null;switch(t){case"value":r=iy.validateBySchema(e,tY);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(oy("database",e.schema)),i(oy("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"),s&&(r=new Error(s.trim()));break;case"conditions":r=iy.validateBySchema(e,rY);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=J1.checkGlobalSchemaTable(e.schema,e.table);if(s)return X1(new Error,s,eY.NOT_FOUND);let o=Z1()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=sy.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!sy.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Hm=T((Cce,uy)=>{"use strict";var nY=We(),sY=Xo(),{getSchemaPath:iY}=Je();uy.exports=oY;function oY(e){let t=sY(e,"hashes");if(t)throw t;let r=iY(e.schema,e.table);return nY.openEnvironment(r,e.table)}a(oY,"initialize")});var xm=T((Lce,ly)=>{"use strict";var aY=Jo(),cY=Hm();ly.exports=uY;async function uY(e){let t=await cY(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return aY.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(uY,"lmdbGetDataByHash")});var jo=T((Uce,_y)=>{"use strict";var Fm=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};_y.exports=Fm});var fy=T((Bce,dy)=>{"use strict";var vce=jo(),lY=Jo(),_Y=Hm();dy.exports=dY;async function dY(e){let t=await _Y(e),r=global.hdb_schema[e.schema][e.table];return lY.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(dY,"lmdbSearchByHash")});var Wn=T((xce,Ey)=>{"use strict";var qm=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};Ey.exports=qm});var H_=T((qce,gy)=>{"use strict";var Wt=Jo(),fY=We(),EY=J(),he=Et(),Fi=M(),hY=Pi(),hy=wr().LMDB_ERRORS_ENUM,{getSchemaPath:mY}=Je(),Rs=Fi.SEARCH_WILDCARDS;async function pY(e,t,r){let n;e.schema===Fi.SYSTEM_SCHEMA_NAME?n=hY[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Ty(e,n.hash_attribute,r,t);return py(e,s,n.hash_attribute,r)}a(pY,"prepSearch");async function py(e,t,r,n){let s=mY(e.schema,e.table),i=await fY.openEnvironment(s,e.table),o=Sy(i,e,t,r),c=o.transaction||i;if([he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,he.SEARCH_TYPES.SEARCH_ALL,he.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(SY(e,r)===!1){let l=e.search_attribute;if(l===r)return n?my(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?my(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Wt.batchSearchByHashToMap(c,r,e.get_attributes,_):Wt.batchSearchByHash(c,r,e.get_attributes,_)}a(py,"executeSearch");function Sy(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<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 he.SEARCH_TYPES.EQUALS:s=Wt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.CONTAINS:s=Wt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.ENDS_WITH:case he.SEARCH_TYPES._ENDS_WITH:s=Wt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.STARTS_WITH:case he.SEARCH_TYPES._STARTS_WITH:s=Wt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Wt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Wt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.SEARCH_ALL:return Wt.searchAll(e,n,t.get_attributes,o,c,u);case he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Wt.searchAllToMap(e,n,t.get_attributes,o,c,u);case he.SEARCH_TYPES.BETWEEN:s=Wt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case he.SEARCH_TYPES.GREATER_THAN:case he.SEARCH_TYPES._GREATER_THAN:s=Wt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.GREATER_THAN_EQUAL:case he.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Wt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.LESS_THAN:case he.SEARCH_TYPES._LESS_THAN:s=Wt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.LESS_THAN_EQUAL:case he.SEARCH_TYPES._LESS_THAN_EQUAL:s=Wt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Sy,"searchByType");function my(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(my,"createMapFromIterable");function SY(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 n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(SY,"checkToFetchMore");function Ty(e,t,r,n){if(EY.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Rs.indexOf(s)>-1)return r===!0?he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:he.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Rs[0])<0&&s.indexOf(Rs[1])<0)return c===!0?r===!0?he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:he.SEARCH_TYPES.EQUALS;if(Rs.indexOf(i)>=0&&Rs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),he.SEARCH_TYPES.CONTAINS;if(Rs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),he.SEARCH_TYPES.ENDS_WITH;if(Rs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),he.SEARCH_TYPES.STARTS_WITH;if(s.includes(Rs[0])||s.includes(Rs[1]))return he.SEARCH_TYPES.EQUALS;throw new Error(hy.UNKNOWN_SEARCH_TYPE)}else switch(n){case Fi.VALUE_SEARCH_COMPARATORS.BETWEEN:return he.SEARCH_TYPES.BETWEEN;case Fi.VALUE_SEARCH_COMPARATORS.GREATER:return he.SEARCH_TYPES.GREATER_THAN;case Fi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return he.SEARCH_TYPES.GREATER_THAN_EQUAL;case Fi.VALUE_SEARCH_COMPARATORS.LESS:return he.SEARCH_TYPES.LESS_THAN;case Fi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return he.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(hy.UNKNOWN_SEARCH_TYPE)}}a(Ty,"createSearchTypeFromSearchObject");gy.exports={executeSearch:py,createSearchTypeFromSearchObject:Ty,prepSearch:pY,searchByType:Sy}});var Ay=T((Vce,Ry)=>{"use strict";var kce=Wn(),TY=Xo(),gY=J(),RY=M(),AY=H_();Ry.exports=OY;function OY(e,t){if(!gY.isEmpty(t)&&RY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=TY(e,"value");if(n)throw n;return AY.prepSearch(e,t,!0)}a(OY,"lmdbGetDataByValue")});var Hc=T((Kce,Oy)=>{"use strict";var Yce=Wn(),bY=Xo(),NY=J(),yY=M(),IY=H_();Oy.exports=wY;async function wY(e,t){if(!NY.isEmpty(t)&&yY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=bY(e,"value");if(n)throw n;return IY.prepSearch(e,t,!1)}a(wY,"lmdbSearchByValue")});var Ny=T((zce,by)=>{"use strict";var Qce=Et(),Gm=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},km=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Vm=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};by.exports={SearchByConditionsObject:Gm,SearchCondition:km,SortAttribute:Vm}});var Dy=T((Zce,Cy)=>{"use strict";var Xce=Ny().SearchByConditionsObject,CY=Wn(),DY=Xo(),$m=Jo(),x_=Et(),{Resource:jce}=(On(),ee(Vh)),wy=H_(),LY=Bm(),MY=require("lodash"),{getSchemaPath:UY}=Je(),yy=We(),{handleHDBError:PY,hdb_errors:vY}=Z(),{HTTP_STATUS_CODES:BY}=vY,HY=1e8;Cy.exports=xY;async function xY(e){let t=DY(e,"conditions");if(t)throw PY(t,t.message,BY.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=UY(e.schema,e.table),n=await yy.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)yy.openDBI(n,_.search_attribute);let i=MY.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===x_.SEARCH_TYPES.EQUALS?_.estimated_count=$m.count(n,_.search_attribute,_.search_value):l===x_.SEARCH_TYPES.CONTAINS||l===x_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=HY}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Iy(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(wy.filterByType),d=l.length,f=$m.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))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(E=>LY.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await Iy(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=$m.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(xY,"lmdbSearchByConditions");async function Iy(e,t,r,n){let s=new CY(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===x_.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,wy.searchByType(e,s,i,n).map(o=>o.value)}a(Iy,"executeConditionSearch")});var xc=T((tue,Ly)=>{"use strict";var FY=M().OPERATIONS_ENUM,Ym=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=FY.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Ly.exports=Ym});var Km=T((nue,Fy)=>{"use strict";var vy=Wn(),By=xc(),Hy=Hc(),xy=Uc(),or=M(),My=J(),Uy=We(),{getTransactionAuditStorePath:qY,getSchemaPath:GY}=Je(),Py=Y();Fy.exports=kY;async function kY(e){try{if(My.isEmpty(global.hdb_schema[e.schema])||My.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await VY(e),await $Y(e);let t=GY(e.schema,e.table);try{await Uy.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Py.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=qY(e.schema,e.table);await Uy.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Py.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(kY,"lmdbDropTable");async function VY(e){let t=new vy(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Hy(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new By(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await xy(s)}a(VY,"deleteAttributesFromSystem");async function $Y(e){let t=new vy(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Hy(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&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new By(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await xy(s)}catch(i){throw i}}a($Y,"dropTableFromSystem")});var Gy=T((iue,qy)=>{"use strict";var YY=require("fs-extra"),KY=Wn(),WY=jo(),QY=xc(),zY=Km(),JY=Uc(),XY=xm(),jY=Hc(),As=M(),{getSchemaPath:ZY}=Je(),{handleHDBError:eK,hdb_errors:tK}=Z(),{HDB_ERROR_MSGS:rK,HTTP_STATUS_CODES:nK}=tK;qy.exports=sK;async function sK(e){let t;try{t=await iK(e.schema);let r=new KY(As.SYSTEM_SCHEMA_NAME,As.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,As.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[As.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await jY(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await zY(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new QY(As.SYSTEM_SCHEMA_NAME,As.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await JY(s);let i=ZY(t);await YY.remove(i)}catch(r){throw r}}a(sK,"lmdbDropSchema");async function iK(e){let t=new WY(As.SYSTEM_SCHEMA_NAME,As.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[As.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await XY(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw eK(new Error,rK.SCHEMA_NOT_FOUND(e),nK.NOT_FOUND,void 0,void 0,!0);return n}a(iK,"validateDropSchema")});var Qm=T((aue,ky)=>{"use strict";var Wm=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};ky.exports=Wm});var $y=T((lue,Vy)=>{"use strict";var oK=require("fs-extra"),F_=We(),{getTransactionAuditStorePath:aK}=Je(),zm=Et(),uue=Qm();Vy.exports=cK;async function cK(e){let t;try{let r=aK(e.schema,e.table);await oK.mkdirp(r),t=await F_.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{F_.createDBI(t,zm.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),F_.createDBI(t,zm.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),F_.createDBI(t,zm.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(cK,"createTransactionsAuditEnvironment")});var Qy=T((due,Wy)=>{"use strict";var Jm=M(),Yy=We(),uK=Yo(),{getSystemSchemaPath:lK,getSchemaPath:_K}=Je(),dK=Pi(),fK=C_(),Xm=w_(),EK=Y(),hK=$y(),Zm=dK.hdb_table,Ky=[];for(let e=0;e<Zm.attributes.length;e++)Ky.push(Zm.attributes[e].attribute);Wy.exports=mK;async function mK(e,t){let r=_K(t.schema,t.table),n=new Xm(t.schema,t.table,Jm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Xm(t.schema,t.table,Jm.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Xm(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Yy.createEnvironment(r,t.table),e!==void 0){let o=await Yy.openEnvironment(lK(),Jm.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await uK.insertRecords(o,Zm.hash_attribute,Ky,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await jm(n),await jm(s),await jm(i)}await hK(t)}catch(o){throw o}}a(mK,"lmdbCreateTable");async function jm(e){try{await fK(e)}catch(t){EK.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(jm,"createAttribute")});var Jy=T((Eue,zy)=>{"use strict";var pK=Nc(),SK=Dc(),TK=L_(),Fc=M(),gK=Yo().updateRecords,RK=We(),{getSchemaPath:AK}=Je(),OK=Lc(),bK=Y();zy.exports=NK;async function NK(e){try{let{schema_table:t,attributes:r}=pK(e);SK(e,r,t.hash_attribute),e.schema!==Fc.SYSTEM_SCHEMA_NAME&&(r.includes(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await TK(e.hdb_auth_header,t,r),s=AK(e.schema,e.table),i=await RK.openEnvironment(s,e.table),o=await gK(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await OK(e,o)}catch(c){bK.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:n,txn_time:o.txn_time}}catch(t){throw t}}a(NK,"lmdbUpdateRecords")});var jy=T((mue,Xy)=>{"use strict";var yK=M().OPERATIONS_ENUM,ep=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=yK.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Xy.exports=ep});var eI=T((Tue,Zy)=>{"use strict";var Sue=jy(),IK=Nc(),wK=Dc(),CK=L_(),qc=M(),DK=Yo().upsertRecords,LK=We(),{getSchemaPath:MK}=Je(),UK=Lc(),PK=Y(),{handleHDBError:vK,hdb_errors:BK}=Z();Zy.exports=HK;async function HK(e){let t;try{t=IK(e)}catch(u){throw vK(u,u.message,BK.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;wK(e,n,r.hash_attribute),e.schema!==qc.SYSTEM_SCHEMA_NAME&&(n.includes(qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await CK(e.hdb_auth_header,r,n),i=MK(e.schema,e.table),o=await LK.openEnvironment(i,e.table),c=await DK(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await UK(e,c)}catch(u){PK.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(HK,"lmdbUpsertRecords")});var rI=T((Rue,tI)=>{"use strict";var tp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};tI.exports=tp});var sI=T((Oue,nI)=>{"use strict";var rp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};nI.exports=rp});var aI=T((yue,oI)=>{"use strict";var np=We(),{getTransactionAuditStorePath:xK}=Je(),Nue=rI(),Gc=Et(),FK=J(),iI=sI(),qK=require("util").promisify,GK=qK(setTimeout),kK=1e4,VK=100;oI.exports=$K;async function $K(e){let t=xK(e.schema,e.table),r=await np.openEnvironment(t,e.table,!0),n=np.listDBIs(r);np.initializeDBIs(r,Gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new iI;do s=await YK(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await GK(VK);while(s.transactions_deleted>0);return i}a($K,"deleteAuditLogsBefore");async function YK(e,t){let r=new iI;try{let n=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[Gc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];FK.isEmpty(c)||(s=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>kK)break}return await s,r}catch(n){throw n}}a(YK,"deleteTransactions")});var uI=T((wue,cI)=>{"use strict";var sp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};cI.exports=sp});var _I=T((Lue,lI)=>{"use strict";var KK=Wn(),WK=xc(),Due=uI(),Qn=M(),QK=J(),ip=We(),zK=Pi(),JK=Hc(),XK=Uc(),{getSchemaPath:jK}=Je();lI.exports=ZK;async function ZK(e,t=!0){let r;e.schema===Qn.SYSTEM_SCHEMA_NAME?r=zK[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await tW(e),s=jK(e.schema,e.table),i=await ip.openEnvironment(s,e.table);return t===!0&&await eW(e,i,r.hash_attribute),ip.dropDBI(i,e.attribute),n}a(ZK,"lmdbDropAttribute");async function eW(e,t,r){let n=ip.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(eW,"removeAttributeFromAllObjects");async function tW(e){let t=new KK(Qn.SYSTEM_SCHEMA_NAME,Qn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await JK(t)).filter(o=>o[Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(QK.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new WK(Qn.SYSTEM_SCHEMA_NAME,Qn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return XK(i)}a(tW,"dropAttributeFromSystem")});var pI=T((Pue,mI)=>{"use strict";var op=We(),Zo=Et(),Uue=Cr(),ap=M(),dI=J(),{getTransactionAuditStorePath:rW}=Je(),nW=Jo(),q_=Wo(),sW=Y();mI.exports=iW;async function iW(e){let t=rW(e.schema,e.table),r=await op.openEnvironment(t,e.table,!0),n=op.listDBIs(r);op.initializeDBIs(r,Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case ap.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return fI(r,e.search_values);case ap.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,aW(r,e.search_values,s);case ap.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return oW(r,e.search_values);default:return fI(r)}}a(iW,"readAuditLog");function fI(e,t=[0,Date.now()]){dI.isEmpty(t[0])&&(t[0]=0),dI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new q_,s))}a(fI,"searchTransactionsByTimestamp");function oW(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,hI(e,i))}return Object.fromEntries(r)}a(oW,"searchTransactionsByUsername");function aW(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=nW.equals(e,Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Zo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=hI(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);EI(u,"records",r,l,o),EI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(aW,"searchTransactionsByHashValues");function EI(e,t,r,n,s){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(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new q_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new q_(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(EI,"loopRecords");function hI(e,t){let r=[];try{let n=e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new q_,i);r.push(o)}}catch(i){sW.warn(i)}return r}catch(n){throw n}}a(hI,"batchSearchTransactions")});var TI=T((xue,SI)=>{"use strict";var{getSchemaPath:Bue}=Je(),Hue=We(),{database:cW}=(Oe(),ee(Ge));SI.exports={writeTransaction:uW};async function uW(e,t,r){return cW({database:e,table:t}).transaction(r)}a(uW,"writeTransaction")});var OI=T((que,AI)=>{"use strict";var{getSchemaPath:gI}=Je(),RI=We();AI.exports={flush:lW,resetReadTxn:_W};async function lW(e,t){return(await RI.openEnvironment(gI(e,t),t.toString())).flushed}a(lW,"flush");async function _W(e,t){try{(await RI.openEnvironment(gI(e,t),t.toString())).resetReadTxn()}catch{}}a(_W,"resetReadTxn")});var II=T((kue,yI)=>{"use strict";var{Readable:dW}=require("stream"),{getDatabases:fW}=(Oe(),ee(Ge)),{readSync:EW,openSync:hW,createReadStream:bI}=require("fs"),{open:mW}=require("lmdb"),NI=p_(),pW=T_(),{AUDIT_STORE_OPTIONS:SW}=(Ci(),ee(YO)),{INTERNAL_DBIS_NAME:TW,AUDIT_STORE_NAME:gW}=Et();yI.exports=AW;var cp=32768,RW=100;async function AW(e){let t=e.database||e.schema||"data",r=fW()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=mW({noSync:!0,maxDbs:pW.MAX_DBS}),f,E=d.openDB(TW,new NI(!1)),h=l.useReadTransaction(),S=0,p=a(async function(A,b){b.encoding="binary",b.encoder=void 0;let v=d.openDB(A,b),G=l.openDB(A,b);for(let{key:H,version:P,value:z}of G.getRange({transaction:h,versions:G.useVersions}))f=v.put(H,z,P),S++%RW===0&&(await new Promise(W=>setTimeout(W,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:b}of l.getRange({transaction:h,start:!1}))if(s.some(v=>A.startsWith?.(v+"/"))){E.put(A,b);let[,v]=A.split("/"),G=!v,H=new NI(!G,G);await p(A,H)}e.include_audit&&await p(gW,Object.assign({},SW)),await f;let g=bI(d.path);return g.headers=u(),g.on("close",()=>{h.done(),d.close()}),g}let o=r[Object.keys(r)[0]].primaryStore,c=hW(o.path);return o.transaction(()=>{let _=Buffer.alloc(cp);EW(c,_,0,cp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=bI(null,{fd:c,start:cp}),f=new dW.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(AW,"getBackup")});var DI=T(($ue,CI)=>{"use strict";var OW=Y(),{handleHDBError:bW}=Z(),NW=Kb(),yW=C_(),IW=Lm(),wW=GN(),CW=Uc(),DW=xm(),LW=fy(),MW=Ay(),UW=Hc(),PW=Dy(),vW=Gy(),BW=Qy(),HW=Jy(),xW=eI(),FW=aI(),qW=Km(),GW=_I(),kW=pI(),VW=TI(),wI=OI(),$W=II(),up=class extends NW{static{a(this,"LMDBBridge")}async searchByConditions(t){return PW(t)}async getDataByHash(t){return await DW(t)}async searchByHash(t){return await LW(t)}async getDataByValue(t,r){return await MW(t,r)}async searchByValue(t){return await UW(t)}async createSchema(t){return await wW(t)}async dropSchema(t){return await vW(t)}async createTable(t,r){return await BW(t,r)}async dropTable(t){return await qW(t)}async createAttribute(t){return await yW(t)}async createRecords(t){return await IW(t)}async updateRecords(t){return await HW(t)}async upsertRecords(t){try{return await xW(t)}catch(r){throw bW(r,null,null,OW.ERR,r)}}async deleteRecords(t){return await CW(t)}async dropAttribute(t){return await GW(t)}async deleteAuditLogsBefore(t){return await FW(t)}async readAuditLog(t){return await kW(t)}writeTransaction(t,r,n){return VW.writeTransaction(t,r,n)}flush(t,r){return wI.flush(t,r)}resetReadTxn(t,r){return wI.resetReadTxn(t,r)}getBackup(t){return $W(t)}};CI.exports=up});var FI={};qe(FI,{ResourceBridge:()=>dp});function fp({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 MI(e,t){let r=zn(e),n=fp(e,r);if(!r)throw new wn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Xe(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&a_(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function zn(e){let t=e.database||e.schema||KW,r=Cn()[t];if(!r)throw(0,wn.handleHDBError)(new Error,YW.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function UI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*PI(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var vI,G_,wn,BI,HI,Dn,lp,_p,xI,YW,KW,WW,QW,LI,dp,qI=Re(()=>{"use strict";vI=B(DI()),G_=B(Xo()),wn=B(Z());Oe();BI=B(Nc()),HI=B(Dc()),Dn=B(M()),lp=B(gs()),_p=B(In()),xI=B(J());Ui();c_();({HDB_ERROR_MSGS:YW}=wn.hdb_errors),KW="data",WW=1e4,QW=10,dp=class extends vI.default{static{a(this,"ResourceBridge")}constructor(t){super(t),LI=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,G_.default)(t,"conditions");if(r)throw(0,wn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=zn(t);if(!n)throw new wn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:fp(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new wn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}_t({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await zn(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=zn(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){zn(t).dropTable()}createSchema(t){return kc({database:t.schema,table:null}),lp.signalSchemaChange(new _p.SchemaEventMsg(process.pid,Dn.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Ep(t.schema),lp.signalSchemaChange(new _p.SchemaEventMsg(process.pid,Dn.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,LI.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,BI.default)(t);(0,HI.default)(t,n,r.primaryKey);let s,i=Cn()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Xe(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(f=>f.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=a_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=Cn()[t.schema][t.table],n={user:t.hdb_user};return Xe(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return UI(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=Cn()[t.schema][t.table];if(!r.createdTimeProperty)throw new wn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Dn.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,xI.async_set_timeout)(QW),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%WW===0&&await _();return u.length>0&&await _(),s?UI(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,G_.default)(t,"hashes");if(r)throw r;return MI(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of MI(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Dn.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,G_.default)(t,"value");if(n)throw n;let s=zn(t);if(!s)throw new wn.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===Dn.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:fp(t,s)})}async getDataByValue(t,r){let n=new Map,s=zn(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){zn({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return zn(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=zn(t),n={};switch(t.search_type){case Dn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Dn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of PI(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return PI(r,t.search_values?.[0],t.search_values?.[1])}}};a(fp,"getSelect");a(MI,"getRecords");a(zn,"getTable");a(UI,"createDeleteResponse");a(PI,"groupRecordsInHistory")});var Ln=T((Jue,GI)=>{"use strict";var{ResourceBridge:zW}=(qI(),ee(FI)),JW=j();JW.initSync();var k_;function XW(){return k_||(k_=new zW,k_)}a(XW,"getBridge");GI.exports=XW()});var YI=T((jue,$I)=>{"use strict";var kI=require("lodash"),Vc=require("mathjs"),jW=require("jsonata"),VI=J();$I.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?kI.uniqWith(e,kI.isEqual):e,searchJSON:ZW,mad:$c.bind(null,Vc.mad),mean:$c.bind(null,Vc.mean),mode:$c.bind(null,Vc.mode),prod:$c.bind(null,Vc.prod),median:$c.bind(null,Vc.median)};function $c(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a($c,"aggregateFunction");function ZW(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(VI.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),VI.isEmpty(this.__ala__.res[r])){let n=jW(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(ZW,"searchJSON")});var WI=T((ele,KI)=>{"use strict";var mt=require("moment"),hp="YYYY-MM-DDTHH:mm:ss.SSSZZ";mt.suppressDeprecationWarnings=!0;KI.exports={current_date:()=>mt().utc().format("YYYY-MM-DD"),current_time:()=>mt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return mt(e).utc().format("YYYY");case"month":return mt(e).utc().format("MM");case"day":return mt(e).utc().format("DD");case"hour":return mt(e).utc().format("HH");case"minute":return mt(e).utc().format("mm");case"second":return mt(e).utc().format("ss");case"millisecond":return mt(e).utc().format("SSS");default:break}},date:e=>mt(e).utc().format(hp),date_format:(e,t)=>mt(e).utc().format(t),date_add:(e,t,r)=>mt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>mt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=mt(e).utc(),s=mt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>mt().utc().valueOf(),get_server_time:()=>mt().format(hp),offset_utc:(e,t)=>mt(e).utc().utcOffset(t).format(hp)}});var XI=T((tle,JI)=>{"use strict";var eQ=require("@turf/area"),tQ=require("@turf/length"),rQ=require("@turf/circle"),nQ=require("@turf/difference"),sQ=require("@turf/distance"),iQ=require("@turf/boolean-contains"),oQ=require("@turf/boolean-equal"),aQ=require("@turf/boolean-disjoint"),cQ=require("@turf/helpers"),QI=M(),Se=J(),Os=Y();JI.exports={geoArea:uQ,geoLength:lQ,geoCircle:_Q,geoDifference:dQ,geoDistance:zI,geoNear:fQ,geoContains:EQ,geoEqual:hQ,geoCrosses:mQ,geoConvert:pQ};function uQ(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return eQ.default(e)}catch(t){return Os.trace(t,e),NaN}}a(uQ,"geoArea");function lQ(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return tQ.default(e,{units:t||"kilometers"})}catch(r){return Os.trace(r,e),NaN}}a(lQ,"geoLength");function _Q(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return rQ.default(e,t,{units:r||"kilometers"})}catch(n){return Os.trace(n,e,t),NaN}}a(_Q,"geoCircle");function dQ(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return nQ(e,t)}catch(r){return Os.trace(r,e,t),NaN}}a(dQ,"geoDifference");function zI(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return sQ.default(e,t,{units:r||"kilometers"})}catch(n){return Os.trace(n,e,t),NaN}}a(zI,"geoDistance");function fQ(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return zI(e,t,n)<=r}catch(s){return Os.trace(s,e,t),!1}}a(fQ,"geoNear");function EQ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return iQ.default(e,t)}catch(r){return Os.trace(r,e,t),!1}}a(EQ,"geoContains");function hQ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return oQ.default(e,t)}catch(r){return Os.trace(r,e,t),!1}}a(hQ,"geoEqual");function mQ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return!aQ.default(e,t)}catch(r){return Os.trace(r,e,t),!1}}a(mQ,"geoCrosses");function pQ(e,t,r){if(Se.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Se.isEmpty(t))throw new Error("geo_type is required");if(Se.isEmpty(QI.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(QI.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),cQ[t](e,r)}a(pQ,"geoConvert")});var V_=T((nle,jI)=>{var qi=YI(),vr=WI(),Jn=XI();jI.exports=e=>{e.aggr.mad=e.aggr.MAD=qi.mad,e.aggr.mean=e.aggr.MEAN=qi.mean,e.aggr.mode=e.aggr.MODE=qi.mode,e.aggr.prod=e.aggr.PROD=qi.prod,e.aggr.median=e.aggr.MEDIAN=qi.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=qi.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=qi.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=vr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=vr.current_time,e.fn.extract=e.fn.EXTRACT=vr.extract,e.fn.date=e.fn.DATE=vr.date,e.fn.date_format=e.fn.DATE_FORMAT=vr.date_format,e.fn.date_add=e.fn.DATE_ADD=vr.date_add,e.fn.date_sub=e.fn.DATE_SUB=vr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=vr.date_diff,e.fn.now=e.fn.NOW=vr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=vr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=vr.get_server_time,e.fn.getdate=e.fn.GETDATE=vr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=vr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=Jn.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=Jn.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=Jn.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=Jn.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=Jn.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=Jn.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=Jn.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=Jn.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=Jn.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=Jn.geoNear}});var rw=T((sle,tw)=>{"use strict";var Yc=require("lodash"),ar=require("alasql");ar.options.cache=!1;var SQ=V_(),ZI=require("clone"),$_=require("recursive-iterator"),ue=Y(),we=J(),ea=Ln(),TQ=M(),{hdb_errors:gQ}=Z(),{getDatabases:ew}=(Oe(),ee(Ge)),RQ="IS NULL",Mn="There was a problem performing this search. Please check the logs and try again.";SQ(ar);var mp=class{static{a(this,"SQLSearch")}constructor(t,r){if(we.isEmpty(t))throw ue.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(),we.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!we.isEmptyOrZeroLength(n))return ue.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw ue.error("Error thrown from checkEmptySQL in SQLSearch class method search."),ue.error(n),new Error(Mn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw ue.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),ue.error(n),new Error(Mn)}if(Object.keys(this.data).length===0)return ue.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw ue.error("Error thrown from processJoins in SQLSearch class method search."),ue.error(n),new Error(Mn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw ue.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),ue.error(n),new Error(Mn)}try{return t=await this._finalSQL(),t}catch(n){throw ue.error("Error thrown from finalSQL in SQLSearch class method search."),ue.error(n),new Error(Mn)}}_getColumns(){let t=new $_(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(ZI(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Yc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=ew()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(we.isEmpty(this.statement.where)){ue.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new $_(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!we.isEmpty(r)&&r.right)if(we.isNotEmptyAndHasValue(r.right.value)){let n=we.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new ar.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=we.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new ar.yy.LogicValue({value:i}):n instanceof ar.yy.StringValue&&we.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new ar.yy.NumValue({value:i}))});if(t){ue.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new $_(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!we.isEmpty(TQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(we.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(we.isEmptyOrZeroLength(r.left.columnid)||we.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(we.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"=":!we.isEmpty(r.right.value)||!we.isEmpty(r.left.value)?n.add(we.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 _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(we.isEmptyOrZeroLength(this.all_table_attributes)&&we.isEmptyOrZeroLength(this.statement.from)&&we.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Yc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(we.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);we.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(we.isEmptyOrZeroLength(this.all_table_attributes)&&!we.isEmptyOrZeroLength(this.columns.columns))return t;if(we.isEmptyOrZeroLength(this.all_table_attributes)&&we.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await ar.promise(r)}catch(r){throw ue.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),ue.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(ZI(n))})}_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,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(we.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(RQ)>-1&&this.tables.forEach(s=>{let i={columnid:ew()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Yc.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!we.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!we.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ea.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw ue.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),ue.error(l),new Error(Mn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await ea.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]):(this.data[i].__merged_data[E]=[...n[i]],this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),ue.error(l),new Error(Mn)}else if(!we.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!we.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await ea.getDataByValue(c,E.operation);if(u)for(let[S]of h)this.data[i].__merged_data[S]||(this.data[i].__merged_data[S]=[...n[i]],this._setMergedHashAttribute(i,S));else for(let[S,p]of h)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,s.attribute,p[s.attribute]):(this.data[i].__merged_data[S]=[...n[i]],this._updateMergedAttribute(i,S,s.attribute,p[s.attribute]),this._setMergedHashAttribute(i,S))}}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),ue.error(l),new Error(Mn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ea.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),ue.error(l),new Error(Mn)}}}_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 ar.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(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.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 n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new ar.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new ar.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 s=t.is_func?new ar.yy.FuncValue:new ar.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,S=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${S}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${S}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,s);f=await ar.promise(h,t),t=null}catch(E){throw ue.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),ue.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let S=f[E];o.forEach(p=>{S[p.key]!==null&&S[p.key]!==void 0&&p.keys.add(S[p.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),S=Yc.difference(h,[...E.keys].map(p=>p.toString()));for(let p=0,g=S.length;p<g;p++){let A=S[p];delete this.data[`${E.schema}_${E.table}`].__merged_data[A]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new $_(this.columns);for(let{node:i}of s)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)&&n.push(o)}}n=Yc.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw ue.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),ue.error(i),new Error(Mn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ea.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let S=s.columns[h],p=E[S]===void 0?null:E[S];this.data[n].__merged_data[f].push(p)}}}}catch(r){throw ue.error("Error thrown from getDataByHash function in SQLSearch class method getData."),ue.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(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.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 s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();ue.trace(`Final SQL: ${s}`),n=await ar.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),ue.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw ue.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),ue.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return ue.error(gQ.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),ue.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${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=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await ea.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw ue.error("There was an error when processing this SQL operation. Check your logs"),ue.error(o),new Error(Mn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};tw.exports=mp});var sn=T((ole,nw)=>{"use strict";var AQ=$b();nw.exports={searchByConditions:bQ,searchByHash:NQ,searchByValue:yQ,search:IQ};var pp=Ln(),{transformReq:Sp}=J(),OQ=rw();async function bQ(e){return Sp(e),pp.searchByConditions(e)}a(bQ,"searchByConditions");async function NQ(e){Sp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of pp.searchByHash(e))r&&t.push(r);return t}a(NQ,"searchByHash");async function yQ(e){Sp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of pp.searchByValue(e))t.push(r);return t}a(yQ,"searchByValue");function IQ(e,t){try{let r=new AQ(e);r.validate(),new OQ(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(IQ,"search")});var bs=T((cle,aw)=>{"use strict";var Kc=require("crypto"),wQ=j(),{CONFIG_PARAMS:CQ}=M(),iw="aes-256-cbc",DQ=32,LQ=16,Tp=64,ow=32,MQ=Tp+ow,sw=new Map;aw.exports={encrypt:UQ,decrypt:PQ,createNatsTableStreamName:vQ};function UQ(e){let t=Kc.randomBytes(DQ),r=Kc.randomBytes(LQ),n=Kc.createCipheriv(iw,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(UQ,"encrypt");function PQ(e){let t=e.substr(0,Tp),r=e.substr(Tp,ow),n=e.substr(MQ,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Kc.createDecipheriv(iw,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(PQ,"decrypt");function vQ(e,t){let r=wQ.get(CQ.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=sw.get(r);return n||(n=Kc.createHash("md5").update(r).digest("hex"),sw.set(r,n)),n}a(vQ,"createNatsTableStreamName")});var Gi=T((_le,uw)=>{"use strict";var lle=sn(),Y_=Y(),cw=I_(),BQ=bs(),K_=J(),{handleHDBError:W_,hdb_errors:HQ}=Z(),{HDB_ERROR_MSGS:Q_,HTTP_STATUS_CODES:gp}=HQ,xQ=j();xQ.initSync();var{getDatabases:Rp}=(Oe(),ee(Ge));uw.exports={describeAll:FQ,describeTable:z_,describeSchema:qQ};async function FQ(e){try{let t=K_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Rp(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let f in d)try{let E;if(t||n)E=await z_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await z_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){Y_.error(E)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return Y_.error("Got an error in describeAll"),Y_.error(t),W_(new Error,Q_.DESCRIBE_ALL_ERR)}}a(FQ,"describeAll");async function z_(e,t){K_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=cw.describe_table(e);if(i)throw i;let c=Rp()[r];if(!c)throw W_(new Error,Q_.SCHEMA_NOT_FOUND(e.schema),gp.NOT_FOUND);let u=c[n];if(!u)throw W_(new Error,Q_.TABLE_NOT_FOUND(e.schema,e.table),gp.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=BQ.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){Y_.warn(`unable to stat table dbi due to ${f}`)}return d}a(z_,"descTable");async function qQ(e){K_.transformReq(e);let t=cw.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 n=e.schema.toString(),i=Rp()[n];if(!i)throw W_(new Error,Q_.SCHEMA_NOT_FOUND(e.schema),gp.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),K_.isEmpty(u)||u.describe){let _=await z_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(qQ,"describeSchema")});var ti=T((hle,Ew)=>{var GQ=Pi(),{callbackify:_w,promisify:kQ}=require("util"),{getDatabases:dw}=(Oe(),ee(Ge));Ew.exports={setSchemaDataToGlobal:lw,getTableSchema:VQ,getSystemSchema:$Q,setSchemaDataToGlobalAsync:kQ(lw)};var fw=Gi(),fle=_w(fw.describeAll),Ele=_w(fw.describeTable);function lw(e){global.hdb_schema=dw(),e&&e()}a(lw,"setSchemaDataToGlobal");function VQ(e,t,r){let n=dw()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(VQ,"getTableSchema");function $Q(){return GQ}a($Q,"getSystemSchema")});var on=T((ple,Sw)=>{"use strict";var X_=Am(),qt=J(),YQ=require("util"),j_=Ln(),KQ=ti(),hw=Y(),{handleHDBError:ki,hdb_errors:WQ}=Z(),{HTTP_STATUS_CODES:Vi}=WQ,QQ=YQ.promisify(KQ.getTableSchema),zQ="updated",mw="inserted",pw="upserted";Sw.exports={insert:XQ,update:jQ,upsert:ZQ,validation:JQ,flush:ez};async function JQ(e){if(qt.isEmpty(e))throw new Error("invalid update parameters defined.");if(qt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(qt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await QQ(e.schema,e.table),r=X_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&qt.isEmptyOrZeroLength(c[n]))throw hw.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(!qt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw hw.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!qt.isEmpty(c[n])&&c[n]!==""&&s.has(qt.autoCast(c[n]))&&(c.skip=!0),s.add(qt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(JQ,"validation");async function XQ(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=X_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await j_.createRecords(e);return J_(mw,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(XQ,"insertData");async function jQ(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=X_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await j_.updateRecords(e);return qt.isEmpty(n.existing_rows)?J_(zQ,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):J_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(jQ,"updateData");async function ZQ(e){if(e.operation!=="upsert")throw ki(new Error,"invalid operation, must be upsert",Vi.INTERNAL_SERVER_ERROR);let t=X_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await j_.upsertRecords(e);return J_(pw,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(ZQ,"upsertData");function J_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===mw?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===pw?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(J_,"returnObject");function ez(e){return qt.transformReq(e),j_.flush(e.schema,e.table)}a(ez,"flush")});var Op=T((Tle,Rw)=>{var tz=rt(),Ap=require("joi"),{hdb_table:rz,hdb_database:Tw}=Yn(),gw={schema:Tw,database:Tw,table:rz},nz={date:Ap.date().iso().required()},sz={timestamp:Ap.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};Rw.exports=function(e,t){let r=t==="timestamp"?{...gw,...sz}:{...gw,...nz},n=Ap.object(r);return tz.validateBySchema(e,n)}});var bw=T((gle,Ow)=>{var iz=rt(),bp=require("joi"),{hdb_table:oz,hdb_database:Aw}=Yn(),az=bp.object({schema:Aw,database:Aw,table:oz,hash_values:bp.array().required(),ids:bp.array()});Ow.exports=function(e){return iz.validateBySchema(e,az)}});var yw=T((Rle,Nw)=>{"use strict";var Np=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},yp=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Ip=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};Nw.exports={InsertObject:Np,NoSQLSeachObject:yp,DeleteResponseObject:Ip}});var Ki=T((Ole,Lw)=>{"use strict";var ww=Op(),cz=bw(),$i=J(),Iw=require("moment"),Cw=Y(),{promisify:uz,callbackify:lz}=require("util"),Yi=M(),_z=ti(),wp=uz(_z.getTableSchema),Cp=Ln(),{DeleteResponseObject:dz}=yw(),{handleHDBError:ri,hdb_errors:fz}=Z(),{HDB_ERROR_MSGS:Z_,HTTP_STATUS_CODES:ni}=fz,Ez="records successfully deleted",hz=lz(Dw);Lw.exports={delete:hz,deleteRecord:Dw,deleteFilesBefore:mz,deleteAuditLogsBefore:pz};async function mz(e){let t=ww(e,"date");if(t)throw ri(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);if($i.transformReq(e),!Iw(e.date,Iw.ISO_8601).isValid())throw ri(new Error,Z_.INVALID_DATE,ni.BAD_REQUEST,Yi.LOG_LEVELS.ERROR,Z_.INVALID_DATE,!0);let n=$i.checkSchemaTableExist(e.schema,e.table);if(n)throw ri(new Error,n,ni.NOT_FOUND,Yi.LOG_LEVELS.ERROR,n,!0);let s=await Cp.deleteRecordsBefore(e);if(await wp(e.schema,e.table),Cw.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(mz,"deleteFilesBefore");async function pz(e){let t=ww(e,"timestamp");if(t)throw ri(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);if($i.transformReq(e),isNaN(e.timestamp))throw ri(new Error,Z_.INVALID_VALUE("Timestamp"),ni.BAD_REQUEST,Yi.LOG_LEVELS.ERROR,Z_.INVALID_VALUE("Timestamp"),!0);let r=$i.checkSchemaTableExist(e.schema,e.table);if(r)throw ri(new Error,r,ni.NOT_FOUND,Yi.LOG_LEVELS.ERROR,r,!0);let n=await Cp.deleteAuditLogsBefore(e);return await wp(e.schema,e.table),Cw.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(pz,"deleteAuditLogsBefore");async function Dw(e){e.ids&&(e.hash_values=e.ids);let t=cz(e);if(t)throw ri(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);$i.transformReq(e);let r=$i.checkSchemaTableExist(e.schema,e.table);if(r)throw ri(new Error,r,ni.NOT_FOUND,Yi.LOG_LEVELS.ERROR,r,!0);try{await wp(e.schema,e.table);let n=await Cp.deleteRecords(e);return $i.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${Ez}`),n}catch(n){if(n.message===Yi.SEARCH_NOT_FOUND_MESSAGE){let s=new dz;return s.message=Yi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(Dw,"deleteRecord")});var ed=T((Nle,Pw)=>{var Sz=require("crypto"),Mw=9;function Tz(e){let t=Rz(Mw),r=Uw(e+t);return t+r}a(Tz,"createHash");function gz(e,t){let r=e?.substr(0,Mw),n=r+Uw(t+r);return e===n}a(gz,"validateHash");function Rz(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(Rz,"generateSalt");function Uw(e){return Sz.createHash("md5").update(e).digest("hex")}a(Uw,"md5");Pw.exports={hash:Tz,validate:gz}});var Bw=T((Ile,vw)=>{var Dp=rt(),Qt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function Az(e){return Qt.password.presence=!0,Qt.username.presence=!0,Qt.role.presence=!0,Qt.active.presence=!0,Dp.validateObject(e,Qt)}a(Az,"addUserValidation");function Oz(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Dp.validateObject(e,Qt)}a(Oz,"alterUserValidation");function bz(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Dp.validateObject(e,Qt)}a(bz,"dropUserValidation");vw.exports={addUserValidation:Az,alterUserValidation:Oz,dropUserValidation:bz}});var nt=T((Dle,xw)=>{"use strict";var{platform:Cle}=require("os"),Nz="nats-server.zip",Lp="nats-server",yz=process.platform==="win32"?`${Lp}.exe`:Lp,Mp="HDB",Iz=/^[^\s.,*>]+$/,Hw="__request__",wz=a(e=>`${e}.${Hw}`,"REQUEST_SUBJECT"),Cz={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},Dz={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},Lz={HUB:"hub.pid",LEAF:"leaf.pid"},Mz={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},Uz={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Mp,deliver_subject:"__HDB__.WORKQUEUE"},Pz={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Mp,deliver_subject:"HDB.SCHEMAQUEUE"},vz={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Mp,deliver_subject:"HDB.USERQUEUE"},Bz={SUCCESS:"success",ERROR:"error"},Hz={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},xz={TXN:"txn",MSGID:"msgid"},ta={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},Fz={[ta.ERR]:1,[ta.WRN]:2,[ta.INF]:3,[ta.DBG]:4,[ta.TRC]:5},qz={debug:"-D",trace:"-DVV"};xw.exports={NATS_SERVER_ZIP:Nz,NATS_SERVER_NAME:Lp,NATS_BINARY_NAME:yz,PID_FILES:Lz,NATS_CONFIG_FILES:Dz,SERVER_SUFFIX:Mz,WORK_QUEUE_CONSUMER_NAMES:Uz,SCHEMA_QUEUE_CONSUMER_NAMES:Pz,USER_QUEUE_CONSUMER_NAMES:vz,NATS_TERM_CONSTRAINTS_RX:Iz,REQUEST_SUFFIX:Hw,UPDATE_REMOTE_RESPONSE_STATUSES:Bz,CLUSTER_STATUS_STATUSES:Hz,REQUEST_SUBJECT:wz,SUBJECT_PREFIXES:xz,MSG_HEADERS:Cz,LOG_LEVELS:ta,LOG_LEVEL_FLAGS:qz,LOG_LEVEL_HIERARCHY:Fz}});var qw=T((Mle,Fw)=>{"use strict";var Gz={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,`\r
5
5
  `),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,`\r
6
- `)},mz="certificate.pem",pz="privateKey.pem",Sz="ca.pem";Iw.exports={CERTIFICATE_VALUES:hz,CERTIFICATE_PEM_NAME:mz,PRIVATEKEY_PEM_NAME:pz,CA_PEM_NAME:Sz}});var gp=T((Xue,Uw)=>{"use strict";var Mw=require("fs-extra"),ae=require("joi"),Tz=require("os"),{boolean:Be,string:us,number:Ut,array:Tp}=ae.types(),{totalmem:Cw}=require("os"),zi=require("path"),gz=q(),J_=z(),Jue=ww(),Lw=w(),Rz=et(),Dw="log",Az="components",Oz="Invalid logging.rotation.maxSize unit. Available units are G, M or K",bz="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Nz="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",yz="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",Iz="rootPath config parameter is undefined",wz="clustering.enabled config parameter is undefined",Ji=Ut.min(0).required(),X_=Tp.items({host:us.required(),port:Ji}).empty(null),rn;Uw.exports={configValidator:Cz,routesValidator:vz,route_constraints:X_};function Cz(e){if(rn=e.rootPath,J_.isEmpty(rn))throw Iz;let t=Be.required(),r=Ut.min(0).max(1e3).empty(null).default(Pz),s=us.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Xc),n=us.optional().empty(null),i=us.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ae.string().empty(null).default(Xc),c=ae.custom(Dz).empty(null).default(Xc),u=e.clustering?.enabled;if(J_.isEmpty(u))throw wz;let _;return u===!0?_=ae.object({enabled:t,hubServer:ae.object({cluster:ae.object({name:ae.required().empty(null),network:ae.object({port:Ji,routes:X_}).required()}).required(),leafNodes:ae.object({network:ae.object({port:Ji}).required()}).required(),network:ae.object({port:Ji}).required()}).required(),leafServer:ae.object({network:ae.object({port:Ji,routes:X_}).required(),streams:ae.object({maxAge:Ut.min(120).allow(null).optional(),maxBytes:Ut.min(1).allow(null).optional(),maxMsgs:Ut.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ae.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:Be.optional(),databaseLevel:Be.optional(),tls:ae.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Be.required(),verify:Be.optional()}),user:us.optional().empty(null)}).required():_=ae.object({enabled:t,tls:ae.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Be.required()})}).required(),ae.object({authentication:ae.object({authorizeLocal:Be,cacheTTL:Ut.required(),enableSessions:Be}),analytics:ae.object({aggregatePeriod:Ut}),componentsRoot:s.optional(),clustering:_,localStudio:ae.object({enabled:t}).required(),logging:ae.object({auditAuthEvents:ae.object({logFailed:Be,logSuccessful:Be}),file:Be.required(),level:ae.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ae.object({enabled:Be.optional(),compress:Be.optional(),interval:us.custom(Uz).optional().empty(null),maxSize:us.custom(Mz).optional().empty(null),path:us.optional().empty(null).default(Xc)}).required(),root:s,stdStreams:Be.required(),auditLog:Be.required()}).required(),operationsApi:ae.object({network:ae.object({cors:Be.optional(),corsAccessList:Tp.optional(),headersTimeout:Ut.min(1).optional(),keepAliveTimeout:Ut.min(1).optional(),port:Ut.optional().empty(null),domainSocket:ae.optional().empty("hdb/operations-server").default(Xc),securePort:Ut.optional().empty(null),timeout:Ut.min(1).optional()}).optional(),tls:ae.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:us.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ae.object({network:ae.object({port:Ji,securePort:Ji,mtls:ae.alternatives([Be.optional(),ae.object({user:us.optional(),certificateAuthority:n})])}).required(),webSocket:Be.optional(),requireAuthentication:Be.optional()}),http:ae.object({compressionThreshold:Ut.optional(),cors:Be.optional(),corsAccessList:Tp.optional(),headersTimeout:Ut.min(1).optional(),port:Ut.min(0).optional().empty(null),securePort:Ut.min(0).optional().empty(null)}).required(),threads:r.optional(),maxHeapMemory:Ut.min(0).optional(),storage:ae.object({writeAsync:Be.required(),overlappingSync:Be.optional(),caching:Be.optional(),compression:Be.optional(),noReadAhead:Be.optional(),path:c,prefetchWrites:Be.optional()}).required(),ignoreScripts:Be.optional(),tls:ae.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:us.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Cz,"configValidator");function Lz(e){return Mw.existsSync(e)?null:`Specified path ${e} does not exist.`}a(Lz,"doesPathExist");function Dz(e,t){ae.assert(e,us.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=Lz(e);if(r)return t.message(r)}a(Dz,"validatePath");function Mz(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(Oz);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(Nz):e}a(Mz,"validateRotationMaxSize");function Uz(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(bz);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(yz):e}a(Uz,"validateRotationInterval");function Pz(e,t){let r=t.state.path.join("."),s=Tz.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||Cw();return i=Math.round(Math.min(i,Cw())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),gz.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(Pz,"setDefaultThreads");function Xc(e,t){let r=t.state.path.join(".");if(!J_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(J_.isEmpty(rn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return zi.join(rn,Az);case"logging.root":return zi.join(rn,Dw);case"clustering.leafServer.streams.path":return zi.join(rn,"clustering","leaf");case"storage.path":let s=zi.join(rn,Lw.LEGACY_DATABASES_DIR_NAME);return Mw.existsSync(s)?s:zi.join(rn,Lw.DATABASES_DIR_NAME);case"logging.rotation.path":return zi.join(rn,Dw);case"operationsApi.network.domainSocket":return r==null?null:zi.join(rn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Xc,"setDefaultRoot");function vz(e){let t=ae.object({routes:X_});return Rz.validateBySchema({routes:e},t)}a(vz,"routesValidator")});var xr=T((ele,kw)=>{"use strict";var Hr=w(),Pt=z(),bt=q(),{configValidator:Bz,routesValidator:Pw}=gp(),lr=require("fs-extra"),Hz=require("yaml"),Bs=require("path"),xz=require("is-number"),Bw=require("properties-reader"),Fz=require("lodash"),{handleHDBError:Gz}=Z(),{HTTP_STATUS_CODES:qz,HDB_ERROR_MSGS:j_}=Cr(),Zue=require("minimist"),{server:kz}=(wr(),ee(Ci)),{DATABASES_PARAM_CONFIG:jc,CONFIG_PARAMS:Br,CONFIG_PARAM_MAP:Hs}=Hr,Vz="Unable to get config value because config is uninitialized",$z="Config successfully initialized",Yz="Error backing up config file",Kz="Empty parameter sent to getConfigValue",Hw=Bs.join(Hr.PACKAGE_ROOT,"config","yaml",Hr.HDB_DEFAULT_CONFIG_FILE),Wz="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",vw={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"},Z_,Nt,ed;kw.exports={createConfigFile:Qz,getDefaultConfig:zz,getConfigValue:Fw,initConfig:Ap,flattenConfig:ta,updateConfigValue:Gw,updateConfigObject:Xz,getConfiguration:eJ,setConfiguration:tJ,readConfigFile:bp,getClusteringRoutes:rJ,initOldConfig:qw,getConfigFromFile:sJ,getConfigFilePath:Xi,addConfig:nJ,deleteConfigFromFile:iJ,getConfigObj:oJ};function Qz(e){let t=ai(Hw);Z_=ta(t.toJSON());let r;for(let o in e){let c=Hs[o.toLowerCase()];if(c===Br.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=Rp(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){bt.error(l)}}}r&&xw(t,r),Op(t);let s=t.toJSON();Nt=ta(s);let n=t.getIn(["rootPath"]),i=Bs.join(n,Hr.HDB_CONFIG_FILE);lr.createFileSync(i),lr.writeFileSync(i,String(t)),bt.trace(`Config file written to ${i}`)}a(Qz,"createConfigFile");function xw(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!Pt.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(jc.TABLES))for(let i in s[n][jc.TABLES])for(let o in s[n][jc.TABLES][i]){let c=s[n][jc.TABLES][i][o],u=[Br.DATABASES,n,jc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[Br.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){bt.error("Error parsing schemas CLI/env config arguments",s)}}a(xw,"setSchemasConfig");function zz(e){if(Z_===void 0){let r=ai(Hw);Z_=ta(r.toJSON())}let t=Hs[e.toLowerCase()];if(t!==void 0)return Z_[t.toLowerCase()]}a(zz,"getDefaultConfig");function Fw(e){if(e==null){bt.error(Kz);return}if(Nt===void 0){bt.trace(Vz);return}let t=Hs[e.toLowerCase()];if(t!==void 0)return Nt[t.toLowerCase()]}a(Fw,"getConfigValue");function Xi(e=Pt.getPropsFilePath()){let t=Pt.getEnvCliRootPath();return t?Bs.join(t,Hr.HDB_CONFIG_FILE):Bw(e).get(Hr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Xi,"getConfigFilePath");function Ap(e=!1){if(Nt===void 0||e){let t;if(!Pt.noBootFile()){t=Pt.getPropsFilePath();try{lr.accessSync(t,lr.constants.F_OK|lr.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Xi(t),s;if(r.includes("config/settings.js"))try{qw(r);return}catch(i){if(i.code!==Hr.NODE_ERROR_CODES.ENOENT)throw i}try{s=ai(r)}catch(i){if(i.code===Hr.NODE_ERROR_CODES.ENOENT){bt.trace(`HarperDB config file not found at ${r}.
7
- This can occur during early stages of install where the config file has not yet been created`);return}else throw bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}Jz(s,r),Op(s);let n=s.toJSON();if(kz.config=n,Nt=ta(n),Nt.logging_rotation_rotate)for(let i in vw)Nt[i]&&bt.error(`Config ${vw[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace($z)}}a(Ap,"initConfig");function Jz(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Bs.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Bs.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Bs.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(bt.trace("Updating config file with missing config params"),lr.writeFileSync(t,String(e)))}a(Jz,"checkForUpdatedConfig");function Op(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=Bz(t);if(r.error)throw j_.CONFIG_VALIDATION(r.error.message);e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),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),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(Op,"validateConfig");function Xz(e,t){Nt===void 0&&(Nt={});let r=Hs[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Nt[r.toLowerCase()]=t}a(Xz,"updateConfigObject");function Gw(e,t,r=void 0,s=!1,n=!1,i=!1){Nt===void 0&&Ap();let o=Fw(Hs.hdb_root),c=Bs.join(o,Hr.HDB_CONFIG_FILE),u=ai(c),_;if(r===void 0&&e.toLowerCase()===Br.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Hs[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Rp(f,t);u.setIn([...E],h)}else for(let f in r){let E=Hs[f.toLowerCase()];if(E===Br.HTTP_SECUREPORT&&r[f]===Nt[Br.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Br.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===Nt[Br.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Br.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=Hr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=Rp(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(R){bt.error(R)}}}_&&xw(u,_),Op(u);let l=u.getIn(["rootPath"]),d=Bs.join(l,Hr.HDB_CONFIG_FILE);s===!0&&jz(c,l),lr.writeFileSync(d,String(u)),n&&(Nt=ta(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(Gw,"updateConfigValue");function jz(e,t){try{let r=Bs.join(t,"backup",`${Hr.HDB_CONFIG_FILE}.bak`);lr.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(Yz),bt.error(r)}}a(jz,"backupConfigFile");var Zz=["databases"];function ta(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),ed=e,r(e);function r(s){let n={};for(let i in s)if(s.hasOwnProperty(i))if(typeof s[i]=="object"&&s[i]!==null&&!Array.isArray(s[i])&&!Zz.includes(i)){let o=r(s[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Br[u.toUpperCase()]&&Hs[u]&&(n[Hs[u].toLowerCase()]=o[c]),n[u]=o[c]}}else n[i.toLowerCase()]=s[i];return n}a(r,"squashObj")}a(ta,"flattenConfig");function Rp(e,t){if(e===Br.CLUSTERING_NODENAME||e===Br.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(xz(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Pt.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 Pt.autoCast(t)}a(Rp,"castConfigValue");function eJ(){let e=Pt.getPropsFilePath(),t=Xi(e);return ai(t).toJSON()}a(eJ,"getConfiguration");async function tJ(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return Gw(void 0,void 0,n,!0),Wz}catch(i){throw typeof i=="string"||i instanceof String?Gz(i,i,qz.BAD_REQUEST,void 0,void 0,!0):i}}a(tJ,"setConfiguration");function bp(){let e=Pt.getPropsFilePath();try{lr.accessSync(e,lr.constants.F_OK|lr.constants.R_OK)}catch(s){if(!Pt.noBootFile())throw bt.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Xi(e);return ai(t).toJSON()}a(bp,"readConfigFile");function ai(e){return Hz.parseDocument(lr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ai,"parseYamlDoc");function rJ(){let e=bp(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Pt.isEmptyOrZeroLength(t)?[]:t;let r=Pw(t);if(r)throw j_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=Pt.isEmptyOrZeroLength(s)?[]:s;let n=Pw(s);if(n)throw j_.CONFIG_VALIDATION(n.message);if(!Pt.isEmptyOrZeroLength(s)&&!Pt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!Pt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw j_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(rJ,"getClusteringRoutes");function qw(e){let t=Bw(e);Nt={};for(let r in Hs){let s=t.get(r.toUpperCase());if(Pt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=Hs[r].toLowerCase();n===Br.LOGGING_ROOT?Nt[n]=Bs.dirname(s):Nt[n]=s}return Nt}a(qw,"initOldConfig");function sJ(e){let t=bp();return Fz.get(t,e.replaceAll("_","."))}a(sJ,"getConfigFromFile");async function nJ(e,t){let r=ai(Xi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await lr.writeFile(Xi(),String(r))}a(nJ,"addConfig");function iJ(e){let t=Xi(Pt.getPropsFilePath()),r=ai(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Bs.join(s,Hr.HDB_CONFIG_FILE);lr.writeFileSync(n,String(r))}a(iJ,"deleteConfigFromFile");function oJ(){return ed||(Ap(),ed)}a(oJ,"getConfigObj")});var $w=T((rle,Vw)=>{"use strict";var td=w(),rd=class{static{a(this,"BaseLicense")}constructor(t=0,r=td.RAM_ALLOCATION_ENUM.DEFAULT,s=td.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},Np=class extends rd{static{a(this,"ExtendedLicense")}constructor(t=0,r=td.RAM_ALLOCATION_ENUM.DEFAULT,s=td.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};Vw.exports={BaseLicense:rd,ExtendedLicense:Np}});var ji=T((nle,Jw)=>{"use strict";var sa=require("fs-extra"),Kw=z_(),Ww=require("crypto"),aJ=require("moment"),cJ=require("uuid").v4,Xt=q(),Ip=require("path"),uJ=z(),ci=w(),{totalmem:Yw}=require("os"),lJ=$w().ExtendedLicense,ra="invalid license key format",_J="061183",dJ="mofi25",fJ="aes-256-cbc",EJ=16,hJ=32,Qw=j();Qw.initSync();var yp;Jw.exports={validateLicense:zw,generateFingerPrint:pJ,licenseSearch:Lp,getLicense:gJ,checkMemoryLimit:RJ};function wp(){return Ip.join(Qw.getHdbBasePath(),ci.LICENSE_KEY_DIR_NAME,ci.LICENSE_FILE_NAME)}a(wp,"getLicenseDirPath");function mJ(){let e=wp();return Ip.join(e,ci.LICENSE_FILE_NAME)}a(mJ,"getLicenseFilePath");function Cp(){let e=wp();return Ip.join(e,ci.REG_KEY_FILE_NAME)}a(Cp,"getFingerPrintFilePath");async function pJ(){let e=Cp();try{return await sa.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await SJ();throw Xt.error(`Error writing fingerprint file to ${e}`),Xt.error(t),new Error("There was an error generating the fingerprint")}}a(pJ,"generateFingerPrint");async function SJ(){let e=cJ(),t=Kw.hash(e),r=Cp();try{await sa.mkdirp(wp()),await sa.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Xt.error(`Error writing fingerprint file to ${r}`),Xt.error(s),new Error("There was an error generating the fingerprint")}return t}a(SJ,"writeFingerprint");function zw(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ci.RAM_ALLOCATION_ENUM.DEFAULT,version:ci.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Xt.error("empty license key passed to validate."),r;let s=Cp(),n=!1;try{n=sa.statSync(s)}catch(i){Xt.error(i)}if(n){let i;try{i=sa.readFileSync(s,"utf8")}catch{Xt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(dJ),c=o[1];c=Buffer.concat([Buffer.from(c)],EJ);let u=Buffer.concat([Buffer.from(i)],hJ),_=Ww.createDecipheriv(fJ,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=TJ(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(ra),Xt.error(ra),new Error(ra)}let d;if(isNaN(l))try{d=JSON.parse(l),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(ra),Xt.error(ra),new Error(ra)}else r.exp_date=l;r.exp_date<aJ().valueOf()&&(r.valid_date=!1),Kw.validate(o[1],`${_J}${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||Xt.error("Invalid licence"),r}a(zw,"validateLicense");function TJ(e,t){try{let r=Ww.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Xt.warn("Check old license failed")}}a(TJ,"checkOldLicense");function Lp(){let e=new lJ,t=[];try{t=sa.readFileSync(mJ(),"utf-8").split(ci.NEW_LINE)}catch(r){r.code==="ENOENT"?Xt.info("no license file found"):Xt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(uJ.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=zw(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){Xt.error("There was an error parsing the license string."),Xt.error(n),e.ram_allocation=ci.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return yp=e,e}a(Lp,"licenseSearch");async function gJ(){return yp||await Lp(),yp}a(gJ,"getLicense");function RJ(){let e=Lp().ram_allocation,t=process.constrainedMemory?.()||Yw();if(t=Math.round(Math.min(t,Yw())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(RJ,"checkMemoryLimit")});var ls=T((ule,dC)=>{"use strict";var eC="username is required",tC="nothing to update, must supply active, role or password to update",rC="password cannot be an empty string",sC="If role is specified, it cannot be empty.",nC="active must be true or false";dC.exports={addUser:LJ,alterUser:DJ,dropUser:UJ,getSuperUser:HJ,userInfo:PJ,listUsers:nd,listUsersExternal:vJ,setUsersToGlobal:ia,findAndValidateUser:lC,getClusterUser:xJ,USERNAME_REQUIRED:eC,ALTERUSER_NOTHING_TO_UPDATE:tC,EMPTY_PASSWORD:rC,EMPTY_ROLE:sC,ACTIVE_BOOLEAN:nC};var iC=cs(),AJ=Qi(),Up=z_(),oC=bw(),aC=as(),Pp=bn(),Fr=z(),cC=require("validate.js"),Ee=q(),{promisify:OJ}=require("util"),vp=wn(),Xw=w(),jw=tt(),bJ=xr(),ole=j(),ale=ji(),NJ=Bi(),{table:cle}=(pe(),ee(Ge)),{handleHDBError:sn,hdb_errors:yJ}=Z(),{HTTP_STATUS_CODES:nn,AUTHENTICATION_ERROR_MSGS:Dp,HDB_ERROR_MSGS:na}=yJ,{UserEventMsg:Bp}=Ls(),Mp=require("lodash"),{server:Hp}=(wr(),ee(Ci)),IJ=q();Hp.getUser=(e,t)=>lC(e,t,t!=null);var uC={username:!0,active:!0,role:!0,password:!0},Zw=new Map,sd=aC.searchByValue,wJ=aC.searchByHash,CJ=OJ(AJ.delete);async function LJ(e){let t=cC.cleanAttributes(e,uC),r=oC.addUserValidation(t);if(r)throw sn(new Error,r.message,nn.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 sd(s),n=n&&Array.from(n)}catch(u){throw Ee.error("There was an error searching for a role in add user"),Ee.error(u),u}if(!n||n.length<1)throw sn(new Error,na.ROLE_NAME_NOT_FOUND(t.role),nn.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw sn(new Error,na.DUP_ROLES_FOUND(t.role),nn.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=vp.encrypt(t.password)),t.password=Up.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await iC.insert(i)}catch(u){throw Ee.error("There was an error searching for a user."),Ee.error(u),u}Ee.debug(o);try{await ia()}catch(u){throw Ee.error("Got an error setting users to global"),Ee.error(u),u}if(o.skipped_hashes.length===1)throw sn(new Error,na.USER_ALREADY_EXISTS(t.username),nn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],Pp.signalUserChange(new Bp(process.pid)),`${c.username} successfully added`}a(LJ,"addUser");async function DJ(e){let t=cC.cleanAttributes(e,uC);if(Fr.isEmptyOrZeroLength(t.username))throw new Error(eC);if(Fr.isEmptyOrZeroLength(t.password)&&Fr.isEmptyOrZeroLength(t.role)&&Fr.isEmptyOrZeroLength(t.active))throw new Error(tC);if(!Fr.isEmpty(t.password)&&Fr.isEmptyOrZeroLength(t.password.trim()))throw new Error(rC);if(!Fr.isEmpty(t.active)&&!Fr.isBoolean(t.active))throw new Error(nC);let r=MJ(t.username);if(!Fr.isEmpty(t.password)&&!Fr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=vp.encrypt(t.password)),t.password=Up.hash(t.password)),t.role==="")throw new Error(sC);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 sd(i)||[])}catch(c){throw Ee.error("Got an error searching for a role."),Ee.error(c),c}if(!o||o.length===0){let c=na.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ee.error(c),sn(new Error,c,nn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=na.ALTER_USER_DUP_ROLES(t.role);throw Ee.error(c),sn(new Error,c,nn.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 iC.update(s)}catch(i){throw Ee.error("Error during update."),Ee.error(i),i}try{await ia()}catch(i){throw Ee.error("Got an error setting users to global"),Ee.error(i),i}return Pp.signalUserChange(new Bp(process.pid)),n}a(DJ,"alterUser");function MJ(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(MJ,"isClusterUser");async function UJ(e){try{let t=oC.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Fr.isEmpty(global.hdb_users.get(e.username)))throw sn(new Error,na.USER_NOT_EXIST(e.username),nn.NOT_FOUND,void 0,void 0,!0);let s;try{s=await CJ(r)}catch(n){throw Ee.error("Got an error deleting a user."),Ee.error(n),n}Ee.debug(s);try{await ia()}catch(n){throw Ee.error("Got an error setting users to global."),Ee.error(n),n}return Pp.signalUserChange(new Bp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(UJ,"dropUser");async function PJ(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Mp.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await wJ(r)}catch(n){throw Ee.error("Got an error searching for a role."),Ee.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ee.error(r),r}return t}a(PJ,"userInfo");async function vJ(){let e;try{e=await nd()}catch(t){throw Ee.error("Got an error listing users."),Ee.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(vJ,"listUsersExternal");async function nd(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await sd(e)}catch(o){throw Ee.error("Got an error searching for roles."),Ee.error(o),o}let r={};for(let o of t)r[o.id]=Mp.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 sd(s)}catch(o){throw Ee.error("Got an error searching for users."),Ee.error(o),o}let i=new Map;for(let o of n)o=Mp.cloneDeep(o),o.role=r[o.role],BJ(o.role),i.set(o.username,o);return i}catch(e){throw Ee.error("got an error listing users"),Ee.error(e),Fr.errorizeMessage(e)}return null}a(nd,"listUsers");function BJ(e){try{if(!e){Ee.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(NJ)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Ee.error("Got an error trying to set system permissions."),Ee.error(t)}}a(BJ,"appendSystemTablesToRole");async function ia(){try{let e=await nd();global.hdb_users=e}catch(e){throw Ee.error(e),e}}a(ia,"setUsersToGlobal");async function lC(e,t,r=!0){global.hdb_users||await ia();let s=global.hdb_users.get(e);if(!s){if(!r)return{username:e};throw sn(new Error,Dp.GENERIC_AUTH_FAIL,nn.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw sn(new Error,Dp.USER_INACTIVE,nn.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(Zw.get(t)===s.password)return n;if(Up.validate(s.password,t))Zw.set(t,s.password);else throw sn(new Error,Dp.GENERIC_AUTH_FAIL,nn.UNAUTHORIZED,void 0,void 0,!0)}return n}a(lC,"findAndValidateUser");async function HJ(){global.hdb_users||await ia();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(HJ,"getSuperUser");async function xJ(){let e=await nd(),t=bJ.getConfigFromFile(Xw.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Fr.isEmpty(r)&&r?.role?.role===Xw.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=vp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+jw.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+jw.SERVER_SUFFIX.ADMIN,r}a(xJ,"getClusterUser");var _C=[];Hp.invalidateUser=function(e){for(let t of _C)try{t(e)}catch(r){IJ.error("Error invalidating user",r)}};Hp.onInvalidatedUser=function(e){_C.push(e)}});var eu=T((fle,mC)=>{"use strict";var Zi=q(),Gr=w(),FJ=Tb(),_le=ni(),dle=Vi(),GJ=ls(),{validateEvent:fC}=Ls(),Zc=Ps(),qJ=require("process"),{resetDatabases:kJ}=(pe(),ee(Ge)),VJ={[Gr.ITC_EVENT_TYPES.SCHEMA]:$J,[Gr.ITC_EVENT_TYPES.USER]:hC};async function $J(e){let t=fC(e);if(t){Zi.error(t);return}Zi.trace("ITC schemaHandler received schema event:",e),await FJ(e.message),await YJ(e.message)}a($J,"schemaHandler");async function YJ(e){try{Zc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Zc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Zc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=kJ();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Zi.error(t)}}a(YJ,"syncSchemaMetadata");var EC=[];async function hC(e){try{try{Zc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Zc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Zi.warn(r)}let t=fC(e);if(t){Zi.error(t);return}Zi.trace(`ITC userHandler ${Gr.HDB_ITC_CLIENT_PREFIX}${qJ.pid} received user event:`,e),await GJ.setUsersToGlobal();for(let r of EC)r()}catch(t){Zi.error(t)}}a(hC,"userHandler");hC.addListener=function(e){EC.push(e)};mC.exports=VJ});var Ls=T((Tle,SC)=>{"use strict";var hle=q(),xp=z(),KJ=w(),{ITC_ERRORS:tu}=Cr(),{parentPort:mle,threadId:WJ,isMainThread:QJ,workerData:ple}=require("worker_threads"),{onMessageFromWorkers:zJ,broadcast:Sle,broadcastWithAcknowledgement:JJ}=Ze();SC.exports={sendItcEvent:XJ,validateEvent:pC,SchemaEventMsg:jJ,UserEventMsg:ZJ};var id;zJ(async(e,t)=>{id=id||eu(),pC(e),id[e.type]&&await id[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function XJ(e){return!QJ&&e.message&&(e.message.originator=WJ),JJ(e)}a(XJ,"sendItcEvent");function pC(e){if(typeof e!="object")return tu.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||xp.isEmpty(e.type))return tu.MISSING_TYPE;if(!e.hasOwnProperty("message")||xp.isEmpty(e.message))return tu.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||xp.isEmpty(e.message.originator))return tu.MISSING_ORIGIN;if(KJ.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return tu.INVALID_EVENT(e.type)}a(pC,"validateEvent");function jJ(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(jJ,"SchemaEventMsg");function ZJ(e){this.originator=e}a(ZJ,"UserEventMsg")});var bn=T((Ale,AC)=>{"use strict";var TC=w(),Rle=z(),od=q(),gC=tb(),oa,{sendItcEvent:RC}=Ls();function e2(e){try{od.trace("signalSchemaChange called with message:",e),oa=oa||eu();let t=new gC(TC.ITC_EVENT_TYPES.SCHEMA,e);return oa.schema(t),RC(t)}catch(t){od.error(t)}}a(e2,"signalSchemaChange");function t2(e){try{od.trace("signalUserChange called with message:",e),oa=oa||eu();let t=new gC(TC.ITC_EVENT_TYPES.USER,e);return oa.user(t),RC(t)}catch(t){od.error(t)}}a(t2,"signalUserChange");AC.exports={signalSchemaChange:e2,signalUserChange:t2}});var iu={};$e(iu,{addAnalyticsListener:()=>nu,recordAction:()=>qr,recordActionBinary:()=>_s,setAnalyticsEnabled:()=>r2});function r2(e){MC=e}function qr(e,t,r,s,n){if(!MC)return;let i=t+(r?"-"+r:"");s!==void 0&&(i+="-"+s),n!==void 0&&(i+="-"+n);let o=ud.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:s,type:n},ud.set(i,o)}ad||s2()}function _s(e,t,r,s,n){qr(!!e,t,r,s,n)}function nu(e){vC.push(e)}function s2(){ad=performance.now(),setTimeout(async()=>{let e=performance.now()-ad;ad=0;let t=[],r={time:Date.now(),period:e,threadId:eo.threadId,metrics:t};for(let[n,i]of ud){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of BC){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await HC()}let s=process.memoryUsage();t.push({metric:"memory",threadId:eo.threadId,byThread:!0,...s});for(let n of vC)n(t);ud=new Map,eo.parentPort?eo.parentPort.postMessage({type:PC,report:r}):GC({report:r})},UC).unref()}async function n2(e,t=6e4){let r=qp(),s=xC(),n;for(let h of s.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){n=h.value.time;break}if(Date.now()-t<n)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:p}of r.primaryStore.getRange({start:n||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:S,threadId:R}=p;for(let O of S||[]){let{path:b,method:P,type:$,metric:x,count:D,total:Y,distribution:V,threads:W,...re}=O;D||(D=1);let be=x+(b?"-"+b:"");P!==void 0&&(be+="-"+P),$!==void 0&&(be+="-"+$);let ne=o.get(be);if(ne){if(ne.threads){let Te=ne.threads[R];if(Te)ne=Te;else{ne.threads[R]=Object.assign({},re);continue}}ne.count||(ne.count=1);let ct=ne.count;for(let Te in re){let Ht=re[Te];typeof Ht=="number"&&(ne[Te]=(ne[Te]*ct+Ht*D)/(ct+D))}ne.count+=D,Y>=0&&(ne.total+=Y,ne.ratio=ne.total/ne.count)}else ne=Object.assign({period:t},O),delete ne.distribution,o.set(be,ne),ne.byThread&&(ne.threads=[],ne.threads[R]=Object.assign({},re),u.push(ne));if(V){V=V.map(Te=>typeof Te=="number"?{value:Te,count:1}:Te);let ct=c.get(be);ct?ct.push(...V):c.set(be,V)}}await HC()}for(let h of u){let{path:p,method:S,type:R,metric:O,count:b,total:P,distribution:$,threads:x,...D}=h;x=x.filter(Y=>Y);for(let Y in D){if(typeof h[Y]!="number")continue;let V=0;for(let W of x){let re=W[Y];typeof re=="number"&&(V+=re)}h[Y]=V}h.count=x.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((Te,Ht)=>Te.value>Ht.value?1:-1);let R=S.count-1,O=[],b=0,P=0,$;for(let Te of BC){let Ht=R*Te;for(;b<Ht;)$=p[P++],b+=$.count,P===1&&b--;let bs=p[P>1?P-2:0];$||($=p[0]),O.push($.value-($.value-bs.value)*(b-Ht)/$.count)}let[x,D,Y,V,W,re,be,ne,ct]=O;Object.assign(S,{p1:x,p10:D,p25:Y,median:V,p75:W,p90:re,p95:be,p99:ne,p999:ct})}let l;for(let[h,p]of o)p.id=(0,cd.getNextMonotonicTime)(),p.time=_,s.primaryStore.put(p.id,p,{append:!0}).then(S=>{S||s.primaryStore.put(p.id,p)}),l=!0;let d=Date.now(),{idle:f,active:E}=performance.eventLoopUtilization();if(l||E*10>f){let h=(0,cd.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-OC,active:E-bC,time:d,...process.memoryUsage()};s.primaryStore.put(h,p,{append:!0}).then(S=>{S||s.primaryStore.put(h,p)})}OC=f,bC=E}async function NC(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function qp(){return yC||(yC=lt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function xC(){return IC||(IC=lt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function a2(){FC=!0;let e=(0,su.get)(Gp.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await n2(UC,e),await NC(qp(),i2),await NC(xC(),o2)},Math.min(e/2,2147483647)).unref()}function GC(e,t){let r=e.report;r.threadId=t?.threadId||eo.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(wC+=s.mean*s.count);r.totalBytesProcessed=wC,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(CC.get(t))}),CC.set(t,t.performance.eventLoopUtilization())),r.id=(0,cd.getNextMonotonicTime)(),qp().primaryStore.put(r.id,r),FC||a2(),c2&&(qC=l2(r))}async function l2(e){if(await qC,!ui){let r=(0,ru.dirname)((0,DC.getLogFilePath)());try{ui=await(0,Fp.open)((0,ru.join)(r,"analytics.log"),"r+")}catch{ui=await(0,Fp.open)((0,ru.join)(r,"analytics.log"),"w+")}}let t=(await ui.stat()).size;if(t>u2){let r=Buffer.alloc(t);await ui.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ui.write(r,{position:0}),await ui.truncate(r.length),t=r.length}await ui.write(JSON.stringify(e)+`
8
- `,t)}var eo,LC,DC,ru,Fp,cd,su,Gp,ud,MC,ad,UC,PC,vC,BC,OC,bC,HC,i2,o2,yC,IC,FC,wC,CC,c2,qC,ui,u2,Cn=ge(()=>{eo=require("worker_threads"),LC=U(Ze());pe();DC=U(q()),ru=require("path"),Fp=require("fs/promises"),cd=U(Lr()),su=U(j()),Gp=U(w());wr();(0,su.initSync)();ud=new Map,MC=(0,su.get)(Gp.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(r2,"setAnalyticsEnabled");a(qr,"recordAction");At.recordAnalytics=qr;a(_s,"recordActionBinary");ad=0,UC=1e3,PC="analytics-report",vC=[];a(nu,"addAnalyticsListener");BC=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(s2,"sendAnalytics");a(n2,"aggregation");OC=0,bC=0,HC=a(()=>new Promise(setImmediate),"rest");a(NC,"cleanup");i2=36e5,o2=31536e6;a(qp,"getRawAnalyticsTable");a(xC,"getAnalyticsTable");(0,LC.setChildListenerByType)(PC,GC);a(a2,"startScheduledTasks");wC=0,CC=new Map,c2=!1;a(GC,"recordAnalytics");u2=1e6;a(l2,"logAnalytics")});var Kp={};$e(Kp,{coerceType:()=>dd,makeTable:()=>Ed,setServerUtilities:()=>p2,updateResource:()=>lu});function Ed(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:p}=e;p||(p=[]),jO(i,u);let S=bh(i,s,u),R=0,O,b,P,$={},x=Promise.resolve(),D,Y,V;for(let K of p)(K.assignCreatedTime||K.name==="__createdtime__")&&(D=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(Y=K),K.expiresAt&&(V=K),K.isPrimaryKey&&($=K);let W,re=[],be=[],ne=1,ct=2,Te={},Ht={},bs=864e5,sA,Ml,Wn,nA=!1,qE,yx=10,Ix=6;E&&oA();class ze 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=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=D;static updatedTimeProperty=Y;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,g){g&&(this.sourceOptions=g,(g.expiration||g.eviction||g.scanInterval)&&this.setTTLExpiration(g)),g?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),b=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let L=a(N=>{let I=this.sources.slice(0,-1);if(I=I.filter(M=>M[N]&&(!M[N].reliesOnPrototype||M.prototype[N])),I.length>0)if(I.length===1){let M=I[0];return(B,H,Q)=>{if(B?.source!==M)return M[N](H,Q,B)}}else return(M,B,H)=>{let Q=[];for(let X of I){if(M?.source===X)break;Q.push(X[N](B,H,M))}return Promise.all(Q)}},"getApplyToIntermediateSource"),A=this.sources[this.sources.length-1],C=a(N=>{if(A[N]&&(!A[N].reliesOnPrototype||A.prototype[N]))return(I,M,B)=>{if(!I?.source)return A[N](M,B,I)}},"getApplyToCanonicalSource");return Te={put:C("put"),delete:C("delete"),publish:C("publish")},Ht={put:L("put"),delete:L("delete"),publish:L("publish"),invalidate:L("invalidate")},(async()=>{let N=!1,I=a(async(M,B)=>{let H=M.value,Q=M.table?st[c][M.table]:ze;if(c===xs.SYSTEM_SCHEMA_NAME&&(M.table===xs.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||M.table===xs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(N=!0),M.id===void 0&&(M.id=H[Q.primaryKey],M.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(M));M.source=m;let X=await Q.getResource(M.id,B,ou);switch(M.type){case"put":return X._writeUpdate(H,ou);case"delete":return X._writeDelete(ou);case"publish":return X._writePublish(H,ou);case"invalidate":return X.invalidate(ou);default:rt.error("Unknown operation",M.type,M.id)}},"writeUpdate");try{let M=m.subscribe;M&&h==null&&(h=!0);let B=m.subscribeOnThisThread?m.subscribeOnThisThread((0,to.getWorkerIndex)()):(0,to.getWorkerIndex)()===0,H=M&&B&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(H){let Q;for await(let X of H)try{if(!(X.type==="transaction"?X.writes[0]:X)){rt.error("Bad subscription event",X);continue}if(X.source=m,Q)if(X.beginTxn)Q.resolve();else{I(X,Q);continue}if(X.type==="end_txn")continue;let Me=Qe(X,()=>{if(X.type==="transaction"){let se=[];for(let he of X.writes)try{se.push(I(he,X))}catch(Dt){throw Dt.message+=" writing "+JSON.stringify(he)+" of event "+JSON.stringify(X),Dt}return Promise.all(se)}else if(X.type==="define_schema"){let se=this.attributes.slice(0),he;for(let Dt of X.attributes)se.find(xe=>xe.name===Dt.name)||(se.push(Dt),he=!0);he&&(lt({table:n,database:c,attributes:se,origin:"cluster"}),du.signalSchemaChange(new fu.SchemaEventMsg(process.pid,xs.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return X.beginTxn?(Q=X,I(X,X),new Promise(se=>{Q.resolve=se})):I(X,X)});N&&(await Me,du.signalUserChange(new fu.UserEventMsg(process.pid))),X.onCommit&&(Me?.then?Me.then(X.onCommit):X.onCommit())}catch(Je){rt.error("error in subscription handler",Je)}}}catch(M){rt.error(M)}})(),this}static getResource(m,g,L){let A=super.getResource(m,g,L);if(m!=null){Ka(m);try{if(A.hasOwnProperty(ye))return A;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let C=!L?.async||i.cache?.get(m),N=Xr(g),I=N.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return kE(m,g,{transaction:I},C,M=>{if(M?lu(A,M):A[ye]=null,g.onlyIfCached&&g.noCacheStore){if(!A.doesExist())throw new ds.ServerError("Entry is not cached",504)}else if(L?.ensureLoaded){let B=VE(m,M,g,A);if(B)return N?.disregardReadTxn(),A[Vp]=!0,Yp(B,H=>(lu(A,H),A))}return A})}catch(C){throw C.message.includes("Unable to serialize object")&&(C.message+=": "+JSON.stringify(m)),C}}return A}ensureLoaded(){let m=VE(this[Le],this[on],this[me]);if(m)return this[Vp]=!0,Yp(m,g=>{this[on]=g,this[ye]=g.value,this[_d]=g.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,bs=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");bs=bs||(d+f)/4,YE()}static enableAuditing(m=!0){E=m,m&&oA(),ze.audit=m}static coerceId(m){return m===""?null:dd(m,$)}static async dropTable(){if(delete st[c][n],c===o){for(let m of p)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.tableName+"/"),i.drop(),await l.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));du.signalSchemaChange(new fu.SchemaEventMsg(process.pid,xs.OPERATIONS_ENUM.DROP_TABLE,c,n))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[ns])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let g=ze.getRecordCount();return{recordCount:g.recordCount,estimatedRecordRange:g.estimatedRange,records:"./",name:n,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[me]?.returnNonexistent)return this}allowRead(m,g){let L=Pl(m);if(L?.read){if(L.isSuperUser)return!0;let A=L.attribute_permissions,C=g?.select;if(A?.length>0||nA&&C){if(g||(g={}),C){let N=A?.length>0&&$p(A,"read");g.select=C.map(I=>{let M=I.name||I;if(!N||N[M]){let B=Wn[M]?.definition?.tableClass;if(B){if(I.name||(I={name:I}),!B.prototype.allowRead.call(null,m,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else g.select=A.filter(N=>N.read&&!Wn[N.attribute_name]).map(N=>N.attribute_name);return g}else return!0}}allowUpdate(m,g){let L=Pl(m);if(L?.update){let A=L.attribute_permissions;if(A?.length>0){let C=$p(A,"update");for(let N in g)if(!C[N])return!1;for(let N of A){let I=N.attribute_name;!N.update&&!(I in g)&&(g[I]=this.getProperty(I))}}return!0}}allowCreate(m,g){if(this[ns]){let L=Pl(m);if(L?.insert){let A=L.attribute_permissions;if(A?.length>0){let C=$p(A,"insert");for(let N in g)if(!C[N])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Pl(m)?.delete}update(m,g){if(!Xr(this[me]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let A;if(typeof m=="object"&&m)if(g){Object.isFrozen(m)&&(m=Object.assign({},m));for(let C in this[ye])m[C]===void 0&&(m[C]=void 0);this[Qt]=m}else A=this[Qt],A&&(m=Object.assign(A,m)),this[Qt]=A=m;return this._writeUpdate(this),this}invalidate(m){let g=this[me],L=this[Le];Ka(L),Xr(this[me]).addWrite({key:L,store:i,invalidated:!0,entry:this[on],nodeName:this[me]?.nodeName,before:Te.invalidate?.bind(this,g,L),beforeIntermediate:Ht.invalidate?.bind(this,g,L),commit:(C,N)=>{if(N?.version>C)return;let I=null;for(let M in r)I||(I={}),I[M]=this.getProperty(M);S(L,I,this[on],C,au,E,this[me],0,"invalidate")}})}static evict(m,g,L){let A=this.Source,C;if(!((b||E)&&(!g||(C=i.getEntry(m),!C||!g)||C.version!==L))){if(b){if(i.hasLock(m,C.version))return;let N;for(let I in r)N||(N={}),N[I]=g[I];if(N)return S(m,N,C,L,cu,null,null,0,null,!0)}return i.ifVersion(L,()=>{Ul(m,g,null)}),E?S(m,null,C,L,cu,null,null,0,null,!0):i.remove(m,L)}}lock(){throw new Error("Not yet implemented")}static operation(m,g){return m.table||=n,m.schema||=c,zC.operation(m,g)}put(m){this.update(m,!0)}_writeUpdate(m,g){let L=this[me],A=Xr(L),C=this[Le];Ka(C);let N=this[on];this[kp]=!0;let I={key:C,store:i,entry:N,nodeName:L?.nodeName,validate:M=>{if(!m[VC]||Ql(m)){if(this.validate(m),L?.source?m=lc(m):(t&&m[t]!==C&&(m[t]=C),Y&&(m[Y.name]=Y.type==="Date"?new Date(M):Y.type==="String"?new Date(M).toISOString():M),D&&(N?.value?m[D.name]=N?.value[D.name]:m[D.name]=D.type==="Date"?new Date(M):D.type==="String"?new Date(M).toISOString():M),m=lc(m)),m[ye])throw new Error("Can not assign a record with a record property");this[ye]=m}else A.removeWrite(I)},before:Te.put&&(()=>Te.put(L,C,m)),beforeIntermediate:Ht.put&&(()=>Ht.put(L,C,m)),commit:(M,B,H)=>{H&&(L&&B?.version>(L.lastModified||0)&&(L.lastModified=B.version),lu(this,B));let Q=B?.value;this[kp]=!1,!(B?.version>M)&&(Ul(C,Q,m),S(C,m,B,M,0,E,L,L.expiresAt||(d?d+Date.now():0)))}};A.addWrite(I)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[ns]){for await(let g of this.search(m))(await ze.getResource(g[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[ye]?this._writeDelete(m):!1}_writeDelete(m){let g=Xr(this[me]),L=this[Le];Ka(L);let A=this[me];return g.addWrite({key:L,store:i,resource:this,nodeName:A?.nodeName,before:Te.delete?.bind(this,A,L),beforeIntermediate:Ht.delete?.bind(this,A,L),commit:(C,N,I)=>{let M=N?.value;I&&(A&&N?.version>(A.lastModified||0)&&(A.lastModified=N.version),lu(this,N)),!(N?.version>C)&&(Ul(this[Le],M),rt.trace("Write delete entry",L,C),E||h?(S(L,null,this[on],C,0,E,this[me],0,"delete"),E||YE()):i.remove(this[Le]))}}),!0}search(m){let g=this[me],L=Xr(g);if(!m)throw new Error("No query provided");let A=m.conditions;A?A.length===void 0&&(A=A[Symbol.iterator]?Array.from(A):[A]):A=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(A=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(A));let C,N={};function I(te,Fe){let He;switch(Fe){case"and":case void 0:if(te.length<1)throw new Error('An "and" operator requires at least one condition');He=!0;break;case"or":if(te.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Fe)}let ft=He&&{},tr;for(let Ne of te){if(Ne.conditions){Ne.conditions=I(Ne.conditions,Ne.operator);continue}let we=Ne[0]??Ne.attribute,Mt=we==null?$:Rn(p,we);if(Mt){if(He){let yr=jn(we),xt=ft[yr];xt?(xt.push(Ne),tr=!0):ft[yr]=[Ne]}Mt.type&&(Ne[1]===void 0?Ne.value=B(Ne.value,Mt):Ne[1]=B(Ne[1],Mt))}else if(we!=null)throw(0,ds.handleHDBError)(new Error,`${we} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return te;if(tr)for(let Ne in ft){let we=ft[Ne],Mt=we.length;if(Mt>1)for(let yr=0;yr<Mt;yr++){let xt=we[yr];if(xt.comparator==="ge"||xt.comparator==="greater_than_equal")for(let Pe=0;Pe<Mt;Pe++){let Zr=we[Pe];(Zr.comparator==="le"||Zr.comparator==="less_than_equal")&&(xt.comparator="between",xt.value=[xt.value,Zr.value],te.splice(te.indexOf(Zr),1))}if(xt.comparator==="equals"||!xt.comparator){for(let Pe=0;Pe<Mt;Pe++)if(Pe!==yr){let Zr=we[Pe];te.splice(te.indexOf(Zr),1)}break}}}return te}a(I,"prepareConditions");function M(te,Fe){if(m.enforceExecutionOrder)return te;for(let He of te)He.conditions&&(He.conditions=M(He.conditions,He.operator));return te.length>1&&Fe!=="or"?(0,QC.sortBy)(te,fh(ze)):te}a(M,"orderConditions");function B(te,Fe){return Array.isArray(te)?te.map(He=>dd(He,Fe)):dd(te,Fe)}a(B,"coerceTypedValues");let H=m.operator;(A.length>0||H)&&(A=I(A,H));let Q=typeof m.sort=="object"&&m.sort,X;if(Q&&H!=="or"){let te=Q.attribute;if(C=A.find(Fe=>jn(Fe.attribute)===jn(te)),!C){if(!Rn(p,te))throw(0,ds.handleHDBError)(new Error,`${te} is not a defined attribute`,404);C={attribute:te},A.push(C)}C.descending=!!Q.descending}A=M(A,H),Q&&(A[0]===C?Q.next&&(X={dbOrderedAttribute:Q.attribute,attribute:Q.next.attribute,descending:Q.next.descending,next:Q.next.next}):(C&&A.splice(A.indexOf(C),1),X=Q));function Je(te,Fe){let He=te[0];if(Fe==="or"){let ft=se(He);for(let Ne=1;Ne<te.length;Ne++){let we=te[Ne],Mt=se(we);ft=ft.concat(Mt)}let tr=new Set;return ft.filter(Ne=>{let we=Ne.key??Ne;return tr.has(we)?!1:(tr.add(we),!0)})}else{let ft=se(He),tr=te.slice(1).map(Ne=>fc(Ne,ze,g,N)).filter(Boolean);return tr.length>0?jr(ft,tr):ft}}a(Je,"executeConditions");let Me=m.reverse===!0;function se(te){return te.conditions?Je(te.conditions,te.operator):dc(te,L,te.descending||Me,ze,m.allowFullScan,N)}a(se,"executeCondition");let he=m.select;if(A.length===0&&(A=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:A,operator:H,postOrdering:X,selectApplied:!!he};let Dt=L.useReadTxn(),xe=Je(A,H);(m.offset||m.limit!==void 0)&&(xe=xe.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0));let Ue=m.ensureLoaded!==!1;function jr(te,Fe){let He=Fe?.length,ft={transaction:Dt,lazy:He>0||typeof he=="string"||he?.length<4,alwaysPrefetch:!0};function tr(we,Mt){let yr=we?.value;if(!yr)return ld.SKIP;for(let xt=0;xt<He;xt++)if(!Fe[xt](yr,we))return ld.SKIP;return Mt!==void 0&&(we.key=Mt),we}a(tr,"processEntry");let Ne=He>0||!te.hasEntries?te.map(we=>typeof we=="object"&&we.key!==void 0?He>0?tr(we):we:kE(we,g,ft,!1,tr)):te;return Ne.hasEntries=!0,Ne}a(jr,"transformToEntries");let ce,Wa=ze.transformEntryForSelect(he,g,N,Ue,!0);if(X){xe=jr(xe,null);let te;ce=new xe.constructor({[Symbol.iterator](){let Fe,He=xe[Symbol.asyncIterator](),ft,tr=X.dbOrderedAttribute,Ne,we,Mt=!0;function yr(Pe){let Zr=Pe.next&&yr(Pe.next),Qa=Pe.descending;return(aA,cA)=>{let uA=$E(aA,Pe.attribute,g),lA=$E(cA,Pe.attribute,g),_A=Qa?(0,ro.compareKeys)(lA,uA):(0,ro.compareKeys)(uA,lA);return _A===0?Zr?.(aA,cA)||0:_A}}a(yr,"createComparator");let xt=yr(X);return{async next(){let Pe;if(Fe)if(Pe=Fe.next(),Pe.done){if(ft)return ce.onDone&&ce.onDone(),Pe}else return{value:Wa(Pe.value)};te=[],Ne&&te.push(Ne);do if(Pe=await He.next(),Pe.done){if(ft=!0,te.length)break;return ce.onDone&&ce.onDone(),Pe}else{let Zr=Pe.value;if(tr){let Qa=$E(Zr,tr,g);if(Mt)Mt=!1,we=Qa;else if(Qa!==we){we=Qa,Ne=Zr;break}}te.push(Zr)}while(!0);return X.isGrouped,te.sort(xt),Fe=te[Symbol.iterator](),Pe=Fe.next(),Pe.done?(ce.onDone&&ce.onDone(),Pe):{value:await Wa(Pe.value)}},return(){ce.onDone&&ce.onDone(),He.return()},throw(){ce.onDone&&ce.onDone(),He.throw()}}}})}else ce=xe.map(Wa);return ce.onDone=()=>{ce.results=null,L.doneReadTxn()},ce.selectApplied=!0,ce}static transformEntryForSelect(m,g,L,A,C){if(m===t||m?.length===1&&m[0]===t){let B=a(H=>H?.key??H,"transform");return m===t?B:m.asArray?H=>[B(H)]:H=>({[t]:B(H)})}let N;A&&b&&!m?.every(B=>{let H;return typeof B=="object"?H=B.name:H=B,r[H]||H===t})&&(N=!0);let I,M=a(B=>{let H;if(B){if(qE=B,H=B.value||B.deref?.(),!H&&(B.key===void 0||B.deref)){if(B=kE(B.key??B,g,{transaction:Xr(g).getReadTxn(),lazy:m?.length<4},!1,Q=>Q),B?.then)return B.then(M);H=B?.value}if(N&&(B.metadataFlags&(au|cu)||B.expiresAt&&B.expiresAt<Date.now())){let Q=VE(B.key??B,B,g);if(Q?.then)return Q.then(M)}}if(H==null)return C?ld.SKIP:H;if(m&&!(m[0]==="*"&&m.length===1)){let Q,X=a((Me,se)=>{let he;typeof Me=="object"?he=Me.name:he=Me;let Dt=Wn?.[he],xe;if(Dt){let Ue=L?.[he];if(Ue)if(Ue.fromRecord)xe=Ue.fromRecord(H);else{let ce=jn(B.key);xe=Ue.get(ce),xe||(xe=[])}else xe=Dt(H,g,B);let jr=a(ce=>{if(ce&&typeof ce=="object"){let Wa=Dt.definition?.tableClass;I||(I={});let te=I[he]||(I[he]=(Wa||ze).transformEntryForSelect(he===Me?null:Me.select||Me,g,Ue,A));if(Array.isArray(ce)){let Fe;if(ce=ce.map(He=>{let ft=te(He);return ft?.then&&(Fe=!0),ft}),Fe){Q||(Q=[]),Q.push(Promise.all(ce).then(He=>se(He,he)));return}}else if(ce=te(ce),ce?.then){Q||(Q=[]),Q.push(ce.then(Fe=>se(Fe,he)));return}}se(ce,he)},"handleResolvedValue");xe?.then?(Q||(Q=[]),Q.push(xe.then(jr))):jr(xe);return}else xe=H[he],xe&&typeof xe=="object"&&he!==Me&&(xe=this.transformEntryForSelect(Me.select||Me,g,null)({value:xe}));se(xe,he)},"selectAttribute"),Je;if(typeof m=="string")X(m,Me=>{Je=Me});else if(Array.isArray(m))if(m.asArray)Je=[],m.forEach((Me,se)=>{Me==="*"?m[se]=H:X(Me,he=>Je[se]=he)});else{Je={};for(let Me of m)if(Me==="*")for(let se in H)Je[se]=H[se];else X(Me,(se,he)=>Je[he]=se)}else throw new ds.ClientError("Invalid select"+m);return Q?Promise.all(Q).then(()=>Je):Je}return H},"transform");return M}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||lt({table:n,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let g=JO(ze,this[Le]??null,function(N,I,M,B){try{let H=I.getValue?.(i);this.send({id:N,timestamp:M,value:H,version:I.version,type:I.type,beginTxn:B})}catch(H){rt.error(H)}},m.startTime,this[ns]);this[ns]&&(g.includeDescendants=!0,m.onlyChildren&&(g.onlyChildren=!0)),m.crossThreads===!1&&(g.crossThreads=!1),m.supportsTransactions&&(g.supportsTransactions=!0);let L=this[Le],A=m.previousCount;A>1e3&&(A=1e3);let C=m.startTime;if(this[ns]){if(C){if(A)throw new ds.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:I}of u.getRange({start:C,exclusiveStart:!0})){let M=Mr(I,i);if(M.tableId!==s)continue;let B=M.recordId;(L==null||KC(L,B))&&g.send({id:B,timestamp:N,...M}),g.startTime=N}}else if(A){let N=[];for(let{key:I,value:M}of u.getRange({start:"z",end:!1,reverse:!0}))try{let B=Mr(M);if(B.tableId!==s)continue;let H=B.recordId;if(L==null||KC(L,H)){let Q=B.getValue(i);if(N.push({id:H,timestamp:I,value:Q,version:B.version,type:B.type}),--A<=0)break}}catch(B){rt.error("Error getting history entry",I,B)}for(let I=N.length;I>0;)g.send(N[--I]);N[0]&&(g.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:I,version:M,localTime:B}of i.getRange({start:L??!1,end:L==null?void 0:[L,ro.MAXIMUM_KEY],versions:!0}))I&&g.send({id:N,version:M,timestamp:B,value:I})}else{A&&!C&&(C=0);let N=this[on]?.localTime;if(rt.trace("Subscription from",C,"from",L),C<N){let I=[],M=N;do{let B=u.get(M);if(B){m.omitCurrent=!0;let H=Mr(B),Q=H.getValue(i);I.push({id:L,value:Q,timestamp:M,...H}),M=H.previousLocalTime}else break;A&&A--}while(M>C&&A!==0);for(let B=I.length;B>0;)g.send(I[--B]);g.startTime=N}!m.omitCurrent&&this.doesExist()&&g.send({id:L,version:this[_d],timestamp:this[on]?.localTime,value:this})}return m.listener&&g.on("data",m.listener),g}doesExist(){return!!(this[ye]||this[kp])}publish(m,g){this._writePublish(m,g)}_writePublish(m,g){let L=Xr(this[me]),A=this[Le]||null;Ka(A);let C=this[me];L.addWrite({key:A,store:i,entry:this[on],nodeName:C?.nodeName,validate:()=>{this.validate(m)},before:Te.publish?.bind(this,C,A,m),beforeIntermediate:Ht.publish?.bind(this,C,A,m),commit:(N,I,M)=>{I===void 0&&h&&!E&&YE(),S(A,I?.value??null,I,I?.version||N,0,!0,C,I?.expiresAt,"message",!1,m)}})}validate(m){let g,L=a((A,C,N)=>{if(C.type&&A!=null)if(C.properties){typeof A!="object"&&(g||(g=[])).push(`Property ${N} must be an object${C.type?" ("+C.type+")":""}`);let I=C.properties;for(let M=0,B=I.length;M<B;M++){let H=I[M],Q=L(A[H.name],H,N+"."+H.name);Q&&(A[H.name]=Q)}}else switch(C.type){case"Int":(typeof A!="number"||A>>0!==A)&&(g||(g=[])).push(`Property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof A!="number"||!(Math.floor(A)===A&&Math.abs(A)<=9007199254740992))&&(g||(g=[])).push(`Property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof A!="number"&&(g||(g=[])).push(`Property ${N} must be a number`);break;case"ID":typeof A=="string"||A?.length>0&&A.every?.(I=>typeof I=="string")||(g||(g=[])).push(`Property ${N} must be a string, or an array of strings`);break;case"String":typeof A!="string"&&(g||(g=[])).push(`Property ${N} must be a string`);break;case"Boolean":typeof A!="boolean"&&(g||(g=[])).push(`Property ${N} must be a boolean`);break;case"Date":if(!(A instanceof Date)){if(typeof A=="string"||typeof A=="number")return new Date(A);(g||(g=[])).push(`Property ${N} must be a Date`)}break;case"BigInt":if(typeof A!="bigint"){if(typeof A=="string"||typeof A=="number")return BigInt(A);(g||(g=[])).push(`Property ${N} must be a bigint`)}break;case"Bytes":A instanceof Uint8Array||(g||(g=[])).push(`Property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(A)){if(C.elements)for(let I=0,M=A.length;I<M;I++){let B=A[I],H=L(B,C.elements,N+"[*]");H&&(A[I]=H)}}else(g||(g=[])).push(`Property ${N} must be a Buffer or Uint8Array`);break}C.nullable===!1&&A==null&&(g||(g=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let A=0,C=p.length;A<C;A++){let N=p[A];if(N.relationship)continue;let I=L(m[N.name],N,N.name);I&&(m[N.name]=I)}if(g)throw new ds.ClientError(g.join(". "))}getUpdatedTime(){return this[_d]}wasLoadedFromSource(){return b?!!this[Vp]:void 0}static async addAttributes(m){let g=p.slice(0);for(let L of m){if(!L.name)throw new ds.ClientError("Attribute name is required");if(L.name.match(/[`/]/))throw new ds.ClientError("Attribute names cannot include backticks or forward slashes");g.push(L)}return lt({table:n,database:c,schemaDefined:_,attributes:g}),ze.indexingOperation}static async removeAttributes(m){let g=p.filter(L=>!m.includes(L.name));return lt({table:n,database:c,schemaDefined:_,attributes:g}),ze.indexingOperation}static getRecordCount(m){let g=i.getStats().entryCount,L=5e3,A=1e3,C;g>L&&!m?.exactCount&&(C=A);let N=0;for(let{value:I}of i.getRange({start:!0,lazy:!0,limit:C}))I!=null&&N++;if(C){let I=N;N=0;for(let{value:he}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:C}))he!=null&&N++;let M=C*2,B=(N+I)/M,H=Math.pow((N-I+1)/C/2,2)+B*(1-B)/M,Q=Math.max(Math.sqrt(H)*g,1),X=Math.round(B*g),Je=Math.max(X-1.96*Q,0),Me=Math.min(X+1.96*Q,g),se=Math.pow(10,Math.round(Math.log10(Q)));return se>X&&(se=se/10),N=Math.round(X/se)*se,{recordCount:N,estimatedRange:[Math.round(Je),Math.round(Me)]}}return{recordCount:N}}static updatedAttributes(){Wn=this.propertyResolvers={$id:(m,g,L)=>L.key,$updatedtime:(m,g,L)=>L.version,$record:(m,g,L)=>L?{value:m}:m};for(let m of this.attributes){m.resolve=null;let g=m.relationship;if(g)if(nA=!0,g.to)m.elements?.definition?(Wn[m.name]=m.resolve=(L,A,C)=>{let N=L[g.from?g.from:t],I=m.elements.definition.tableClass;return C?dc({attribute:g.to,value:N},Xr(A).getReadTxn(),!1,I).asArray:I.search([{attribute:g.to,value:N}],A).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${n}" must have an array type referencing a table as the elements`);else if(g.from){let L=m.definition||m.elements?.definition;L?(Wn[m.name]=m.resolve=(A,C,N)=>{let I=A[g.from];if(I!==void 0){if(m.elements){let M,B=I.map(H=>{let Q=N?L.tableClass.primaryStore.getEntry(H,{transaction:Xr(C).getReadTxn()}):L.tableClass.get(H,C);return Q?.then&&(M=!0),Q});return g.filterMissing?M?Promise.all(B).then(H=>H.filter(WC)):B.filter(WC):M?Promise.all(B):B}return N?L.tableClass.primaryStore.getEntry(I,{transaction:Xr(C).getReadTxn()}):L.tableClass.get(I,C)}},m.set=(A,C)=>{if(Array.isArray(C)){let N=C.map(I=>I[Le]||I[L.tableClass.primaryKey]);A[g.from]=N}else{let N=C[Le]||C[L.tableClass.primaryKey];A[g.from]=N}},m.resolve.definition=m.definition||m.elements?.definition):console.error(`The relationship property "${m.name}" in table "${n}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${n}" must use either "from" or "to" arguments`)}Jl(this,this)}static async deleteHistory(m=0){let g;for(let{key:L,value:A}of u.getRange({start:0,end:m}))await uu(),Mr(A).tableId===s&&(g=u.remove(L));await g}static async*getHistory(m=0,g=1/0){for(let{key:L,value:A}of u.getRange({start:m,end:g})){await uu();let C=Mr(A);C.tableId===s&&(yield{id:C.recordId,localTime:L,version:C.version,type:C.type,value:C.getValue(i),user:C.user})}}static async getHistoryOfRecord(m){let g=[],L=i.getEntry(m);if(!L)return g;let A=L.localTime,C=0;do{await uu();let N=u.get(A);if(N){let I=Mr(N);g.push({id:I.recordId,localTime:A,version:I.version,type:I.type,value:I.getValue(i),user:I.user}),A=I.previousLocalTime}else break}while(C<1e3&&A);return g.reverse()}static cleanup(){W?.remove()}}ze.updatedAttributes();let wx=ze.prototype;return wx[VC]=!0,d&&ze.setTTLExpiration(d/1e3),V&&Cx(),ze;function Ul(K,m,g){let L;for(let A in r){let C=r[A],N=C.isIndexing,I=g?.[A],M=m?.[A];if(I===M&&!N)continue;L=!0;let B=C.indexNulls,H=(0,_u.getIndexedValues)(M,B);if(H){kC&&C.prefetch(H.map(Q=>({key:Q,value:K})),YC);for(let Q=0,X=H.length;Q<X;Q++)C.remove(H[Q],K)}if(H=(0,_u.getIndexedValues)(I,B),H){kC&&C.prefetch(H.map(Q=>({key:Q,value:K})),YC);for(let Q=0,X=H.length;Q<X;Q++)C.put(H[Q],K)}}return L}a(Ul,"updateIndices");function Ka(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>$C)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,ro.writeKey)(K,h2,0)>$C)throw new Error("Primary key size is too large: "+K.length);return!0}a(Ka,"checkValidId");function kE(K,m,g,L,A){let C=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),g.transaction?.isDone)return A(null,K);let N=i.getEntry(K,g);return N&&m&&(N?.version>(m.lastModified||0)&&(m.lastModified=N.version),N?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=N.localTime)),A(N,K)},"whenPrefetched");return L?C():ne>0?(ne--,C()):new Promise((N,I)=>{ne===0?(ne--,i.prefetch([K],()=>{M(),B()})):(re.push(K),be.push(B),re.length>Ix&&(ne--,M()));function M(){if(re.length>0){let H=be;i.prefetch(re,()=>{ne===-1?M():ne++;for(let Q of H)Q()}),re=[],be=[],ct>2&&ct--}else ne=ct,ct<yx&&ct++}a(M,"prefetch");function B(){try{N(C())}catch(H){I(H)}}a(B,"load")})}a(kE,"loadLocalRecord");function Pl(K){if(!K)return;let m=K.role.permission;if(m.super_user)return m2;let g=m[c],L,A=g?.tables;if(A)return A[n];if(c==="data"&&(L=m[n])&&!L.tables)return L}a(Pl,"getTablePermissions");function VE(K,m,g,L){if(b){let A;if(g.noCache?A=!0:(m?(!m.value||m.metadataFlags&(au|cu)||m.expiresAt&&m.expiresAt<Date.now())&&(A=!0):A=!0,_s(!A,"cache-hit",n)),A){let C=iA(K,m,g).then(N=>(N?.value?.[ye]&&rt.error("Can not assign a record with a record property"),g&&(N?.version>(g.lastModified||0)&&(g.lastModified=N.version),g.lastRefreshed=Date.now()),N));if(g?.onlyIfCached||m?.value&&L?.allowStaleWhileRevalidate?.(m,K)){if(C.catch(N=>rt.warn(N)),g?.onlyIfCached&&!L.doesExist())throw new ds.ServerError("Entry is not cached",504);return}else return C}}}a(VE,"ensureLoadedFromSource");function Xr(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let g=m.next;if(!g)return m=m.next=new Mi,m.lmdbDb=i,m;m=g}while(!0)}else return new Zl}a(Xr,"txnForContext");function $E(K,m,g){if(!K)return;qE=K;let L=K.value||K.deref?.()||(qE=i.getEntry(K.key))?.value;if(typeof m=="object"){let C=Wn,N=L;for(let I=0,M=m.length;I<M;I++){let B=m[I],H=C?.[B];N=H?H(N,g):N?.[B],C=H?.definition?.tableClass?.propertyResolvers}return N}let A=Wn[m];return A?A(L,g):L[m]}a($E,"getAttributeValue");async function iA(K,m,g){let L=m?.metadataFlags,A=m?.version,C,N;if(!i.attemptLock(K,A,()=>{clearTimeout(N);let H=i.getEntry(K);!H||!H.value||H.metadataFlags&(au|cu)?C(iA(K,i.getEntry(K),g)):C(H)}))return new Promise(H=>{C=H,N=setTimeout(()=>{i.unlock(K,A)},E2)});let I=m?.value,M={requestContext:g,replacingRecord:I,replacingVersion:A,source:null,resourceCache:g?.resourceCache},B=g?.responseHeaders;return new Promise((H,Q)=>{let X;Yp(Qe(M,async Je=>{let Me=performance.now(),se,he,Dt;try{for(let ce of ze.sources)if(ce.get&&(!ce.get.reliesOnPrototype||ce.prototype.get)&&(M.source=ce,se=await ce.get(K,M),se))break;Dt=L&au;let Ue=M.lastModified||Dt&&A;he=Dt||Ue>A||!I,Ue||(Ue=(0,_u.getNextMonotonicTime)());let jr=performance.now()-Me;if(qr(jr,"cache-resolution",n),B&&B.append("Server-Timing",`cache-resolve;dur=${jr.toFixed(2)}`),Je.timestamp=Ue,d&&!M.expiresAt&&(M.expiresAt=Date.now()+d),se){if(typeof se!="object")throw new Error("Only objects can be cached and stored in tables");typeof se.toJSON=="function"&&(se=se.toJSON()),t&&se[t]!==K&&(se[t]=K)}X=!0,H({version:Ue,value:se})}catch(Ue){Ue.message+=` while resolving record ${K} for ${n}`,I&&((Ue.code==="ECONNRESET"||Ue.code==="ECONNREFUSED"||Ue.code==="EAI_AGAIN")&&!g?.mustRevalidate||g?.staleIfError&&(Ue.statusCode===500||Ue.statusCode===502||Ue.statusCode===503||Ue.statusCode===504))?(H({version:A,value:I}),rt.trace(Ue.message,"(returned stale record)")):Q(Ue),M.transaction.abort();return}if(g?.noCacheStore){M.transaction.abort();return}Xr(M).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(Ue,jr)=>{if(jr?.version!==A)return;let ce=Ul(K,I,se);se?(Ht.put?.(M,K,se),S(K,se,jr,Ue,0,E&&he||null,M,M.expiresAt,"put",!!Dt)):(Ht.delete?.(M,K),E||h?S(K,null,jr,Ue,0,E&&he||null,M,0,"delete",!!Dt):i.remove(K,A))}})}),()=>{i.unlock(K,A)},Je=>{i.unlock(K,A),X&&rt.error("Error committing cache update",Je)})})}a(iA,"getFromSource");function YE(){if(bs!==sA&&(sA=bs,(0,to.getWorkerIndex)()===(0,to.getWorkerCount)()-1)){if(Ml&&clearTimeout(Ml),!bs)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/bs)*bs+K.getTime(),g=a(L=>{rt.trace(`Scheduled next cleanup scan at ${new Date(L)}ms`),Ml=setTimeout(()=>x=x.then(async()=>{if(g(Math.max(L+bs,Date.now())),i.rootStore.status!=="open"){clearTimeout(Ml);return}let A=50,C=new Array(A),N=0;rt.trace(`Starting cleanup scan for ${n}`);try{let I=0;for(let{key:M,value:B,version:H,expiresAt:Q}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let X;B===null&&!E&&H+f2<Date.now()?X=i.remove(M,H):Q&&Q+f<Date.now()&&(X=ze.evict(M,B,H),I++),X&&(await C[N],C[N]=X.catch(Je=>{rt.error("Cleanup error",Je)}),++N>=A&&(N=0)),await uu()}rt.trace(`Finished cleanup scan for ${n}, evicted ${I} entries`)}catch(I){rt.trace(`Error in cleanup scan for ${n}:`,I)}}),Math.min(L-Date.now(),2147483647)).unref()},"startNextTimer");g(m)}}a(YE,"scheduleCleanup");function oA(){W=u?.addDeleteRemovalCallback(s,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(oA,"addDeleteRemoval");function Cx(){(0,to.getWorkerIndex)()===0&&setInterval(async()=>{try{let K=V.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${V} must be indexed`);for(let{value:g}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let L=i.getEntry(g);L?.value?.[K]<Date.now()&&ze.evict(g,L.value,L.version),await uu()}}catch(K){rt.error("Error in evicting old records",K)}},d2).unref()}a(Cx,"runRecordExpirationEviction")}function $p(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 YC(){}function p2(e){zC=e}function dd(e,t){let r=t?.type;return e===null?e:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Date"?(typeof e!="number"&&!S2.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,fd.autoCast)(e):e}function KC(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}function Yp(e,t,r){return e?.then?e.then(t,r):t(e)}function lu(e,t){e[on]=t,e[ye]=t?.value??null,e[_d]=t?.version}function WC(e){return e!=null}var xs,ld,_u,QC,Eu,ds,du,fu,rt,ro,to,fd,_2,zC,d2,f2,kC,E2,_d,VC,on,kp,Vp,ou,au,cu,h2,$C,m2,Kle,S2,uu,hd=ge(()=>{xs=U(w()),ld=require("lmdb"),_u=U(Lr()),QC=require("lodash");Is();_h();Eu=U(j());ZO();ds=U(Z()),du=U(bn()),fu=U(Ls());pe();t_();rt=U(q());jl();Ui();ro=require("ordered-binary"),to=U(Ze());Fo();fd=U(z());Sc();Cn();_2=new Uint8Array(9);_2[8]=192;d2=6e4,f2=864e5;Eu.initSync();kC=Eu.get(xs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),E2=1e4,_d=Symbol.for("version"),VC=Symbol.for("incremental-update"),on=Symbol("entry"),kp=Symbol("is-saving"),Vp=Symbol("loaded-from-source"),ou={isNotification:!0,ensureLoaded:!1},au=1,cu=8,h2=Buffer.allocUnsafeSlow(8192),$C=1978,m2={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},Kle=(0,fd.convertToMS)(Eu.get(xs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(Ed,"makeTable");a($p,"attributesAsObject");a(YC,"noop");a(p2,"setServerUtilities");S2=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(dd,"coerceType");a(KC,"isDescendantId");uu=a(()=>new Promise(setImmediate),"rest");a(Yp,"when");a(lu,"updateResource");a(WC,"exists")});var Ge={};$e(Ge,{database:()=>Kc,databases:()=>st,dropDatabase:()=>ep,dropTableMeta:()=>b2,getDatabases:()=>Ms,getTables:()=>T2,onUpdatedTable:()=>Xp,readMetaDb:()=>hu,resetDatabases:()=>g2,table:()=>lt,tables:()=>Vr});function T2(){return gd||Ms(),Vr||{}}function Ms(){if(gd)return st;gd=!0,ua=new Map;let e=(0,jt.getHdbBasePath)()&&(0,je.join)((0,jt.getHdbBasePath)(),$r.DATABASES_DIR_NAME),t=(0,jt.get)($r.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,jt.get)($r.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,kr.existsSync)(e)?e:(0,je.join)((0,jt.getHdbBasePath)(),$r.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,kr.existsSync)(e))for(let r of(0,kr.readdirSync)(e,{withFileTypes:!0})){let s=(0,je.basename)(r.name,".mdb");r.isFile()&&(0,je.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&hu((0,je.join)(e,r.name),null,s)}if((0,kr.existsSync)((0,ca.getBaseSchemaPath)())){for(let r of(0,kr.readdirSync)((0,ca.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,je.join)((0,ca.getBaseSchemaPath)(),r.name),n=(0,je.join)((0,ca.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,kr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,je.extname)(i.name).toLowerCase()===".mdb"){let o=(0,je.join)(n,i.name);hu((0,je.join)(s,i.name),(0,je.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,kr.existsSync)(n))for(let o of(0,kr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,je.extname)(o.name).toLowerCase()===".mdb"&&hu((0,je.join)(n,o.name),(0,je.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,je.join)(c.path,(0,je.basename)(o+".mdb"));(0,kr.existsSync)(u)&&hu(u,o,r,null,!0)}}for(let r in st){let s=ua.get(r);if(s){let n=st[r];r.includes("delete")&&Es.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Es.trace(`delete table class ${i}`),delete n[i])}else if(delete st[r],r==="data"){for(let n in Vr)delete Vr[n];delete Vr[Rd]}}return ua=null,st}}function g2(){gd=!1;for(let[,e]of li)e.needsDeletion=!0;Ms();for(let[e,t]of li)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),li.delete(e));return st}function hu(e,t,r=zp,s,n){let i=new Wp.default(e,!1);try{let o=li.get(e);o?o.needsDeletion=!1:(o=(0,pd.open)(i),li.set(e,o));let c=new so.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(md.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,kr.existsSync)(s)&&(i.path=s,_=(0,pd.open)(i),_.isLegacy=!0):_=__(o));let l=ZC(r),d=l[Rd],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[p,S]=E.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let R=f.get(p);R||f.set(p,R={attributes:[]}),(S==null||h.is_hash_attribute)&&(R.primary=h),S!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:p,primary:S}=h;if(!S){for(let W of p)if(W.is_hash_attribute||W.isPrimaryKey){S=W;break}if(!S){Es.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let R=l[E],O={},b=[],P,$,x=typeof S.audit=="boolean"?S.audit:(0,jt.get)($r.CONFIG_PARAMS.LOGGING_AUDITLOG),D=S.trackDeletes,Y=S.expiration,V=S.eviction;if(R)O=R.indices,b=R.attributes,R.schemaVersion++;else{P=S.tableId,P?P>=(u.get(aa)||0)&&u.putSync(aa,P+1):(S.tableId=P=u.get(aa),P||(P=1),u.putSync(aa,P+1),u.putSync(S.key,S));let W=new so.default(!S.is_hash_attribute,S.is_hash_attribute);$=u_(o.openDB(S.key,W)),$.rootStore=o,$.tableId=P}for(let W of p){W.attribute=W.name;try{if(!W.is_hash_attribute&&(W.indexed||W.attribute&&!W.name)){if(!O[W.name]){let be=new so.default(!W.is_hash_attribute,W.is_hash_attribute);O[W.name]=o.openDB(W.key,be),O[W.name].indexNulls=W.indexNulls}let re=b.find(be=>be.name===W.name);re?b.splice(b.indexOf(re),1,W):b.push(W)}}catch(re){Es.error("Error trying to update attribute",W,b,O,re)}}if(!R){R=eL(l,E,Ed({primaryStore:$,auditStore:_,audit:x,expirationMS:Y&&Y*1e3,evictionMS:V&&V*1e3,trackDeletes:D,tableName:E,tableId:P,primaryKey:S.name,databasePath:n?r+"/"+E:r,databaseName:r,indices:O,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),R.schemaVersion=1;for(let W of Jp)W(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function ZC(e){let t=st[e];if(t||(e==="data"?t=st[e]=Vr:e==="system"?Object.defineProperty(st,"system",{value:t=Object.create(null),configurable:!0}):t=st[e]=Object.create(null)),ua&&!ua.has(e)){let r=new Set;t[Rd]=r,ua.set(e,r)}return t}function eL(e,t,r){return e[t]=r,r}function Kc({database:e,table:t}){e||(e=zp),Ms();let r=ZC(e),s=(0,je.join)((0,jt.getHdbBasePath)(),$r.DATABASES_DIR_NAME),n=(0,jt.get)($r.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(n.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&n[e]?.tables?.[t]?.path;s=i||n[e]?.path||process.env.STORAGE_PATH||(0,jt.get)($r.CONFIG_PARAMS.STORAGE_PATH)||((0,kr.existsSync)(s)?s:(0,je.join)((0,jt.getHdbBasePath)(),$r.LEGACY_DATABASES_DIR_NAME));let o=(0,je.join)(s,(i?t:e)+".mdb"),c=li.get(o);if(!c){let u=new Wp.default(o,!1);c=(0,pd.open)(u),li.set(o,c)}return c}async function ep(e){if(!st[e])throw new Error("Schema does not exist");let t=st[e];for(let r in t){let n=t[r].primaryStore.rootStore;li.delete(n.path),n.status==="open"&&(await n.close(),await JC.remove(n.path))}if(e==="data"){for(let r in Vr)delete Vr[r];delete Vr[Rd]}delete st[e]}function lt({table:e,database:t,expiration:r,eviction:s,scanInterval:n,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=zp);let l=Kc({database:t,table:e}),d=st[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,p,S;u==null&&(u=!0);let R=new so.default(!1);for(let D of i)D.attribute?(D.name=D.attribute,D.indexed=!0):D.attribute=D.name,D.expiresAt&&(D.indexed=!0);let O,b;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let D=l.auditStore;D||(D=__(l)),h=i.find(re=>re.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,jt.get)($r.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),s&&(h.eviction=s),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),Es.trace(`${e} table loading, opening primary store`);let Y=new so.default(!1,!0),V=e+"/",W=u_(l.openDB(V,Y));W.rootStore=l,S=l.dbisDb=l.openDB(md.INTERNAL_DBIS_NAME,R),W.tableId=S.get(aa),W.tableId||(W.tableId=1),S.putSync(aa,W.tableId+1),h.tableId=W.tableId,f=eL(d,e,Ed({primaryStore:W,auditStore:D,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:s&&s*1e3,primaryKey:E,tableName:e,tableId:W.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,O=!0,x(),S.put(V,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(md.INTERNAL_DBIS_NAME,R)),f.dbisDB=S;let P=[];for(let{key:D,value:Y}of S.getRange({start:!0})){let[V,W]=D.toString().split("/");if(W===""&&(W=Y.name),W){if(V!==e)continue}else W=V;if(!i.find(be=>be.name===W)?.indexed&&Y.indexed&&!Y.isPrimaryKey){x(),O=!0,S.remove(D);let be=f.indices[V];be&&P.push(be)}}let $=[];try{for(let D of i||[]){if(D.relationship)continue;let Y=e+"/"+(D.name||"");Object.defineProperty(D,"key",{value:Y,configurable:!0});let V=S.get(Y);if(D.isPrimaryKey){if(V=V||S.get(Y=e+"/")||{},o!==f.audit||(+r||void 0)!==(+V.expiration||void 0)||(+s||void 0)!==(+V.eviction||void 0)){let re=Object.assign({},V);typeof o=="boolean"&&(o&&f.enableAuditing(o),re.audit=o),r&&(re.expiration=+r),s&&(re.eviction=+s),O=!0,x(),S.put(Y,re)}continue}V?.attribute&&!V.name&&(V.indexed=!0);let W=!V||V.type!==D.type||V.indexed!==D.indexed||JSON.stringify(V.attributes)!==JSON.stringify(D.attributes)||JSON.stringify(V.elements)!==JSON.stringify(D.elements);if(D.indexed){let re=new so.default(!0,!1),be=l.openDB(Y,re);(W||V.indexingPID&&V.indexingPID!==process.pid||V.restartNumber<mu.workerData?.restartNumber)&&(O=!0,x(),V=S.get(Y),(W||V.indexingPID&&V.indexingPID!==process.pid||V.restartNumber<mu.workerData?.restartNumber)&&(O=!0,D.lastIndexedKey=V?.lastIndexedKey||!1,D.indexingPID=process.pid,be.isIndexing=!0,Object.defineProperty(D,"dbi",{value:be}),D.indexNulls===void 0&&(D.indexNulls=!0),$.push(D)),S.put(Y,D)),V?.indexNulls&&D.indexNulls===void 0&&(D.indexNulls=!0),be.indexNulls=D.indexNulls,p[D.name]=be}else W&&(O=!0,x(),S.put(Y,D))}}finally{b&&b()}if(O&&(f.schemaVersion++,f.updatedAttributes()),Es.trace(`${e} table loading, running index`),$.length>0||P.length>0?f.indexingOperation=O2(f,$,P):O&&Sd.signalSchemaChange(new Td.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,O)for(let D of Jp)D(f,_!=="cluster");return(r||s||n)&&f.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),Es.trace(`${e} table loaded`),f;function x(){b||l.transactionSync(()=>({then(D){b=D}}))}a(x,"startTxn")}async function O2(e,t,r){try{let s=e.schemaVersion;await Sd.signalSchemaChange(new Td.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:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,n=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,XC.getIndexedValues)(l[h]);if(p)for(let S=0,R=p.length;S<R;S++)E.dbi.put(p[S],_)}}),n.then(()=>u--,f=>{u--,Es.error(f)}),mu.workerData&&mu.workerData.restartNumber!==jC.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>R2?await n:u>A2&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,n=e.dbisDB.put(_.key,_)}await n,await Sd.signalSchemaChange(new Td.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Es.error("Error in indexing",s)}}function b2({table:e,database:t}){let r=Kc({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 Xp(e){Jp.push(e)}var jt,md,pd,je,kr,ca,so,Wp,$r,JC,Qp,XC,Sd,Td,mu,Es,jC,zp,Rd,Vr,st,aa,Jp,gd,li,ua,R2,A2,pe=ge(()=>{jt=U(j()),md=U(Et()),pd=require("lmdb"),je=require("path"),kr=require("fs"),ca=U(We());hd();so=U(d_()),Wp=U(E_()),$r=U(w()),JC=U(require("fs-extra")),Qp=require("../index"),XC=U(Lr()),Sd=U(bn()),Td=U(Ls()),mu=require("worker_threads"),Es=U(q()),jC=U(Ze());Fo();Sc();zp="data",Rd=Symbol("defined-tables");(0,jt.initSync)();Vr=Object.create(null),st=Object.create(null);(0,Qp._assignPackageExport)("databases",st);(0,Qp._assignPackageExport)("tables",Vr);aa=Symbol.for("next-table-id"),Jp=[],li=new Map;a(T2,"getTables");a(Ms,"getDatabases");a(g2,"resetDatabases");a(hu,"readMetaDb");a(ZC,"ensureDB");a(eL,"setTable");a(Kc,"database");a(ep,"dropDatabase");a(lt,"table");R2=1e3,A2=10;a(O2,"runIndexing");a(b2,"dropTableMeta");a(Xp,"onUpdatedTable")});var z=T((t_e,EL)=>{"use strict";var _i=require("path"),iL=require("fs-extra"),_r=q(),tL=require("fs-extra"),Ad=require("os"),N2=require("net"),y2=require("recursive-iterator"),nt=w(),I2=$A(),rL=require("papaparse"),Od=require("moment"),{inspect:w2}=require("util"),sL=require("is-number"),e_e=require("lodash"),C2=require("minimist"),L2=require("https"),D2=require("http"),{hdb_errors:bd}=Z(),M2=/^((\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)))$/,oL=require("util").promisify(setTimeout),U2=100,P2=5,v2="",B2=4,nL={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};EL.exports={isEmpty:Yr,isEmptyOrZeroLength:an,arrayHasEmptyValues:F2,arrayHasEmptyOrZeroLengthValues:G2,buildFolderPath:q2,isBoolean:aL,errorizeMessage:H2,stripFileExtension:V2,autoCast:$2,autoCastJSON:cL,autoCastJSONDeep:Zp,removeDir:Y2,compareVersions:K2,isCompatibleDataVersion:W2,escapeRawValue:Q2,unescapeValue:z2,stringifyProps:J2,timeoutPromise:j2,isClusterOperation:e4,getClusterUser:r4,checkGlobalSchemaTable:t4,getHomeDir:lL,getPropsFilePath:X2,promisifyPapaParse:s4,removeBOM:_L,createEventPromise:n4,checkProcessRunning:i4,checkSchemaTableExist:o4,checkSchemaExists:dL,checkTableExists:fL,getStartOfTomorrowInSeconds:a4,getLimitKey:c4,isObject:k2,isNotEmptyAndHasValue:x2,autoCasterIsNumberCheck:uL,backtickASTSchemaItems:u4,isPortTaken:Z2,createForkArgs:l4,autoCastBoolean:_4,async_set_timeout:oL,getTableHashAttribute:d4,doesSchemaExist:f4,doesTableExist:E4,stringifyObj:h4,ms_to_time:m4,changeExtension:p4,getEnvCliRootPath:eS,noBootFile:S4,httpRequest:T4,transformReq:g4,convertToMS:R4,PACKAGE_ROOT:nt.PACKAGE_ROOT};function H2(e){return e instanceof Error?e:new Error(e)}a(H2,"errorizeMessage");function Yr(e){return e==null}a(Yr,"isEmpty");function x2(e){return!Yr(e)&&(e||e===0||e===""||aL(e))}a(x2,"isNotEmptyAndHasValue");function an(e){return Yr(e)||e.length===0||e.size===0}a(an,"isEmptyOrZeroLength");function F2(e){if(Yr(e))return!0;for(let t=0;t<e.length;t++)if(Yr(e[t]))return!0;return!1}a(F2,"arrayHasEmptyValues");function G2(e){if(an(e))return!0;for(let t=0;t<e.length;t++)if(an(e[t]))return!0;return!1}a(G2,"arrayHasEmptyOrZeroLengthValues");function q2(...e){try{return e.join(_i.sep)}catch{console.error(e)}}a(q2,"buildFolderPath");function aL(e){return Yr(e)?!1:e===!0||e===!1}a(aL,"isBoolean");function k2(e){return Yr(e)?!1:typeof e=="object"}a(k2,"isObject");function V2(e){return an(e)?v2:e.slice(0,-B2)}a(V2,"stripFileExtension");function $2(e){return Yr(e)||e===""||typeof e!="string"?e:nL[e]!==void 0?nL[e]:uL(e)===!0?Number(e):M2.test(e)?new Date(e):e}a($2,"autoCast");function cL(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(cL,"autoCastJSON");function Zp(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=Zp(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=Zp(r);s!==r&&(e[t]=s)}return e}else return cL(e)}a(Zp,"autoCastJSONDeep");function uL(e){if(e.startsWith("0.")&&sL(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&sL(e))}a(uL,"autoCasterIsNumberCheck");async function Y2(e){if(an(e))throw new Error(`Directory path: ${e} does not exist`);try{await tL.emptyDir(e),await tL.remove(e)}catch(t){throw _r.error(`Error removing files in ${e} -- ${t}`),t}}a(Y2,"removeDir");function K2(e,t){if(an(e)){_r.info("Invalid current version sent as parameter.");return}if(an(t)){_r.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 _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(K2,"compareVersions");function W2(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(W2,"isCompatibleDataVersion");function Q2(e){if(Yr(e))return e;let t=String(e);return t==="."?nt.UNICODE_PERIOD:t===".."?nt.UNICODE_PERIOD+nt.UNICODE_PERIOD:t.replace(nt.FORWARD_SLASH_REGEX,nt.UNICODE_FORWARD_SLASH)}a(Q2,"escapeRawValue");function z2(e){if(Yr(e))return e;let t=String(e);return t===nt.UNICODE_PERIOD?".":t===nt.UNICODE_PERIOD+nt.UNICODE_PERIOD?"..":String(e).replace(nt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(z2,"unescapeValue");function J2(e,t){if(Yr(e))return _r.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+Ad.EOL}!an(s)&&s[0]===";"?r+=" "+s+n+Ad.EOL:an(s)||(r+=s+"="+n+Ad.EOL)}catch{_r.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(J2,"stringifyProps");function lL(){let e;try{e=Ad.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(lL,"getHomeDir");function X2(){let e=_i.join(lL(),nt.HDB_HOME_DIR_NAME,nt.BOOT_PROPS_FILE_NAME);return iL.existsSync(e)||(e=_i.join(__dirname,"../","hdb_boot_properties.file")),e}a(X2,"getPropsFilePath");function j2(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(j2,"timeoutPromise");async function Z2(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=N2.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(Z2,"isPortTaken");function e4(e){try{return nt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){_r.error(`Error checking operation against cluster ops ${t}`)}return!1}a(e4,"isClusterOperation");function t4(e,t){let r=(pe(),ee(Ge)).getDatabases();if(!r[e])return bd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return bd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(t4,"checkGlobalSchemaTable");function r4(e,t){if(Yr(t)){_r.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Yr(e)||an(e)){_r.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){_r.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){_r.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(r4,"getClusterUser");function s4(){rL.parsePromise=function(e,t,r){return new Promise(function(s,n){rL.parse(e,{header:!0,transformHeader:_L,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(s4,"promisifyPapaParse");function _L(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(_L,"removeBOM");function n4(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;_r.info(`Got cluster status event response: ${w2(n)}`);try{i.cancel()}catch{_r.error("Error trying to cancel timeout.")}s(n)})})}a(n4,"createEventPromise");async function i4(e){let t=!0,r=0;do await oL(U2*r++),(await I2.findPs(e)).length>0&&(t=!1);while(t&&r<P2);if(t)throw new Error(`process ${e} was not started`)}a(i4,"checkProcessRunning");function o4(e,t){let r=dL(e);if(r)return r;let s=fL(e,t);if(s)return s}a(o4,"checkSchemaTableExist");function dL(e){let{getDatabases:t}=(pe(),ee(Ge));if(!t()[e])return bd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(dL,"checkSchemaExists");function fL(e,t){let{getDatabases:r}=(pe(),ee(Ge));if(!r()[e][t])return bd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(fL,"checkTableExists");function a4(){let e=Od().utc().add(1,nt.MOMENT_DAYS_TAG).startOf(nt.MOMENT_DAYS_TAG).unix(),t=Od().utc().unix();return e-t}a(a4,"getStartOfTomorrowInSeconds");function c4(){return Od().utc().format("DD-MM-YYYY")}a(c4,"getLimitKey");function u4(e){try{let t=new y2(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){_r.error("Got an error back ticking items."),_r.error(t)}}a(u4,"backtickASTSchemaItems");function l4(e){return[e]}a(l4,"createForkArgs");function _4(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(_4,"autoCastBoolean");function d4(e,t){let{getDatabases:r}=(pe(),ee(Ge)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(d4,"getTableHashAttribute");function f4(e){let{getDatabases:t}=(pe(),ee(Ge));return t()[e]!==void 0}a(f4,"doesSchemaExist");function E4(e,t){let{getDatabases:r}=(pe(),ee(Ge));return r()[e]?.[t]!==void 0}a(E4,"doesTableExist");function h4(e){try{return JSON.stringify(e)}catch{return e}}a(h4,"stringifyObj");function m4(e){let t=Od.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(m4,"ms_to_time");function p4(e,t){let r=_i.basename(e,_i.extname(e));return _i.join(_i.dirname(e),r+t)}a(p4,"changeExtension");function eS(){if(process.env[nt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[nt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=C2(process.argv);if(e[nt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[nt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(eS,"getEnvCliRootPath");var jp;function S4(){if(jp)return jp;let e=eS();eS()&&iL.pathExistsSync(_i.join(e,nt.HDB_CONFIG_FILE))&&(jp=!0)}a(S4,"noBootFile");function T4(e,t){let r;return e.protocol==="http:"?r=D2:r=L2,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(T4,"httpRequest");function g4(e){if(!e.schema&&!e.database){e.schema=nt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(g4,"transformReq");function R4(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(R4,"convertToMS")});var j=T((s_e,SL)=>{"use strict";var tS=require("fs-extra"),Fs=require("path"),hL=require("os"),A4=require("properties-reader"),Su=q(),pu=z(),ie=w(),Nd=xr(),O4="Error initializing environment manager",yd="BOOT_PROPS_FILE_PATH",mL=!1,b4={[ie.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ie.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ln={};SL.exports={BOOT_PROPS_FILE_PATH:yd,getHdbBasePath:N4,setHdbBasePath:y4,get:pL,initSync:w4,setProperty:Se,initTestEnvironment:C4};function N4(){return Ln[ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(N4,"getHdbBasePath");function y4(e){Ln[ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(y4,"setHdbBasePath");function pL(e){let t=Nd.getConfigValue(e);return t===void 0?Ln[e]:t}a(pL,"get");function Se(e,t){b4[e]&&(Ln[e]=t),Nd.updateConfigObject(e,t)}a(Se,"setProperty");function I4(){let e;try{e=pu.getPropsFilePath(),tS.accessSync(e,tS.constants.F_OK|tS.constants.R_OK),mL=!0;let t=A4(e);return Ln[ie.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ie.HDB_SETTINGS_NAMES.INSTALL_USER),Ln[ie.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ie.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ln[yd]=e,!0}catch{return Su.trace(`Environment manager found no properties file at ${e}`),!1}}a(I4,"doesPropFileExist");function w4(e=!1){try{(mL||I4()||pu.noBootFile())&&(Nd.initConfig(e),Ln[ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Nd.getConfigValue(ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Su.error(O4),Su.error(t),console.error(t),process.exit(1)}}a(w4,"initSync");function C4(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=Fs.join(__dirname,"../../","unitTests");Ln[yd]=Fs.join(u,"hdb_boot_properties.file"),Se(ie.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Fs.join(u,"settings.test")),Se(ie.HDB_SETTINGS_NAMES.INSTALL_USER,hL.userInfo()?hL.userInfo().username:void 0),Se(ie.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,Fs.join(u,"envDir","utility","keys","privateKey.pem")),Se(ie.HDB_SETTINGS_NAMES.CERT_KEY,Fs.join(u,"envDir","utility","keys","certificate.pem")),Se(ie.CONFIG_PARAMS.TLS_PRIVATEKEY,Fs.join(u,"envDir","utility","keys","privateKey.pem")),Se(ie.CONFIG_PARAMS.TLS_CERTIFICATE,Fs.join(u,"envDir","utility","keys","certificate.pem")),Se(ie.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Se(ie.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Fs.join(u,"envDir","log")),Se(ie.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Se(ie.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Se(ie.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Se(ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Fs.join(u,"envDir")),Se(ie.CONFIG_PARAMS.STORAGE_PATH,Fs.join(u,"envDir")),n&&(Se(ie.CONFIG_PARAMS.HTTP_SECUREPORT,pL(ie.CONFIG_PARAMS.HTTP_PORT)),Se(ie.CONFIG_PARAMS.HTTP_PORT,null)),Se(ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Se(ie.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Se(ie.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,pu.isEmpty(i)?!1:i),Se(ie.CONFIG_PARAMS.HTTP_CORS,pu.isEmpty(i)?!1:i),Se(ie.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Se(ie.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Se(ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Se(ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Se(ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Fs.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Se(ie.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,pu.isEmpty(c)?!1:c),o&&(Se("CORS_ACCESSLIST",o),Se(ie.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Se(ie.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Se(ie.CONFIG_PARAMS.HTTP_TIMEOUT,s)),t&&(Se(ie.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Se(ie.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Se(ie.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Se(ie.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${yd}. Please check your boot props and settings files`;Su.fatal(r),Su.error(t)}}a(C4,"initTestEnvironment")});var sS={};$e(sS,{loadGQLSchema:()=>M4,start:()=>rS,startOnMainThread:()=>D4});function rS({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),n)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let $=function(x){if(x.kind==="NonNullType"){let V=$(x.type);return V.nullable=!1,V}if(x.kind==="ListType")return{type:"array",elements:$(x.type)};let Y={type:x.name?.value};return Object.defineProperty(Y,"location",{value:x.loc.startToken}),Y};a($,"getProperty");let R=S.name.value,O=[],b={table:null,database:null,properties:O};f.set(R,b);for(let x of S.directives){if(x.name.value==="table"){for(let D of x.arguments)b[D.name.value]=D.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=R),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,E.push(b)}if(x.name.value==="sealed"&&(b.sealed=!0),x.name.value==="export"){b.export=!0;for(let D of x.arguments)D.name.value==="name"&&(b.export={name:D.value.value})}}let P=!1;for(let x of S.fields){let D=$(x.type);D.name=x.name.value,O.push(D);for(let Y of x.directives)if(Y.name.value==="primaryKey")P?console.warn("Can not define two attributes as a primary key"):(D.isPrimaryKey=!0,P=!0);else if(Y.name.value==="indexed")D.indexed=!0;else if(Y.name.value==="relationship"){let V={};for(let W of Y.arguments)V[W.name.value]=W.value.value;D.relationship=V}else if(Y.name.value==="createdTime")D.assignCreatedTime=!0;else if(Y.name.value==="updatedTime")D.assignUpdatedTime=!0;else if(Y.name.value==="expiresAt")D.expiresAt=!0;else if(Y.name.value==="allow"){let V=D.authorizedRoles=[];for(let W of Y.arguments)W.name.value==="role"&&V.push(W.value.value)}}b.type=R,R==="Query"&&(h=b)}function p(S){let R=f.get(S.type);R?(Object.defineProperty(S,"properties",{value:R.properties}),Object.defineProperty(S,"definition",{value:R})):S.type==="array"?p(S.elements):L4.includes(S.type)||(0,TL.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${n}`)}a(p,"connectPropertyType");for(let S of f.values())for(let R of S.properties)p(R);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Id.dirname)(s),S.tableClass):i.set((0,Id.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass));if(h)for(let S of h.properties){let R=f.get(S.type);if(!R)throw new Error(`${S.type} was not found as a Query export`);i.set((0,Id.dirname)(s)+"/"+S.name,R.tableClass)}}}var Id,TL,L4,D4,M4,gL=ge(()=>{Id=require("path");pe();TL=U(Ze()),L4=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(rS,"start");D4=rS,M4=rS({ensureTable:lt}).handleFile});async function wd(e){return U4?(Tu||(Tu=P4(B4)),(await(await Tu).import(e)).namespace):import(e)}async function P4(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Tu=new Compartment({console,Math,Date,fetch:v4,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,AL.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:Vr,databases:st})}};let s=await(0,RL.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),Tu}function v4(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 B4(){return{Resource:Ft,tables:Vr}}var RL,AL,U4,Tu,nS=ge(()=>{Is();pe();RL=require("fs/promises"),AL=require("path"),U4=!1;a(wd,"secureImport");a(P4,"getCompartment");a(v4,"secureOnlyFetch");a(B4,"getGlobalVars")});var oS={};$e(oS,{handleFile:()=>H4});async function H4(e,t,r,s){let n=new Map,i=(0,OL.pathToFileURL)(r).toString(),o=await wd(i);u(o.default)&&s.set((0,iS.dirname)(t),o.default),c(o,(0,iS.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?s.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),n}var OL,iS,bL=ge(()=>{OL=require("url");nS();iS=require("path");a(H4,"handleFile")});var cS={};$e(cS,{start:()=>x4});function x4({resources:e}){e.set("login",aS),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var aS,NL=ge(()=>{Is();a(x4,"start");aS=class extends Ft{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 ML={};$e(ML,{parse:()=>lS,streamAsJSON:()=>gu,stringify:()=>no});function gu(e){return new uS({value:e})}function yL(e){return console.error(e),JSON.stringify(e.toString())}function IL(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function no(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===LL)return DL(e);if(t.resolution)return t.resolution.then(()=>no(e));throw t}}function DL(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let s=0;s<e.length;s++)s>0&&(r+=","),r+=DL(e[s]);return r+"]"}else{r="{";let s=!0;for(let n in e)s?s=!1:r+=",",r+=JSON.stringify(n)+":"+no(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function lS(e){return q4.test(e)?F4.parse(e):JSON.parse(e)}var wL,CL,F4,G4,LL,uS,q4,_S=ge(()=>{wL=require("stream"),CL=U(require("json-bigint-fixes")),F4=(0,CL.default)({useNativeBigInt:!0}),G4=1e4,LL={};BigInt.prototype.toJSON=function(){throw LL};a(gu,"streamAsJSON");uS=class extends wL.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*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]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),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),yL)}catch(n){yield yL(n)}else yield no(t)}else yield no(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);IL(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>G4?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 IL(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}}_destroy(t,r){for(let s of this.activeIterators)t?s.throw(t):s.return();r()}};a(yL,"handleError");a(IL,"when");a(no,"stringify");a(DL,"jsStringify");q4=/-?\d{16,}/;a(lS,"parse")});var Cd=T((m_e,UL)=>{"use strict";var k4=Ps();UL.exports={writeTransaction:V4};function V4(e,t,r){return k4.writeTransaction(e,t,r)}a(V4,"writeTransaction")});var HL=T((T_e,BL)=>{"use strict";var $4=as(),Y4=ni(),PL=q(),K4=cs(),S_e=Cd(),W4=require("clone"),fS=require("alasql"),Q4=x_(),vL=require("util"),z4=vL.promisify(Y4.getTableSchema),J4=vL.promisify($4.search),X4=w(),dS=z();Q4(fS);BL.exports={update:Z4};var j4="There was a problem performing this update. Please check the logs and try again.";async function Z4({statement:e,hdb_user:t}){let r=await z4(e.table.databaseid,e.table.tableid),s=e3(e.columns);dS.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=W4(n),c=dS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=fS.parse(u).statements[0],l=await J4(_),d=t3(s,l);return r3(o,d,t)}a(Z4,"update");function e3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=fS.compile(`SELECT ${r.expression.toString()} AS [${X4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw PL.error(t),new Error(j4)}}a(e3,"createUpdateRecord");function t3(e,t){return dS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(t3,"buildUpdateRecords");async function r3(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await K4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){PL.error(`Error delete new_attributes from update response: ${i}`)}return n}a(r3,"updateRecords")});var FL=T((O_e,xL)=>{var s3=require("alasql"),n3=as(),i3=q(),o3=Ps(),hS=require("util"),ES=z(),a3=w(),c3=ni(),R_e=Cd(),A_e=cs(),u3="record",l3="successfully deleted",_3=hS.callbackify(h3),d3=hS.promisify(n3.search),f3=hS.promisify(c3.getTableSchema);xL.exports={convertDelete:_3};function E3(e){return`${e.deleted_hashes.length} ${u3}${e.deleted_hashes.length===1?"":"s"} ${l3}`}a(E3,"generateReturnMessage");async function h3({statement:e,hdb_user:t}){let r=await f3(e.table.databaseid,e.table.tableid);ES.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=ES.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=s3.parse(o).statements[0],u={operation:a3.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await d3(c);let _=await o3.deleteRecords(u);return ES.isEmptyOrZeroLength(_.message)&&(_.message=E3(_)),delete _.txn_time,_}catch(_){throw i3.error(_),_.hdb_code?_.message:_}}a(h3,"convertDelete")});var $L=T((N_e,VL)=>{"use strict";var m3=Vi(),{hdb_errors:GL}=Z(),{getDatabases:qL}=(pe(),ee(Ge));VL.exports={checkSchemaExists:kL,checkSchemaTableExists:p3,schema_describe:m3};async function kL(e){if(!qL()[e])return GL.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(kL,"checkSchemaExists");async function p3(e,t){let r=await kL(e);if(r)return r;if(!qL()[e][t])return GL.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(p3,"checkSchemaTableExists")});var Ru=T((I_e,S3)=>{S3.exports={name:"harperdb",version:"4.3.0-alpha.1",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:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},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":"pm2 kill && 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:resources && 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:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","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":"pm2 kill && 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/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.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:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.9.2",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.0",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",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:"^5.3.3","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 yt=T((M_e,lD)=>{"use strict";var qt=j();qt.initSync();var T3=require("fs-extra"),g3=require("semver"),bu=require("path"),{monotonicFactory:R3}=require("ulidx"),KL=R3(),A3=require("util"),WL=require("child_process"),O3=A3.promisify(WL.exec),b3=WL.spawn,Re=tt(),De=w(),TS=z(),Kr=q(),Ld=wn(),N3=Cd(),Au=xr(),{onMessageByType:y3}=Ze(),{isMainThread:I3}=require("worker_threads"),{Encoder:w3,decode:gS}=require("msgpackr"),QL=new w3,{isEmpty:co}=TS,zL=ls(),C3=48*36e11,L3=5e9;I3&&y3(De.ITC_EVENT_TYPES.RESTART,()=>{hs=void 0,ao=void 0});var{connect:D3,StorageType:JL,RetentionPolicy:XL,AckPolicy:Dd,DeliverPolicy:Md,DiscardPolicy:M3,NatsConnection:w_e,JetStreamManager:C_e,JetStreamClient:L_e,StringCodec:D_e,JSONCodec:U3,createInbox:RS,headers:P3,ErrorCode:YL}=require("nats"),{PACKAGE_ROOT:v3}=w(),B3=Ru(),{recordAction:H3}=(Cn(),ee(iu)),jL=U3(),x3="clustering",F3=B3.engines[Re.NATS_SERVER_NAME],G3=bu.join(v3,"dependencies"),SS=bu.join(G3,`${process.platform}-${process.arch}`,Re.NATS_BINARY_NAME),mS,pS,Ou,io,oo;lD.exports={runCommand:ZL,checkNATSServerInstalled:q3,createConnection:AS,getConnection:Ud,getJetStreamManager:Nu,getJetStream:tD,getNATSReferences:dr,getServerList:V3,createLocalStream:OS,listStreams:rD,deleteLocalStream:$3,getServerConfig:yu,listRemoteStreams:Y3,viewStream:K3,viewStreamIterator:W3,publishToStream:Q3,createWorkQueueStream:z3,addSourceToWorkStream:nD,request:X3,removeSourceFromWorkStream:oD,reloadNATS:bS,reloadNATSHub:j3,reloadNATSLeaf:Z3,extractServerName:iD,requestErrorHandler:eX,updateWorkStream:tX,createLocalTableStream:cD,createTableStreams:rX,purgeTableStream:uD,purgeSchemaTableStreams:sX,getStreamInfo:nX,updateLocalStreams:oX,closeConnection:k3,getJsmServerName:Iu,addNatsMsgHeader:sD,updateIngestStreamConsumer:J3,clearClientCache:eD};async function ZL(e,t=void 0){let{stdout:r,stderr:s}=await O3(e,{cwd:t});if(s)throw new Error(s.replace(`
6
+ `)},kz="certificate.pem",Vz="privateKey.pem",$z="ca.pem";Fw.exports={CERTIFICATE_VALUES:Gz,CERTIFICATE_PEM_NAME:kz,PRIVATEKEY_PEM_NAME:Vz,CA_PEM_NAME:$z}});var Pp=T((Ple,Yw)=>{"use strict";var $w=require("fs-extra"),le=require("joi"),Yz=require("os"),{boolean:ve,string:an,number:Pt,array:Up}=le.types(),{totalmem:Gw}=require("os"),Wi=require("path"),Kz=Y(),td=J(),Ule=qw(),kw=M(),Wz=rt(),Vw="log",Qz="components",zz="Invalid logging.rotation.maxSize unit. Available units are G, M or K",Jz="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Xz="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",jz="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",Zz="rootPath config parameter is undefined",e2="clustering.enabled config parameter is undefined",Qi=Pt.min(0).required(),rd=Up.items({host:an.required(),port:Qi}).empty(null),Xn;Yw.exports={configValidator:t2,routesValidator:a2,route_constraints:rd};function t2(e){if(Xn=e.rootPath,td.isEmpty(Xn))throw Zz;let t=ve.required(),r=Pt.min(0).max(1e3).empty(null).default(o2),n=an.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Wc),s=an.optional().empty(null),i=an.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=le.string().empty(null).default(Wc),c=le.custom(n2).empty(null).default(Wc),u=e.clustering?.enabled;if(td.isEmpty(u))throw e2;let _;return u===!0?_=le.object({enabled:t,hubServer:le.object({cluster:le.object({name:le.required().empty(null),network:le.object({port:Qi,routes:rd}).required()}).required(),leafNodes:le.object({network:le.object({port:Qi}).required()}).required(),network:le.object({port:Qi}).required()}).required(),leafServer:le.object({network:le.object({port:Qi,routes:rd}).required(),streams:le.object({maxAge:Pt.min(120).allow(null).optional(),maxBytes:Pt.min(1).allow(null).optional(),maxMsgs:Pt.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:le.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:ve.optional(),databaseLevel:ve.optional(),tls:le.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:ve.required(),verify:ve.optional()}),user:an.optional().empty(null)}).required():_=le.object({enabled:t,tls:le.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:ve.required()})}).required(),le.object({authentication:le.object({authorizeLocal:ve,cacheTTL:Pt.required(),enableSessions:ve}),analytics:le.object({aggregatePeriod:Pt}),componentsRoot:n.optional(),clustering:_,localStudio:le.object({enabled:t}).required(),logging:le.object({auditAuthEvents:le.object({logFailed:ve,logSuccessful:ve}),file:ve.required(),level:le.valid("notify","fatal","error","warn","info","debug","trace"),rotation:le.object({enabled:ve.optional(),compress:ve.optional(),interval:an.custom(i2).optional().empty(null),maxSize:an.custom(s2).optional().empty(null),path:an.optional().empty(null).default(Wc)}).required(),root:n,stdStreams:ve.required(),auditLog:ve.required()}).required(),operationsApi:le.object({network:le.object({cors:ve.optional(),corsAccessList:Up.optional(),headersTimeout:Pt.min(1).optional(),keepAliveTimeout:Pt.min(1).optional(),port:Pt.optional().empty(null),domainSocket:le.optional().empty("hdb/operations-server").default(Wc),securePort:Pt.optional().empty(null),timeout:Pt.min(1).optional()}).optional(),tls:le.object({certificate:s,certificateAuthority:s,privateKey:s})}).required(),rootPath:an.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:le.object({network:le.object({port:Qi,securePort:Qi,mtls:le.alternatives([ve.optional(),le.object({user:an.optional(),certificateAuthority:s,required:ve.optional()})])}).required(),webSocket:ve.optional(),requireAuthentication:ve.optional()}),http:le.object({compressionThreshold:Pt.optional(),cors:ve.optional(),corsAccessList:Up.optional(),headersTimeout:Pt.min(1).optional(),port:Pt.min(0).optional().empty(null),securePort:Pt.min(0).optional().empty(null)}).required(),threads:r.optional(),maxHeapMemory:Pt.min(0).optional(),storage:le.object({writeAsync:ve.required(),overlappingSync:ve.optional(),caching:ve.optional(),compression:ve.optional(),noReadAhead:ve.optional(),path:c,prefetchWrites:ve.optional()}).required(),ignoreScripts:ve.optional(),tls:le.object({certificate:s.optional(),certificateAuthority:s.optional(),privateKey:s.optional(),ciphers:an.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(t2,"configValidator");function r2(e){return $w.existsSync(e)?null:`Specified path ${e} does not exist.`}a(r2,"doesPathExist");function n2(e,t){le.assert(e,an.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=r2(e);if(r)return t.message(r)}a(n2,"validatePath");function s2(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(zz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Xz):e}a(s2,"validateRotationMaxSize");function i2(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(Jz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(jz):e}a(i2,"validateRotationInterval");function o2(e,t){let r=t.state.path.join("."),n=Yz.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||Gw();return i=Math.round(Math.min(i,Gw())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Kz.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(o2,"setDefaultThreads");function Wc(e,t){let r=t.state.path.join(".");if(!td.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(td.isEmpty(Xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(Xn,Qz);case"logging.root":return Wi.join(Xn,Vw);case"clustering.leafServer.streams.path":return Wi.join(Xn,"clustering","leaf");case"storage.path":let n=Wi.join(Xn,kw.LEGACY_DATABASES_DIR_NAME);return $w.existsSync(n)?n:Wi.join(Xn,kw.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(Xn,Vw);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(Xn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Wc,"setDefaultRoot");function a2(e){let t=le.object({routes:rd});return Wz.validateBySchema({routes:e},t)}a(a2,"routesValidator")});var xr=T((Hle,eC)=>{"use strict";var Hr=M(),vt=J(),bt=Y(),{configValidator:c2,routesValidator:Kw}=Pp(),cr=require("fs-extra"),u2=require("yaml"),Un=require("path"),l2=require("is-number"),Qw=require("properties-reader"),_2=require("lodash"),{handleHDBError:d2}=Z(),{HTTP_STATUS_CODES:f2,HDB_ERROR_MSGS:nd}=wr(),Ble=require("minimist"),{server:E2}=(Zt(),ee(yi)),{DATABASES_PARAM_CONFIG:Qc,CONFIG_PARAMS:Br,CONFIG_PARAM_MAP:Pn}=Hr,h2="Unable to get config value because config is uninitialized",m2="Config successfully initialized",p2="Error backing up config file",S2="Empty parameter sent to getConfigValue",zw=Un.join(Hr.PACKAGE_ROOT,"config","yaml",Hr.HDB_DEFAULT_CONFIG_FILE),T2="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ww={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"},sd,Nt,id;eC.exports={createConfigFile:g2,getDefaultConfig:R2,getConfigValue:Xw,initConfig:Bp,flattenConfig:ra,updateConfigValue:jw,updateConfigObject:O2,getConfiguration:y2,setConfiguration:I2,readConfigFile:xp,getClusteringRoutes:w2,initOldConfig:Zw,getConfigFromFile:C2,getConfigFilePath:zi,addConfig:D2,deleteConfigFromFile:L2,getConfigObj:M2};function g2(e){let t=si(zw);sd=ra(t.toJSON());let r;for(let o in e){let c=Pn[o.toLowerCase()];if(c===Br.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=vp(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){bt.error(l)}}}r&&Jw(t,r),Hp(t);let n=t.toJSON();Nt=ra(n);let s=t.getIn(["rootPath"]),i=Un.join(s,Hr.HDB_CONFIG_FILE);cr.createFileSync(i),cr.writeFileSync(i,String(t)),bt.trace(`Config file written to ${i}`)}a(g2,"createConfigFile");function Jw(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!vt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Qc.TABLES))for(let i in n[s][Qc.TABLES])for(let o in n[s][Qc.TABLES][i]){let c=n[s][Qc.TABLES][i][o],u=[Br.DATABASES,s,Qc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Br.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){bt.error("Error parsing schemas CLI/env config arguments",n)}}a(Jw,"setSchemasConfig");function R2(e){if(sd===void 0){let r=si(zw);sd=ra(r.toJSON())}let t=Pn[e.toLowerCase()];if(t!==void 0)return sd[t.toLowerCase()]}a(R2,"getDefaultConfig");function Xw(e){if(e==null){bt.error(S2);return}if(Nt===void 0){bt.trace(h2);return}let t=Pn[e.toLowerCase()];if(t!==void 0)return Nt[t.toLowerCase()]}a(Xw,"getConfigValue");function zi(e=vt.getPropsFilePath()){let t=vt.getEnvCliRootPath();return t?Un.join(t,Hr.HDB_CONFIG_FILE):Qw(e).get(Hr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function Bp(e=!1){if(Nt===void 0||e){let t;if(!vt.noBootFile()){t=vt.getPropsFilePath();try{cr.accessSync(t,cr.constants.F_OK|cr.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=zi(t),n;if(r.includes("config/settings.js"))try{Zw(r);return}catch(i){if(i.code!==Hr.NODE_ERROR_CODES.ENOENT)throw i}try{n=si(r)}catch(i){if(i.code===Hr.NODE_ERROR_CODES.ENOENT){bt.trace(`HarperDB config file not found at ${r}.
7
+ This can occur during early stages of install where the config file has not yet been created`);return}else throw bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}A2(n,r),Hp(n);let s=n.toJSON();if(E2.config=s,Nt=ra(s),Nt.logging_rotation_rotate)for(let i in Ww)Nt[i]&&bt.error(`Config ${Ww[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(m2)}}a(Bp,"initConfig");function A2(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Un.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Un.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Un.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),n&&(bt.trace("Updating config file with missing config params"),cr.writeFileSync(t,String(e)))}a(A2,"checkForUpdatedConfig");function Hp(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=c2(t);if(r.error)throw nd.CONFIG_VALIDATION(r.error.message);e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),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),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(Hp,"validateConfig");function O2(e,t){Nt===void 0&&(Nt={});let r=Pn[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Nt[r.toLowerCase()]=t}a(O2,"updateConfigObject");function jw(e,t,r=void 0,n=!1,s=!1,i=!1){Nt===void 0&&Bp();let o=Xw(Pn.hdb_root),c=Un.join(o,Hr.HDB_CONFIG_FILE),u=si(c),_;if(r===void 0&&e.toLowerCase()===Br.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Pn[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=vp(f,t);u.setIn([...E],h)}else for(let f in r){let E=Pn[f.toLowerCase()];if(E===Br.HTTP_SECUREPORT&&r[f]===Nt[Br.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Br.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===Nt[Br.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Br.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),S=Hr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];S&&S.startsWith("customFunctions")&&u.hasIn(S.split("_"))&&(E=S,h=S.split("_"));let p=vp(E,r[f]);E==="rootPath"&&p?.endsWith("/")&&(p=p.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],p)}catch(g){bt.error(g)}}}_&&Jw(u,_),Hp(u);let l=u.getIn(["rootPath"]),d=Un.join(l,Hr.HDB_CONFIG_FILE);n===!0&&b2(c,l),cr.writeFileSync(d,String(u)),s&&(Nt=ra(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(jw,"updateConfigValue");function b2(e,t){try{let r=Un.join(t,"backup",`${Hr.HDB_CONFIG_FILE}.bak`);cr.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(p2),bt.error(r)}}a(b2,"backupConfigFile");var N2=["databases"];function ra(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),id=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i))if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!N2.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Br[u.toUpperCase()]&&Pn[u]&&(s[Pn[u].toLowerCase()]=o[c]),s[u]=o[c]}}else s[i.toLowerCase()]=n[i];return s}a(r,"squashObj")}a(ra,"flattenConfig");function vp(e,t){if(e===Br.CLUSTERING_NODENAME||e===Br.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(l2(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||vt.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 vt.autoCast(t)}a(vp,"castConfigValue");function y2(){let e=vt.getPropsFilePath(),t=zi(e);return si(t).toJSON()}a(y2,"getConfiguration");async function I2(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return jw(void 0,void 0,s,!0),T2}catch(i){throw typeof i=="string"||i instanceof String?d2(i,i,f2.BAD_REQUEST,void 0,void 0,!0):i}}a(I2,"setConfiguration");function xp(){let e=vt.getPropsFilePath();try{cr.accessSync(e,cr.constants.F_OK|cr.constants.R_OK)}catch(n){if(!vt.noBootFile())throw bt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return si(t).toJSON()}a(xp,"readConfigFile");function si(e){return u2.parseDocument(cr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(si,"parseYamlDoc");function w2(){let e=xp(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=vt.isEmptyOrZeroLength(t)?[]:t;let r=Kw(t);if(r)throw nd.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=vt.isEmptyOrZeroLength(n)?[]:n;let s=Kw(n);if(s)throw nd.CONFIG_VALIDATION(s.message);if(!vt.isEmptyOrZeroLength(n)&&!vt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!vt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw nd.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(w2,"getClusteringRoutes");function Zw(e){let t=Qw(e);Nt={};for(let r in Pn){let n=t.get(r.toUpperCase());if(vt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Pn[r].toLowerCase();s===Br.LOGGING_ROOT?Nt[s]=Un.dirname(n):Nt[s]=n}return Nt}a(Zw,"initOldConfig");function C2(e){let t=xp();return _2.get(t,e.replaceAll("_","."))}a(C2,"getConfigFromFile");async function D2(e,t){let r=si(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await cr.writeFile(zi(),String(r))}a(D2,"addConfig");function L2(e){let t=zi(vt.getPropsFilePath()),r=si(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Un.join(n,Hr.HDB_CONFIG_FILE);cr.writeFileSync(s,String(r))}a(L2,"deleteConfigFromFile");function M2(){return id||(Bp(),id)}a(M2,"getConfigObj")});var rC=T((Fle,tC)=>{"use strict";var od=M(),ad=class{static{a(this,"BaseLicense")}constructor(t=0,r=od.RAM_ALLOCATION_ENUM.DEFAULT,n=od.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},Fp=class extends ad{static{a(this,"ExtendedLicense")}constructor(t=0,r=od.RAM_ALLOCATION_ENUM.DEFAULT,n=od.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};tC.exports={BaseLicense:ad,ExtendedLicense:Fp}});var Ji=T((Gle,cC)=>{"use strict";var sa=require("fs-extra"),sC=ed(),iC=require("crypto"),U2=require("moment"),P2=require("uuid").v4,zt=Y(),Gp=require("path"),v2=J(),ii=M(),{totalmem:nC}=require("os"),B2=rC().ExtendedLicense,na="invalid license key format",H2="061183",x2="mofi25",F2="aes-256-cbc",q2=16,G2=32,oC=j();oC.initSync();var qp;cC.exports={validateLicense:aC,generateFingerPrint:V2,licenseSearch:$p,getLicense:K2,checkMemoryLimit:W2};function kp(){return Gp.join(oC.getHdbBasePath(),ii.LICENSE_KEY_DIR_NAME,ii.LICENSE_FILE_NAME)}a(kp,"getLicenseDirPath");function k2(){let e=kp();return Gp.join(e,ii.LICENSE_FILE_NAME)}a(k2,"getLicenseFilePath");function Vp(){let e=kp();return Gp.join(e,ii.REG_KEY_FILE_NAME)}a(Vp,"getFingerPrintFilePath");async function V2(){let e=Vp();try{return await sa.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await $2();throw zt.error(`Error writing fingerprint file to ${e}`),zt.error(t),new Error("There was an error generating the fingerprint")}}a(V2,"generateFingerPrint");async function $2(){let e=P2(),t=sC.hash(e),r=Vp();try{await sa.mkdirp(kp()),await sa.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw zt.error(`Error writing fingerprint file to ${r}`),zt.error(n),new Error("There was an error generating the fingerprint")}return t}a($2,"writeFingerprint");function aC(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ii.RAM_ALLOCATION_ENUM.DEFAULT,version:ii.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return zt.error("empty license key passed to validate."),r;let n=Vp(),s=!1;try{s=sa.statSync(n)}catch(i){zt.error(i)}if(s){let i;try{i=sa.readFileSync(n,"utf8")}catch{zt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(x2),c=o[1];c=Buffer.concat([Buffer.from(c)],q2);let u=Buffer.concat([Buffer.from(i)],G2),_=iC.createDecipheriv(F2,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=Y2(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(na),zt.error(na),new Error(na)}let d;if(isNaN(l))try{d=JSON.parse(l),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(na),zt.error(na),new Error(na)}else r.exp_date=l;r.exp_date<U2().valueOf()&&(r.valid_date=!1),sC.validate(o[1],`${H2}${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||zt.error("Invalid licence"),r}a(aC,"validateLicense");function Y2(e,t){try{let r=iC.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{zt.warn("Check old license failed")}}a(Y2,"checkOldLicense");function $p(){let e=new B2,t=[];try{t=sa.readFileSync(k2(),"utf-8").split(ii.NEW_LINE)}catch(r){r.code==="ENOENT"?zt.info("no license file found"):zt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(v2.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=aC(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){zt.error("There was an error parsing the license string."),zt.error(s),e.ram_allocation=ii.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return qp=e,e}a($p,"licenseSearch");async function K2(){return qp||await $p(),qp}a(K2,"getLicense");function W2(){let e=$p().ram_allocation,t=process.constrainedMemory?.()||nC();if(t=Math.round(Math.min(t,nC())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(W2,"checkMemoryLimit")});var cn=T((Kle,bC)=>{"use strict";var dC="username is required",fC="nothing to update, must supply active, role or password to update",EC="password cannot be an empty string",hC="If role is specified, it cannot be empty.",mC="active must be true or false";bC.exports={addUser:rJ,alterUser:nJ,dropUser:iJ,getSuperUser:uJ,userInfo:oJ,listUsers:ud,listUsersExternal:aJ,setUsersToGlobal:oa,findAndValidateUser:AC,getClusterUser:lJ,USERNAME_REQUIRED:dC,ALTERUSER_NOTHING_TO_UPDATE:fC,EMPTY_PASSWORD:EC,EMPTY_ROLE:hC,ACTIVE_BOOLEAN:mC};var pC=on(),Q2=Ki(),Wp=ed(),SC=Bw(),TC=sn(),Qp=gs(),Fr=J(),gC=require("validate.js"),ge=Y(),{promisify:z2}=require("util"),zp=bs(),uC=M(),lC=nt(),J2=xr(),Vle=j(),$le=Ji(),X2=Pi(),{table:Yle}=(Oe(),ee(Ge)),{handleHDBError:jn,hdb_errors:j2}=Z(),{HTTP_STATUS_CODES:Zn,AUTHENTICATION_ERROR_MSGS:Yp,HDB_ERROR_MSGS:ia}=j2,{UserEventMsg:Jp}=In(),Kp=require("lodash"),{server:Xp}=(Zt(),ee(yi)),Z2=Y();Xp.getUser=(e,t)=>AC(e,t,t!=null);var RC={username:!0,active:!0,role:!0,password:!0},_C=new Map,cd=TC.searchByValue,eJ=TC.searchByHash,tJ=z2(Q2.delete);async function rJ(e){let t=gC.cleanAttributes(e,RC),r=SC.addUserValidation(t);if(r)throw jn(new Error,r.message,Zn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await cd(n),s=s&&Array.from(s)}catch(u){throw ge.error("There was an error searching for a role in add user"),ge.error(u),u}if(!s||s.length<1)throw jn(new Error,ia.ROLE_NAME_NOT_FOUND(t.role),Zn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw jn(new Error,ia.DUP_ROLES_FOUND(t.role),Zn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=zp.encrypt(t.password)),t.password=Wp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await pC.insert(i)}catch(u){throw ge.error("There was an error searching for a user."),ge.error(u),u}ge.debug(o);try{await oa()}catch(u){throw ge.error("Got an error setting users to global"),ge.error(u),u}if(o.skipped_hashes.length===1)throw jn(new Error,ia.USER_ALREADY_EXISTS(t.username),Zn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],Qp.signalUserChange(new Jp(process.pid)),`${c.username} successfully added`}a(rJ,"addUser");async function nJ(e){let t=gC.cleanAttributes(e,RC);if(Fr.isEmptyOrZeroLength(t.username))throw new Error(dC);if(Fr.isEmptyOrZeroLength(t.password)&&Fr.isEmptyOrZeroLength(t.role)&&Fr.isEmptyOrZeroLength(t.active))throw new Error(fC);if(!Fr.isEmpty(t.password)&&Fr.isEmptyOrZeroLength(t.password.trim()))throw new Error(EC);if(!Fr.isEmpty(t.active)&&!Fr.isBoolean(t.active))throw new Error(mC);let r=sJ(t.username);if(!Fr.isEmpty(t.password)&&!Fr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=zp.encrypt(t.password)),t.password=Wp.hash(t.password)),t.role==="")throw new Error(hC);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 cd(i)||[])}catch(c){throw ge.error("Got an error searching for a role."),ge.error(c),c}if(!o||o.length===0){let c=ia.ALTER_USER_ROLE_NOT_FOUND(t.role);throw ge.error(c),jn(new Error,c,Zn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=ia.ALTER_USER_DUP_ROLES(t.role);throw ge.error(c),jn(new Error,c,Zn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await pC.update(n)}catch(i){throw ge.error("Error during update."),ge.error(i),i}try{await oa()}catch(i){throw ge.error("Got an error setting users to global"),ge.error(i),i}return Qp.signalUserChange(new Jp(process.pid)),s}a(nJ,"alterUser");function sJ(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(sJ,"isClusterUser");async function iJ(e){try{let t=SC.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Fr.isEmpty(global.hdb_users.get(e.username)))throw jn(new Error,ia.USER_NOT_EXIST(e.username),Zn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await tJ(r)}catch(s){throw ge.error("Got an error deleting a user."),ge.error(s),s}ge.debug(n);try{await oa()}catch(s){throw ge.error("Got an error setting users to global."),ge.error(s),s}return Qp.signalUserChange(new Jp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(iJ,"dropUser");async function oJ(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Kp.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await eJ(r)}catch(s){throw ge.error("Got an error searching for a role."),ge.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw ge.error(r),r}return t}a(oJ,"userInfo");async function aJ(){let e;try{e=await ud()}catch(t){throw ge.error("Got an error listing users."),ge.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(aJ,"listUsersExternal");async function ud(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await cd(e)}catch(o){throw ge.error("Got an error searching for roles."),ge.error(o),o}let r={};for(let o of t)r[o.id]=Kp.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await cd(n)}catch(o){throw ge.error("Got an error searching for users."),ge.error(o),o}let i=new Map;for(let o of s)o=Kp.cloneDeep(o),o.role=r[o.role],cJ(o.role),i.set(o.username,o);return i}catch(e){throw ge.error("got an error listing users"),ge.error(e),Fr.errorizeMessage(e)}return null}a(ud,"listUsers");function cJ(e){try{if(!e){ge.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(X2)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){ge.error("Got an error trying to set system permissions."),ge.error(t)}}a(cJ,"appendSystemTablesToRole");async function oa(){try{let e=await ud();global.hdb_users=e}catch(e){throw ge.error(e),e}}a(oa,"setUsersToGlobal");async function AC(e,t,r=!0){global.hdb_users||await oa();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw jn(new Error,Yp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw jn(new Error,Yp.USER_INACTIVE,Zn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(_C.get(t)===n.password)return s;if(Wp.validate(n.password,t))_C.set(t,n.password);else throw jn(new Error,Yp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(AC,"findAndValidateUser");async function uJ(){global.hdb_users||await oa();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(uJ,"getSuperUser");async function lJ(){let e=await ud(),t=J2.getConfigFromFile(uC.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Fr.isEmpty(r)&&r?.role?.role===uC.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=zp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+lC.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+lC.SERVER_SUFFIX.ADMIN,r}a(lJ,"getClusterUser");var OC=[];Xp.invalidateUser=function(e){for(let t of OC)try{t(e)}catch(r){Z2.error("Error invalidating user",r)}};Xp.onInvalidatedUser=function(e){OC.push(e)}});var Jc=T((Jle,wC)=>{"use strict";var Xi=Y(),qr=M(),_J=Lb(),Qle=ti(),zle=Gi(),dJ=cn(),{validateEvent:NC}=In(),zc=Ln(),fJ=require("process"),{resetDatabases:EJ}=(Oe(),ee(Ge)),hJ={[qr.ITC_EVENT_TYPES.SCHEMA]:mJ,[qr.ITC_EVENT_TYPES.USER]:IC};async function mJ(e){let t=NC(e);if(t){Xi.error(t);return}Xi.trace("ITC schemaHandler received schema event:",e),await _J(e.message),await pJ(e.message)}a(mJ,"schemaHandler");async function pJ(e){try{zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=EJ();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Xi.error(t)}}a(pJ,"syncSchemaMetadata");var yC=[];async function IC(e){try{try{zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Xi.warn(r)}let t=NC(e);if(t){Xi.error(t);return}Xi.trace(`ITC userHandler ${qr.HDB_ITC_CLIENT_PREFIX}${fJ.pid} received user event:`,e),await dJ.setUsersToGlobal();for(let r of yC)r()}catch(t){Xi.error(t)}}a(IC,"userHandler");IC.addListener=function(e){yC.push(e)};wC.exports=hJ});var In=T((r_e,DC)=>{"use strict";var jle=Y(),jp=J(),SJ=M(),{ITC_ERRORS:Xc}=wr(),{parentPort:Zle,threadId:TJ,isMainThread:gJ,workerData:e_e}=require("worker_threads"),{onMessageFromWorkers:RJ,broadcast:t_e,broadcastWithAcknowledgement:AJ}=tt();DC.exports={sendItcEvent:OJ,validateEvent:CC,SchemaEventMsg:bJ,UserEventMsg:NJ};var ld;RJ(async(e,t)=>{ld=ld||Jc(),CC(e),ld[e.type]&&await ld[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function OJ(e){return!gJ&&e.message&&(e.message.originator=TJ),AJ(e)}a(OJ,"sendItcEvent");function CC(e){if(typeof e!="object")return Xc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||jp.isEmpty(e.type))return Xc.MISSING_TYPE;if(!e.hasOwnProperty("message")||jp.isEmpty(e.message))return Xc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||jp.isEmpty(e.message.originator))return Xc.MISSING_ORIGIN;if(SJ.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Xc.INVALID_EVENT(e.type)}a(CC,"validateEvent");function bJ(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(bJ,"SchemaEventMsg");function NJ(e){this.originator=e}a(NJ,"UserEventMsg")});var gs=T((i_e,PC)=>{"use strict";var LC=M(),s_e=J(),_d=Y(),MC=fb(),aa,{sendItcEvent:UC}=In();function yJ(e){try{_d.trace("signalSchemaChange called with message:",e),aa=aa||Jc();let t=new MC(LC.ITC_EVENT_TYPES.SCHEMA,e);return aa.schema(t),UC(t)}catch(t){_d.error(t)}}a(yJ,"signalSchemaChange");function IJ(e){try{_d.trace("signalUserChange called with message:",e),aa=aa||Jc();let t=new MC(LC.ITC_EVENT_TYPES.USER,e);return aa.user(t),UC(t)}catch(t){_d.error(t)}}a(IJ,"signalUserChange");PC.exports={signalSchemaChange:yJ,signalUserChange:IJ}});var tu={};qe(tu,{addAnalyticsListener:()=>eu,recordAction:()=>Gr,recordActionBinary:()=>un,setAnalyticsEnabled:()=>wJ});function wJ(e){$C=e}function Gr(e,t,r,n,s){if(!$C)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Ed.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},Ed.set(i,o)}dd||CJ()}function un(e,t,r,n,s){Gr(!!e,t,r,n,s)}function eu(e){WC.push(e)}function CJ(){dd=performance.now(),setTimeout(async()=>{let e=performance.now()-dd;dd=0;let t=[],r={time:Date.now(),period:e,threadId:ji.threadId,metrics:t};for(let[s,i]of Ed){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of QC){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let S=_[_.length-1];typeof S=="number"?_[_.length-1]={value:S,count:1+h}:S.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await zC()}let n=process.memoryUsage();t.push({metric:"memory",threadId:ji.threadId,byThread:!0,...n});for(let s of WC)s(t);Ed=new Map,ji.parentPort?ji.parentPort.postMessage({type:KC,report:r}):jC({report:r})},YC).unref()}async function DJ(e,t=6e4){let r=tS(),n=JC(),s;for(let h of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){s=h.value.time;break}if(Date.now()-t<s)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:S}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:p,threadId:g}=S;for(let A of p||[]){let{path:b,method:v,type:G,metric:H,count:P,total:z,distribution:W,threads:Q,...se}=A;P||(P=1);let pe=H+(b?"-"+b:"");v!==void 0&&(pe+="-"+v),G!==void 0&&(pe+="-"+G);let oe=o.get(pe);if(oe){if(oe.threads){let ce=oe.threads[g];if(ce)oe=ce;else{oe.threads[g]=Object.assign({},se);continue}}oe.count||(oe.count=1);let Fe=oe.count;for(let ce in se){let Lt=se[ce];typeof Lt=="number"&&(oe[ce]=(oe[ce]*Fe+Lt*P)/(Fe+P))}oe.count+=P,z>=0&&(oe.total+=z,oe.ratio=oe.total/oe.count)}else oe=Object.assign({period:t},A),delete oe.distribution,o.set(pe,oe),oe.byThread&&(oe.threads=[],oe.threads[g]=Object.assign({},se),u.push(oe));if(W){W=W.map(ce=>typeof ce=="number"?{value:ce,count:1}:ce);let Fe=c.get(pe);Fe?Fe.push(...W):c.set(pe,W)}}await zC()}for(let h of u){let{path:S,method:p,type:g,metric:A,count:b,total:v,distribution:G,threads:H,...P}=h;H=H.filter(z=>z);for(let z in P){if(typeof h[z]!="number")continue;let W=0;for(let Q of H){let se=Q[z];typeof se=="number"&&(W+=se)}h[z]=W}h.count=H.length,delete h.threads,delete h.byThread}for(let[h,S]of c){let p=o.get(h);S.sort((ce,Lt)=>ce.value>Lt.value?1:-1);let g=p.count-1,A=[],b=0,v=0,G;for(let ce of QC){let Lt=g*ce;for(;b<Lt;)G=S[v++],b+=G.count,v===1&&b--;let Il=S[v>1?v-2:0];G||(G=S[0]),A.push(G.value-(G.value-Il.value)*(b-Lt)/G.count)}let[H,P,z,W,Q,se,pe,oe,Fe]=A;Object.assign(p,{p1:H,p10:P,p25:z,median:W,p75:Q,p90:se,p95:pe,p99:oe,p999:Fe})}let l;for(let[h,S]of o)S.id=(0,fd.getNextMonotonicTime)(),S.time=_,n.primaryStore.put(S.id,S,{append:!0}).then(p=>{p||n.primaryStore.put(S.id,S)}),l=!0;let d=Date.now(),{idle:f,active:E}=performance.eventLoopUtilization();if(l||E*10>f){let h=(0,fd.getNextMonotonicTime)(),S={id:h,metric:"main-thread-utilization",idle:f-vC,active:E-BC,time:d,...process.memoryUsage()};n.primaryStore.put(h,S,{append:!0}).then(p=>{p||n.primaryStore.put(h,S)})}vC=f,BC=E}async function HC(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function tS(){return xC||(xC=_t({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function JC(){return FC||(FC=_t({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function UJ(){XC=!0;let e=(0,Zc.get)(eS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await DJ(YC,e),await HC(tS(),LJ),await HC(JC(),MJ)},Math.min(e/2,2147483647)).unref()}function jC(e,t){let r=e.report;r.threadId=t?.threadId||ji.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(qC+=n.mean*n.count);r.totalBytesProcessed=qC,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(GC.get(t))}),GC.set(t,t.performance.eventLoopUtilization())),r.id=(0,fd.getNextMonotonicTime)(),tS().primaryStore.put(r.id,r),XC||UJ(),PJ&&(ZC=BJ(r))}async function BJ(e){if(await ZC,!oi){let r=(0,jc.dirname)((0,VC.getLogFilePath)());try{oi=await(0,Zp.open)((0,jc.join)(r,"analytics.log"),"r+")}catch{oi=await(0,Zp.open)((0,jc.join)(r,"analytics.log"),"w+")}}let t=(await oi.stat()).size;if(t>vJ){let r=Buffer.alloc(t);await oi.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await oi.write(r,{position:0}),await oi.truncate(r.length),t=r.length}await oi.write(JSON.stringify(e)+`
8
+ `,t)}var ji,kC,VC,jc,Zp,fd,Zc,eS,Ed,$C,dd,YC,KC,WC,QC,vC,BC,zC,LJ,MJ,xC,FC,XC,qC,GC,PJ,ZC,oi,vJ,Ns=Re(()=>{ji=require("worker_threads"),kC=B(tt());Oe();VC=B(Y()),jc=require("path"),Zp=require("fs/promises"),fd=B(Cr()),Zc=B(j()),eS=B(M());Zt();(0,Zc.initSync)();Ed=new Map,$C=(0,Zc.get)(eS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(wJ,"setAnalyticsEnabled");a(Gr,"recordAction");ut.recordAnalytics=Gr;a(un,"recordActionBinary");dd=0,YC=1e3,KC="analytics-report",WC=[];a(eu,"addAnalyticsListener");QC=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(CJ,"sendAnalytics");a(DJ,"aggregation");vC=0,BC=0,zC=a(()=>new Promise(setImmediate),"rest");a(HC,"cleanup");LJ=36e5,MJ=31536e6;a(tS,"getRawAnalyticsTable");a(JC,"getAnalyticsTable");(0,kC.setChildListenerByType)(KC,jC);a(UJ,"startScheduledTasks");qC=0,GC=new Map,PJ=!1;a(jC,"recordAnalytics");vJ=1e6;a(BJ,"logAnalytics")});var iS={};qe(iS,{coerceType:()=>hd,makeTable:()=>Sd,setServerUtilities:()=>YJ,updateResource:()=>md});function Sd(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:S}=e;S||(S=[]),lb(i,u);let p=Nh(i,n,u),g=0,A,b,v={},G=Promise.resolve(),H,P,z;for(let $ of S)($.assignCreatedTime||$.name==="__createdtime__")&&(H=$),($.assignUpdatedTime||$.name==="__updatedtime__")&&(P=$),$.expiresAt&&(z=$),$.isPrimaryKey&&(v=$);let W,Q=[],se=[],pe=1,oe=2,Fe={},ce={},Lt=864e5,Il,wl,Vs,gA=!1,QE,Qx=i.getRange({start:!1,end:!1}).constructor,zx=10,Jx=6;E&&OA();class ze extends Ft{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=H;static updatedTimeProperty=P;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,R){R&&(this.sourceOptions=R,(R.expiration||R.eviction||R.scanInterval)&&this.setTTLExpiration(R)),R?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),b=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(y=>{let I=this.sources.slice(0,-1);if(I=I.filter(U=>U[y]&&(!U[y].reliesOnPrototype||U.prototype[y])),I.length>0)if(I.length===1){let U=I[0];return(L,D,x)=>{if(L?.source!==U)return U[y](D,x,L)}}else return(U,L,D)=>{let x=[];for(let k of I){if(U?.source===k)break;x.push(k[y](L,D,U))}return Promise.all(x)}},"getApplyToIntermediateSource"),O=this.sources[this.sources.length-1],N=a(y=>{if(O[y]&&(!O[y].reliesOnPrototype||O.prototype[y]))return(I,U,L)=>{if(!I?.source)return O[y](U,L,I)}},"getApplyToCanonicalSource");return Fe={put:N("put"),patch:N("patch"),delete:N("delete"),publish:N("publish")},ce={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let y=!1,I=a(async(U,L)=>{let D=U.value,x=U.table?st[c][U.table]:ze;if(c===vn.SYSTEM_SCHEMA_NAME&&(U.table===vn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===vn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(y=!0),U.id===void 0&&(U.id=D[x.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let k=await x.getResource(U.id,L,ca);switch(U.type){case"put":return k._writeUpdate(D,!0,ca);case"patch":return k._writeUpdate(D,!1,ca);case"delete":return k._writeDelete(ca);case"publish":return k._writePublish(D,ca);case"invalidate":return k.invalidate(ca);default:Ze.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&h==null&&(h=!0);let L=m.subscribeOnThisThread?m.subscribeOnThisThread((0,eo.getWorkerIndex)()):(0,eo.getWorkerIndex)()===0,D=U&&L&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let x;for await(let k of D)try{if(!(k.type==="transaction"?k.writes[0]:k)){Ze.error("Bad subscription event",k);continue}if(k.source=m,x)if(k.beginTxn)x.resolve();else{I(k,x);continue}if(k.type==="end_txn")continue;let de=Xe(k,()=>{if(k.type==="transaction"){let te=[];for(let ne of k.writes)try{te.push(I(ne,k))}catch(Be){throw Be.message+=" writing "+JSON.stringify(ne)+" of event "+JSON.stringify(k),Be}return Promise.all(te)}else if(k.type==="define_schema"){let te=this.attributes.slice(0),ne;for(let Be of k.attributes)te.find(ie=>ie.name===Be.name)||(te.push(Be),ne=!0);ne&&(_t({table:s,database:c,attributes:te,origin:"cluster"}),cu.signalSchemaChange(new uu.SchemaEventMsg(process.pid,vn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return k.beginTxn?(x=k,I(k,k),new Promise(te=>{x.resolve=te})):I(k,k)});y&&(await de,cu.signalUserChange(new uu.UserEventMsg(process.pid))),k.onCommit&&(de?.then?de.then(k.onCommit):k.onCommit())}catch(_e){Ze.error("error in subscription handler",_e)}}}catch(U){Ze.error(U)}})(),this}static getResource(m,R,w){let O=super.getResource(m,R,w);if(m!=null){Qa(m);try{if(O.hasOwnProperty(be))return O;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let N=!w?.async||i.cache?.get(m),y=br(R),I=y.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return zE(m,R,{transaction:I},N,U=>{if(U?md(O,U):O[be]=null,R.onlyIfCached&&R.noCacheStore){if(!O.doesExist())throw new ln.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let L=JE(m,U,R,O);if(L)return y?.disregardReadTxn(),O[rS]=!0,sS(L,D=>(md(O,D),O))}return O})}catch(N){throw N.message.includes("Unable to serialize object")&&(N.message+=": "+JSON.stringify(m)),N}}return O}ensureLoaded(){let m=JE(this[Ce],this[kr],this[Ae]);if(m)return this[rS]=!0,sS(m,R=>{this[kr]=R,this[be]=R.value,this[ou]=R.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,Lt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");Lt=Lt||(d+f)/4,jE()}static enableAuditing(m=!0){E=m,m&&OA(),ze.audit=m}static coerceId(m){return m===""?null:hd(m,v)}static async dropTable(){if(delete st[c][s],c===o){for(let m of S)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.tableName+"/"),i.drop(),await l.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));cu.signalSchemaChange(new uu.SchemaEventMsg(process.pid,vn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[rn])return this.search(m);if(this[Ce]===null){if(m?.conditions)return this.search(m);let R=ze.getRecordCount();return{recordCount:R.recordCount,estimatedRecordRange:R.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Ae]?.returnNonexistent)return this}allowRead(m,R){let w=Dl(m);if(w?.read){if(w.isSuperUser)return!0;let O=w.attribute_permissions,N=R?.select;if(O?.length>0||gA&&N){if(R||(R={}),N){let y=O?.length>0&&nS(O,"read");R.select=N.map(I=>{let U=I.name||I;if(!y||y[U]){let L=Vs[U]?.definition?.tableClass;if(L){if(I.name||(I={name:I}),!L.prototype.allowRead.call(null,m,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else R.select=O.filter(y=>y.read&&!Vs[y.attribute_name]).map(y=>y.attribute_name);return R}else return!0}}allowUpdate(m,R){let w=Dl(m);if(w?.update){let O=w.attribute_permissions;if(O?.length>0){let N=nS(O,"update");for(let y in R)if(!N[y])return!1;for(let y of O){let I=y.attribute_name;!y.update&&!(I in R)&&(R[I]=this.getProperty(I))}}return!0}}allowCreate(m,R){if(this[rn]){let w=Dl(m);if(w?.insert){let O=w.attribute_permissions;if(O?.length>0){let N=nS(O,"insert");for(let y in R)if(!N[y])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Dl(m)?.delete}update(m,R){if(!br(this[Ae]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let O;return typeof m=="object"&&m&&(R?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[be]={},this[Ot]=m):(O=this[Ot],O&&(m=Object.assign(O,m)),this[Ot]=O=m)),this._writeUpdate(this[Ot],R),this}addTo(m,R){if(typeof R=="number")this[ru]===tD?this.set(m,(+this.getProperty(m)||0)+R):(this[ru]||this.update(),this.set(m,new i_(R)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,R){if(typeof R=="number")return this.addTo(m,-R);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let R=this[Ae],w=this[Ce];Qa(w),br(this[Ae]).addWrite({key:w,store:i,invalidated:!0,entry:this[kr],nodeName:this[Ae]?.nodeName,before:Fe.invalidate?.bind(this,R,w),beforeIntermediate:ce.invalidate?.bind(this,R,w),commit:(N,y)=>{if(y?.version>N)return;let I=null;for(let U in r)I||(I={}),I[U]=this.getProperty(U);p(w,I,this[kr],N,nu,E,this[Ae],0,"invalidate")}})}static evict(m,R,w){let O=this.Source,N;if(!((b||E)&&(!R||(N=i.getEntry(m),!N||!R)||N.version!==w))){if(b){if(i.hasLock(m,N.version))return;let y;for(let I in r)y||(y={}),y[I]=R[I];if(y)return p(m,y,N,w,su,null,null,0,null,!0)}return i.ifVersion(w,()=>{Cl(m,R,null)}),E?p(m,null,N,w,su,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,R){return m.table||=s,m.schema||=c,aD.operation(m,R)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,R,w){let O=this[Ae],N=br(O),y=this[Ce];Qa(y);let I=this[kr];this[ru]=R?tD:kJ;let U={key:y,store:i,entry:I,nodeName:O?.nodeName,validate:L=>{m||(m=this[Ot]),R||m&&n_(m)?(this.validate(m,!R),O?.source||(P&&(m[P.name]=P.type==="Date"?new Date(L):P.type==="String"?new Date(L).toISOString():L),R&&(t&&m[t]!==y&&(m[t]=y),H&&(I?.value?m[H.name]=I?.value[H.name]:m[H.name]=H.type==="Date"?new Date(L):H.type==="String"?new Date(L).toISOString():L),m=Li(m)))):N.removeWrite(U)},before:R?Fe.put?()=>Fe.put(O,y,m):null:Fe.patch?()=>Fe.patch(O,y,m):Fe.put?()=>Fe.put(O,y,Li(this)):null,beforeIntermediate:R?ce.put?()=>ce.put(O,y,m):null:ce.patch?()=>ce.patch(O,y,m):ce.put?()=>ce.put(O,y,Li(this)):null,commit:(L,D,x)=>{x&&(O&&D?.version>(O.lastModified||0)&&(O.lastModified=D.version),this[kr]=D,R||(this[be]=D?.value??null)),this[Ot]=m,this[ou]=L;let k=D?.value,_e=m;if(this[ru]=0,D?.version>L)if(E){let Be=D.localTime,ie=D.version;for(;_e&&(Be>L||ie>L&&Be>0);){let fe=u.get(Be),Ye=Ut(fe);if(ie=Ye.version,ie>L)if(Ye.type==="patch"){let Me=Ye.getValue(i);_e=t_(_e,Me)}else(Ye.type==="put"||Ye.type==="delete")&&(_e=null);Be=Ye.previousLocalTime}}else R?_e=null:_e=t_(_e,k);let de=Li(this,_e);this[be]=de;let te;R||(te=m),Cl(y,k,de);let ne=R?"put":"patch";p(y,de,D,L,0,E,O,O.expiresAt||(d?d+Date.now():0),ne,!1,te)}};N.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[rn]){for await(let R of this.search(m))(await ze.getResource(R[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[be]?this._writeDelete(m):!1}_writeDelete(m){let R=br(this[Ae]),w=this[Ce];Qa(w);let O=this[Ae];return R.addWrite({key:w,store:i,resource:this,nodeName:O?.nodeName,before:Fe.delete?.bind(this,O,w),beforeIntermediate:ce.delete?.bind(this,O,w),commit:(N,y,I)=>{let U=y?.value;I&&(O&&y?.version>(O.lastModified||0)&&(O.lastModified=y.version),md(this,y)),!(y?.version>N)&&(Cl(this[Ce],U),Ze.trace("Write delete entry",w,N),E||h?(p(w,null,this[kr],N,0,E,this[Ae],0,"delete"),E||jE()):i.remove(this[Ce]))}}),!0}search(m){let R=this[Ae],w=br(R);if(!m)throw new Error("No query provided");let O=m.conditions;O?O.length===void 0&&(O=O[Symbol.iterator]?Array.from(O):[O]):O=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Ce]&&(O=[{attribute:null,comparator:"prefix",value:this[Ce]}].concat(O));let N,y={};function I(re,je){let Ke;switch(je){case"and":case void 0:if(re.length<1)throw new Error('An "and" operator requires at least one condition');Ke=!0;break;case"or":if(re.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+je)}let Mt=Ke&&{},Nr;for(let Ue of re){if(Ue.conditions){Ue.conditions=I(Ue.conditions,Ue.operator);continue}let xe=Ue[0]??Ue.attribute,yr=xe==null?v:ps(S,xe);if(yr){if(Ke){let _s=bn(xe),jr=Mt[_s];jr?(jr.push(Ue),Nr=!0):Mt[_s]=[Ue]}(yr.type||Fh[Ue.comparator])&&(Ue[1]===void 0?Ue.value=L(Ue.value,yr):Ue[1]=L(Ue[1],yr))}else if(xe!=null)throw(0,ln.handleHDBError)(new Error,`${xe} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return re;if(Nr)for(let Ue in Mt){let xe=Mt[Ue],yr=xe.length;if(yr>1)for(let _s=0;_s<yr;_s++){let jr=xe[_s];if(jr.comparator==="ge"||jr.comparator==="greater_than_equal")for(let $s=0;$s<yr;$s++){let Lo=xe[$s];(Lo.comparator==="le"||Lo.comparator==="less_than_equal")&&(jr.comparator="between",jr.value=[jr.value,Lo.value],re.splice(re.indexOf(Lo),1))}if(jr.comparator==="equals"||!jr.comparator){for(let $s=0;$s<yr;$s++)if($s!==_s){let Lo=xe[$s];re.splice(re.indexOf(Lo),1)}break}}}return re}a(I,"prepareConditions");function U(re,je){if(m.enforceExecutionOrder)return re;for(let Ke of re)Ke.conditions&&(Ke.conditions=U(Ke.conditions,Ke.operator));return re.length>1&&je!=="or"?(0,oD.sortBy)(re,l_(ze)):re}a(U,"orderConditions");function L(re,je){return Array.isArray(re)?re.map(Ke=>hd(Ke,je)):hd(re,je)}a(L,"coerceTypedValues");let D=m.operator;(O.length>0||D)&&(O=I(O,D));let x=typeof m.sort=="object"&&m.sort,k;if(x&&D!=="or"){let re=x.attribute;if(N=O.find(je=>bn(je.attribute)===bn(re)),!N){if(!ps(S,re))throw(0,ln.handleHDBError)(new Error,`${Array.isArray(re)?re.join("."):re} is not a defined attribute`,404);N={attribute:re},O.push(N)}N.descending=!!x.descending}O=U(O,D),x&&(O[0]===N?x.next&&(k={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(N&&O.splice(O.indexOf(N),1),k=x));function _e(re,je){let Ke=re[0];if(je==="or"){let Mt=te(Ke);for(let Ue=1;Ue<re.length;Ue++){let xe=re[Ue],yr=te(xe);Mt=Mt.concat(yr)}let Nr=new Set;return Mt.filter(Ue=>{let xe=Ue.key??Ue;return Nr.has(xe)?!1:(Nr.add(xe),!0)})}else{let Mt=te(Ke),Nr=Ke.estimated_count,Ue=re.slice(1).map((xe,yr)=>{let _s=(xe.attribute||xe[0])===t,jr=hc(xe,ze,R,y,_s,Nr);return yr<re.length-2&&Nr&&(Nr=tb(i,xe.estimated_count,Nr)),jr}).filter(Boolean);return Ue.length>0?RA(Mt,ne,R,Ue):Mt}}a(_e,"executeConditions");let de=m.reverse===!0;function te(re){return re.conditions?_e(re.conditions,re.operator):Go(re,w,re.descending||de,ze,m.allowFullScan,y)}a(te,"executeCondition");let ne=m.select;if(O.length===0&&(O=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:O,operator:D,postOrdering:k,selectApplied:!!ne};let Be=w.useReadTxn(),ie=_e(O,D);(m.offset||m.limit!==void 0)&&(ie=ie.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0));let fe=m.ensureLoaded!==!1,Ye=ze.transformEntryForSelect(ne,R,y,fe,!0),Me=ze.transformToOrderedSelect(ie,ne,k,R,Ye);return Me.onDone=()=>{Me.onDone=null,w.doneReadTxn()},Me.selectApplied=!0,Me.getColumns=()=>{if(ne){let re=[];for(let je of ne)je==="*"?re.push(...S.map(Ke=>Ke.name)):re.push(je.name||je);return re}return S.map(re=>re.name)},Me}static transformToOrderedSelect(m,R,w,O,N){let y=new Qx;if(w){m=RA(m,R,O,null);let I;y.iterate=function(){let L,D=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),x,k=w.dbOrderedAttribute,_e,de,te=!0;function ne(ie){let fe=ie.next&&ne(ie.next),Ye=ie.descending;return(Me,re)=>{let je=XE(Me,ie.attribute,O),Ke=XE(re,ie.attribute,O),Mt=Ye?(0,to.compareKeys)(Ke,je):(0,to.compareKeys)(je,Ke);return Mt===0?fe?.(Me,re)||0:Mt}}a(ne,"createComparator");let Be=ne(w);return{async next(){let ie;if(L)if(ie=L.next(),ie.done){if(x)return y.onDone&&y.onDone(),ie}else return{value:await N(ie.value)};I=[],_e&&I.push(_e);do if(ie=await D.next(),ie.done){if(x=!0,I.length)break;return y.onDone&&y.onDone(),ie}else{let fe=ie.value;if(fe?.then&&(fe=await fe),k){let Ye=XE(fe,k,O);if(te)te=!1,de=Ye;else if(Ye!==de){de=Ye,_e=fe;break}}I.push(fe)}while(!0);return w.isGrouped,I.sort(Be),L=I[Symbol.iterator](),ie=L.next(),ie.done?(y.onDone&&y.onDone(),ie):{value:await N(ie.value)}},return(){y.onDone&&y.onDone(),D.return()},throw(){y.onDone&&y.onDone(),D.throw()}}};let U=a(L=>{if(typeof R=="object"&&Array.isArray(L.attribute))for(let D=0;D<R.length;D++){let x=R[D],k;if(x.name===L.attribute[0]){for(k=x.sort||(x.sort={});k.next;)k=k.next;k.attribute=L.attribute.slice(1),k.descending=L.descending}else x===L.attribute[0]&&(R[D]=k={name:x,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&U(L.next)},"applySortingOnSelect");U(w)}else y.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),y=y.map(N);return y}static transformEntryForSelect(m,R,w,O,N){if(m&&(m===t||m?.length===1&&m[0]===t)){let L=a(D=>D?.key??D,"transform");return m===t?L:m.asArray?D=>[L(D)]:D=>({[t]:L(D)})}let y;O&&b&&!m?.every(L=>{let D;return typeof L=="object"?D=L.name:D=L,r[D]||D===t})&&(y=!0);let I,U=a(L=>{let D;if(L){if(QE=L,D=L.value||L.deref?.(),!D&&(L.key===void 0||L.deref)){if(L=zE(L.key??L,R,{transaction:br(R).getReadTxn(),lazy:m?.length<4},!1,x=>x),L?.then)return L.then(U);D=L?.value}if(y&&(L.metadataFlags&(nu|su)||L.expiresAt&&L.expiresAt<Date.now())){let x=JE(L.key??L,L,R);if(x?.then)return x.then(U)}}if(D==null)return N?Zi.SKIP:D;if(m&&!(m[0]==="*"&&m.length===1)){let x,k=a((de,te)=>{let ne;typeof de=="object"?ne=de.name:ne=de;let Be=Vs?.[ne],ie;if(Be){let fe=w?.[ne];if(fe)if(fe.hasMappings){let Me=Be.from?D[Be.from]:bn(L.key);ie=fe.get(Me),ie||(ie=[])}else ie=fe.fromRecord?.(D);else ie=Be(D,R,L);let Ye=a(Me=>{if(Me&&typeof Me=="object"){let re=Be.definition?.tableClass||ze;I||(I={});let je=I[ne]||(I[ne]=re.transformEntryForSelect(ne===de?null:de.select||(Array.isArray(de)?de:null),R,fe,O));if(Array.isArray(Me)){let Ke=[],Mt=re.transformToOrderedSelect(Me,de.select,typeof de.sort=="object"&&de.sort,R,je)[Symbol.asyncIterator](),Nr=a(xe=>{for(;!xe.done;){if(xe?.then)return xe.then(Nr);Ke.push(xe.value),xe=Mt.next()}te(Ke,ne)},"nextValue"),Ue=Nr(Mt.next());Ue&&(x||(x=[]),x.push(Ue));return}else if(Me=je(Me),Me?.then){x||(x=[]),x.push(Me.then(Ke=>te(Ke,ne)));return}}te(Me,ne)},"handleResolvedValue");ie?.then?(x||(x=[]),x.push(ie.then(Ye))):Ye(ie);return}else ie=D[ne],ie&&typeof ie=="object"&&ne!==de&&(ie=this.transformEntryForSelect(de.select||de,R,null)({value:ie}));te(ie,ne)},"selectAttribute"),_e;if(typeof m=="string")k(m,de=>{_e=de});else if(Array.isArray(m))if(m.asArray)_e=[],m.forEach((de,te)=>{de==="*"?m[te]=D:k(de,ne=>_e[te]=ne)});else{_e={};let de=m.forceNulls;for(let te of m)if(te==="*")for(let ne in D)_e[ne]=D[ne];else k(te,(ne,Be)=>{ne===void 0&&de&&(ne=null),_e[Be]=ne})}else throw new ln.ClientError("Invalid select"+m);return x?Promise.all(x).then(()=>_e):_e}return D},"transform");return U}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||_t({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let R=!m.rawEvents,w=cb(ze,this[Ce]??null,function(I,U,L,D){try{let x=U.getValue?.(i,R);if(!x&&U.type==="patch"&&R){let k=i.getEntry(I);k?.version===U.version?x=k.value:x=U.getValue?.(i,!0,L),U.type="put"}this.send({id:I,timestamp:L,value:x,version:U.version,type:U.type,beginTxn:D})}catch(x){Ze.error(x)}},m.startTime||0,this[rn]);this[rn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.crossThreads===!1&&(w.crossThreads=!1),m.supportsTransactions&&(w.supportsTransactions=!0);let O=this[Ce],N=m.previousCount;N>1e3&&(N=1e3);let y=m.startTime;if(this[rn]){if(y){if(N)throw new ln.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:I,value:U}of u.getRange({start:y,exclusiveStart:!0})){let L=Ut(U);if(L.tableId!==n)continue;let D=L.recordId;(O==null||sD(O,D))&&w.send({id:D,timestamp:I,...L}),w.startTime=I}}else if(N){let I=[];for(let{key:U,value:L}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Ut(L);if(D.tableId!==n)continue;let x=D.recordId;if(O==null||sD(O,x)){let k=D.getValue(i,R,U);if(I.push({id:x,timestamp:U,value:k,version:D.version,type:D.type}),--N<=0)break}}catch(D){Ze.error("Error getting history entry",U,D)}for(let U=I.length;U>0;)w.send(I[--U]);I[0]&&(w.startTime=I[0].timestamp)}else if(!m.omitCurrent)for(let{key:I,value:U,version:L,localTime:D}of i.getRange({start:O??!1,end:O==null?void 0:[O,to.MAXIMUM_KEY],versions:!0}))U&&w.send({id:I,version:L,timestamp:D,value:U})}else{N&&!y&&(y=0);let I=this[kr]?.localTime;if(I===bh&&(i.cache?.delete(O),this[kr]=i.getEntry(O),Ze.trace("re-retrieved record",I,this[kr]?.localTime),I=this[kr]?.localTime),Ze.trace("Subscription from",y,"from",O,I),y<I){let U=[],L=I;do{let D=u.get(L);if(D){m.omitCurrent=!0;let x=Ut(D),k=x.getValue(i,R,L);R&&(x.type="put"),U.push({id:O,value:k,timestamp:L,...x}),L=x.previousLocalTime}else break;N&&N--}while(L>y&&N!==0);for(let D=U.length;D>0;)w.send(U[--D]);w.startTime=I}!m.omitCurrent&&this.doesExist()&&w.send({id:O,version:this[ou],timestamp:I,value:this})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[be]||this[ru])}publish(m,R){this._writePublish(m,R)}_writePublish(m,R){let w=br(this[Ae]),O=this[Ce]||null;Qa(O);let N=this[Ae];w.addWrite({key:O,store:i,entry:this[kr],nodeName:N?.nodeName,validate:()=>{this.validate(m)},before:Fe.publish?.bind(this,N,O,m),beforeIntermediate:ce.publish?.bind(this,N,O,m),commit:(y,I,U)=>{I===void 0&&h&&!E&&jE(),p(O,I?.value??null,I,I?.version||y,0,!0,N,I?.expiresAt,"message",!1,m)}})}validate(m,R){let w,O=a((N,y,I)=>{if(y.type&&N!=null)if(R&&N.__op__&&(N=N.value),y.properties){typeof N!="object"&&(w||(w=[])).push(`Property ${I} must be an object${y.type?" ("+y.type+")":""}`);let U=y.properties;for(let L=0,D=U.length;L<D;L++){let x=U[L],k=O(N[x.name],x,I+"."+x.name);k&&(N[x.name]=k)}}else switch(y.type){case"Int":(typeof N!="number"||N>>0!==N)&&(w||(w=[])).push(`Property ${I} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof N!="number"||!(Math.floor(N)===N&&Math.abs(N)<=9007199254740992))&&(w||(w=[])).push(`Property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof N!="number"&&(w||(w=[])).push(`Property ${I} must be a number`);break;case"ID":typeof N=="string"||N?.length>0&&N.every?.(U=>typeof U=="string")||(w||(w=[])).push(`Property ${I} must be a string, or an array of strings`);break;case"String":typeof N!="string"&&(w||(w=[])).push(`Property ${I} must be a string`);break;case"Boolean":typeof N!="boolean"&&(w||(w=[])).push(`Property ${I} must be a boolean`);break;case"Date":if(!(N instanceof Date)){if(typeof N=="string"||typeof N=="number")return new Date(N);(w||(w=[])).push(`Property ${I} must be a Date`)}break;case"BigInt":if(typeof N!="bigint"){if(typeof N=="string"||typeof N=="number")return BigInt(N);(w||(w=[])).push(`Property ${I} must be a bigint`)}break;case"Bytes":N instanceof Uint8Array||(w||(w=[])).push(`Property ${I} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(N)){if(y.elements)for(let U=0,L=N.length;U<L;U++){let D=N[U],x=O(D,y.elements,I+"[*]");x&&(N[U]=x)}}else(w||(w=[])).push(`Property ${I} must be a Buffer or Uint8Array`);break}y.nullable===!1&&N==null&&(w||(w=[])).push(`Property ${I} is required (and not does not allow null values)`)},"validateValue");for(let N=0,y=S.length;N<y;N++){let I=S[N];if(!I.relationship&&(!R||I.name in m)){let U=O(m[I.name],I,I.name);U&&(m[I.name]=U)}}if(w)throw new ln.ClientError(w.join(". "))}getUpdatedTime(){return this[ou]}wasLoadedFromSource(){return b?!!this[rS]:void 0}static async addAttributes(m){let R=S.slice(0);for(let w of m){if(!w.name)throw new ln.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new ln.ClientError("Attribute names cannot include backticks or forward slashes");R.push(w)}return _t({table:s,database:c,schemaDefined:_,attributes:R}),ze.indexingOperation}static async removeAttributes(m){let R=S.filter(w=>!m.includes(w.name));return _t({table:s,database:c,schemaDefined:_,attributes:R}),ze.indexingOperation}static getRecordCount(m){let R=i.getStats().entryCount,w=5e3,O=1e3,N;R>w&&!m?.exactCount&&(N=O);let y=0;for(let{value:I}of i.getRange({start:!0,lazy:!0,limit:N}))I!=null&&y++;if(N){let I=y;y=0;for(let{value:ne}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:N}))ne!=null&&y++;let U=N*2,L=(y+I)/U,D=Math.pow((y-I+1)/N/2,2)+L*(1-L)/U,x=Math.max(Math.sqrt(D)*R,1),k=Math.round(L*R),_e=Math.max(k-1.96*x,0),de=Math.min(k+1.96*x,R),te=Math.pow(10,Math.round(Math.log10(x)));return te>k&&(te=te/10),y=Math.round(k/te)*te,{recordCount:y,estimatedRange:[Math.round(_e),Math.round(de)]}}return{recordCount:y}}static updatedAttributes(){Vs=this.propertyResolvers={$id:(m,R,w)=>({value:w.key}),$updatedtime:(m,R,w)=>w.version,$record:(m,R,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let R=m.relationship;if(R)if(gA=!0,R.to)m.elements?.definition?(Vs[m.name]=m.resolve=(w,O,N)=>{let y=w[R.from?R.from:t],I=m.elements.definition.tableClass;return N?Go({attribute:R.to,value:y},br(O).getReadTxn(),!1,I).asArray:I.search([{attribute:R.to,value:y}],O).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,R.from&&(m.resolve.from=R.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(R.from){let w=m.definition||m.elements?.definition;w?(Vs[m.name]=m.resolve=(O,N,y)=>{let I=O[R.from];if(I!==void 0){if(m.elements){let U,L=I.map(D=>{let x=y?w.tableClass.primaryStore.getEntry(D,{transaction:br(N).getReadTxn()}):w.tableClass.get(D,N);return x?.then&&(U=!0),x});return R.filterMissing?U?Promise.all(L).then(D=>D.filter(iD)):L.filter(iD):U?Promise.all(L):L}return y?w.tableClass.primaryStore.getEntry(I,{transaction:br(N).getReadTxn()}):w.tableClass.get(I,N)}},m.set=(O,N)=>{if(Array.isArray(N)){let y=N.map(I=>I[Ce]||I[w.tableClass.primaryKey]);O[R.from]=y}else{let y=N[Ce]||N[w.tableClass.primaryKey];O[R.from]=y}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=R.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}o_(this,this)}static async deleteHistory(m=0){let R;for(let{key:w,value:O}of u.getRange({start:0,end:m}))await iu(),Ut(O).tableId===n&&(R=u.remove(w));await R}static async*getHistory(m=0,R=1/0){for(let{key:w,value:O}of u.getRange({start:m,end:R})){await iu();let N=Ut(O);N.tableId===n&&(yield{id:N.recordId,localTime:w,version:N.version,type:N.type,value:N.getValue(i,!0,w),user:N.user})}}static async getHistoryOfRecord(m){let R=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return R;let O=w.localTime;if(!O)throw new Error("The entry does not have a local audit time");let N=0;do{await iu();let y=u.get(O);if(y){let I=Ut(y);R.push({id:I.recordId,localTime:O,version:I.version,type:I.type,value:I.getValue(i,!0,O),user:I.user}),O=I.previousLocalTime}else break}while(N<1e3&&O);return R.reverse()}static cleanup(){W?.remove()}}ze.updatedAttributes();let Xx=ze.prototype;return Xx[GJ]=!0,d&&ze.setTTLExpiration(d/1e3),z&&jx(),ze;function Cl($,m,R){let w;for(let O in r){let N=r[O],y=N.isIndexing,I=R?.[O],U=m?.[O];if(I===U&&!y)continue;w=!0;let L=N.indexNulls,D=(0,au.getIndexedValues)(U,L);if(D){eD&&N.prefetch(D.map(x=>({key:x,value:$})),nD);for(let x=0,k=D.length;x<k;x++)N.remove(D[x],$)}if(D=(0,au.getIndexedValues)(I,L),D){eD&&N.prefetch(D.map(x=>({key:x,value:$})),nD);for(let x=0,k=D.length;x<k;x++)N.put(D[x],$)}}return w}a(Cl,"updateIndices");function Qa($){switch(typeof $){case"number":return!0;case"string":if($.length<659)return!0;if($.length>rD)throw new Error("Primary key size is too large: "+$.length);break;case"object":if($===null)return!0;break;case"bigint":if($<2n**64n&&$>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof $)}if((0,to.writeKey)($,VJ,0)>rD)throw new Error("Primary key size is too large: "+$.length);return!0}a(Qa,"checkValidId");function zE($,m,R,w,O){let N=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),R.transaction?.isDone)return O(null,$);let y=i.getEntry($,R);return y&&m&&(y?.version>(m.lastModified||0)&&(m.lastModified=y.version),y?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=y.localTime)),O(y,$)},"whenPrefetched");return w?N():pe>0?(pe--,N()):new Promise((y,I)=>{pe===0?(pe--,i.prefetch([$],()=>{U(),L()})):(Q.push($),se.push(L),Q.length>Jx&&(pe--,U()));function U(){if(Q.length>0){let D=se;i.prefetch(Q,()=>{pe===-1?U():pe++;for(let x of D)x()}),Q=[],se=[],oe>2&&oe--}else pe=oe,oe<zx&&oe++}a(U,"prefetch");function L(){try{y(N())}catch(D){I(D)}}a(L,"load")})}a(zE,"loadLocalRecord");function Dl($){if(!$?.role)return;let m=$.role.permission;if(m.super_user)return $J;let R=m[c],w,O=R?.tables;if(O)return O[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(Dl,"getTablePermissions");function JE($,m,R,w){if(b){let O;if(R.noCache?O=!0:(m?(!m.value||m.metadataFlags&(nu|su)||m.expiresAt&&m.expiresAt<Date.now())&&(O=!0):O=!0,un(!O,"cache-hit",s)),O){let N=AA($,m,R).then(y=>(y?.value?.[be]&&Ze.error("Can not assign a record with a record property"),R&&(y?.version>(R.lastModified||0)&&(R.lastModified=y.version),R.lastRefreshed=Date.now()),y));if(R?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,$)){if(N.catch(y=>Ze.warn(y)),R?.onlyIfCached&&!w.doesExist())throw new ln.ServerError("Entry is not cached",504);return}else return N}}}a(JE,"ensureLoadedFromSource");function br($){let m=$?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let R=m.next;if(!R)return m=m.next=new Mi,m.lmdbDb=i,m;m=R}while(!0)}else return new u_}a(br,"txnForContext");function XE($,m,R){if(!$)return;QE=$;let w=$.value||$.deref?.()||(QE=i.getEntry($.key))?.value;if(typeof m=="object"){let N=Vs,y=w;for(let I=0,U=m.length;I<U;I++){let L=m[I],D=N?.[L];y=D&&y?D(y,R,!0)?.value:y?.[L],N=D?.definition?.tableClass?.propertyResolvers}return y}let O=Vs[m];return O?O(w,R):w[m]}a(XE,"getAttributeValue");function RA($,m,R,w){let O=br(R).getReadTxn(),N=w?.length,y={transaction:O,lazy:N>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},I;function U(L,D){let x=L?.value;if(!x)return Zi.SKIP;for(let k=0;k<N;k++)if(!I?.includes(k)&&!w[k](x,L))return Zi.SKIP;return D!==void 0&&(L.key=D),L}if(a(U,"processEntry"),N>0||!$.hasEntries){let L=$.map(D=>{if(I=null,typeof D=="object"&&D.key!==void 0)return N>0?U(D):D;if(D==null)return Zi.SKIP;for(let x=0;x<N;x++){let _e=w[x].idFilter;if(_e){if(!_e(D))return Zi.SKIP;I||(I=[]),I.push(x)}}return zE(D,R,y,!1,U)});return Array.isArray($)&&(L=L.filter(D=>D!==Zi.SKIP)),L.hasEntries=!0,L}return $}a(RA,"transformToEntries");async function AA($,m,R){let w=m?.metadataFlags,O=m?.version,N,y;if(!i.attemptLock($,O,()=>{clearTimeout(y);let D=i.getEntry($);!D||!D.value||D.metadataFlags&(nu|su)?N(AA($,i.getEntry($),R)):N(D)}))return new Promise(D=>{N=D,y=setTimeout(()=>{i.unlock($,O)},qJ)});let I=m?.value,U={requestContext:R,replacingRecord:I,replacingVersion:O,source:null,resourceCache:R?.resourceCache},L=R?.responseHeaders;return new Promise((D,x)=>{let k;sS(Xe(U,async _e=>{let de=performance.now(),te,ne,Be;try{for(let Me of ze.sources)if(Me.get&&(!Me.get.reliesOnPrototype||Me.prototype.get)&&(U.source=Me,te=await Me.get($,U),te))break;Be=w&nu;let fe=U.lastModified||Be&&O;ne=Be||fe>O||!I,fe||(fe=(0,au.getNextMonotonicTime)());let Ye=performance.now()-de;if(Gr(Ye,"cache-resolution",s),L&&L.append("Server-Timing",`cache-resolve;dur=${Ye.toFixed(2)}`),_e.timestamp=fe,d&&!U.expiresAt&&(U.expiresAt=Date.now()+d),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==$&&(te[t]=$)}k=!0,D({version:fe,value:te})}catch(fe){fe.message+=` while resolving record ${$} for ${s}`,I&&((fe.code==="ECONNRESET"||fe.code==="ECONNREFUSED"||fe.code==="EAI_AGAIN")&&!R?.mustRevalidate||R?.staleIfError&&(fe.statusCode===500||fe.statusCode===502||fe.statusCode===503||fe.statusCode===504))?(D({version:O,value:I}),Ze.trace(fe.message,"(returned stale record)")):x(fe),U.transaction.abort();return}if(R?.noCacheStore){U.transaction.abort();return}br(U).addWrite({key:$,store:i,entry:m,nodeName:"source",commit:(fe,Ye)=>{if(Ye?.version!==O)return;let Me=Cl($,I,te);te?(ce.put?.(U,$,te),p($,te,Ye,fe,0,E&&ne||null,U,U.expiresAt,"put",!!Be)):(ce.delete?.(U,$),E||h?p($,null,Ye,fe,0,E&&ne||null,U,0,"delete",!!Be):i.remove($,O))}})}),()=>{i.unlock($,O)},_e=>{i.unlock($,O),k&&Ze.error("Error committing cache update",_e)})})}a(AA,"getFromSource");function jE(){if(Lt!==Il&&(Il=Lt,(0,eo.getWorkerIndex)()===(0,eo.getWorkerCount)()-1)){if(wl&&clearTimeout(wl),!Lt)return;let $=new Date;$.setMonth(0),$.setDate(1),$.setHours(0),$.setMinutes(0),$.setSeconds(0);let m=Math.ceil((Date.now()-$.getTime())/Lt)*Lt+$.getTime(),R=a(w=>{Ze.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),wl=setTimeout(()=>G=G.then(async()=>{if(R(Math.max(w+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout(wl);return}let O=50,N=new Array(O),y=0;Ze.trace(`Starting cleanup scan for ${s}`);try{let I=0;for(let{key:U,value:L,version:D,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let k;L===null&&!E&&D+FJ<Date.now()?k=i.remove(U,D):x&&x+f<Date.now()&&(k=ze.evict(U,L,D),I++),k&&(await N[y],N[y]=k.catch(_e=>{Ze.error("Cleanup error",_e)}),++y>=O&&(y=0)),await iu()}Ze.trace(`Finished cleanup scan for ${s}, evicted ${I} entries`)}catch(I){Ze.trace(`Error in cleanup scan for ${s}:`,I)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");R(m)}}a(jE,"scheduleCleanup");function OA(){W=u?.addDeleteRemovalCallback(n,$=>{let m=i.getEntry($);m?.value===null&&i.remove($,m.version)})}a(OA,"addDeleteRemoval");function jx(){(0,eo.getWorkerIndex)()===0&&setInterval(async()=>{try{let $=z.name,m=r[$];if(!m)throw new Error(`expiresAt attribute ${z} must be indexed`);for(let{value:R}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let w=i.getEntry(R);w?.value?.[$]<Date.now()&&ze.evict(R,w.value,w.version),await iu()}}catch($){Ze.error("Error in evicting old records",$)}},xJ).unref()}a(jx,"runRecordExpirationEviction")}function nS(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function nD(){}function YJ(e){aD=e}function hd(e,t){let r=t?.type;return e===null?e:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Date"?(typeof e!="number"&&!KJ.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,pd.autoCast)(e):e}function sD(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 n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function sS(e,t,r){return e?.then?e.then(t,r):t(e)}function md(e,t){e[kr]=t,e[be]=t?.value??null,e[ou]=t?.version}function iD(e){return e!=null}var vn,Zi,au,oD,lu,ln,cu,uu,Ze,to,eo,pd,HJ,aD,xJ,FJ,eD,qJ,ou,GJ,kr,ru,tD,kJ,rS,ca,nu,su,VJ,rD,$J,w_e,KJ,iu,Td=Re(()=>{vn=B(M()),Zi=require("lmdb"),au=B(Cr()),oD=require("lodash");On();Bh();lu=B(j());_b();ln=B(Z()),cu=B(gs()),uu=B(In());Oe();d_();Ze=B(Y());c_();Ui();to=require("ordered-binary"),eo=B(tt());Ci();pd=B(J());Bo();Ns();Zl();HJ=new Uint8Array(9);HJ[8]=192;xJ=6e4,FJ=864e5;lu.initSync();eD=lu.get(vn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),qJ=1e4,ou=Symbol.for("version"),GJ=Symbol.for("incremental-update"),kr=Symbol("entry"),ru=Symbol("is-saving"),tD=1,kJ=2,rS=Symbol("loaded-from-source"),ca={isNotification:!0,ensureLoaded:!1},nu=1,su=8,VJ=Buffer.allocUnsafeSlow(8192),rD=1978,$J={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},w_e=(0,pd.convertToMS)(lu.get(vn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(Sd,"makeTable");a(nS,"attributesAsObject");a(nD,"noop");a(YJ,"setServerUtilities");KJ=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(hd,"coerceType");a(sD,"isDescendantId");iu=a(()=>new Promise(setImmediate),"rest");a(sS,"when");a(md,"updateResource");a(iD,"exists")});var Ge={};qe(Ge,{database:()=>kc,databases:()=>st,dropDatabase:()=>Ep,dropTableMeta:()=>jJ,getDatabases:()=>Cn,getTables:()=>WJ,onUpdatedTable:()=>lS,readMetaDb:()=>_u,resetDatabases:()=>QJ,table:()=>_t,tables:()=>$r});function WJ(){return bd||Cn(),$r||{}}function Cn(){if(bd)return st;bd=!0,_a=new Map;let e=(0,Jt.getHdbBasePath)()&&(0,et.join)((0,Jt.getHdbBasePath)(),Yr.DATABASES_DIR_NAME),t=(0,Jt.get)(Yr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Jt.get)(Yr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Vr.existsSync)(e)?e:(0,et.join)((0,Jt.getHdbBasePath)(),Yr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Vr.existsSync)(e))for(let r of(0,Vr.readdirSync)(e,{withFileTypes:!0})){let n=(0,et.basename)(r.name,".mdb");r.isFile()&&(0,et.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&_u((0,et.join)(e,r.name),null,n)}if((0,Vr.existsSync)((0,la.getBaseSchemaPath)())){for(let r of(0,Vr.readdirSync)((0,la.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,et.join)((0,la.getBaseSchemaPath)(),r.name),s=(0,et.join)((0,la.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Vr.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,et.extname)(i.name).toLowerCase()===".mdb"){let o=(0,et.join)(s,i.name);_u((0,et.join)(n,i.name),(0,et.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,Vr.existsSync)(s))for(let o of(0,Vr.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,et.extname)(o.name).toLowerCase()===".mdb"&&_u((0,et.join)(s,o.name),(0,et.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,et.join)(c.path,(0,et.basename)(o+".mdb"));(0,Vr.existsSync)(u)&&_u(u,o,r,null,!0)}}for(let r in st){let n=_a.get(r);if(n){let s=st[r];r.includes("delete")&&_n.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(_n.trace(`delete table class ${i}`),delete s[i])}else if(delete st[r],r==="data"){for(let s in $r)delete $r[s];delete $r[Nd]}}return _a=null,st}}function QJ(){bd=!1;for(let[,e]of ai)e.needsDeletion=!0;Cn();for(let[e,t]of ai)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),ai.delete(e));return st}function _u(e,t,r=cS,n,s){let i=new oS.default(e,!1);try{let o=ai.get(e);o?o.needsDeletion=!1:(o=(0,Rd.open)(i),ai.set(e,o));let c=new ro.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(gd.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,Vr.existsSync)(n)&&(i.path=n,_=(0,Rd.open)(i),_.isLegacy=!0):_=jl(o));let l=_D(r),d=l[Nd],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[S,p]=E.toString().split("/");p===""?p=h.name:p||(p=S,S=t,h.name||(h.name=p,h.indexed=!h.is_hash_attribute)),d?.add(S);let g=f.get(S);g||f.set(S,g={attributes:[]}),(p==null||h.is_hash_attribute)&&(g.primary=h),p!=null&&g.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:S,primary:p}=h;if(!p){for(let Q of S)if(Q.is_hash_attribute||Q.isPrimaryKey){p=Q;break}if(!p){_n.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(S)}`);continue}}let g=l[E],A={},b=[],v,G,H=typeof p.audit=="boolean"?p.audit:(0,Jt.get)(Yr.CONFIG_PARAMS.LOGGING_AUDITLOG),P=p.trackDeletes,z=p.expiration,W=p.eviction;if(g)A=g.indices,b=g.attributes,g.schemaVersion++;else{v=p.tableId,v?v>=(u.get(ua)||0)&&u.putSync(ua,v+1):(p.tableId=v=u.get(ua),v||(v=1),u.putSync(ua,v+1),u.putSync(p.key,p));let Q=new ro.default(!p.is_hash_attribute,p.is_hash_attribute);G=Ql(o.openDB(p.key,Q)),G.rootStore=o,G.tableId=v}for(let Q of S){Q.attribute=Q.name;try{if(!Q.is_hash_attribute&&(Q.indexed||Q.attribute&&!Q.name)){if(!A[Q.name]){let pe=new ro.default(!Q.is_hash_attribute,Q.is_hash_attribute);A[Q.name]=o.openDB(Q.key,pe),A[Q.name].indexNulls=Q.indexNulls}let se=b.find(pe=>pe.name===Q.name);se?b.splice(b.indexOf(se),1,Q):b.push(Q)}}catch(se){_n.error("Error trying to update attribute",Q,b,A,se)}}if(!g){g=dD(l,E,Sd({primaryStore:G,auditStore:_,audit:H,expirationMS:z&&z*1e3,evictionMS:W&&W*1e3,trackDeletes:P,tableName:E,tableId:v,primaryKey:p.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:A,attributes:S,schemaDefined:p.schemaDefined,dbisDB:u})),g.schemaVersion=1;for(let Q of uS)Q(g)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function _D(e){let t=st[e];if(t||(e==="data"?t=st[e]=$r:e==="system"?Object.defineProperty(st,"system",{value:t=Object.create(null),configurable:!0}):t=st[e]=Object.create(null)),_a&&!_a.has(e)){let r=new Set;t[Nd]=r,_a.set(e,r)}return t}function dD(e,t,r){return e[t]=r,r}function kc({database:e,table:t}){e||(e=cS),Cn();let r=_D(e),n=(0,et.join)((0,Jt.getHdbBasePath)(),Yr.DATABASES_DIR_NAME),s=(0,Jt.get)(Yr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Jt.get)(Yr.CONFIG_PARAMS.STORAGE_PATH)||((0,Vr.existsSync)(n)?n:(0,et.join)((0,Jt.getHdbBasePath)(),Yr.LEGACY_DATABASES_DIR_NAME));let o=(0,et.join)(n,(i?t:e)+".mdb"),c=ai.get(o);if(!c){let u=new oS.default(o,!1);c=(0,Rd.open)(u),ai.set(o,c)}return c}async function Ep(e){if(!st[e])throw new Error("Schema does not exist");let t=st[e];for(let r in t){let s=t[r].primaryStore.rootStore;ai.delete(s.path),s.status==="open"&&(await s.close(),await cD.remove(s.path))}if(e==="data"){for(let r in $r)delete $r[r];delete $r[Nd]}delete st[e]}function _t({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=cS);let l=kc({database:t,table:e}),d=st[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,S,p;u==null&&(u=!0);let g=new ro.default(!1);for(let P of i)P.attribute?(P.name=P.attribute,P.indexed=!0):P.attribute=P.name,P.expiresAt&&(P.indexed=!0);let A,b;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let P=l.auditStore;P||(P=jl(l)),h=i.find(se=>se.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Jt.get)(Yr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),n&&(h.eviction=n),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),_n.trace(`${e} table loading, opening primary store`);let z=new ro.default(!1,!0),W=e+"/",Q=Ql(l.openDB(W,z));Q.rootStore=l,p=l.dbisDb=l.openDB(gd.INTERNAL_DBIS_NAME,g),Q.tableId=p.get(ua),Q.tableId||(Q.tableId=1),p.putSync(ua,Q.tableId+1),h.tableId=Q.tableId,f=dD(d,e,Sd({primaryStore:Q,auditStore:P,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:E,tableName:e,tableId:Q.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:p})),f.schemaVersion=1,A=!0,H(),p.put(W,h)}S=f.indices,p=p||(l.dbisDb=l.openDB(gd.INTERNAL_DBIS_NAME,g)),f.dbisDB=p;let v=[];for(let{key:P,value:z}of p.getRange({start:!0})){let[W,Q]=P.toString().split("/");if(Q===""&&(Q=z.name),Q){if(W!==e)continue}else Q=W;if(!i.find(pe=>pe.name===Q)?.indexed&&z.indexed&&!z.isPrimaryKey){H(),A=!0,p.remove(P);let pe=f.indices[W];pe&&v.push(pe)}}let G=[];try{for(let P of i||[]){if(P.relationship)continue;let z=e+"/"+(P.name||"");Object.defineProperty(P,"key",{value:z,configurable:!0});let W=p.get(z);if(P.isPrimaryKey){if(W=W||p.get(z=e+"/")||{},o!==f.audit||(+r||void 0)!==(+W.expiration||void 0)||(+n||void 0)!==(+W.eviction||void 0)){let se=Object.assign({},W);typeof o=="boolean"&&(o&&f.enableAuditing(o),se.audit=o),r&&(se.expiration=+r),n&&(se.eviction=+n),A=!0,H(),p.put(z,se)}continue}W?.attribute&&!W.name&&(W.indexed=!0);let Q=!W||W.type!==P.type||W.indexed!==P.indexed||JSON.stringify(W.attributes)!==JSON.stringify(P.attributes)||JSON.stringify(W.elements)!==JSON.stringify(P.elements);if(P.indexed){let se=new ro.default(!0,!1),pe=l.openDB(z,se);(Q||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<du.workerData?.restartNumber)&&(A=!0,H(),W=p.get(z),(Q||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<du.workerData?.restartNumber)&&(A=!0,P.lastIndexedKey=W?.lastIndexedKey||!1,P.indexingPID=process.pid,pe.isIndexing=!0,Object.defineProperty(P,"dbi",{value:pe}),P.indexNulls===void 0&&(P.indexNulls=!0),G.push(P)),p.put(z,P)),W?.indexNulls&&P.indexNulls===void 0&&(P.indexNulls=!0),pe.indexNulls=P.indexNulls,S[P.name]=pe}else Q&&(A=!0,H(),p.put(z,P))}}finally{b&&b()}if(A&&(f.schemaVersion++,f.updatedAttributes()),_n.trace(`${e} table loading, running index`),G.length>0||v.length>0?f.indexingOperation=XJ(f,G,v):A&&Ad.signalSchemaChange(new Od.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,A)for(let P of uS)P(f,_!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),_n.trace(`${e} table loaded`),f;function H(){b||l.transactionSync(()=>({then(P){b=P}}))}a(H,"startTxn")}async function XJ(e,t,r){try{let n=e.schemaVersion;await Ad.signalSchemaChange(new Od.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,S=(0,uD.getIndexedValues)(l[h]);if(S)for(let p=0,g=S.length;p<g;p++)E.dbi.put(S[p],_)}}),s.then(()=>u--,f=>{u--,_n.error(f)}),du.workerData&&du.workerData.restartNumber!==lD.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>zJ?await s:u>JJ&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await Ad.signalSchemaChange(new Od.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){_n.error("Error in indexing",n)}}function jJ({table:e,database:t}){let r=kc({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function lS(e){uS.push(e)}var Jt,gd,Rd,et,Vr,la,ro,oS,Yr,cD,aS,uD,Ad,Od,du,_n,lD,cS,Nd,$r,st,ua,uS,bd,ai,_a,zJ,JJ,Oe=Re(()=>{Jt=B(j()),gd=B(Et()),Rd=require("lmdb"),et=require("path"),Vr=require("fs"),la=B(Je());Td();ro=B(p_()),oS=B(T_()),Yr=B(M()),cD=B(require("fs-extra")),aS=require("../index"),uD=B(Cr()),Ad=B(gs()),Od=B(In()),du=require("worker_threads"),_n=B(Y()),lD=B(tt());Ci();Bo();cS="data",Nd=Symbol("defined-tables");(0,Jt.initSync)();$r=Object.create(null),st=Object.create(null);(0,aS._assignPackageExport)("databases",st);(0,aS._assignPackageExport)("tables",$r);ua=Symbol.for("next-table-id"),uS=[],ai=new Map;a(WJ,"getTables");a(Cn,"getDatabases");a(QJ,"resetDatabases");a(_u,"readMetaDb");a(_D,"ensureDB");a(dD,"setTable");a(kc,"database");a(Ep,"dropDatabase");a(_t,"table");zJ=1e3,JJ=10;a(XJ,"runIndexing");a(jJ,"dropTableMeta");a(lS,"onUpdatedTable")});var J=T((H_e,yD)=>{"use strict";var ci=require("path"),pD=require("fs-extra"),ur=Y(),fD=require("fs-extra"),yd=require("os"),ZJ=require("net"),e4=require("recursive-iterator"),it=M(),t4=rO(),ED=require("papaparse"),Id=require("moment"),{inspect:r4}=require("util"),hD=require("is-number"),B_e=require("lodash"),n4=require("minimist"),s4=require("https"),i4=require("http"),{hdb_errors:wd}=Z(),o4=/^((\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)))$/,SD=require("util").promisify(setTimeout),a4=100,c4=5,u4="",l4=4,mD={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};yD.exports={isEmpty:Kr,isEmptyOrZeroLength:es,arrayHasEmptyValues:f4,arrayHasEmptyOrZeroLengthValues:E4,buildFolderPath:h4,isBoolean:TD,errorizeMessage:_4,stripFileExtension:p4,autoCast:S4,autoCastJSON:gD,autoCastJSONDeep:dS,removeDir:T4,compareVersions:g4,isCompatibleDataVersion:R4,escapeRawValue:A4,unescapeValue:O4,stringifyProps:b4,timeoutPromise:y4,isClusterOperation:w4,getClusterUser:D4,checkGlobalSchemaTable:C4,getHomeDir:AD,getPropsFilePath:N4,promisifyPapaParse:L4,removeBOM:OD,createEventPromise:M4,checkProcessRunning:U4,checkSchemaTableExist:P4,checkSchemaExists:bD,checkTableExists:ND,getStartOfTomorrowInSeconds:v4,getLimitKey:B4,isObject:m4,isNotEmptyAndHasValue:d4,autoCasterIsNumberCheck:RD,backtickASTSchemaItems:H4,isPortTaken:I4,createForkArgs:x4,autoCastBoolean:F4,async_set_timeout:SD,getTableHashAttribute:q4,doesSchemaExist:G4,doesTableExist:k4,stringifyObj:V4,ms_to_time:$4,changeExtension:Y4,getEnvCliRootPath:fS,noBootFile:K4,httpRequest:W4,transformReq:Q4,convertToMS:z4,PACKAGE_ROOT:it.PACKAGE_ROOT};function _4(e){return e instanceof Error?e:new Error(e)}a(_4,"errorizeMessage");function Kr(e){return e==null}a(Kr,"isEmpty");function d4(e){return!Kr(e)&&(e||e===0||e===""||TD(e))}a(d4,"isNotEmptyAndHasValue");function es(e){return Kr(e)||e.length===0||e.size===0}a(es,"isEmptyOrZeroLength");function f4(e){if(Kr(e))return!0;for(let t=0;t<e.length;t++)if(Kr(e[t]))return!0;return!1}a(f4,"arrayHasEmptyValues");function E4(e){if(es(e))return!0;for(let t=0;t<e.length;t++)if(es(e[t]))return!0;return!1}a(E4,"arrayHasEmptyOrZeroLengthValues");function h4(...e){try{return e.join(ci.sep)}catch{console.error(e)}}a(h4,"buildFolderPath");function TD(e){return Kr(e)?!1:e===!0||e===!1}a(TD,"isBoolean");function m4(e){return Kr(e)?!1:typeof e=="object"}a(m4,"isObject");function p4(e){return es(e)?u4:e.slice(0,-l4)}a(p4,"stripFileExtension");function S4(e){return Kr(e)||e===""||typeof e!="string"?e:mD[e]!==void 0?mD[e]:RD(e)===!0?Number(e):o4.test(e)?new Date(e):e}a(S4,"autoCast");function gD(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(gD,"autoCastJSON");function dS(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=dS(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=dS(r);n!==r&&(e[t]=n)}return e}else return gD(e)}a(dS,"autoCastJSONDeep");function RD(e){if(e.startsWith("0.")&&hD(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&hD(e))}a(RD,"autoCasterIsNumberCheck");async function T4(e){if(es(e))throw new Error(`Directory path: ${e} does not exist`);try{await fD.emptyDir(e),await fD.remove(e)}catch(t){throw ur.error(`Error removing files in ${e} -- ${t}`),t}}a(T4,"removeDir");function g4(e,t){if(es(e)){ur.info("Invalid current version sent as parameter.");return}if(es(t)){ur.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(g4,"compareVersions");function R4(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(R4,"isCompatibleDataVersion");function A4(e){if(Kr(e))return e;let t=String(e);return t==="."?it.UNICODE_PERIOD:t===".."?it.UNICODE_PERIOD+it.UNICODE_PERIOD:t.replace(it.FORWARD_SLASH_REGEX,it.UNICODE_FORWARD_SLASH)}a(A4,"escapeRawValue");function O4(e){if(Kr(e))return e;let t=String(e);return t===it.UNICODE_PERIOD?".":t===it.UNICODE_PERIOD+it.UNICODE_PERIOD?"..":String(e).replace(it.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(O4,"unescapeValue");function b4(e,t){if(Kr(e))return ur.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+yd.EOL}!es(n)&&n[0]===";"?r+=" "+n+s+yd.EOL:es(n)||(r+=n+"="+s+yd.EOL)}catch{ur.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(b4,"stringifyProps");function AD(){let e;try{e=yd.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(AD,"getHomeDir");function N4(){let e=ci.join(AD(),it.HDB_HOME_DIR_NAME,it.BOOT_PROPS_FILE_NAME);return pD.existsSync(e)||(e=ci.join(__dirname,"../","hdb_boot_properties.file")),e}a(N4,"getPropsFilePath");function y4(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(y4,"timeoutPromise");async function I4(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=ZJ.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(I4,"isPortTaken");function w4(e){try{return it.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){ur.error(`Error checking operation against cluster ops ${t}`)}return!1}a(w4,"isClusterOperation");function C4(e,t){let r=(Oe(),ee(Ge)).getDatabases();if(!r[e])return wd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return wd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(C4,"checkGlobalSchemaTable");function D4(e,t){if(Kr(t)){ur.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Kr(e)||es(e)){ur.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){ur.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){ur.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(D4,"getClusterUser");function L4(){ED.parsePromise=function(e,t,r){return new Promise(function(n,s){ED.parse(e,{header:!0,transformHeader:OD,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(L4,"promisifyPapaParse");function OD(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(OD,"removeBOM");function M4(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;ur.info(`Got cluster status event response: ${r4(s)}`);try{i.cancel()}catch{ur.error("Error trying to cancel timeout.")}n(s)})})}a(M4,"createEventPromise");async function U4(e){let t=!0,r=0;do await SD(a4*r++),(await t4.findPs(e)).length>0&&(t=!1);while(t&&r<c4);if(t)throw new Error(`process ${e} was not started`)}a(U4,"checkProcessRunning");function P4(e,t){let r=bD(e);if(r)return r;let n=ND(e,t);if(n)return n}a(P4,"checkSchemaTableExist");function bD(e){let{getDatabases:t}=(Oe(),ee(Ge));if(!t()[e])return wd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(bD,"checkSchemaExists");function ND(e,t){let{getDatabases:r}=(Oe(),ee(Ge));if(!r()[e][t])return wd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(ND,"checkTableExists");function v4(){let e=Id().utc().add(1,it.MOMENT_DAYS_TAG).startOf(it.MOMENT_DAYS_TAG).unix(),t=Id().utc().unix();return e-t}a(v4,"getStartOfTomorrowInSeconds");function B4(){return Id().utc().format("DD-MM-YYYY")}a(B4,"getLimitKey");function H4(e){try{let t=new e4(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){ur.error("Got an error back ticking items."),ur.error(t)}}a(H4,"backtickASTSchemaItems");function x4(e){return[e]}a(x4,"createForkArgs");function F4(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(F4,"autoCastBoolean");function q4(e,t){let{getDatabases:r}=(Oe(),ee(Ge)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(q4,"getTableHashAttribute");function G4(e){let{getDatabases:t}=(Oe(),ee(Ge));return t()[e]!==void 0}a(G4,"doesSchemaExist");function k4(e,t){let{getDatabases:r}=(Oe(),ee(Ge));return r()[e]?.[t]!==void 0}a(k4,"doesTableExist");function V4(e){try{return JSON.stringify(e)}catch{return e}}a(V4,"stringifyObj");function $4(e){let t=Id.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a($4,"ms_to_time");function Y4(e,t){let r=ci.basename(e,ci.extname(e));return ci.join(ci.dirname(e),r+t)}a(Y4,"changeExtension");function fS(){if(process.env[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=n4(process.argv);if(e[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(fS,"getEnvCliRootPath");var _S;function K4(){if(_S)return _S;let e=fS();fS()&&pD.pathExistsSync(ci.join(e,it.HDB_CONFIG_FILE))&&(_S=!0)}a(K4,"noBootFile");function W4(e,t){let r;return e.protocol==="http:"?r=i4:r=s4,new Promise((n,s)=>{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",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(W4,"httpRequest");function Q4(e){if(!e.schema&&!e.database){e.schema=it.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Q4,"transformReq");function z4(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(z4,"convertToMS")});var j=T((F_e,DD)=>{"use strict";var ES=require("fs-extra"),no=require("path"),ID=require("os"),J4=require("properties-reader"),Eu=Y(),fu=J(),ae=M(),Cd=xr(),X4="Error initializing environment manager",Dd="BOOT_PROPS_FILE_PATH",wD=!1,j4={[ae.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},ys={};DD.exports={BOOT_PROPS_FILE_PATH:Dd,getHdbBasePath:Z4,setHdbBasePath:e3,get:CD,initSync:r3,setProperty:De,initTestEnvironment:n3};function Z4(){return ys[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Z4,"getHdbBasePath");function e3(e){ys[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(e3,"setHdbBasePath");function CD(e){let t=Cd.getConfigValue(e);return t===void 0?ys[e]:t}a(CD,"get");function De(e,t){j4[e]&&(ys[e]=t),Cd.updateConfigObject(e,t)}a(De,"setProperty");function t3(){let e;try{e=fu.getPropsFilePath(),ES.accessSync(e,ES.constants.F_OK|ES.constants.R_OK),wD=!0;let t=J4(e);return ys[ae.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ae.HDB_SETTINGS_NAMES.INSTALL_USER),ys[ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),ys[Dd]=e,!0}catch{return Eu.trace(`Environment manager found no properties file at ${e}`),!1}}a(t3,"doesPropFileExist");function r3(e=!1){try{(wD||t3()||fu.noBootFile())&&(Cd.initConfig(e),ys[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Cd.getConfigValue(ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Eu.error(X4),Eu.error(t),console.error(t),process.exit(1)}}a(r3,"initSync");function n3(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=no.join(__dirname,"../../","unitTests");ys[Dd]=no.join(u,"hdb_boot_properties.file"),De(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,no.join(u,"settings.test")),De(ae.HDB_SETTINGS_NAMES.INSTALL_USER,ID.userInfo()?ID.userInfo().username:void 0),De(ae.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),De(ae.HDB_SETTINGS_NAMES.LOG_PATH_KEY,no.join(u,"envDir","log")),De(ae.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),De(ae.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),De(ae.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),De(ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,no.join(u,"envDir")),De(ae.CONFIG_PARAMS.STORAGE_PATH,no.join(u,"envDir")),s&&(De(ae.CONFIG_PARAMS.HTTP_SECUREPORT,CD(ae.CONFIG_PARAMS.HTTP_PORT)),De(ae.CONFIG_PARAMS.HTTP_PORT,null)),De(ae.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),De(ae.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),De(ae.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,fu.isEmpty(i)?!1:i),De(ae.CONFIG_PARAMS.HTTP_CORS,fu.isEmpty(i)?!1:i),De(ae.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),De(ae.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),De(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),De(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),De(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,no.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),De(ae.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,fu.isEmpty(c)?!1:c),o&&(De("CORS_ACCESSLIST",o),De(ae.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(De(ae.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),De(ae.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(De(ae.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),De(ae.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(De(ae.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),De(ae.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Dd}. Please check your boot props and settings files`;Eu.fatal(r),Eu.error(t)}}a(n3,"initTestEnvironment")});var mS={};qe(mS,{loadGQLSchema:()=>o3,start:()=>hS,startOnMainThread:()=>i3});function hS({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),f=new Map,E=[],h;for(let p of d.definitions)switch(p.kind){case u.OBJECT_TYPE_DEFINITION:let G=function(H){if(H.kind==="NonNullType"){let W=G(H.type);return W.nullable=!1,W}if(H.kind==="ListType")return{type:"array",elements:G(H.type)};let z={type:H.name?.value};return Object.defineProperty(z,"location",{value:H.loc.startToken}),z};a(G,"getProperty");let g=p.name.value,A=[],b={table:null,database:null,properties:A};f.set(g,b);for(let H of p.directives){if(H.name.value==="table"){for(let P of H.arguments)b[P.name.value]=P.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=g),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,E.push(b)}if(H.name.value==="sealed"&&(b.sealed=!0),H.name.value==="export"){b.export=!0;for(let P of H.arguments)P.name.value==="name"&&(b.export={name:P.value.value})}}let v=!1;for(let H of p.fields){let P=G(H.type);P.name=H.name.value,A.push(P);for(let z of H.directives)if(z.name.value==="primaryKey")v?console.warn("Can not define two attributes as a primary key"):(P.isPrimaryKey=!0,v=!0);else if(z.name.value==="indexed")P.indexed=!0;else if(z.name.value==="relationship"){let W={};for(let Q of z.arguments)W[Q.name.value]=Q.value.value;P.relationship=W}else if(z.name.value==="createdTime")P.assignCreatedTime=!0;else if(z.name.value==="updatedTime")P.assignUpdatedTime=!0;else if(z.name.value==="expiresAt")P.expiresAt=!0;else if(z.name.value==="allow"){let W=P.authorizedRoles=[];for(let Q of z.arguments)Q.name.value==="role"&&W.push(Q.value.value)}}b.type=g,g==="Query"&&(h=b)}function S(p){let g=f.get(p.type);g?(Object.defineProperty(p,"properties",{value:g.properties}),Object.defineProperty(p,"definition",{value:g})):p.type==="array"?S(p.elements):s3.includes(p.type)||(0,LD.getWorkerIndex)()===0&&console.error(`The type ${p.type} is unknown at line ${p.location.line}, column ${p.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let p of f.values())for(let g of p.properties)S(g);for(let p of E)p.tableClass=e(p),p.export&&(p.export.name===""?i.set((0,Ld.dirname)(n),p.tableClass):i.set((0,Ld.dirname)(n)+"/"+(p.export.name||p.type),p.tableClass));if(h)for(let p of h.properties){let g=f.get(p.type);if(!g)throw new Error(`${p.type} was not found as a Query export`);i.set((0,Ld.dirname)(n)+"/"+p.name,g.tableClass)}}}var Ld,LD,s3,i3,o3,MD=Re(()=>{Ld=require("path");Oe();LD=B(tt()),s3=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(hS,"start");i3=hS,o3=hS({ensureTable:_t}).handleFile});async function Md(e){return a3?(hu||(hu=c3(l3)),(await(await hu).import(e)).namespace):import(e)}async function c3(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),hu=new Compartment({console,Math,Date,fetch:u3,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,PD.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:Ft,tables:$r,databases:st})}};let n=await(0,UD.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),hu}function u3(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 l3(){return{Resource:Ft,tables:$r}}var UD,PD,a3,hu,pS=Re(()=>{On();Oe();UD=require("fs/promises"),PD=require("path"),a3=!1;a(Md,"secureImport");a(c3,"getCompartment");a(u3,"secureOnlyFetch");a(l3,"getGlobalVars")});var TS={};qe(TS,{handleFile:()=>_3});async function _3(e,t,r,n){let s=new Map,i=(0,vD.pathToFileURL)(r).toString(),o=await Md(i);u(o.default)&&n.set((0,SS.dirname)(t),o.default),c(o,(0,SS.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var vD,SS,BD=Re(()=>{vD=require("url");pS();SS=require("path");a(_3,"handleFile")});var RS={};qe(RS,{start:()=>d3});function d3({resources:e}){e.set("login",gS),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var gS,HD=Re(()=>{On();a(d3,"start");gS=class extends Ft{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var $D={};qe($D,{parse:()=>OS,streamAsJSON:()=>mu,stringify:()=>so});function mu(e){return new AS({value:e})}function xD(e){return console.error(e),JSON.stringify(e.toString())}function FD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function so(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===kD)return VD(e);if(t.resolution)return t.resolution.then(()=>so(e));throw t}}function VD(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=VD(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+so(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function OS(e){return h3.test(e)?f3.parse(e):JSON.parse(e)}var qD,GD,f3,E3,kD,AS,h3,bS=Re(()=>{qD=require("stream"),GD=B(require("json-bigint-fixes")),f3=(0,GD.default)({useNativeBigInt:!0}),E3=1e4,kD={};BigInt.prototype.toJSON=function(){throw kD};a(mu,"streamAsJSON");AS=class extends qD.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),xD)}catch(s){yield xD(s)}else yield so(t)}else yield so(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);FD(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>E3?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 FD(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))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}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(xD,"handleError");a(FD,"when");a(so,"stringify");a(VD,"jsStringify");h3=/-?\d{16,}/;a(OS,"parse")});var Ud=T((j_e,YD)=>{"use strict";var m3=Ln();YD.exports={writeTransaction:p3};function p3(e,t,r){return m3.writeTransaction(e,t,r)}a(p3,"writeTransaction")});var zD=T((tde,QD)=>{"use strict";var S3=sn(),T3=ti(),KD=Y(),g3=on(),ede=Ud(),R3=require("clone"),yS=require("alasql"),A3=V_(),WD=require("util"),O3=WD.promisify(T3.getTableSchema),b3=WD.promisify(S3.search),N3=M(),NS=J();A3(yS);QD.exports={update:I3};var y3="There was a problem performing this update. Please check the logs and try again.";async function I3({statement:e,hdb_user:t}){let r=await O3(e.table.databaseid,e.table.tableid),n=w3(e.columns);NS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=R3(s),c=NS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=yS.parse(u).statements[0],l=await b3(_),d=C3(n,l);return D3(o,d,t)}a(I3,"update");function w3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=yS.compile(`SELECT ${r.expression.toString()} AS [${N3.FUNC_VAL}] FROM ?`)}),t}catch(t){throw KD.error(t),new Error(y3)}}a(w3,"createUpdateRecord");function C3(e,t){return NS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(C3,"buildUpdateRecords");async function D3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await g3.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){KD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(D3,"updateRecords")});var XD=T((ide,JD)=>{var L3=require("alasql"),M3=sn(),U3=Y(),P3=Ln(),wS=require("util"),IS=J(),v3=M(),B3=ti(),nde=Ud(),sde=on(),H3="record",x3="successfully deleted",F3=wS.callbackify(V3),q3=wS.promisify(M3.search),G3=wS.promisify(B3.getTableSchema);JD.exports={convertDelete:F3};function k3(e){return`${e.deleted_hashes.length} ${H3}${e.deleted_hashes.length===1?"":"s"} ${x3}`}a(k3,"generateReturnMessage");async function V3({statement:e,hdb_user:t}){let r=await G3(e.table.databaseid,e.table.tableid);IS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=IS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=L3.parse(o).statements[0],u={operation:v3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await q3(c);let _=await P3.deleteRecords(u);return IS.isEmptyOrZeroLength(_.message)&&(_.message=k3(_)),delete _.txn_time,_}catch(_){throw U3.error(_),_.hdb_code?_.message:_}}a(V3,"convertDelete")});var rL=T((ade,tL)=>{"use strict";var $3=Gi(),{hdb_errors:jD}=Z(),{getDatabases:ZD}=(Oe(),ee(Ge));tL.exports={checkSchemaExists:eL,checkSchemaTableExists:Y3,schema_describe:$3};async function eL(e){if(!ZD()[e])return jD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(eL,"checkSchemaExists");async function Y3(e,t){let r=await eL(e);if(r)return r;if(!ZD()[e][t])return jD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Y3,"checkSchemaTableExists")});var pu=T((ude,K3)=>{K3.exports={name:"harperdb",version:"4.3.0-beta.1",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:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},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":"pm2 kill && 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:resources && 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:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","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":"pm2 kill && 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/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.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:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.9.3-beta.3-debug",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",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:"^5.3.3","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 yt=T((Ede,AL)=>{"use strict";var Gt=j();Gt.initSync();var W3=require("fs-extra"),Q3=require("semver"),gu=require("path"),{monotonicFactory:z3}=require("ulidx"),sL=z3(),J3=require("util"),iL=require("child_process"),X3=J3.promisify(iL.exec),j3=iL.spawn,Ne=nt(),Pe=M(),MS=J(),Wr=Y(),Pd=bs(),Z3=Ud(),Su=xr(),{onMessageByType:eX}=tt(),{isMainThread:tX}=require("worker_threads"),{Encoder:rX,decode:US}=require("msgpackr"),oL=new rX,{isEmpty:co}=MS,aL=cn(),nX=48*36e11,sX=5e9;tX&&eX(Pe.ITC_EVENT_TYPES.RESTART,()=>{dn=void 0,ao=void 0});var{connect:iX,StorageType:cL,RetentionPolicy:uL,AckPolicy:vd,DeliverPolicy:Bd,DiscardPolicy:oX,NatsConnection:lde,JetStreamManager:_de,JetStreamClient:dde,StringCodec:fde,JSONCodec:aX,createInbox:PS,headers:cX,ErrorCode:nL}=require("nats"),{PACKAGE_ROOT:uX}=M(),lX=pu(),{recordAction:_X}=(Ns(),ee(tu)),lL=aX(),dX="clustering",fX=lX.engines[Ne.NATS_SERVER_NAME],EX=gu.join(uX,"dependencies"),LS=gu.join(EX,`${process.platform}-${process.arch}`,Ne.NATS_BINARY_NAME),CS,DS,Tu,io,oo;AL.exports={runCommand:_L,checkNATSServerInstalled:hX,createConnection:vS,getConnection:Hd,getJetStreamManager:Ru,getJetStream:fL,getNATSReferences:lr,getServerList:pX,createLocalStream:BS,listStreams:EL,deleteLocalStream:SX,getServerConfig:Au,listRemoteStreams:TX,viewStream:gX,viewStreamIterator:RX,publishToStream:AX,createWorkQueueStream:OX,addSourceToWorkStream:mL,request:NX,removeSourceFromWorkStream:SL,reloadNATS:HS,reloadNATSHub:yX,reloadNATSLeaf:IX,extractServerName:pL,requestErrorHandler:wX,updateWorkStream:CX,createLocalTableStream:gL,createTableStreams:DX,purgeTableStream:RL,purgeSchemaTableStreams:LX,getStreamInfo:MX,updateLocalStreams:PX,closeConnection:mX,getJsmServerName:Ou,addNatsMsgHeader:hL,updateIngestStreamConsumer:bX,clearClientCache:dL};async function _L(e,t=void 0){let{stdout:r,stderr:n}=await X3(e,{cwd:t});if(n)throw new Error(n.replace(`
9
9
  `,""));return r.replace(`
10
- `,"")}a(ZL,"runCommand");async function q3(){try{await T3.access(SS)}catch{return!1}let e=await ZL(`${SS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return g3.eq(t,F3)}a(q3,"checkNATSServerInstalled");async function AS(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await zL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Kr.trace("create nats connection called");let i=await D3({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:2e5,tls:{keyFile:qt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:qt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:qt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Kr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Kr.error("Error with Nats client connection, connection closed",o),eD()}),i}a(AS,"createConnection");function eD(){hs=void 0,io=void 0,oo=void 0,ao=void 0}a(eD,"clearClientCache");async function k3(){hs&&(await hs.drain(),hs=void 0,io=void 0,oo=void 0,ao=void 0)}a(k3,"closeConnection");var hs,ao;async function Ud(){return ao||(ao=AS(qt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),hs=await ao),hs||ao}a(Ud,"getConnection");async function Nu(){if(io)return io;co(hs)&&await Ud();let{domain:e}=yu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await hs.jetstreamManager({domain:e,timeout:6e4}),io}a(Nu,"getJetStreamManager");async function tD(){if(oo)return oo;co(hs)&&await Ud();let{domain:e}=yu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=hs.jetstream({domain:e,timeout:6e4}),oo}a(tD,"getJetStream");async function dr(){let e=hs||await Ud(),t=io||await Nu(),r=oo||await tD();return{connection:e,jsm:t,js:r}}a(dr,"getNATSReferences");async function V3(e){let t=qt.get(De.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await zL.getClusterUser(),n=await AS(t,r,s),i=RS(),o=n.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=jL.decode(l.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 TS.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(V3,"getServerList");async function OS(e,t){let{jsm:r}=await dr(),s=qt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=qt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=qt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:JL.File,retention:XL.Limits,subjects:t,discard:M3.Old,max_msgs:n,max_bytes:i,max_age:s})}a(OS,"createLocalStream");async function rD(){let{jsm:e}=await dr(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(rD,"listStreams");async function $3(e){let{jsm:t}=await dr();await t.streams.delete(e)}a($3,"deleteLocalStream");async function Y3(e){let{connection:t}=await dr(),r=[],s=RS(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(jL.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(Y3,"listRemoteStreams");async function K3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await dr(),i=KL(),o={durable_name:i,ack_policy:Dd.Explicit};t&&(o.deliver_policy=Md.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 _=[];for await(let l of u){let d=gS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Re.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(K3,"viewStream");async function*W3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await dr(),i=KL(),o={durable_name:i,ack_policy:Dd.Explicit};t&&(o.deliver_policy=Md.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 _ of u){let l=gS(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(Re.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(W3,"viewStreamIterator");async function Q3(e,t,r,s){Kr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=sD(s,r);let{js:n}=await dr(),i=await Iu(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:QL.encode(s);try{Kr.trace(`publishToStream publishing to subject: ${o}`),H3(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 aD(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Kr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await OS(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(Q3,"publishToStream");function sD(e,t){t===void 0&&(t=P3());let r=qt.get(De.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Re.MSG_HEADERS.ORIGIN)&&r&&t.append(Re.MSG_HEADERS.ORIGIN,r),t}a(sD,"addNatsMsgHeader");function yu(e){e=e.toLowerCase();let t=bu.join(qt.get(De.CONFIG_PARAMS.ROOTPATH),x3);if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(pS)&&(pS={port:Au.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Au.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Re.SERVER_SUFFIX.HUB,config_file:Re.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:bu.join(t,Re.PID_FILES.HUB),hdb_nats_path:t}),pS;if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(mS)&&(mS={port:Au.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Au.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Re.SERVER_SUFFIX.LEAF,config_file:Re.NATS_CONFIG_FILES.LEAF_SERVER,domain:Au.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Re.SERVER_SUFFIX.LEAF,pid_file_path:bu.join(t,Re.PID_FILES.LEAF),hdb_nats_path:t}),mS;Kr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(yu,"getServerConfig");async function z3(e){let{jsm:t}=await dr(),r=await Iu();try{await t.streams.add({name:e.stream_name,storage:JL.File,retention:XL.Limits,max_age:C3,max_bytes:L3,subjects:[`${Re.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:Dd.Explicit,durable_name:e.durable_name,deliver_policy:Md.All,max_ack_pending:1e4});else throw s}}a(z3,"createWorkQueueStream");async function J3(){let{jsm:e}=await dr();(await e.consumers.info(Re.WORK_QUEUE_CONSUMER_NAMES.stream_name,Re.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Kr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(Re.WORK_QUEUE_CONSUMER_NAMES.stream_name,Re.WORK_QUEUE_CONSUMER_NAMES.durable_name),Kr.info("Adding pull consumer to ingest stream"),await e.consumers.add(Re.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:Dd.Explicit,durable_name:Re.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:Md.All,max_ack_pending:1e4}))}a(J3,"updateIngestStreamConsumer");async function nD(e,t,r){let{jsm:s}=await dr(),n=await s.streams.info(t),i=iD(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=Ld.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let p=0,S=n.config.sources.length;p<S;p++)if(d=n.config.sources[p],f=p,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let p=`txn.${c}.${u}.${e}`;await s.streams.purge(t,{filter:p}),n.config.sources.splice(f,1),await s.streams.update(t,n.config)}let h={name:_,opt_start_time:o,filter_subject:`${Re.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(nD,"addSourceToWorkStream");function iD(e){return e.split(".")[1]}a(iD,"extractServerName");async function oD(e,t,r){let{jsm:s}=await dr(),{schema:n,table:i}=r,o=`txn.${n}.${i}.${e}`;await s.streams.purge(t,{filter:o});let c=Ld.createNatsTableStreamName(n,i),u=await s.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await s.streams.update(t,u.config)}a(oD,"removeSourceFromWorkStream");async function X3(e,t,r=6e4,s=RS()){if(!TS.isObject(t))throw new Error("data param must be an object");let n=QL.encode(t),{connection:i}=await dr(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return gS(c.data)}a(X3,"request");function bS(e){return new Promise(async(t,r)=>{let s=b3(SS,["--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(bS,"reloadNATS");async function j3(){let{pid_file_path:e}=yu(De.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await bS(e)}a(j3,"reloadNATSHub");async function Z3(){let{pid_file_path:e}=yu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await bS(e)}a(Z3,"reloadNATSLeaf");function eX(e,t,r){let s;switch(e.code){case YL.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case YL.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(eX,"requestErrorHandler");async function tX(e,t){let r=t+Re.SERVER_SUFFIX.LEAF;await aD(async()=>{e.subscribe===!0?await nD(r,Re.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await oD(r,Re.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(tX,"updateWorkStream");function aD(e){return N3.writeTransaction(De.SYSTEM_SCHEMA_NAME,De.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(aD,"exclusiveLock");async function cD(e,t){let r=Ld.createNatsTableStreamName(e,t),s=await Iu(),n=iX(e,t,s);await OS(r,[n])}a(cD,"createLocalTableStream");async function rX(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await cD(s,n)}}a(rX,"createTableStreams");async function uD(e,t,r=!1){if(qt.get(De.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let s=Ld.createNatsTableStreamName(e,t),{jsm:n}=await dr();r?await n.streams.purge(Re.WORK_QUEUE_CONSUMER_NAMES.stream_name):await n.streams.purge(s)}catch(s){if(s.message==="stream not found")Kr.warn(s);else throw s}}a(uD,"purgeTableStream");async function sX(e,t){if(qt.get(De.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await uD(e,t[r])}a(sX,"purgeSchemaTableStreams");async function nX(e){return(await Nu()).streams.info(e)}a(nX,"getStreamInfo");function iX(e,t,r){return`${Re.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(iX,"createSubjectName");async function Iu(){if(Ou)return Ou;if(Ou=(await Nu())?.nc?.info?.server_name,Ou===void 0)throw new Error("Unable to get jetstream manager server name");return Ou}a(Iu,"getJsmServerName");async function oX(){let e=await Nu(),t=await Iu(),r=await rD();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=aX(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===Re.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Re.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Kr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===Re.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Re.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Kr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Kr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}await e.streams.update(n.name,n)}}}a(oX,"updateLocalStreams");function aX(e){let{config:t}=e,r=!1;if(t.name===Re.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===Re.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=qt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=qt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=qt.get(De.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(aX,"updateStreamLimits")});var Hd=T((v_e,ED)=>{"use strict";var la=A_(),_a=$L(),cX=q(),uX=require("uuid").v4,P_e=require("clone"),vd=bn(),da=w(),lX=require("util"),di=Ps(),{handleHDBError:fr,hdb_errors:_X}=Z(),{HDB_ERROR_MSGS:Pd,HTTP_STATUS_CODES:Er}=_X,{SchemaEventMsg:Bd}=Ls(),_D=yt(),{getDatabases:dX}=(pe(),ee(Ge)),{transformReq:fa}=z();ED.exports={createSchema:fX,createSchemaStructure:dD,createTable:EX,createTableStructure:fD,createAttribute:TX,dropSchema:hX,dropTable:mX,dropAttribute:pX,getBackup:gX};async function fX(e){let t=await dD(e);return vd.signalSchemaChange(new Bd(process.pid,e.operation,e.schema)),t}a(fX,"createSchema");async function dD(e){let t=la.schema_object(e);if(t)throw fr(t,t.message,Er.BAD_REQUEST,void 0,void 0,!0);if(fa(e),!await _a.checkSchemaExists(e.schema))throw fr(new Error,Pd.SCHEMA_EXISTS_ERR(e.schema),Er.BAD_REQUEST,da.LOG_LEVELS.ERROR,Pd.SCHEMA_EXISTS_ERR(e.schema),!0);return await di.createSchema(e),`database '${e.schema}' successfully created`}a(dD,"createSchemaStructure");async function EX(e){return fa(e),e.hash_attribute=e.primary_key??e.hash_attribute,await fD(e)}a(EX,"createTable");async function fD(e){let t=la.create_table_object(e);if(t)throw fr(t,t.message,Er.BAD_REQUEST,void 0,void 0,!0);if(la.validateTableResidence(e.residence),!await _a.checkSchemaTableExists(e.schema,e.table))throw fr(new Error,Pd.TABLE_EXISTS_ERR(e.schema,e.table),Er.BAD_REQUEST,da.LOG_LEVELS.ERROR,Pd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:uX(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await di.createTable(s,e);else throw fr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Er.BAD_REQUEST);else await di.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(fD,"createTableStructure");async function hX(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=la.schema_object(e),s=t??r;if(s)throw fr(s,s.message,Er.BAD_REQUEST,void 0,void 0,!0);fa(e);let n=await _a.checkSchemaExists(e.schema);if(n)throw fr(new Error,n,Er.NOT_FOUND,da.LOG_LEVELS.ERROR,n,!0);let i=await _a.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await di.dropSchema(e),vd.signalSchemaChange(new Bd(process.pid,e.operation,e.schema)),await _D.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(hX,"dropSchema");async function mX(e){let t=la.table_object(e);if(t)throw fr(t,t.message,Er.BAD_REQUEST,void 0,void 0,!0);fa(e);let r=await _a.checkSchemaTableExists(e.schema,e.table);if(r)throw fr(new Error,r,Er.NOT_FOUND,da.LOG_LEVELS.ERROR,r,!0);return await di.dropTable(e),await _D.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(mX,"dropTable");async function pX(e){let t=la.attribute_object(e);if(t)throw fr(t,t.message,Er.BAD_REQUEST,void 0,void 0,!0);fa(e);let r=await _a.checkSchemaTableExists(e.schema,e.table);if(r)throw fr(new Error,r,Er.NOT_FOUND,da.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw fr(new Error,"You cannot drop a hash attribute",Er.BAD_REQUEST,void 0,void 0,!0);if(da.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw fr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Er.BAD_REQUEST,void 0,void 0,!0);try{return await di.dropAttribute(e),SX(e),vd.signalSchemaChange(new Bd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw cX.error(`Got an error deleting attribute ${lX.inspect(e)}.`),s}}a(pX,"dropAttribute");function SX(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(SX,"dropAttributeFromGlobal");async function TX(e){fa(e);let t=dX()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw fr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Er.BAD_REQUEST,void 0,void 0,!0);return await di.createAttribute(e),vd.signalSchemaChange(new Bd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(TX,"createAttribute");function gX(e){return di.getBackup(e)}a(gX,"getBackup")});var mD=T((H_e,hD)=>{"use strict";var{OPERATIONS_ENUM:RX}=w(),NS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=RX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};hD.exports=NS});var yS=T((G_e,RD)=>{"use strict";var AX=Ps(),F_e=mD(),xd=z(),Fd=w(),OX=j(),{handleHDBError:pD,hdb_errors:bX}=Z(),{HDB_ERROR_MSGS:SD,HTTP_STATUS_CODES:TD}=bX,NX=Object.values(Fd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),gD="To use this operation audit log must be enabled in harperdb-config.yaml";RD.exports=yX;async function yX(e){if(xd.isEmpty(e.schema))throw new Error(SD.SCHEMA_REQUIRED_ERR);if(xd.isEmpty(e.table))throw new Error(SD.TABLE_REQUIRED_ERR);if(!OX.get(Fd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw pD(new Error,gD,TD.BAD_REQUEST,Fd.LOG_LEVELS.ERROR,gD,!0);let t=xd.checkSchemaTableExist(e.schema,e.table);if(t)throw pD(new Error,t,TD.NOT_FOUND,Fd.LOG_LEVELS.ERROR,t,!0);if(!xd.isEmpty(e.search_type)&&NX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await AX.readAuditLog(e)}a(yX,"readAuditLog")});var OD=T((k_e,AD)=>{"use strict";var{OPERATIONS_ENUM:IX}=w(),IS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=IX.GET_BACKUP,this.schema=t,this.table=r}};AD.exports=IS});var yD=T((K_e,ND)=>{"use strict";var wX=Ps(),$_e=OD(),wS=z(),CX=w(),Y_e=j(),{handleHDBError:LX,hdb_errors:DX}=Z(),{HDB_ERROR_MSGS:bD,HTTP_STATUS_CODES:MX}=DX;ND.exports=UX;async function UX(e){if(wS.isEmpty(e.schema))throw new Error(bD.SCHEMA_REQUIRED_ERR);if(wS.isEmpty(e.table))throw new Error(bD.TABLE_REQUIRED_ERR);let t=wS.checkSchemaTableExist(e.schema,e.table);if(t)throw LX(new Error,t,MX.NOT_FOUND,CX.LOG_LEVELS.ERROR,t,!0);return await wX.getBackup(read_audit_log_object)}a(UX,"getBackup")});var MD=T((Q_e,DD)=>{var fi=require("validate.js"),wD=et(),Ea=w(),{handleHDBError:PX,hdb_errors:vX}=Z(),{HDB_ERROR_MSGS:_t,HTTP_STATUS_CODES:BX}=vX,CS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),HX={STRUCTURE_USER:"structure_user"},ID=Object.values(Ea.ROLE_TYPES_ENUM),xX="attribute_permissions",FX="attribute_name",{PERMS_CRUD_ENUM:ha}=Ea,GX=[xX,...Object.values(ha)],CD=[ha.READ,ha.INSERT,ha.UPDATE],qX=[FX,...CD];function kX(e){let t=CS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,LD(e,t)}a(kX,"addRoleValidation");function VX(e){let t=CS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,LD(e,t)}a(VX,"alterRoleValidation");function $X(e){let t=CS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,wD.validateObject(e,t)}a($X,"dropRoleValidation");var YX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function LD(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)YX.includes(s[o])||n.push(s[o]);n.length>0&&pt(_t.INVALID_ROLE_JSON_KEYS(n),r);let i=wD.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{pt(o,r)}),e.permission){let o=KX(e);o&&pt(o,r),ID.forEach(c=>{e.permission[c]&&!fi.isBoolean(e.permission[c])&&pt(_t.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(ID.indexOf(o)<0){if(o===HX.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||pt(_t.SCHEMA_NOT_FOUND(d),r)}continue}pt(_t.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){pt(_t.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){pt(_t.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{GX.includes(l)||pt(_t.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ha).forEach(l=>{fi.isDefined(_[l])?fi.isBoolean(_[l])||pt(_t.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):pt(_t.TABLE_PERM_MISSING(l),r,o,u)}),fi.isDefined(_.attribute_permissions)){if(!fi.isArray(_.attribute_permissions)){pt(_t.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{pt(_t.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(p=>{!qX.includes(p)&&p!==ha.DELETE&&pt(_t.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!fi.isDefined(E.attribute_name)){pt(_t.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){pt(_t.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}CD.forEach(p=>{fi.isDefined(E[p])?fi.isBoolean(E[p])||pt(_t.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):pt(_t.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;pt(_t.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return WX(r)}a(LD,"customValidate");DD.exports={addRoleValidation:kX,alterRoleValidation:VX,dropRoleValidation:$X};function KX(e){let{operation:t,permission:r}=e;if(t===Ea.OPERATIONS_ENUM.ADD_ROLE||t===Ea.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 _t.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Ea.ROLE_TYPES_ENUM.SUPER_USER:Ea.ROLE_TYPES_ENUM.CLUSTER_USER;return _t.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(KX,"validateNoSUPerms");function WX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:_t.ROLE_PERMS_ERROR,...e};return PX(new Error,s,BX.BAD_REQUEST)}else return null}a(WX,"generateRolePermResponse");function pt(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(pt,"addPermError")});var vS=T((J_e,BD)=>{"use strict";var UD=cs(),PD=as(),QX=Qi(),DS=MD(),MS=bn(),zX=require("uuid").v4,JX=require("util"),Gd=w(),XX=z(),US=PD.searchByValue,jX=PD.searchByHash,ZX=JX.promisify(QX.delete),ej=js(),tj=Xo(),{hdb_errors:rj,handleHDBError:uo}=Z(),{HDB_ERROR_MSGS:vD,HTTP_STATUS_CODES:wu}=rj,{UserEventMsg:PS}=Ls();BD.exports={addRole:sj,alterRole:nj,dropRole:ij,listRoles:oj};function LS(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(LS,"scrubRoleDetails");async function sj(e){let t=DS.addRoleValidation(e);if(t)throw t;e=LS(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 US(r)||[])}catch(i){throw uo(i)}if(s&&s.length>0)throw uo(new Error,vD.ROLE_ALREADY_EXISTS(e.role),wu.CONFLICT,void 0,void 0,!0);e.id||(e.id=zX());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await UD.insert(n),MS.signalUserChange(new PS(process.pid)),e=LS(e),e}a(sj,"addRole");async function nj(e){let t=DS.alterRoleValidation(e);if(t)throw t;e=LS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await UD.update(r)}catch(n){throw uo(n)}if(s&&s?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",wu.BAD_REQUEST,void 0,void 0,!0);return await MS.signalUserChange(new PS(process.pid)),e}a(nj,"alterRole");async function ij(e){let t=DS.dropRoleValidation(e);if(t)throw uo(new Error,t,wu.BAD_REQUEST,void 0,void 0,!0);let r=new tj(Gd.SYSTEM_SCHEMA_NAME,Gd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await jX(r));if(s.length===0)throw uo(new Error,vD.ROLE_NOT_FOUND,wu.NOT_FOUND,void 0,void 0,!0);let n=new ej(Gd.SYSTEM_SCHEMA_NAME,Gd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await US(n)),o=!1;if(XX.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`,wu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await ZX(c),MS.signalUserChange(new PS(process.pid)),`${s[0].role} successfully deleted`}a(ij,"dropRole");async function oj(){return US({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(oj,"listRoles")});var GD=T((j_e,FD)=>{"use strict";var aj=j(),Ei=require("joi"),cj=et(),HD=require("moment"),uj=require("fs-extra"),BS=require("path"),lj=require("lodash"),Cu=w(),{LOG_LEVELS:lo}=w(),_j="YYYY-MM-DD hh:mm:ss",dj=BS.resolve(__dirname,"../logs");FD.exports=function(e){return cj.validateBySchema(e,fj)};var fj=Ei.object({from:Ei.custom(xD),until:Ei.custom(xD),level:Ei.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:Ei.valid("asc","desc"),limit:Ei.number().min(1),start:Ei.number().min(0),log_name:Ei.custom(Ej)});function xD(e,t){if(HD(e,HD.ISO_8601).format(_j)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(xD,"validateDatetime");function Ej(e,t){if(lj.invert(Cu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=aj.get(Cu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?Cu.LOG_NAMES.HDB:e,i=n===Cu.LOG_NAMES.INSTALL?BS.join(dj,Cu.LOG_NAMES.INSTALL):BS.join(s,n);return uj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Ej,"validateReadLogPath")});var xS=T((ede,kD)=>{"use strict";var qd=w(),hj=q(),mj=j(),pj=GD(),HS=require("path"),qD=require("fs-extra"),{once:Sj}=require("events"),{handleHDBError:Tj,hdb_errors:gj}=Z(),{PACKAGE_ROOT:Rj}=w(),Aj=HS.join(Rj,"logs"),Oj=1e3,bj=200;kD.exports=Nj;async function Nj(e){let t=pj(e);if(t)throw Tj(t,t.message,gj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=mj.get(qd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?qd.LOG_NAMES.HDB:e.log_name,n=s===qd.LOG_NAMES.INSTALL?HS.join(Aj,qd.LOG_NAMES.INSTALL):HS.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,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?Oj:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(qD.statSync(n).size-(h+5)*bj,0));let S=qD.createReadStream(n,{start:p});S.on("error",x=>{hj.error(x)});let R=0,O=[],b="",P;S.on("data",x=>{let D=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;x=b+x;let Y=0,V;for(;(V=D.exec(x))&&!S.destroyed;){P&&(P.message=x.slice(Y,V.index),$(P));let[W,re,be]=V,ne=be.split("] ["),ct=ne[0],Te=ne[1];ne.splice(0,2),P={timestamp:re,thread:ct,level:Te,tags:ne,message:""},Y=V.index+W.length}b=x.slice(Y)}),S.on("end",x=>{S.destroyed||P&&(P.message=b.trim(),$(P))}),S.resume();function $(x){let D,Y,V;switch(!0){case(i&&c&&_):D=new Date(x.timestamp),Y=new Date(u),V=new Date(l),x.level===o&&D>=Y&&D<=V&&R<E?R++:x.level===o&&D>=Y&&D<=V&&(hi(x,f,O),R++,R===h&&S.destroy());break;case(i&&c):D=new Date(x.timestamp),Y=new Date(u),x.level===o&&D>=Y&&R<E?R++:x.level===o&&D>=Y&&(hi(x,f,O),R++,R===h&&S.destroy());break;case(i&&_):D=new Date(x.timestamp),V=new Date(l),x.level===o&&D<=V&&R<E?R++:x.level===o&&D<=V&&(hi(x,f,O),R++,R===h&&S.destroy());break;case(c&&_):D=new Date(x.timestamp),Y=new Date(u),V=new Date(l),D>=Y&&D<=V&&R<E?R++:D>=Y&&D<=V&&(hi(x,f,O),R++,R===h&&S.destroy());break;case i:x.level===o&&R<E?R++:x.level===o&&(hi(x,f,O),R++,R===h&&S.destroy());break;case c:D=new Date(x.timestamp),Y=new Date(u),D>=Y&&R<E?R++:D>=Y&&R>=E&&(hi(x,f,O),R++,R===h&&S.destroy());break;case _:D=new Date(x.timestamp),V=new Date(l),D<=V&&R<E?R++:D<=V&&R>=E&&(hi(x,f,O),R++,R===h&&S.destroy());break;default:R<E?R++:(hi(x,f,O),R++,R===h&&S.destroy())}}return a($,"onLogMessage"),await Sj(S,"close"),O}a(Nj,"readLog");function hi(e,t,r){t==="desc"?yj(e,r):t==="asc"?Ij(e,r):r.push(e)}a(hi,"pushLineToResult");function yj(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(yj,"insertDescending");function Ij(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(Ij,"insertAscending")});var kd=T((ide,KD)=>{"use strict";var FS=require("joi"),{string:Lu,boolean:VD,date:wj}=FS.types(),Cj=et(),{validateSchemaExists:rde,validateTableExists:sde,validateSchemaName:nde}=Js(),Lj=w(),Dj=tt(),$D=j();$D.initSync();var Mj=Lu.invalid($D.get(Lj.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Dj.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(),YD={operation:Lu.valid("add_node","update_node","set_node_replication"),node_name:Mj,subscriptions:FS.array().items({table:Lu.optional(),schema:Lu.optional(),database:Lu.optional(),subscribe:VD.required(),publish:VD.required().custom(Pj),start_time:wj.iso()}).min(1).required()};function Uj(e){return Cj.validateBySchema(e,FS.object(YD))}a(Uj,"addUpdateNodeValidator");function Pj(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(Pj,"checkForFalsy");KD.exports={addUpdateNodeValidator:Uj,validation_schema:YD}});var QD=T((ade,WD)=>{var vj=et(),Bj={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};WD.exports=function(e){return vj.validateObject(e,Bj)}});var qS=T((cde,zD)=>{"use strict";var Hj=w().OPERATIONS_ENUM,GS=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=Hj.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};zD.exports=GS});var XD=T((lde,JD)=>{"use strict";var xj={OPERATION:"operation",REFRESH:"refresh"},kS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},VS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};JD.exports={JWTTokens:kS,TOKEN_TYPE_ENUM:xj,JWTRSAKeys:VS}});var Uu=T((dde,tM)=>{"use strict";var Mu=require("jsonwebtoken"),$S=require("fs-extra"),YS=z(),ms=w(),{handleHDBError:hr,hdb_errors:Fj}=Z(),{HTTP_STATUS_CODES:mr,AUTHENTICATION_ERROR_MSGS:pr}=Fj,Du=q(),jD=z_(),QS=ls(),Gj=cs().update,qj=qS(),kj=bn(),{UserEventMsg:Vj}=Ls(),mi=j();mi.initSync();var KS=require("path"),{JWTTokens:$j,JWTRSAKeys:Yj,TOKEN_TYPE_ENUM:Vd}=XD(),Kj=mi.get(ms.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?mi.get(ms.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",Wj=mi.get(ms.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?mi.get(ms.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",$d="RS256",WS;tM.exports={createTokens:Qj,validateOperationToken:Jj,refreshOperationToken:zj,validateRefreshToken:eM};async function Qj(e){if(YS.isEmpty(e)||typeof e!="object")throw hr(new Error,pr.INVALID_AUTH_OBJECT,mr.BAD_REQUEST,void 0,void 0,!0);if(YS.isEmpty(e.username))throw hr(new Error,pr.USERNAME_REQUIRED,mr.BAD_REQUEST,void 0,void 0,!0);if(YS.isEmpty(e.password))throw hr(new Error,pr.PASSWORD_REQUIRED,mr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await QS.findAndValidateUser(e.username,e.password),!t)throw hr(new Error,pr.INVALID_CREDENTIALS,mr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Du.error(f),hr(new Error,pr.INVALID_CREDENTIALS,mr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Yd(),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 ZD(i,r.private_key,r.passphrase),c=await Mu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:Wj,algorithm:$d,subject:Vd.REFRESH}),u=jD.hash(c),_=new qj(ms.SYSTEM_SCHEMA_NAME,ms.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await Gj(_)}catch(f){Du.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw hr(new Error,pr.REFRESH_TOKEN_SAVE_FAILED,mr.INTERNAL_SERVER_ERROR);return kj.signalUserChange(new Vj(process.pid)),new $j(o,c)}a(Qj,"createTokens");async function ZD(e,t,r){return await Mu.sign(e,{key:t,passphrase:r},{expiresIn:Kj,algorithm:$d,subject:Vd.OPERATION})}a(ZD,"signOperationToken");async function Yd(){if(WS===void 0)try{let e=KS.join(mi.getHdbBasePath(),ms.LICENSE_KEY_DIR_NAME,ms.JWT_ENUM.JWT_PASSPHRASE_NAME),t=KS.join(mi.getHdbBasePath(),ms.LICENSE_KEY_DIR_NAME,ms.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=KS.join(mi.getHdbBasePath(),ms.LICENSE_KEY_DIR_NAME,ms.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await $S.readFile(e)).toString(),n=(await $S.readFile(t)).toString(),i=(await $S.readFile(r)).toString();WS=new Yj(i,n,s)}catch(e){throw Du.error(e),hr(new Error,pr.NO_ENCRYPTION_KEYS,mr.INTERNAL_SERVER_ERROR)}return WS}a(Yd,"getJWTRSAKeys");async function zj(e){if(!e)throw hr(new Error,pr.INVALID_BODY,mr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw hr(new Error,pr.REFRESH_TOKEN_REQUIRED,mr.BAD_REQUEST,void 0,void 0,!0);await eM(e.refresh_token);let t=await Yd(),r=await Mu.decode(e.refresh_token);return{operation_token:await ZD({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(zj,"refreshOperationToken");async function Jj(e){try{let t=await Yd(),r=await Mu.verify(e,t.public_key,{algorithms:$d,subject:Vd.OPERATION});return await QS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Du.warn(t),t.name&&t.name==="TokenExpiredError"?hr(new Error,pr.TOKEN_EXPIRED,mr.FORBIDDEN):hr(new Error,pr.INVALID_TOKEN,mr.UNAUTHORIZED)}}a(Jj,"validateOperationToken");async function eM(e){let t;try{let r=await Yd(),s=await Mu.verify(e,r.public_key,{algorithms:$d,subject:Vd.REFRESH});t=await QS.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Du.warn(r),r.name&&r.name==="TokenExpiredError"?hr(new Error,pr.TOKEN_EXPIRED,mr.FORBIDDEN):hr(new Error,pr.INVALID_TOKEN,mr.UNAUTHORIZED)}if(!jD.validate(t.refresh_token,e))throw hr(new Error,pr.INVALID_TOKEN,mr.UNAUTHORIZED);return t}a(eM,"validateRefreshToken")});var zS=T((hde,nM)=>{"use strict";var Xj=QD(),ma=require("passport"),jj=require("passport-local").Strategy,Zj=require("passport-http").BasicStrategy,eZ=require("util"),tZ=ls(),sM=eZ.callbackify(tZ.findAndValidateUser),Ede=Cr(),rZ=w(),rM=Uu();ma.use(new jj(function(e,t,r){sM(e,t,r)}));ma.use(new Zj(function(e,t,r){sM(e,t,r)}));ma.serializeUser(function(e,t){t(null,e)});ma.deserializeUser(function(e,t){t(null,e)});function sZ(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":ma.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===rZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?rM.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):rM.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:ma.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(sZ,"authorize");function nZ(e,t){let r=Xj(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(nZ,"checkPermissions");nM.exports={authorize:sZ,checkPermissions:nZ}});var pa=T((pde,iM)=>{"use strict";var JS=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},XS=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};iM.exports={Node:JS,NodeSubscription:XS}});var aM=T((Tde,oM)=>{"use strict";var iZ=w().OPERATIONS_ENUM,jS=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=iZ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};oM.exports=jS});var Pu=T((Rde,cM)=>{"use strict";var ZS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},eT=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)}};cM.exports={RemotePayloadObject:ZS,RemotePayloadSubscription:eT}});var lM=T((Ode,uM)=>{"use strict";var tT=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}};uM.exports=tT});var fM=T((wde,dM)=>{"use strict";var oZ=lM(),Nde=Et(),_M=Ye(),aZ=q(),{getSchemaPath:yde,getTransactionAuditStorePath:Ide}=We(),{getDatabases:cZ}=(pe(),ee(Ge));dM.exports=uZ;async function uZ(e){let t=new oZ;try{let r=cZ()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await _M.environmentDataSize(schema_path,e.name),o=await _M.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){aZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(uZ,"lmdbGetTableSize")});var hM=T((Lde,EM)=>{"use strict";var rT=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}};EM.exports=rT});var Sa=T((Pde,TM)=>{"use strict";var lZ=require("fs-extra"),_Z=require("path"),Zt=require("systeminformation"),pi=q(),dZ=yt(),sT=tt(),Wd=w(),fZ=fM(),SM=Vi(),{getThreadInfo:mM}=Ze(),fT=j();fT.initSync();var EZ=hM(),{openEnvironment:Mde}=Ye(),{getSchemaPath:Ude}=We(),{database:hZ}=(pe(),ee(Ge)),Kd;TM.exports={getHDBProcessInfo:aT,getNetworkInfo:uT,getDiskInfo:cT,getMemoryInfo:oT,getCPUInfo:iT,getTimeInfo:nT,getSystemInformation:lT,systemInformation:mZ,getTableSize:_T,getMetrics:dT};function nT(){return Zt.time()}a(nT,"getTimeInfo");async function iT(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Zt.cpu();l.cpu_speed=await Zt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:R,...O}=await Zt.currentLoad();return O.cpus=[],R.forEach(b=>{let{raw_load:P,raw_load_idle:$,raw_load_irq:x,raw_load_nice:D,raw_load_system:Y,raw_load_user:V,...W}=b;O.cpus.push(W)}),l.current_load=O,l}catch(e){return pi.error(`error in getCPUInfo: ${e}`),{}}}a(iT,"getCPUInfo");async function oT(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Zt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return pi.error(`error in getMemoryInfo: ${e}`),{}}}a(oT,"getMemoryInfo");async function aT(){let e={core:[],clustering:[]};try{let t=await Zt.processes(),r;try{r=Number.parseInt(await lZ.readFile(_Z.join(fT.get(Wd.CONFIG_PARAMS.ROOTPATH),Wd.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===Wd.NODE_ERROR_CODES.ENOENT)pi.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 pi.error(`error in getHDBProcessInfo: ${t}`),e}}a(aT,"getHDBProcessInfo");async function cT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Zt.fsStats();return e.read_write=_,e.size=await Zt.fsSize(),e}catch(t){return pi.error(`error in getDiskInfo: ${t}`),e}}a(cT,"getDiskInfo");async function uT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Zt.networkInterfaceDefault(),e.latency=await Zt.inetChecksite("google.com"),(await Zt.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=s;e.interfaces.push(f)}),(await Zt.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return pi.error(`error in getNetworkInfo: ${t}`),e}}a(uT,"getNetworkInfo");async function lT(){if(Kd!==void 0)return Kd;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Zt.osInfo();e=c;let u=await Zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Kd=e,Kd}catch(t){return pi.error(`error in getSystemInformation: ${t}`),e}}a(lT,"getSystemInformation");async function _T(){let e=[],t=await SM.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await fZ(s));return e}a(_T,"getTableSize");async function dT(){let e=await SM.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let i=hZ({database:r,table:n}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),s[n]=o}catch(i){pi.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(dT,"getMetrics");async function pM(){if(fT.get(Wd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await dZ.getNATSReferences(),r=await t.streams.info(sT.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(sT.WORK_QUEUE_CONSUMER_NAMES.stream_name,sT.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.sources&&(n.ingest.stream.sources=r.sources),n}}a(pM,"getNatsStreamInfo");async function mZ(e){let t=new EZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await lT(),t.time=nT(),t.cpu=await iT(),t.memory=await oT(),t.disk=await cT(),t.network=await uT(),t.harperdb_processes=await aT(),t.table_size=await _T(),t.metrics=await dT(),t.threads=await mM(),t.replication=await pM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await lT();break;case"time":t.time=nT();break;case"cpu":t.cpu=await iT();break;case"memory":t.memory=await oT();break;case"disk":t.disk=await cT();break;case"network":t.network=await uT();break;case"harperdb_processes":t.harperdb_processes=await aT();break;case"table_size":t.table_size=await _T();break;case"database_metrics":case"metrics":t.metrics=await dT();break;case"threads":t.threads=await mM();break;case"replication":t.replication=await pM();break;default:break}return t}a(mZ,"systemInformation")});var ET=T((Bde,gM)=>{"use strict";gM.exports={version:pZ,printVersion:SZ};var Qd=Ru();function pZ(){if(Qd)return Qd.version}a(pZ,"version");function SZ(){Qd&&console.log(`HarperDB Version ${Qd.version}`)}a(SZ,"printVersion")});var Dn=T((Gde,bM)=>{"use strict";var TZ=cs(),hT=z(),gZ=require("util"),_o=w(),RM=j();RM.initSync();var RZ=zS(),AM=as(),{Node:xde,NodeSubscription:Fde}=pa(),AZ=Xo(),OZ=aM(),{RemotePayloadObject:bZ,RemotePayloadSubscription:NZ}=Pu(),{handleHDBError:yZ,hdb_errors:IZ}=Z(),{HTTP_STATUS_CODES:wZ,HDB_ERROR_MSGS:CZ}=IZ,LZ=js(),DZ=Sa(),MZ=ET(),{getDatabases:UZ}=(pe(),ee(Ge)),PZ=gZ.promisify(RZ.authorize),vZ=AM.searchByHash,BZ=AM.searchByValue;bM.exports={authHeaderToUser:HZ,isEmpty:xZ,getNodeRecord:FZ,upsertNodeRecord:GZ,buildNodePayloads:qZ,checkClusteringEnabled:kZ,getAllNodeRecords:VZ,getSystemInfo:$Z,reverseSubscription:OM};async function HZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await PZ(t,null),e}a(HZ,"authHeaderToUser");function xZ(e){return e==null}a(xZ,"isEmpty");async function FZ(e){let t=new AZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return vZ(t)}a(FZ,"getNodeRecord");async function GZ(e){let t=new OZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return TZ.upsert(t)}a(GZ,"upsertNodeRecord");function OM(e){if(hT.isEmpty(e.subscribe)||hT.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(OM,"reverseSubscription");function qZ(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=hT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=OM(c),E=UZ()[u]?.[_],h=new NZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new bZ(r,t,n,s)}a(qZ,"buildNodePayloads");function kZ(){if(!RM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw yZ(new Error,CZ.CLUSTERING_NOT_ENABLED,wZ.BAD_REQUEST,void 0,void 0,!0)}a(kZ,"checkClusteringEnabled");async function VZ(){let e=new LZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await BZ(e))}a(VZ,"getAllNodeRecords");async function $Z(){let e=await DZ.getSystemInformation();return{hdb_version:MZ.version(),node_version:e.node_version,platform:e.platform}}a($Z,"getSystemInfo")});var mT=T((kde,MM)=>{"use strict";var zd=yt(),NM=z(),yM=tt(),IM=w(),Jd=q(),wM=Hd(),YZ=Pm(),{RemotePayloadObject:KZ}=Pu(),{handleHDBError:CM,hdb_errors:WZ}=Z(),{HTTP_STATUS_CODES:LM}=WZ,{NodeSubscription:DM}=pa();MM.exports=QZ;async function QZ(e,t){let r;try{r=await zd.request(`${t}.${yM.REQUEST_SUFFIX}`,new KZ(IM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Jd.trace("Response from remote describe all request:",r)}catch(o){Jd.error(`addNode received error from describe all request to remote node: ${o}`);let c=zd.requestErrorHandler(o,"add_node",t);throw CM(new Error,c,LM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===yM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw CM(new Error,o,LM.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===IM.SYSTEM_SCHEMA_NAME){await zd.createLocalTableStream(u,c);let h=new DM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=NM.doesSchemaExist(u),l=s[u]!==void 0,d=c?NM.doesTableExist(u,c):!0,f=c?s?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){n.push(o);continue}if(!_&&l&&(Jd.trace(`addNode creating schema: ${u}`),await wM.createSchema({operation:"create_schema",schema:u})),!d&&f){Jd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(s[u][c].attributes)}`);let h=new YZ(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await wM.createTable(h)}await zd.createLocalTableStream(u,c);let E=new DM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(QZ,"reviewSubscriptions")});var Zd=T(($de,vM)=>{"use strict";var{handleHDBError:Xd,hdb_errors:zZ}=Z(),{HTTP_STATUS_CODES:jd}=zZ,{addUpdateNodeValidator:JZ}=kd(),vu=q(),PM=w(),UM=tt(),XZ=z(),pT=yt(),Bu=Dn(),jZ=j(),ZZ=mT(),{Node:e5,NodeSubscription:t5}=pa(),{broadcast:r5}=Ze(),s5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",n5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",i5=jZ.get(PM.CONFIG_PARAMS.CLUSTERING_NODENAME);vM.exports=o5;async function o5(e,t=!1){vu.trace("addNode called with:",e),Bu.checkClusteringEnabled();let r=JZ(e);if(r)throw Xd(r,r.message,jd.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await Bu.getNodeRecord(s);if(!XZ.isEmptyOrZeroLength(d))throw Xd(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,jd.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await ZZ(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=s5,o;let c=Bu.buildNodePayloads(n,i5,PM.OPERATIONS_ENUM.ADD_NODE,await Bu.getSystemInfo());vu.trace("addNode sending remote payload:",c);let u;try{u=await pT.request(`${s}.${UM.REQUEST_SUFFIX}`,c)}catch(d){vu.error(`addNode received error from request: ${d}`);let f=pT.requestErrorHandler(d,"add_node",s);throw Xd(new Error,f,jd.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===UM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw Xd(new Error,d,jd.INTERNAL_SERVER_ERROR,"error",d)}vu.trace(u);let _=[];for(let d=0,f=n.length;d<f;d++){let E=n[d];vu.trace("Add node updating work stream for node:",s,"subscriptions:",E),await pT.updateWorkStream(E,s),n[d].start_time===void 0&&delete n[d].start_time,_.push(new t5(E.schema,E.table,E.publish,E.subscribe))}let l=new e5(s,_,u.system_info);return await Bu.upsertNodeRecord(l),r5({type:"nats_update"}),i.length>0?o.message=n5:o.message=`Successfully added '${s}' to manifest`,o}a(o5,"addNode")});var RT=T((Wde,xM)=>{"use strict";var{handleHDBError:ST,hdb_errors:a5}=Z(),{HTTP_STATUS_CODES:TT}=a5,{addUpdateNodeValidator:c5}=kd(),Hu=q(),HM=w(),BM=tt(),Kde=z(),gT=yt(),xu=Dn(),u5=j(),{cloneDeep:l5}=require("lodash"),_5=mT(),{Node:d5,NodeSubscription:f5}=pa(),{broadcast:E5}=Ze(),h5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",m5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",p5=u5.get(HM.CONFIG_PARAMS.CLUSTERING_NODENAME);xM.exports=S5;async function S5(e){Hu.trace("updateNode called with:",e),xu.checkClusteringEnabled();let t=c5(e);if(t)throw ST(t,t.message,TT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await xu.getNodeRecord(r);n.length>0&&(s=l5(n));let{added:i,skipped:o}=await _5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=h5,c;let u=xu.buildNodePayloads(i,p5,HM.OPERATIONS_ENUM.UPDATE_NODE,await xu.getSystemInfo());Hu.trace("updateNode sending remote payload:",u);let _;try{_=await gT.request(`${r}.${BM.REQUEST_SUFFIX}`,u)}catch(l){Hu.error(`updateNode received error from request: ${l}`);let d=gT.requestErrorHandler(l,"update_node",r);throw ST(new Error,d,TT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===BM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw ST(new Error,l,TT.INTERNAL_SERVER_ERROR,"error",l)}Hu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];Hu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await gT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return s||(s=[new d5(r,[],_.system_info)]),await T5(s[0],i,_.system_info),o.length>0?c.message=m5:c.message=`Successfully updated '${r}'`,c}a(S5,"updateNode");async function T5(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,_=e.subscriptions.length;u<_;u++){let l=s.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new f5(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await xu.upsertNodeRecord(s),E5({type:"nats_update"})}a(T5,"updateNodeTable")});var VM=T((zde,kM)=>{"use strict";var qM=require("joi"),{string:FM}=qM.types(),g5=et(),GM=w(),R5=j(),A5=tt();kM.exports=O5;function O5(e){let t=FM.invalid(R5.get(GM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(A5.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=qM.object({operation:FM.valid(GM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return g5.validateBySchema(e,r)}a(O5,"removeNodeValidator")});var tf=T((Xde,zM)=>{"use strict";var{handleHDBError:$M,hdb_errors:b5}=Z(),{HTTP_STATUS_CODES:YM}=b5,N5=VM(),Fu=q(),KM=Dn(),y5=z(),ef=w(),WM=tt(),QM=yt(),I5=j(),{RemotePayloadObject:w5}=Pu(),{NodeSubscription:C5}=pa(),L5=kc(),D5=Qi(),{broadcast:M5}=Ze(),U5=I5.get(ef.CONFIG_PARAMS.CLUSTERING_NODENAME);zM.exports=P5;async function P5(e){Fu.trace("removeNode called with:",e),KM.checkClusteringEnabled();let t=N5(e);if(t)throw $M(t,t.message,YM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await KM.getNodeRecord(r);if(y5.isEmptyOrZeroLength(s))throw $M(new Error,`Node '${r}' was not found.`,YM.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new w5(ef.OPERATIONS_ENUM.REMOVE_NODE,U5,[]),i,o=!1;try{i=await QM.request(`${r}.${WM.REQUEST_SUFFIX}`,n),Fu.trace("Remove node reply from remote node:",r,i)}catch(u){Fu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=s.subscriptions.length;u<_;u++){let l=s.subscriptions[u];Fu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new C5(l.schema,l.table,!1,!1);await QM.updateWorkStream(d,r)}let c=new L5(ef.SYSTEM_SCHEMA_NAME,ef.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await D5.deleteRecord(c),M5({type:"nats_update"}),i?.status===WM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Fu.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(P5,"removeNode")});var jM=T((Zde,XM)=>{"use strict";var JM=require("joi"),{string:v5,array:B5}=JM.types(),H5=et(),x5=kd();XM.exports=F5;function F5(e){let t=JM.object({operation:v5.valid("configure_cluster").required(),connections:B5.items(x5.validation_schema).required()});return H5.validateBySchema(e,t)}a(F5,"configureClusterValidator")});var AT=T((tfe,sU)=>{"use strict";var G5=w(),rf=q(),q5=z(),k5=tf(),V5=Zd(),ZM=Dn(),$5=jM(),{handleHDBError:eU,hdb_errors:Y5}=Z(),{HTTP_STATUS_CODES:tU}=Y5,K5="Configure cluster complete.",W5="Failed to configure the cluster. Check the logs for more details.",Q5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";sU.exports=z5;async function z5(e){rf.trace("configure cluster called with:",e),ZM.checkClusteringEnabled();let t=$5(e);if(t)throw eU(t,t.message,tU.BAD_REQUEST,void 0,void 0,!0);let r=await ZM.getAllNodeRecords(),s=[];for(let f=0,E=r.length;f<E;f++)s.push(rU(k5,{operation:G5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let n=await Promise.allSettled(s);rf.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(rU(V5,E,E.node_name))}let c=await Promise.allSettled(i);rf.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=n.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(rf.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let p=h?.value?.result;typeof p=="string"&&p.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(q5.isEmptyOrZeroLength(u))return{message:K5,connections:_};if(l)return{message:Q5,failed_nodes:u,connections:_};throw eU(new Error,W5,tU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(z5,"configureCluster");async function rU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(rU,"functionWrapper")});var iU=T((sfe,nU)=>{"use strict";var sf=require("joi"),J5=et(),{validateSchemaExists:X5,validateTableExists:j5,validateSchemaName:Z5}=Js(),e8=sf.object({operation:sf.string().valid("purge_stream"),schema:sf.string().custom(X5).custom(Z5).required(),table:sf.string().custom(j5).required()});function t8(e){return J5.validateBySchema(e,e8)}a(t8,"purgeStreamValidator");nU.exports=t8});var OT=T((ife,oU)=>{"use strict";var{handleHDBError:r8,hdb_errors:s8}=Z(),{HTTP_STATUS_CODES:n8}=s8,i8=iU(),o8=yt(),a8=Dn();oU.exports=c8;async function c8(e){if(e.purge_ingest!==!0){let n=i8(e);if(n)throw r8(n,n.message,n8.BAD_REQUEST,void 0,void 0,!0)}a8.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:s}=e;return await o8.purgeTableStream(t,r,s),s?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(c8,"purgeStream")});var yT=T((afe,dU)=>{"use strict";var NT=Dn(),u8=yt(),uU=j(),nf=w(),fo=tt(),l8=z(),bT=q(),{RemotePayloadObject:_8}=Pu(),{ErrorCode:aU}=require("nats"),cU=uU.get(nf.CONFIG_PARAMS.CLUSTERING_ENABLED),lU=uU.get(nf.CONFIG_PARAMS.CLUSTERING_NODENAME);dU.exports={clusterStatus:d8,buildNodeStatus:_U};async function d8(){let e={node_name:lU,is_enabled:cU,connections:[]};if(!cU)return e;let t=await NT.getAllNodeRecords();if(l8.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(_U(t[s],e.connections));return await Promise.allSettled(r),e}a(d8,"clusterStatus");async function _U(e,t){let r=e.name,s=new _8(nf.OPERATIONS_ENUM.CLUSTER_STATUS,lU,void 0,await NT.getSystemInfo()),n,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await u8.request(fo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,bT.error(`Error getting node status from ${r} `,n))}catch(u){bT.warn(`Error getting node status from ${r}`,u),u.code===aU.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===aU.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new f8(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!==nf.PRE_4_0_0_VERSION&&await NT.upsertNodeRecord(u)}catch(u){bT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(_U,"buildNodeStatus");function f8(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(f8,"NodeStatusObject")});var wT=T((ufe,fU)=>{"use strict";var{handleHDBError:E8,hdb_errors:h8}=Z(),{HTTP_STATUS_CODES:m8}=h8,p8=yt(),S8=Dn(),IT=z(),of=require("joi"),T8=et(),g8=2e3,R8=of.object({timeout:of.number().min(1),connected_nodes:of.boolean(),routes:of.boolean()});fU.exports=A8;async function A8(e){S8.checkClusteringEnabled();let t=T8.validateBySchema(e,R8);if(t)throw E8(t,t.message,m8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||IT.autoCastBoolean(s),o=n===void 0||IT.autoCastBoolean(n),c={nodes:[]},u=await p8.getServerList(r??g8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(p=>({host:p.split(":")[0],port:IT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(A8,"clusterNetwork")});var pU=T((_fe,mU)=>{"use strict";var CT=require("joi"),EU=et(),{route_constraints:hU}=gp();mU.exports={setRoutesValidator:O8,deleteRoutesValidator:b8};function O8(e){let t=CT.object({server:CT.valid("hub","leaf").required(),routes:hU.required()});return EU.validateBySchema(e,t)}a(O8,"setRoutesValidator");function b8(e){let t=CT.object({routes:hU.required()});return EU.validateBySchema(e,t)}a(b8,"deleteRoutesValidator")});var DT=T((ffe,RU)=>{"use strict";var Eo=xr(),LT=z(),af=w(),SU=pU(),{handleHDBError:TU,hdb_errors:N8}=Z(),{HTTP_STATUS_CODES:gU}=N8,y8="cluster routes successfully set",I8="cluster routes successfully deleted";RU.exports={setRoutes:w8,getRoutes:C8,deleteRoutes:L8};function w8(e){let t=SU.setRoutesValidator(e);if(t)throw TU(t,t.message,gU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.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 _=e.routes[c];_.port=LT.autoCast(_.port);let l=s.some(f=>f.host===_.host&&f.port===_.port),d=n.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(s.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(af.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Eo.updateConfigValue(af.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:y8,set:o,skipped:i}}a(w8,"setRoutes");function C8(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(C8,"getRoutes");function L8(e){let t=SU.deleteRoutesValidator(e);if(t)throw TU(t,t.message,gU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=s.length;E<h;E++){let p=s[E];if(d.host===p.host&&d.port===p.port){s.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=n.length;h<p;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(s=LT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(af.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=LT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(af.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:I8,deleted:i,skipped:o}}a(L8,"deleteRoutes")});var OU=T((hfe,AU)=>{"use strict";var Gu=require("alasql"),ho=require("recursive-iterator"),Gs=q(),D8=z(),qu=w(),MT=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,U8(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=>qu.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=>!qu.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][qu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=M8(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!qu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Gu.yy.Column({columnid:_});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function M8(e){return e.filter(t=>t[qu.PERMS_CRUD_ENUM.READ])}a(M8,"filterReadRestrictedAttrs");function U8(e,t,r,s,n){P8(e,t,r,s,n)}a(U8,"interpretAST");function ku(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(ku,"addSchemaTableToMap");function P8(e,t,r,s,n){if(!e){Gs.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Gu.yy.Insert?x8(e,t,r):e instanceof Gu.yy.Select?v8(e,t,r,s,n):e instanceof Gu.yy.Update?B8(e,t,r):e instanceof Gu.yy.Delete?H8(e,t,r):Gs.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(P8,"getRecordAttributesAST");function v8(e,t,r,s,n){if(!e){Gs.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(D8.isEmptyOrZeroLength(i)){Gs.error("No schema specified");return}e.from.forEach(c=>{ku(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),ku(c.table,t,r,s,n)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Gs.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Gs.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=n.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Gs.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Gs.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(v8,"getSelectAttributes");function B8(e,t,r){if(!e){Gs.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new ho(e.columns),n=e.table.databaseid;ku(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&UT(e.table.tableid,n,i.columnid,t,r)}a(B8,"getUpdateAttributes");function H8(e,t,r){if(!e){Gs.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new ho(e.where),n=e.table.databaseid;ku(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&UT(e.table.tableid,n,i.columnid,t,r)}a(H8,"getDeleteAttributes");function x8(e,t,r){if(!e){Gs.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new ho(e.columns),n=e.into.databaseid;ku(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&UT(e.into.tableid,n,i.columnid,t,r)}a(x8,"getInsertAttributes");function UT(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(UT,"pushAttribute");AU.exports=MT});var BT=T((pfe,IU)=>{var cf=ji(),bU=require("chalk"),Wr=q(),NU=require("prompt"),{promisify:F8}=require("util"),PT=w(),G8=require("fs-extra"),q8=require("path"),k8=z(),V8=ET(),yU=j();yU.initSync();var $8=require("moment"),Y8=F8(NU.get),K8=q8.join(yU.getHdbBasePath(),PT.LICENSE_KEY_DIR_NAME,PT.LICENSE_FILE_NAME,PT.LICENSE_FILE_NAME);IU.exports={getFingerprint:Q8,setLicense:W8,parseLicense:vT,register:z8,getRegistrationInfo:X8};async function W8(e){if(e&&e.key&&e.company){try{Wr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await vT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Wr.error(r),Wr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(W8,"setLicense");async function Q8(){let e={};try{e=await cf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Wr.error(r),Wr.error(t),new Error(r)}return e}a(Q8,"getFingerprint");async function vT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Wr.info("Validating license input...");let r=cf.validateLicense(e,t);if(Wr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Wr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Wr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Wr.info("writing license to disk"),await G8.writeFile(K8,JSON.stringify({license_key:e,company:t}))}catch(s){throw Wr.error("Failed to write License"),s}return"Registration successful."}a(vT,"parseLicense");async function z8(){let e=await J8();return vT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(z8,"register");async function J8(){let e=await cf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:bU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:bU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{NU.start()}catch(s){Wr.error(s)}let r;try{r=await Y8(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(J8,"promptForRegistration");async function X8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await cf.getLicense()}catch(r){throw Wr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(k8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=V8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=$8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(X8,"getRegistrationInfo")});var CU=T((Tfe,wU)=>{"use strict";var j8=tt(),HT=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+j8.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:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};wU.exports=HT});var MU=T((Rfe,DU)=>{"use strict";var LU=tt(),xT=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+LU.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+LU.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,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"}};DU.exports=xT});var PU=T((Ofe,UU)=>{"use strict";var FT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};UU.exports=FT});var BU=T((Nfe,vU)=>{"use strict";var Z8=tt(),GT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+Z8.SERVER_SUFFIX.ADMIN,this.password=r}};vU.exports=GT});var VT=T((Ife,FU)=>{"use strict";var Ta=require("path"),_f=require("fs-extra"),e6=CU(),t6=MU(),r6=PU(),s6=BU(),qT=ls(),Ra=z(),Sr=xr(),lf=w(),Vu=tt(),{CONFIG_PARAMS:dt}=lf,$u=q(),Yu=j(),HU=wn(),kT=yt(),ga="clustering",n6=1e4,xU=5;FU.exports={generateNatsConfig:o6,removeNatsConfig:a6,getHubConfigPath:i6};function i6(){let e=Yu.get(dt.ROOTPATH);return Ta.join(e,ga,Vu.NATS_CONFIG_FILES.HUB_SERVER)}a(i6,"getHubConfigPath");async function o6(e=!1,t=void 0){Yu.initSync();let r=Yu.get(dt.ROOTPATH),s=Ta.join(r,ga,Vu.PID_FILES.HUB),n=Ta.join(r,ga,Vu.PID_FILES.LEAF),i=Sr.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ta.join(r,ga,Vu.NATS_CONFIG_FILES.HUB_SERVER),c=Ta.join(r,ga,Vu.NATS_CONFIG_FILES.LEAF_SERVER),u=Sr.getConfigFromFile(dt.CLUSTERING_TLS_CERTIFICATE),_=Sr.getConfigFromFile(dt.CLUSTERING_TLS_PRIVATEKEY),l=Sr.getConfigFromFile(dt.CLUSTERING_TLS_CERT_AUTH),d=Sr.getConfigFromFile(dt.CLUSTERING_TLS_INSECURE),f=Sr.getConfigFromFile(dt.CLUSTERING_TLS_VERIFY),E=Sr.getConfigFromFile(dt.CLUSTERING_NODENAME),h=Sr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await kT.checkNATSServerInstalled()||df("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await qT.listUsers(),S=Sr.getConfigFromFile(dt.CLUSTERING_USER),R=await qT.getClusterUser();(Ra.isEmpty(R)||R.active!==!0)&&df(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await uf(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await uf(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await uf(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),await uf(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let O=[],b=[];for(let[W,re]of p.entries())re.role.role===lf.ROLE_TYPES_ENUM.CLUSTER_USER&&re.active&&(O.push(new s6(re.username,HU.decrypt(re.hash))),b.push(new r6(re.username,HU.decrypt(re.hash))));let P=[],{hub_routes:$}=Sr.getClusteringRoutes();if(!Ra.isEmptyOrZeroLength($))for(let W of $)P.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${W.host}:${W.port}`);let x=new e6(Sr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,Sr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NAME),Sr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),P,O,b);l==null&&(delete x.tls.ca_file,delete x.leafnodes.tls.ca_file),t=Ra.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===lf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await _f.writeJson(o,x),$u.trace(`Hub server config written to ${o}`));let D=`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,Y=`tls://${R.uri_encoded_name}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,V=new t6(Sr.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[D],[Y],O,b,u,_,l,d);l==null&&delete V.tls.ca_file,(t===void 0||t===lf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await _f.writeJson(c,V),$u.trace(`Leaf server config written to ${c}`))}a(o6,"generateNatsConfig");async function uf(e){let t=Yu.get(e);return Ra.isEmpty(t)&&df(`port undefined for '${e}'`),await Ra.isPortTaken(t)&&df(`'${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(uf,"isPortAvailable");function df(e){let t=`Error generating clustering config: ${e}`;$u.error(t),console.error(t),process.exit(1)}a(df,"generateNatsConfigError");async function a6(e){let{port:t,config_file:r}=kT.getServerConfig(e),{username:s,decrypt_hash:n}=await qT.getClusterUser(),i=0,o=2e3;for(;i<xU;){try{let _=await kT.createConnection(t,s,n,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){$u.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=xU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await Ra.async_set_timeout(o*(i*2))}let c="0".repeat(n6),u=Ta.join(Yu.get(dt.ROOTPATH),ga,r);await _f.writeFile(u,c),await _f.remove(u),$u.notify(e,"started.")}a(a6,"removeNatsConfig")});var YU=T((Cfe,$U)=>{"use strict";var Qr=j(),c6=ji(),_e=w(),Ku=tt(),Mn=require("path"),{PACKAGE_ROOT:Ef}=w(),GU=j(),ff=z(),Aa="/dev/null",u6=Mn.join(Ef,"launchServiceScripts"),qU=Mn.join(Ef,"utility/scripts"),l6=Mn.join(qU,_e.HDB_RESTART_SCRIPT),kU=Mn.resolve(Ef,"dependencies",`${process.platform}-${process.arch}`,Ku.NATS_BINARY_NAME);function VU(){let t=c6.licenseSearch().ram_allocation||_e.RAM_ALLOCATION_ENUM.DEFAULT,r=_e.MEM_SETTING_KEY+t,s={[_e.PROCESS_NAME_ENV_PROP]:_e.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return ff.noBootFile()&&(s[_e.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=ff.getEnvCliRootPath()),{name:_e.PROCESS_DESCRIPTORS.HDB,script:_e.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:Ef}}a(VU,"generateMainServerConfig");var _6=9930;function d6(){Qr.initSync(!0);let e=Qr.get(_e.CONFIG_PARAMS.ROOTPATH),t=Mn.join(e,"clustering",Ku.NATS_CONFIG_FILES.HUB_SERVER),r=Mn.join(Qr.get(_e.HDB_SETTINGS_NAMES.LOG_PATH_KEY),_e.LOG_NAMES.HDB),s=GU.get(_e.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=Ku.LOG_LEVEL_FLAGS[Qr.get(_e.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:_e.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==_6?"-"+s:""),script:kU,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[_e.PROCESS_NAME_ENV_PROP]:_e.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Qr.get(_e.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Aa,i.error_file=Aa),i}a(d6,"generateNatsHubServerConfig");var f6=9940;function E6(){Qr.initSync(!0);let e=Qr.get(_e.CONFIG_PARAMS.ROOTPATH),t=Mn.join(e,"clustering",Ku.NATS_CONFIG_FILES.LEAF_SERVER),r=Mn.join(Qr.get(_e.HDB_SETTINGS_NAMES.LOG_PATH_KEY),_e.LOG_NAMES.HDB),s=GU.get(_e.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=Ku.LOG_LEVEL_FLAGS[Qr.get(_e.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:_e.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==f6?"-"+s:""),script:kU,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[_e.PROCESS_NAME_ENV_PROP]:_e.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Qr.get(_e.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Aa,i.error_file=Aa),i}a(E6,"generateNatsLeafServerConfig");function h6(){Qr.initSync();let e=Mn.join(Qr.get(_e.CONFIG_PARAMS.LOGGING_ROOT),_e.LOG_NAMES.HDB),t={name:_e.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:_e.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[_e.PROCESS_NAME_ENV_PROP]:_e.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:u6,autorestart:!1};return Qr.get(_e.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Aa,t.error_file=Aa),t}a(h6,"generateClusteringUpgradeV4ServiceConfig");function m6(){let e={[_e.PROCESS_NAME_ENV_PROP]:_e.PROCESS_DESCRIPTORS.RESTART_HDB};return ff.noBootFile()&&(e[_e.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=ff.getEnvCliRootPath()),{...{name:_e.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:qU},script:l6}}a(m6,"generateRestart");function p6(){return{apps:[VU()]}}a(p6,"generateAllServiceConfigs");$U.exports={generateAllServiceConfigs:p6,generateMainServerConfig:VU,generateRestart:m6,generateNatsHubServerConfig:d6,generateNatsLeafServerConfig:E6,generateClusteringUpgradeV4ServiceConfig:h6}});var iP=T((Mfe,nP)=>{"use strict";var Ce=w(),S6=z(),Un=VT(),Wu=yt(),cn=tt(),Si=YU(),hf=j(),Ti=q(),T6=Dn(),{startWorker:KU,onMessageFromWorkers:g6}=Ze(),R6=Sa(),Dfe=require("util"),A6=require("child_process"),O6=require("fs"),{execFile:b6}=A6,Ae;nP.exports={enterPM2Mode:N6,start:gi,stop:$T,reload:QU,restart:zU,list:YT,describe:XU,connect:Pn,kill:L6,startAllServices:D6,startService:KT,getUniqueServicesList:jU,restartAllServices:M6,isServiceRegistered:ZU,reloadStopStart:eP,restartHdb:JU,deleteProcess:w6,startClusteringProcesses:rP,startClusteringThreads:sP,isHdbRestartRunning:C6,isClusteringRunning:P6,stopClustering:U6,reloadClustering:v6};var Qu=!1;g6(e=>{e.type==="restart"&&hf.initSync(!0)});function N6(){Qu=!0}a(N6,"enterPM2Mode");function Pn(){return Ae||(Ae=require("pm2")),new Promise((e,t)=>{Ae.connect((r,s)=>{Ti.setupConsoleLogging(),r&&t(r),e(s)})})}a(Pn,"connect");var Tr,y6=10,WU;function gi(e,t=!1){if(Qu)return I6(e);let r=b6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Tr.indexOf(r);o>-1&&Tr.splice(o,1),!WU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<y6&&(O6.existsSync(Un.getHubConfigPath())?gi(e):(await Un.generateNatsConfig(!0),gi(e),await new Promise(c=>setTimeout(c,3e3)),await Un.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Un.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=hf.get(Ce.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&cn.LOG_LEVEL_HIERARCHY[o]>=cn.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===cn.LOG_LEVELS.ERR||l===cn.LOG_LEVELS.WRN?Ti.OUTPUTS.STDERR:Ti.OUTPUTS.STDOUT;Ti.logCustomLevel(l||"info",E,s,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=cn.LOG_LEVELS[f]}if(cn.LOG_LEVEL_HIERARCHY[o]>=cn.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===cn.LOG_LEVELS.ERR||l===cn.LOG_LEVELS.WRN?Ti.OUTPUTS.STDERR:Ti.OUTPUTS.STDOUT;Ti.logCustomLevel(l||"info",d,s,i.slice(_).trim())}}if(a(n,"extractMessages"),r.stdout.on("data",n),r.stderr.on("data",n),r.unref(),Tr=[],!Tr&&!t){let i=a(()=>{WU=!0,Tr&&(Tr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}Tr.push(r)}a(gi,"start");function I6(e){return new Promise(async(t,r)=>{try{await Pn()}catch(s){r(s)}Ae.start(e,(s,n)=>{s&&(Ae.disconnect(),r(s)),Ae.disconnect(),t(n)})})}a(I6,"startWithPM2");function $T(e){if(!Qu){for(let t of Tr||[])t.name===e&&(Tr.splice(Tr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Pn()}catch(s){r(s)}Ae.stop(e,async(s,n)=>{s&&(Ae.disconnect(),r(s)),Ae.delete(e,(i,o)=>{i&&(Ae.disconnect(),r(s)),Ae.disconnect(),t(o)})})})}a($T,"stop");function QU(e){return new Promise(async(t,r)=>{try{await Pn()}catch(s){r(s)}Ae.reload(e,(s,n)=>{s&&(Ae.disconnect(),r(s)),Ae.disconnect(),t(n)})})}a(QU,"reload");function zU(e){if(!Qu)for(let t of Tr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Pn()}catch(s){r(s)}Ae.restart(e,(s,n)=>{Ae.disconnect(),t(n)})})}a(zU,"restart");function w6(e){return new Promise(async(t,r)=>{try{await Pn()}catch(s){r(s)}Ae.delete(e,(s,n)=>{s&&(Ae.disconnect(),r(s)),Ae.disconnect(),t(n)})})}a(w6,"deleteProcess");async function JU(){await gi(Si.generateRestart())}a(JU,"restartHdb");async function C6(){let e=await YT();for(let t in e)if(e[t].name===Ce.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(C6,"isHdbRestartRunning");function YT(){return new Promise(async(e,t)=>{try{await Pn()}catch(r){t(r)}Ae.list((r,s)=>{r&&(Ae.disconnect(),t(r)),Ae.disconnect(),e(s)})})}a(YT,"list");function XU(e){return new Promise(async(t,r)=>{try{await Pn()}catch(s){r(s)}Ae.describe(e,(s,n)=>{s&&(Ae.disconnect(),r(s)),Ae.disconnect(),t(n)})})}a(XU,"describe");function L6(){if(!Qu){for(let e of Tr||[])e.kill();Tr=[];return}return new Promise(async(e,t)=>{try{await Pn()}catch(r){t(r)}Ae.killDaemon((r,s)=>{r&&(Ae.disconnect(),t(r)),Ae.disconnect(),e(s)})})}a(L6,"kill");async function D6(){try{await rP(),await sP(),await gi(Si.generateAllServiceConfigs())}catch(e){throw Ae?.disconnect(),e}}a(D6,"startAllServices");async function KT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ce.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Si.generateMainServerConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Si.generateNatsIngestServiceConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Si.generateNatsReplyServiceConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Si.generateNatsHubServerConfig(),await gi(r,t),await Un.removeNatsConfig(e);return;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Si.generateNatsLeafServerConfig(),await gi(r,t),await Un.removeNatsConfig(e);return;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Si.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await gi(r)}catch(r){throw Ae?.disconnect(),r}}a(KT,"startService");async function jU(){try{let e=await YT(),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 Ae?.disconnect(),e}}a(jU,"getUniqueServicesList");async function M6(e=[]){try{let t=!1,r=await jU();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===Ce.PROCESS_DESCRIPTORS.HDB?t=!0:await zU(o))}t&&await eP(Ce.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ae?.disconnect(),t}}a(M6,"restartAllServices");async function ZU(e){if(Tr?.find(r=>r.name===e))return!0;let t=await R6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(ZU,"isServiceRegistered");async function eP(e){let t=e===Ce.PROCESS_DESCRIPTORS.HDB?hf.get(Ce.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):hf.get(Ce.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await XU(e),s=S6.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await $T(e),await KT(e)):e===Ce.PROCESS_DESCRIPTORS.HDB?await JU():await QU(e)}a(eP,"reloadStopStart");var tP;async function rP(e=!1){for(let t in Ce.CLUSTERING_PROCESSES){let r=Ce.CLUSTERING_PROCESSES[t];await KT(r,e)}}a(rP,"startClusteringProcesses");async function sP(){tP=KU(Ce.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ce.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Wu.createWorkQueueStream(cn.WORK_QUEUE_CONSUMER_NAMES),await Wu.updateIngestStreamConsumer(),await Wu.updateLocalStreams();let e=await T6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ce.PRE_4_0_0_VERSION){Ti.info("Starting clustering upgrade 4.0.0 process"),KU(Ce.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(sP,"startClusteringThreads");async function U6(){for(let e in Ce.CLUSTERING_PROCESSES)if(e!==Ce.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ce.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await tP.terminate();else{let t=Ce.CLUSTERING_PROCESSES[e];await $T(t)}}a(U6,"stopClustering");async function P6(){for(let e in Ce.CLUSTERING_PROCESSES){let t=Ce.CLUSTERING_PROCESSES[e];if(await ZU(t)===!1)return!1}return!0}a(P6,"isClusteringRunning");async function v6(){await Un.generateNatsConfig(!0),await Wu.reloadNATSHub(),await Wu.reloadNATSLeaf(),await Un.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Un.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(v6,"reloadClustering")});var Tf=T((Pfe,dP)=>{"use strict";var B6=require("minimist"),{isMainThread:zT,parentPort:cP}=require("worker_threads"),it=w(),{PROCESS_DESCRIPTORS_VALIDATE:zu}=it,un=q(),JT=z(),mf=VT(),Oa=yt(),WT=tt(),uP=xr(),ln=iP(),oP=Sa(),H6=jE(),{restartWorkers:pf,onMessageByType:x6}=Ze(),{handleHDBError:F6,hdb_errors:G6}=Z(),{HTTP_STATUS_CODES:q6}=G6,Sf=j();Sf.initSync();var Ju=`Restarting HarperDB. This may take up to ${it.RESTART_TIMEOUT_MS/1e3} seconds.`,k6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",aP="Clustering is not enabled so cannot be restarted",V6="Invalid service",ba,ps;dP.exports={restart:lP,restartService:XT};zT&&x6(it.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?XT({service:e.workerType}):lP({operation:"restart"})});async function lP(e){ps=Object.keys(e).length===0,ba=await ln.isServiceRegistered(it.HDB_PROC_DESCRIPTOR);let t=B6(process.argv);if(t.service){await XT(t);return}if(ps&&!ba){console.error(k6);return}if(ps&&console.log(Ju),ba){ln.enterPM2Mode(),un.notify(Ju);let r=H6(Object.keys(it.CONFIG_PARAM_MAP),!0);return JT.isEmptyOrZeroLength(Object.keys(r))||uP.updateConfigValue(void 0,void 0,r,!0,!0),Y6(),Ju}return zT?(un.notify(Ju),setTimeout(()=>{pf()},50)):cP.postMessage({type:it.ITC_EVENT_TYPES.RESTART}),Ju}a(lP,"restart");async function XT(e){let{service:t}=e;if(it.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw F6(new Error,V6,q6.BAD_REQUEST,void 0,void 0,!0);if(ba=await ln.isServiceRegistered(it.HDB_PROC_DESCRIPTOR),!zT)return cP.postMessage({type:it.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case zu.clustering:if(!Sf.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=aP;break}ps&&console.log("Restarting clustering"),un.notify("Restarting clustering"),await _P();break;case zu.clustering_config:case zu["clustering config"]:if(!Sf.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=aP;break}ps&&console.log("Restarting clustering_config"),un.notify("Restarting clustering_config"),await ln.reloadClustering();break;case"custom_functions":case"custom functions":case zu.harperdb:case zu.http_workers:if(ps&&!ba){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}ps&&console.log("Restarting http_workers"),un.notify("Restarting http_workers"),ps?await ln.restart(it.HDB_PROC_DESCRIPTOR):setTimeout(()=>{pf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(un.error(r),ps&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(XT,"restartService");async function $6(){await Oa.publishToStream(`${WT.SUBJECT_PREFIXES.TXN}.${WT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,WT.WORK_QUEUE_CONSUMER_NAMES.stream_name,Oa.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a($6,"postDummyNatsMsg");async function Y6(){await _P(),await ln.restart(it.HDB_PROC_DESCRIPTOR),await JT.async_set_timeout(2e3),Sf.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await QT(),ps&&(await Oa.closeConnection(),process.exit(0))}a(Y6,"restartPM2Mode");async function _P(){if(!uP.getConfigFromFile(it.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await oP.getHDBProcessInfo()).clustering.length===0)un.trace("Clustering not running, restart will start clustering services"),await mf.generateNatsConfig(!0),await ln.startClusteringProcesses(),await ln.startClusteringThreads(),await QT(),ps&&await Oa.closeConnection();else{await $6(),await mf.generateNatsConfig(!0),ba?(un.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await ln.restart(it.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ln.restart(it.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await oP.getHDBProcessInfo()).clustering.forEach(n=>{un.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await JT.async_set_timeout(3e3),await QT(),await Oa.updateLocalStreams(),ps&&await Oa.closeConnection(),un.trace("Restart clustering restarting ingest and reply service threads");let t=pf(it.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=pf(it.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(_P,"restartClustering");async function QT(){await mf.removeNatsConfig(it.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await mf.removeNatsConfig(it.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(QT,"removeNatsConfig")});var OP=T((Hfe,AP)=>{"use strict";var Bfe=require("lodash"),gr=w(),{handleHDBError:fP,hdb_errors:K6}=Z(),{HDB_ERROR_MSGS:W6,HTTP_STATUS_CODES:Q6}=K6,jT=q();AP.exports={getRolePermissions:J6};var mo=Object.create(null),z6=a(e=>({key:e,perms:{}}),"perms_template_obj"),pP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),SP=a((e=!1,t=!1,r=!1,s=!1)=>({[gr.PERMS_CRUD_ENUM.READ]:e,[gr.PERMS_CRUD_ENUM.INSERT]:t,[gr.PERMS_CRUD_ENUM.UPDATE]:r,[gr.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),ZT=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...SP(t,r,s,n)}),"table_perms_template"),EP=a((e,t=SP())=>({attribute_name:e,describe:RP(t),[Xu]:t[Xu],[eg]:t[eg],[tg]:t[tg]}),"attr_perms_template"),hP=a((e,t=!1)=>({attribute_name:e,describe:t,[Xu]:t}),"timestamp_attr_perms_template"),{READ:Xu,INSERT:eg,UPDATE:tg}=gr.PERMS_CRUD_ENUM,TP=Object.values(gr.PERMS_CRUD_ENUM),gP=[Xu,eg,tg];function J6(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[gr.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(mo[t]&&mo[t].key===s)return mo[t].perms;let n=X6(e,r);return mo[t]?mo[t].key=s:mo[t]=z6(s),mo[t].perms=n,n}catch(r){if(!e[gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<gr.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 jT.error(s),jT.debug(r),fP(new Error,W6.OUTDATED_PERMS_TRANSLATION_ERROR,Q6.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
11
- ${r.stack}`;throw jT.error(s),fP(new Error)}}}a(J6,"getRolePermissions");function X6(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[gr.SYSTEM_SCHEMA_NAME]=s[gr.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]=j6(t[i]);return}r[i]=pP(),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],_=Z6(c,u);r[i].describe||TP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=ZT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=ZT()})}),r}a(X6,"translateRolePermissions");function j6(e){let t=pP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=ZT(!0,!0,!0,!0,!0)}),t}a(j6,"createStructureUserPermissions");function Z6(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}=l,f=l;return gr.TIME_STAMP_NAMES.includes(d)&&(f=hP(d,l[Xu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=EP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=RP(l),n.attribute_permissions.push(l),c||e9(l,u)}else if(_!==o){let l;gr.TIME_STAMP_NAMES.includes(_)?l=hP(_):l=EP(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=mP(n),n}else return e.describe=mP(e),e}a(Z6,"getTableAttrPerms");function mP(e){return TP.filter(t=>e[t]).length>0}a(mP,"getSchemaTableDescribePerm");function RP(e){return gP.filter(t=>e[t]).length>0}a(RP,"getAttributeDescribePerm");function e9(e,t){gP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(e9,"checkForHashPerms")});var bP={};$e(bP,{Headers:()=>Ri});var Ri,gf=ge(()=>{Ri=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]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase();if(!super.has(s))return super.set(s,[t,r])}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 ju={};$e(ju,{authentication:()=>MP,bypassAuth:()=>a9,login:()=>u9,logout:()=>l9,start:()=>c9});function a9(){DP=!0}async function MP(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?n9?s9:[]:r9?t9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Ri([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Rf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Rf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Rf){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(E);if(h>=0){let p=n.indexOf(";",h),S=n.indexOf("=",h);u=n.slice(S+1,p===-1?n.length:p),_=await yP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Of.AuthAuditLog(E,h,kt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===kt.AUTH_AUDIT_STATUS.SUCCESS?NP.notify(S):NP.error(S)},"authAuditLog"),d;if(s){if(d=po.get(s),!d){let[E,h]=s.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await At.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Af.validateOperationToken)(h)}catch(R){if(R.message==="invalid token")try{return await(0,Af.validateRefreshToken)(h),c({status:-1})}catch{throw R}}break}}catch(R){return o9&&(po.get(h)||(po.set(h,h),l(p,kt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ai({error:R.message},e)})}po.set(s,d),i9&&l(d.username,kt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await At.getUser(_.user,null,e):(DP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,wP.getSuperUser)());Rf&&(e.session.update=function(E){if(!u){u=(0,CP.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):f?.headers?.set&&f.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,yP.put(E)},e.login=async function(E,h){e.user=await At.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&Zn.loginPath?(f.status=302,f.headers.set("Location",Zn.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new Ri);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function c9({server:e,port:t}){e.request(MP,{port:t||"all"}),IP||(IP=!0,setInterval(()=>{po=new Map},Ss.get(kt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),LP.user.addListener(()=>{po=new Map}))}async function u9(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 l9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var wP,Af,CP,Ss,kt,Of,LP,NP,t9,r9,s9,n9,yP,Rf,DP,i9,o9,po,IP,bf=ge(()=>{wP=U(ls());wr();hc();Af=U(Uu());pe();CP=require("uuid"),Ss=U(j()),kt=U(w()),Of=U(q()),LP=U(eu());gf();Na();NP=(0,Of.loggerWithTag)("auth-event");Ss.initSync();t9=Ss.get(kt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),r9=Ss.get(kt.CONFIG_PARAMS.HTTP_CORS),s9=Ss.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),n9=Ss.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),yP=lt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Rf=Ss.get(kt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,DP=Ss.get(kt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,i9=Ss.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,o9=Ss.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,po=new Map;At.onInvalidatedUser(()=>{po=new Map});a(a9,"bypassAuth");a(MP,"authentication");a(c9,"start");a(u9,"login");a(l9,"logout")});var FP=T((Kfe,xP)=>{"use strict";var Oe=require("joi"),UP=require("fs-extra"),PP=require("path"),Bn=et(),vP=j(),BP=w(),HP=q(),{hdb_errors:_9}=Z(),{HDB_ERROR_MSGS:er}=_9,vn=/^[a-zA-Z0-9-_]+$/;xP.exports={getDropCustomFunctionValidator:f9,setCustomFunctionValidator:E9,addComponentValidator:S9,dropCustomFunctionProjectValidator:T9,packageComponentValidator:g9,deployComponentValidator:R9,setComponentFileValidator:h9,getComponentFileValidator:p9,dropComponentFileValidator:m9};function Nf(e,t,r){try{let s=vP.get(BP.CONFIG_PARAMS.COMPONENTSROOT),n=PP.join(s,t);return UP.existsSync(n)?e?t:r.message(er.PROJECT_EXISTS):e?r.message(er.NO_PROJECT):t}catch(s){return HP.error(s),r.message(er.VALIDATION_ERR)}}a(Nf,"checkProjectExists");function Zu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Zu,"checkFilePath");function d9(e,t,r,s){try{let n=vP.get(BP.CONFIG_PARAMS.COMPONENTSROOT),i=PP.join(n,e,t,r+".js");return UP.existsSync(i)?r:s.message(er.NO_FILE)}catch(n){return HP.error(n),s.message(er.VALIDATION_ERR)}}a(d9,"checkFileExists");function f9(e){let t=Oe.object({project:Oe.string().pattern(vn).custom(Nf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:Oe.string().valid("helpers","routes").required(),file:Oe.string().pattern(vn).custom(d9.bind(null,e.project,e.type)).custom(Zu).required().messages({"string.pattern.base":er.BAD_FILE_NAME})});return Bn.validateBySchema(e,t)}a(f9,"getDropCustomFunctionValidator");function E9(e){let t=Oe.object({project:Oe.string().pattern(vn).custom(Nf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:Oe.string().valid("helpers","routes").required(),file:Oe.string().custom(Zu).required(),function_content:Oe.string().required()});return Bn.validateBySchema(e,t)}a(E9,"setCustomFunctionValidator");function h9(e){let t=Oe.object({project:Oe.string().pattern(vn).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:Oe.string().custom(Zu).required(),payload:Oe.string().allow("").optional(),encoding:Oe.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Bn.validateBySchema(e,t)}a(h9,"setComponentFileValidator");function m9(e){let t=Oe.object({project:Oe.string().pattern(vn).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:Oe.string().custom(Zu).optional()});return Bn.validateBySchema(e,t)}a(m9,"dropComponentFileValidator");function p9(e){let t=Oe.object({project:Oe.string().required(),file:Oe.string().custom(Zu).required(),encoding:Oe.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Bn.validateBySchema(e,t)}a(p9,"getComponentFileValidator");function S9(e){let t=Oe.object({project:Oe.string().pattern(vn).custom(Nf.bind(null,!1)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Bn.validateBySchema(e,t)}a(S9,"addComponentValidator");function T9(e){let t=Oe.object({project:Oe.string().pattern(vn).custom(Nf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Bn.validateBySchema(e,t)}a(T9,"dropCustomFunctionProjectValidator");function g9(e){let t=Oe.object({project:Oe.string().pattern(vn).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),skip_node_modules:Oe.boolean()});return Bn.validateBySchema(e,t)}a(g9,"packageComponentValidator");function R9(e){let t=Oe.object({project:Oe.string().pattern(vn).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),payload:Oe.string().optional().messages({"string.pattern.base":er.BAD_PACKAGE}),package:Oe.string().optional()});return Bn.validateBySchema(e,t)}a(R9,"deployComponentValidator")});var Cf=T((Qfe,KP)=>{"use strict";var yf=require("joi"),If=require("path"),GP=require("fs-extra"),{exec:A9}=require("child_process"),O9=require("util"),qP=O9.promisify(A9),el=w(),{handleHDBError:ya,hdb_errors:b9}=Z(),{HTTP_STATUS_CODES:Ia}=b9,tl=j(),N9=et(),wa=q();tl.initSync();var rg=tl.get(el.CONFIG_PARAMS.COMPONENTSROOT),kP="npm install --omit=dev --json",y9=`${kP} --dry-run`;KP.exports={installModules:L9,auditModules:D9,installAllRootModules:I9,uninstallRootModule:w9,linkHarperdb:C9};async function I9(e=!1){await wf(),await rl(e?"npm install --ignore-scripts":"npm install",tl.get(el.CONFIG_PARAMS.ROOTPATH))}a(I9,"installAllRootModules");async function w9(e){await rl(`npm uninstall ${e}`,tl.get(el.CONFIG_PARAMS.ROOTPATH))}a(w9,"uninstallRootModule");async function C9(){await wf(),await rl(`npm link ${el.PACKAGE_ROOT}`,tl.get(el.CONFIG_PARAMS.ROOTPATH))}a(C9,"linkHarperdb");async function rl(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await qP(e,{cwd:t}))}catch(n){throw new Error(n.stderr.replace(`
12
- `,""))}return s&&!s.includes("Debugger listening")&&wa.error("Error running NPM command:",e,s),wa.trace(r,s),r?.replace(`
13
- `,"")}a(rl,"runCommand");async function L9(e){wa.info(`starting installModules for request: ${e}`);let t=YP(e);if(t)throw ya(t,t.message,Ia.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?y9:kP;await wf(),await $P(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 _=If.join(rg,u),l,d=null;try{let{stdout:f,stderr:E}=await qP(n,{cwd:_});l=f?f.replace(`
10
+ `,"")}a(_L,"runCommand");async function hX(){try{await W3.access(LS)}catch{return!1}let e=await _L(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return Q3.eq(t,fX)}a(hX,"checkNATSServerInstalled");async function vS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await aL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Wr.trace("create nats connection called");let i=await iX({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Wr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Wr.error("Error with Nats client connection, connection closed",o),dL()}),i}a(vS,"createConnection");function dL(){dn=void 0,io=void 0,oo=void 0,ao=void 0}a(dL,"clearClientCache");async function mX(){dn&&(await dn.drain(),dn=void 0,io=void 0,oo=void 0,ao=void 0)}a(mX,"closeConnection");var dn,ao;async function Hd(){return ao||(ao=vS(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),dn=await ao),dn||ao}a(Hd,"getConnection");async function Ru(){if(io)return io;co(dn)&&await Hd();let{domain:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await dn.jetstreamManager({domain:e,timeout:6e4}),io}a(Ru,"getJetStreamManager");async function fL(){if(oo)return oo;co(dn)&&await Hd();let{domain:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=dn.jetstream({domain:e,timeout:6e4}),oo}a(fL,"getJetStream");async function lr(){let e=dn||await Hd(),t=io||await Ru(),r=oo||await fL();return{connection:e,jsm:t,js:r}}a(lr,"getNATSReferences");async function pX(e){let t=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await aL.getClusterUser(),s=await vS(t,r,n),i=PS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=lL.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await MS.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(pX,"getServerList");async function BS(e,t){let{jsm:r}=await lr(),n=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:cL.File,retention:uL.Limits,subjects:t,discard:oX.Old,max_msgs:s,max_bytes:i,max_age:n})}a(BS,"createLocalStream");async function EL(){let{jsm:e}=await lr(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(EL,"listStreams");async function SX(e){let{jsm:t}=await lr();await t.streams.delete(e)}a(SX,"deleteLocalStream");async function TX(e){let{connection:t}=await lr(),r=[],n=PS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(lL.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(TX,"listRemoteStreams");async function gX(e,t=void 0,r=void 0){let{jsm:n,js:s}=await lr(),i=sL(),o={durable_name:i,ack_policy:vd.Explicit};t&&(o.deliver_policy=Bd.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.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 _=[];for await(let l of u){let d=US(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Ne.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(gX,"viewStream");async function*RX(e,t=void 0,r=void 0){let{jsm:n,js:s}=await lr(),i=sL(),o={durable_name:i,ack_policy:vd.Explicit};t&&(o.deliver_policy=Bd.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.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 _ of u){let l=US(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(Ne.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(RX,"viewStreamIterator");async function AX(e,t,r,n){Wr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=hL(n,r);let{js:s}=await lr(),i=await Ou(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:oL.encode(n);try{Wr.trace(`publishToStream publishing to subject: ${o}`),_X(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return TL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Wr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await BS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(AX,"publishToStream");function hL(e,t){t===void 0&&(t=cX());let r=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Ne.MSG_HEADERS.ORIGIN)&&r&&t.append(Ne.MSG_HEADERS.ORIGIN,r),t}a(hL,"addNatsMsgHeader");function Au(e){e=e.toLowerCase();let t=gu.join(Gt.get(Pe.CONFIG_PARAMS.ROOTPATH),dX);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(DS)&&(DS={port:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.HUB,config_file:Ne.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:gu.join(t,Ne.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(CS)&&(CS={port:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.LEAF,config_file:Ne.NATS_CONFIG_FILES.LEAF_SERVER,domain:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.LEAF,pid_file_path:gu.join(t,Ne.PID_FILES.LEAF),hdb_nats_path:t}),CS;Wr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Au,"getServerConfig");async function OX(e){let{jsm:t}=await lr(),r=await Ou();try{await t.streams.add({name:e.stream_name,storage:cL.File,retention:uL.Limits,max_age:nX,max_bytes:sX,subjects:[`${Ne.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(n){if(n.code!=="400")throw n}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(n){if(n.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:vd.Explicit,durable_name:e.durable_name,deliver_policy:Bd.All,max_ack_pending:1e4});else throw n}}a(OX,"createWorkQueueStream");async function bX(){let{jsm:e}=await lr();(await e.consumers.info(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Wr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name),Wr.info("Adding pull consumer to ingest stream"),await e.consumers.add(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:vd.Explicit,durable_name:Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:Bd.All,max_ack_pending:1e4}))}a(bX,"updateIngestStreamConsumer");async function mL(e,t,r){let{jsm:n}=await lr(),s=await n.streams.info(t),i=pL(n.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=Pd.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(s.config.sources)||s.config.sources.length===0)s.config.sources=[];else for(let S=0,p=s.config.sources.length;S<p;S++)if(d=s.config.sources[S],f=S,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let S=`txn.${c}.${u}.${e}`;await n.streams.purge(t,{filter:S}),s.config.sources.splice(f,1),await n.streams.update(t,s.config)}let h={name:_,opt_start_time:o,filter_subject:`${Ne.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),s.config.sources.push(h),await n.streams.update(t,s.config)}a(mL,"addSourceToWorkStream");function pL(e){return e.split(".")[1]}a(pL,"extractServerName");async function SL(e,t,r){let{jsm:n}=await lr(),{schema:s,table:i}=r,o=`txn.${s}.${i}.${e}`;await n.streams.purge(t,{filter:o});let c=Pd.createNatsTableStreamName(s,i),u=await n.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await n.streams.update(t,u.config)}a(SL,"removeSourceFromWorkStream");async function NX(e,t,r=6e4,n=PS()){if(!MS.isObject(t))throw new Error("data param must be an object");let s=oL.encode(t),{connection:i}=await lr(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return US(c.data)}a(NX,"request");function HS(e){return new Promise(async(t,r)=>{let n=j3(LS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(HS,"reloadNATS");async function yX(){let{pid_file_path:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await HS(e)}a(yX,"reloadNATSHub");async function IX(){let{pid_file_path:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await HS(e)}a(IX,"reloadNATSLeaf");function wX(e,t,r){let n;switch(e.code){case nL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case nL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(wX,"requestErrorHandler");async function CX(e,t){let r=t+Ne.SERVER_SUFFIX.LEAF;await TL(async()=>{e.subscribe===!0?await mL(r,Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await SL(r,Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(CX,"updateWorkStream");function TL(e){return Z3.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(TL,"exclusiveLock");async function gL(e,t){let r=Pd.createNatsTableStreamName(e,t),n=await Ou(),s=UX(e,t,n);await BS(r,[s])}a(gL,"createLocalTableStream");async function DX(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await gL(n,s)}}a(DX,"createTableStreams");async function RL(e,t,r=!1){if(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Pd.createNatsTableStreamName(e,t),{jsm:s}=await lr();r?await s.streams.purge(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name):await s.streams.purge(n)}catch(n){if(n.message==="stream not found")Wr.warn(n);else throw n}}a(RL,"purgeTableStream");async function LX(e,t){if(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await RL(e,t[r])}a(LX,"purgeSchemaTableStreams");async function MX(e){return(await Ru()).streams.info(e)}a(MX,"getStreamInfo");function UX(e,t,r){return`${Ne.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(UX,"createSubjectName");async function Ou(){if(Tu)return Tu;if(Tu=(await Ru())?.nc?.info?.server_name,Tu===void 0)throw new Error("Unable to get jetstream manager server name");return Tu}a(Ou,"getJsmServerName");async function PX(){let e=await Ru(),t=await Ou(),r=await EL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=vX(n),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(s.name===Ne.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Ne.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Wr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else if(s.name===Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Wr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Wr.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l}await e.streams.update(s.name,s)}}}a(PX,"updateLocalStreams");function vX(e){let{config:t}=e,r=!1;if(t.name===Ne.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let n=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(vX,"updateStreamLimits")});var Gd=T((pde,yL)=>{"use strict";var da=I_(),fa=rL(),BX=Y(),HX=require("uuid").v4,mde=require("clone"),Fd=gs(),Ea=M(),xX=require("util"),ui=Ln(),{handleHDBError:_r,hdb_errors:FX}=Z(),{HDB_ERROR_MSGS:xd,HTTP_STATUS_CODES:dr}=FX,{SchemaEventMsg:qd}=In(),OL=yt(),{getDatabases:qX}=(Oe(),ee(Ge)),{transformReq:ha}=J();yL.exports={createSchema:GX,createSchemaStructure:bL,createTable:kX,createTableStructure:NL,createAttribute:WX,dropSchema:VX,dropTable:$X,dropAttribute:YX,getBackup:QX};async function GX(e){let t=await bL(e);return Fd.signalSchemaChange(new qd(process.pid,e.operation,e.schema)),t}a(GX,"createSchema");async function bL(e){let t=da.schema_object(e);if(t)throw _r(t,t.message,dr.BAD_REQUEST,void 0,void 0,!0);if(ha(e),!await fa.checkSchemaExists(e.schema))throw _r(new Error,xd.SCHEMA_EXISTS_ERR(e.schema),dr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,xd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ui.createSchema(e),`database '${e.schema}' successfully created`}a(bL,"createSchemaStructure");async function kX(e){return ha(e),e.hash_attribute=e.primary_key??e.hash_attribute,await NL(e)}a(kX,"createTable");async function NL(e){let t=da.create_table_object(e);if(t)throw _r(t,t.message,dr.BAD_REQUEST,void 0,void 0,!0);if(da.validateTableResidence(e.residence),!await fa.checkSchemaTableExists(e.schema,e.table))throw _r(new Error,xd.TABLE_EXISTS_ERR(e.schema,e.table),dr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,xd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:HX(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ui.createTable(n,e);else throw _r(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",dr.BAD_REQUEST);else await ui.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(NL,"createTableStructure");async function VX(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=da.schema_object(e),n=t??r;if(n)throw _r(n,n.message,dr.BAD_REQUEST,void 0,void 0,!0);ha(e);let s=await fa.checkSchemaExists(e.schema);if(s)throw _r(new Error,s,dr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,s,!0);let i=await fa.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ui.dropSchema(e),Fd.signalSchemaChange(new qd(process.pid,e.operation,e.schema)),await OL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(VX,"dropSchema");async function $X(e){let t=da.table_object(e);if(t)throw _r(t,t.message,dr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw _r(new Error,r,dr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);return await ui.dropTable(e),await OL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a($X,"dropTable");async function YX(e){let t=da.attribute_object(e);if(t)throw _r(t,t.message,dr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw _r(new Error,r,dr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw _r(new Error,"You cannot drop a hash attribute",dr.BAD_REQUEST,void 0,void 0,!0);if(Ea.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw _r(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,dr.BAD_REQUEST,void 0,void 0,!0);try{return await ui.dropAttribute(e),KX(e),Fd.signalSchemaChange(new qd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw BX.error(`Got an error deleting attribute ${xX.inspect(e)}.`),n}}a(YX,"dropAttribute");function KX(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(KX,"dropAttributeFromGlobal");async function WX(e){ha(e);let t=qX()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw _r(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,dr.BAD_REQUEST,void 0,void 0,!0);return await ui.createAttribute(e),Fd.signalSchemaChange(new qd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(WX,"createAttribute");function QX(e){return ui.getBackup(e)}a(QX,"getBackup")});var wL=T((Tde,IL)=>{"use strict";var{OPERATIONS_ENUM:zX}=M(),xS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=zX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};IL.exports=xS});var FS=T((Ade,UL)=>{"use strict";var JX=Ln(),Rde=wL(),kd=J(),Vd=M(),XX=j(),{handleHDBError:CL,hdb_errors:jX}=Z(),{HDB_ERROR_MSGS:DL,HTTP_STATUS_CODES:LL}=jX,ZX=Object.values(Vd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),ML="To use this operation audit log must be enabled in harperdb-config.yaml";UL.exports=ej;async function ej(e){if(kd.isEmpty(e.schema))throw new Error(DL.SCHEMA_REQUIRED_ERR);if(kd.isEmpty(e.table))throw new Error(DL.TABLE_REQUIRED_ERR);if(!XX.get(Vd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw CL(new Error,ML,LL.BAD_REQUEST,Vd.LOG_LEVELS.ERROR,ML,!0);let t=kd.checkSchemaTableExist(e.schema,e.table);if(t)throw CL(new Error,t,LL.NOT_FOUND,Vd.LOG_LEVELS.ERROR,t,!0);if(!kd.isEmpty(e.search_type)&&ZX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await JX.readAuditLog(e)}a(ej,"readAuditLog")});var vL=T((bde,PL)=>{"use strict";var{OPERATIONS_ENUM:tj}=M(),qS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=tj.GET_BACKUP,this.schema=t,this.table=r}};PL.exports=qS});var xL=T((wde,HL)=>{"use strict";var rj=Ln(),yde=vL(),GS=J(),nj=M(),Ide=j(),{handleHDBError:sj,hdb_errors:ij}=Z(),{HDB_ERROR_MSGS:BL,HTTP_STATUS_CODES:oj}=ij;HL.exports=aj;async function aj(e){if(GS.isEmpty(e.schema))throw new Error(BL.SCHEMA_REQUIRED_ERR);if(GS.isEmpty(e.table))throw new Error(BL.TABLE_REQUIRED_ERR);let t=GS.checkSchemaTableExist(e.schema,e.table);if(t)throw sj(new Error,t,oj.NOT_FOUND,nj.LOG_LEVELS.ERROR,t,!0);return await rj.getBackup(read_audit_log_object)}a(aj,"getBackup")});var $L=T((Dde,VL)=>{var li=require("validate.js"),qL=rt(),ma=M(),{handleHDBError:cj,hdb_errors:uj}=Z(),{HDB_ERROR_MSGS:dt,HTTP_STATUS_CODES:lj}=uj,kS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),_j={STRUCTURE_USER:"structure_user"},FL=Object.values(ma.ROLE_TYPES_ENUM),dj="attribute_permissions",fj="attribute_name",{PERMS_CRUD_ENUM:pa}=ma,Ej=[dj,...Object.values(pa)],GL=[pa.READ,pa.INSERT,pa.UPDATE],hj=[fj,...GL];function mj(e){let t=kS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,kL(e,t)}a(mj,"addRoleValidation");function pj(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,kL(e,t)}a(pj,"alterRoleValidation");function Sj(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,qL.validateObject(e,t)}a(Sj,"dropRoleValidation");var Tj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function kL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Tj.includes(n[o])||s.push(n[o]);s.length>0&&pt(dt.INVALID_ROLE_JSON_KEYS(s),r);let i=qL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{pt(o,r)}),e.permission){let o=gj(e);o&&pt(o,r),FL.forEach(c=>{e.permission[c]&&!li.isBoolean(e.permission[c])&&pt(dt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(FL.indexOf(o)<0){if(o===_j.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||pt(dt.SCHEMA_NOT_FOUND(d),r)}continue}pt(dt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){pt(dt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){pt(dt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{Ej.includes(l)||pt(dt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(pa).forEach(l=>{li.isDefined(_[l])?li.isBoolean(_[l])||pt(dt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):pt(dt.TABLE_PERM_MISSING(l),r,o,u)}),li.isDefined(_.attribute_permissions)){if(!li.isArray(_.attribute_permissions)){pt(dt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{pt(dt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(S=>{!hj.includes(S)&&S!==pa.DELETE&&pt(dt.INVALID_ATTR_PERM_KEY(S),r,o,u)}),!li.isDefined(E.attribute_name)){pt(dt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){pt(dt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}GL.forEach(S=>{li.isDefined(E[S])?li.isBoolean(E[S])||pt(dt.ATTR_PERM_NOT_BOOLEAN(S,h),r,o,u):pt(dt.ATTR_PERM_MISSING(S,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;pt(dt.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return Rj(r)}a(kL,"customValidate");VL.exports={addRoleValidation:mj,alterRoleValidation:pj,dropRoleValidation:Sj};function gj(e){let{operation:t,permission:r}=e;if(t===ma.OPERATIONS_ENUM.ADD_ROLE||t===ma.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return dt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ma.ROLE_TYPES_ENUM.SUPER_USER:ma.ROLE_TYPES_ENUM.CLUSTER_USER;return dt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(gj,"validateNoSUPerms");function Rj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:dt.ROLE_PERMS_ERROR,...e};return cj(new Error,n,lj.BAD_REQUEST)}else return null}a(Rj,"generateRolePermResponse");function pt(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(pt,"addPermError")});var QS=T((Mde,QL)=>{"use strict";var YL=on(),KL=sn(),Aj=Ki(),$S=$L(),YS=gs(),Oj=require("uuid").v4,bj=require("util"),$d=M(),Nj=J(),KS=KL.searchByValue,yj=KL.searchByHash,Ij=bj.promisify(Aj.delete),wj=Wn(),Cj=jo(),{hdb_errors:Dj,handleHDBError:uo}=Z(),{HDB_ERROR_MSGS:WL,HTTP_STATUS_CODES:bu}=Dj,{UserEventMsg:WS}=In();QL.exports={addRole:Lj,alterRole:Mj,dropRole:Uj,listRoles:Pj};function VS(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(VS,"scrubRoleDetails");async function Lj(e){let t=$S.addRoleValidation(e);if(t)throw t;e=VS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await KS(r)||[])}catch(i){throw uo(i)}if(n&&n.length>0)throw uo(new Error,WL.ROLE_ALREADY_EXISTS(e.role),bu.CONFLICT,void 0,void 0,!0);e.id||(e.id=Oj());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await YL.insert(s),YS.signalUserChange(new WS(process.pid)),e=VS(e),e}a(Lj,"addRole");async function Mj(e){let t=$S.alterRoleValidation(e);if(t)throw t;e=VS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await YL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",bu.BAD_REQUEST,void 0,void 0,!0);return await YS.signalUserChange(new WS(process.pid)),e}a(Mj,"alterRole");async function Uj(e){let t=$S.dropRoleValidation(e);if(t)throw uo(new Error,t,bu.BAD_REQUEST,void 0,void 0,!0);let r=new Cj($d.SYSTEM_SCHEMA_NAME,$d.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await yj(r));if(n.length===0)throw uo(new Error,WL.ROLE_NOT_FOUND,bu.NOT_FOUND,void 0,void 0,!0);let s=new wj($d.SYSTEM_SCHEMA_NAME,$d.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await KS(s)),o=!1;if(Nj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,bu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Ij(c),YS.signalUserChange(new WS(process.pid)),`${n[0].role} successfully deleted`}a(Uj,"dropRole");async function Pj(){return KS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Pj,"listRoles")});var jL=T((Pde,XL)=>{"use strict";var vj=j(),_i=require("joi"),Bj=rt(),zL=require("moment"),Hj=require("fs-extra"),zS=require("path"),xj=require("lodash"),Nu=M(),{LOG_LEVELS:lo}=M(),Fj="YYYY-MM-DD hh:mm:ss",qj=zS.resolve(__dirname,"../logs");XL.exports=function(e){return Bj.validateBySchema(e,Gj)};var Gj=_i.object({from:_i.custom(JL),until:_i.custom(JL),level:_i.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:_i.valid("asc","desc"),limit:_i.number().min(1),start:_i.number().min(0),log_name:_i.custom(kj)});function JL(e,t){if(zL(e,zL.ISO_8601).format(Fj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(JL,"validateDatetime");function kj(e,t){if(xj.invert(Nu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=vj.get(Nu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Nu.LOG_NAMES.HDB:e,i=s===Nu.LOG_NAMES.INSTALL?zS.join(qj,Nu.LOG_NAMES.INSTALL):zS.join(n,s);return Hj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(kj,"validateReadLogPath")});var XS=T((Bde,eM)=>{"use strict";var Yd=M(),Vj=Y(),$j=j(),Yj=jL(),JS=require("path"),ZL=require("fs-extra"),{once:Kj}=require("events"),{handleHDBError:Wj,hdb_errors:Qj}=Z(),{PACKAGE_ROOT:zj}=M(),Jj=JS.join(zj,"logs"),Xj=1e3,jj=200;eM.exports=Zj;async function Zj(e){let t=Yj(e);if(t)throw Wj(t,t.message,Qj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=$j.get(Yd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Yd.LOG_NAMES.HDB:e.log_name,s=n===Yd.LOG_NAMES.INSTALL?JS.join(Jj,Yd.LOG_NAMES.INSTALL):JS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?Xj:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,S=0;f==="desc"&&!u&&!l&&(S=Math.max(ZL.statSync(s).size-(h+5)*jj,0));let p=ZL.createReadStream(s,{start:S});p.on("error",H=>{Vj.error(H)});let g=0,A=[],b="",v;p.on("data",H=>{let P=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;H=b+H;let z=0,W;for(;(W=P.exec(H))&&!p.destroyed;){v&&(v.message=H.slice(z,W.index),G(v));let[Q,se,pe]=W,oe=pe.split("] ["),Fe=oe[0],ce=oe[1];oe.splice(0,2),v={timestamp:se,thread:Fe,level:ce,tags:oe,message:""},z=W.index+Q.length}b=H.slice(z)}),p.on("end",H=>{p.destroyed||v&&(v.message=b.trim(),G(v))}),p.resume();function G(H){let P,z,W;switch(!0){case(i&&c&&_):P=new Date(H.timestamp),z=new Date(u),W=new Date(l),H.level===o&&P>=z&&P<=W&&g<E?g++:H.level===o&&P>=z&&P<=W&&(di(H,f,A),g++,g===h&&p.destroy());break;case(i&&c):P=new Date(H.timestamp),z=new Date(u),H.level===o&&P>=z&&g<E?g++:H.level===o&&P>=z&&(di(H,f,A),g++,g===h&&p.destroy());break;case(i&&_):P=new Date(H.timestamp),W=new Date(l),H.level===o&&P<=W&&g<E?g++:H.level===o&&P<=W&&(di(H,f,A),g++,g===h&&p.destroy());break;case(c&&_):P=new Date(H.timestamp),z=new Date(u),W=new Date(l),P>=z&&P<=W&&g<E?g++:P>=z&&P<=W&&(di(H,f,A),g++,g===h&&p.destroy());break;case i:H.level===o&&g<E?g++:H.level===o&&(di(H,f,A),g++,g===h&&p.destroy());break;case c:P=new Date(H.timestamp),z=new Date(u),P>=z&&g<E?g++:P>=z&&g>=E&&(di(H,f,A),g++,g===h&&p.destroy());break;case _:P=new Date(H.timestamp),W=new Date(l),P<=W&&g<E?g++:P<=W&&g>=E&&(di(H,f,A),g++,g===h&&p.destroy());break;default:g<E?g++:(di(H,f,A),g++,g===h&&p.destroy())}}return a(G,"onLogMessage"),await Kj(p,"close"),A}a(Zj,"readLog");function di(e,t,r){t==="desc"?eZ(e,r):t==="asc"?tZ(e,r):r.push(e)}a(di,"pushLineToResult");function eZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(eZ,"insertDescending");function tZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(tZ,"insertAscending")});var Kd=T((Gde,sM)=>{"use strict";var jS=require("joi"),{string:yu,boolean:tM,date:rZ}=jS.types(),nZ=rt(),{validateSchemaExists:xde,validateTableExists:Fde,validateSchemaName:qde}=Yn(),sZ=M(),iZ=nt(),rM=j();rM.initSync();var oZ=yu.invalid(rM.get(sZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(iZ.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(),nM={operation:yu.valid("add_node","update_node","set_node_replication"),node_name:oZ,subscriptions:jS.array().items({table:yu.optional(),schema:yu.optional(),database:yu.optional(),subscribe:tM.required(),publish:tM.required().custom(cZ),start_time:rZ.iso()}).min(1).required()};function aZ(e){return nZ.validateBySchema(e,jS.object(nM))}a(aZ,"addUpdateNodeValidator");function cZ(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(cZ,"checkForFalsy");sM.exports={addUpdateNodeValidator:aZ,validation_schema:nM}});var oM=T((Vde,iM)=>{var uZ=rt(),lZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};iM.exports=function(e){return uZ.validateObject(e,lZ)}});var eT=T(($de,aM)=>{"use strict";var _Z=M().OPERATIONS_ENUM,ZS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=_Z.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};aM.exports=ZS});var uM=T((Kde,cM)=>{"use strict";var dZ={OPERATION:"operation",REFRESH:"refresh"},tT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},rT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};cM.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:dZ,JWTRSAKeys:rT}});var Cu=T((Qde,fM)=>{"use strict";var wu=require("jsonwebtoken"),nT=require("fs-extra"),sT=J(),fn=M(),{handleHDBError:fr,hdb_errors:fZ}=Z(),{HTTP_STATUS_CODES:Er,AUTHENTICATION_ERROR_MSGS:hr}=fZ,Iu=Y(),lM=ed(),aT=cn(),EZ=on().update,hZ=eT(),mZ=gs(),{UserEventMsg:pZ}=In(),fi=j();fi.initSync();var iT=require("path"),{JWTTokens:SZ,JWTRSAKeys:TZ,TOKEN_TYPE_ENUM:Wd}=uM(),gZ=fi.get(fn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?fi.get(fn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",RZ=fi.get(fn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?fi.get(fn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Qd="RS256",oT;fM.exports={createTokens:AZ,validateOperationToken:bZ,refreshOperationToken:OZ,validateRefreshToken:dM};async function AZ(e){if(sT.isEmpty(e)||typeof e!="object")throw fr(new Error,hr.INVALID_AUTH_OBJECT,Er.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.username))throw fr(new Error,hr.USERNAME_REQUIRED,Er.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.password))throw fr(new Error,hr.PASSWORD_REQUIRED,Er.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw fr(new Error,hr.INVALID_CREDENTIALS,Er.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Iu.error(f),fr(new Error,hr.INVALID_CREDENTIALS,Er.UNAUTHORIZED,void 0,void 0,!0)}let r=await zd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await _M(i,r.private_key,r.passphrase),c=await wu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:RZ,algorithm:Qd,subject:Wd.REFRESH}),u=lM.hash(c),_=new hZ(fn.SYSTEM_SCHEMA_NAME,fn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await EZ(_)}catch(f){Iu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw fr(new Error,hr.REFRESH_TOKEN_SAVE_FAILED,Er.INTERNAL_SERVER_ERROR);return mZ.signalUserChange(new pZ(process.pid)),new SZ(o,c)}a(AZ,"createTokens");async function _M(e,t,r){return await wu.sign(e,{key:t,passphrase:r},{expiresIn:gZ,algorithm:Qd,subject:Wd.OPERATION})}a(_M,"signOperationToken");async function zd(){if(oT===void 0)try{let e=iT.join(fi.getHdbBasePath(),fn.LICENSE_KEY_DIR_NAME,fn.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(fi.getHdbBasePath(),fn.LICENSE_KEY_DIR_NAME,fn.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(fi.getHdbBasePath(),fn.LICENSE_KEY_DIR_NAME,fn.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await nT.readFile(e)).toString(),s=(await nT.readFile(t)).toString(),i=(await nT.readFile(r)).toString();oT=new TZ(i,s,n)}catch(e){throw Iu.error(e),fr(new Error,hr.NO_ENCRYPTION_KEYS,Er.INTERNAL_SERVER_ERROR)}return oT}a(zd,"getJWTRSAKeys");async function OZ(e){if(!e)throw fr(new Error,hr.INVALID_BODY,Er.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw fr(new Error,hr.REFRESH_TOKEN_REQUIRED,Er.BAD_REQUEST,void 0,void 0,!0);await dM(e.refresh_token);let t=await zd(),r=await wu.decode(e.refresh_token);return{operation_token:await _M({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(OZ,"refreshOperationToken");async function bZ(e){try{let t=await zd(),r=await wu.verify(e,t.public_key,{algorithms:Qd,subject:Wd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Iu.warn(t),t.name&&t.name==="TokenExpiredError"?fr(new Error,hr.TOKEN_EXPIRED,Er.FORBIDDEN):fr(new Error,hr.INVALID_TOKEN,Er.UNAUTHORIZED)}}a(bZ,"validateOperationToken");async function dM(e){let t;try{let r=await zd(),n=await wu.verify(e,r.public_key,{algorithms:Qd,subject:Wd.REFRESH});t=await aT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Iu.warn(r),r.name&&r.name==="TokenExpiredError"?fr(new Error,hr.TOKEN_EXPIRED,Er.FORBIDDEN):fr(new Error,hr.INVALID_TOKEN,Er.UNAUTHORIZED)}if(!lM.validate(t.refresh_token,e))throw fr(new Error,hr.INVALID_TOKEN,Er.UNAUTHORIZED);return t}a(dM,"validateRefreshToken")});var cT=T((Xde,mM)=>{"use strict";var NZ=oM(),Sa=require("passport"),yZ=require("passport-local").Strategy,IZ=require("passport-http").BasicStrategy,wZ=require("util"),CZ=cn(),hM=wZ.callbackify(CZ.findAndValidateUser),Jde=wr(),DZ=M(),EM=Cu();Sa.use(new yZ(function(e,t,r){hM(e,t,r)}));Sa.use(new IZ(function(e,t,r){hM(e,t,r)}));Sa.serializeUser(function(e,t){t(null,e)});Sa.deserializeUser(function(e,t){t(null,e)});function LZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":Sa.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===DZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?EM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):EM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Sa.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(LZ,"authorize");function MZ(e,t){let r=NZ(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(MZ,"checkPermissions");mM.exports={authorize:LZ,checkPermissions:MZ}});var Ta=T((Zde,pM)=>{"use strict";var uT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},lT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};pM.exports={Node:uT,NodeSubscription:lT}});var TM=T((tfe,SM)=>{"use strict";var UZ=M().OPERATIONS_ENUM,_T=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=UZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};SM.exports=_T});var Du=T((nfe,gM)=>{"use strict";var dT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},fT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};gM.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var AM=T((ife,RM)=>{"use strict";var ET=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};RM.exports=ET});var NM=T((lfe,bM)=>{"use strict";var PZ=AM(),afe=Et(),OM=We(),vZ=Y(),{getSchemaPath:cfe,getTransactionAuditStorePath:ufe}=Je(),{getDatabases:BZ}=(Oe(),ee(Ge));bM.exports=HZ;async function HZ(e){let t=new PZ;try{let r=BZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await OM.environmentDataSize(schema_path,e.name),o=await OM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){vZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(HZ,"lmdbGetTableSize")});var IM=T((dfe,yM)=>{"use strict";var hT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};yM.exports=hT});var ga=T((mfe,LM)=>{"use strict";var xZ=require("fs-extra"),FZ=require("path"),Xt=require("systeminformation"),Ei=Y(),qZ=yt(),mT=nt(),Xd=M(),GZ=NM(),DM=Gi(),{getThreadInfo:wM}=tt(),yT=j();yT.initSync();var kZ=IM(),{openEnvironment:Efe}=We(),{getSchemaPath:hfe}=Je(),{database:VZ}=(Oe(),ee(Ge)),Jd;LM.exports={getHDBProcessInfo:gT,getNetworkInfo:AT,getDiskInfo:RT,getMemoryInfo:TT,getCPUInfo:ST,getTimeInfo:pT,getSystemInformation:OT,systemInformation:$Z,getTableSize:bT,getMetrics:NT};function pT(){return Xt.time()}a(pT,"getTimeInfo");async function ST(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Xt.cpu();l.cpu_speed=await Xt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:S,raw_currentload_user:p,cpus:g,...A}=await Xt.currentLoad();return A.cpus=[],g.forEach(b=>{let{raw_load:v,raw_load_idle:G,raw_load_irq:H,raw_load_nice:P,raw_load_system:z,raw_load_user:W,...Q}=b;A.cpus.push(Q)}),l.current_load=A,l}catch(e){return Ei.error(`error in getCPUInfo: ${e}`),{}}}a(ST,"getCPUInfo");async function TT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Xt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ei.error(`error in getMemoryInfo: ${e}`),{}}}a(TT,"getMemoryInfo");async function gT(){let e={core:[],clustering:[]};try{let t=await Xt.processes(),r;try{r=Number.parseInt(await xZ.readFile(FZ.join(yT.get(Xd.CONFIG_PARAMS.ROOTPATH),Xd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Xd.NODE_ERROR_CODES.ENOENT)Ei.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Ei.error(`error in getHDBProcessInfo: ${t}`),e}}a(gT,"getHDBProcessInfo");async function RT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Xt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Xt.fsStats();return e.read_write=_,e.size=await Xt.fsSize(),e}catch(t){return Ei.error(`error in getDiskInfo: ${t}`),e}}a(RT,"getDiskInfo");async function AT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Xt.networkInterfaceDefault(),e.latency=await Xt.inetChecksite("google.com"),(await Xt.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=n;e.interfaces.push(f)}),(await Xt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Ei.error(`error in getNetworkInfo: ${t}`),e}}a(AT,"getNetworkInfo");async function OT(){if(Jd!==void 0)return Jd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Xt.osInfo();e=c;let u=await Xt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Jd=e,Jd}catch(t){return Ei.error(`error in getSystemInformation: ${t}`),e}}a(OT,"getSystemInformation");async function bT(){let e=[],t=await DM.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await GZ(n));return e}a(bT,"getTableSize");async function NT(){let e=await DM.describeAll(),t={};for(let r in e){let n=t[r]={};for(let s in e[r])try{let i=VZ({database:r,table:s}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),n[s]=o}catch(i){Ei.notify(`Error getting stats for table ${s}: ${i}`)}}return t}a(NT,"getMetrics");async function CM(){if(yT.get(Xd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await qZ.getNATSReferences(),r=await t.streams.info(mT.WORK_QUEUE_CONSUMER_NAMES.stream_name),n=await e.consumers.get(mT.WORK_QUEUE_CONSUMER_NAMES.stream_name,mT.WORK_QUEUE_CONSUMER_NAMES.durable_name),s={ingest:{stream:{...r.state},consumer:{num_ack_pending:n._info.num_ack_pending,num_redelivered:n._info.num_redelivered,num_waiting:n._info.num_waiting,num_pending:n._info.num_pending}}};return r.sources&&(s.ingest.stream.sources=r.sources),s}}a(CM,"getNatsStreamInfo");async function $Z(e){let t=new kZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await OT(),t.time=pT(),t.cpu=await ST(),t.memory=await TT(),t.disk=await RT(),t.network=await AT(),t.harperdb_processes=await gT(),t.table_size=await bT(),t.metrics=await NT(),t.threads=await wM(),t.replication=await CM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await OT();break;case"time":t.time=pT();break;case"cpu":t.cpu=await ST();break;case"memory":t.memory=await TT();break;case"disk":t.disk=await RT();break;case"network":t.network=await AT();break;case"harperdb_processes":t.harperdb_processes=await gT();break;case"table_size":t.table_size=await bT();break;case"database_metrics":case"metrics":t.metrics=await NT();break;case"threads":t.threads=await wM();break;case"replication":t.replication=await CM();break;default:break}return t}a($Z,"systemInformation")});var Zd=T((Sfe,MM)=>{"use strict";MM.exports={version:YZ,printVersion:KZ};var jd=pu();function YZ(){if(jd)return jd.version}a(YZ,"version");function KZ(){jd&&console.log(`HarperDB Version ${jd.version}`)}a(KZ,"printVersion")});var Is=T((Afe,BM)=>{"use strict";var WZ=on(),IT=J(),QZ=require("util"),_o=M(),UM=j();UM.initSync();var zZ=cT(),PM=sn(),{Node:gfe,NodeSubscription:Rfe}=Ta(),JZ=jo(),XZ=TM(),{RemotePayloadObject:jZ,RemotePayloadSubscription:ZZ}=Du(),{handleHDBError:e5,hdb_errors:t5}=Z(),{HTTP_STATUS_CODES:r5,HDB_ERROR_MSGS:n5}=t5,s5=Wn(),i5=ga(),o5=Zd(),{getDatabases:a5}=(Oe(),ee(Ge)),c5=QZ.promisify(zZ.authorize),u5=PM.searchByHash,l5=PM.searchByValue;BM.exports={authHeaderToUser:_5,isEmpty:d5,getNodeRecord:f5,upsertNodeRecord:E5,buildNodePayloads:h5,checkClusteringEnabled:m5,getAllNodeRecords:p5,getSystemInfo:S5,reverseSubscription:vM};async function _5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await c5(t,null),e}a(_5,"authHeaderToUser");function d5(e){return e==null}a(d5,"isEmpty");async function f5(e){let t=new JZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return u5(t)}a(f5,"getNodeRecord");async function E5(e){let t=new XZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return WZ.upsert(t)}a(E5,"upsertNodeRecord");function vM(e){if(IT.isEmpty(e.subscribe)||IT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(vM,"reverseSubscription");function h5(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=IT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=vM(c),E=a5()[u]?.[_],h=new ZZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new jZ(r,t,s,n)}a(h5,"buildNodePayloads");function m5(){if(!UM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw e5(new Error,n5.CLUSTERING_NOT_ENABLED,r5.BAD_REQUEST,void 0,void 0,!0)}a(m5,"checkClusteringEnabled");async function p5(){let e=new s5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await l5(e))}a(p5,"getAllNodeRecords");async function S5(){let e=await i5.getSystemInformation();return{hdb_version:o5.version(),node_version:e.node_version,platform:e.platform}}a(S5,"getSystemInfo")});var wT=T((bfe,$M)=>{"use strict";var ef=yt(),HM=J(),xM=nt(),FM=M(),tf=Y(),qM=Gd(),T5=Qm(),{RemotePayloadObject:g5}=Du(),{handleHDBError:GM,hdb_errors:R5}=Z(),{HTTP_STATUS_CODES:kM}=R5,{NodeSubscription:VM}=Ta();$M.exports=A5;async function A5(e,t){let r;try{r=await ef.request(`${t}.${xM.REQUEST_SUFFIX}`,new g5(FM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),tf.trace("Response from remote describe all request:",r)}catch(o){tf.error(`addNode received error from describe all request to remote node: ${o}`);let c=ef.requestErrorHandler(o,"add_node",t);throw GM(new Error,c,kM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===xM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw GM(new Error,o,kM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===FM.SYSTEM_SCHEMA_NAME){await ef.createLocalTableStream(u,c);let h=new VM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=HM.doesSchemaExist(u),l=n[u]!==void 0,d=c?HM.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(tf.trace(`addNode creating schema: ${u}`),await qM.createSchema({operation:"create_schema",schema:u})),!d&&f){tf.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new T5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await qM.createTable(h)}await ef.createLocalTableStream(u,c);let E=new VM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(A5,"reviewSubscriptions")});var sf=T((yfe,WM)=>{"use strict";var{handleHDBError:rf,hdb_errors:O5}=Z(),{HTTP_STATUS_CODES:nf}=O5,{addUpdateNodeValidator:b5}=Kd(),Lu=Y(),KM=M(),YM=nt(),N5=J(),CT=yt(),Mu=Is(),y5=j(),I5=wT(),{Node:w5,NodeSubscription:C5}=Ta(),{broadcast:D5}=tt(),L5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",M5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",U5=y5.get(KM.CONFIG_PARAMS.CLUSTERING_NODENAME);WM.exports=P5;async function P5(e,t=!1){Lu.trace("addNode called with:",e),Mu.checkClusteringEnabled();let r=b5(e);if(r)throw rf(r,r.message,nf.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Mu.getNodeRecord(n);if(!N5.isEmptyOrZeroLength(d))throw rf(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,nf.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await I5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=L5,o;let c=Mu.buildNodePayloads(s,U5,KM.OPERATIONS_ENUM.ADD_NODE,await Mu.getSystemInfo());Lu.trace("addNode sending remote payload:",c);let u;try{u=await CT.request(`${n}.${YM.REQUEST_SUFFIX}`,c)}catch(d){Lu.error(`addNode received error from request: ${d}`);let f=CT.requestErrorHandler(d,"add_node",n);throw rf(new Error,f,nf.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===YM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${u.message}`;throw rf(new Error,d,nf.INTERNAL_SERVER_ERROR,"error",d)}Lu.trace(u);let _=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];Lu.trace("Add node updating work stream for node:",n,"subscriptions:",E),await CT.updateWorkStream(E,n),s[d].start_time===void 0&&delete s[d].start_time,_.push(new C5(E.schema,E.table,E.publish,E.subscribe))}let l=new w5(n,_,u.system_info);return await Mu.upsertNodeRecord(l),D5({type:"nats_update"}),i.length>0?o.message=M5:o.message=`Successfully added '${n}' to manifest`,o}a(P5,"addNode")});var UT=T((Cfe,JM)=>{"use strict";var{handleHDBError:DT,hdb_errors:v5}=Z(),{HTTP_STATUS_CODES:LT}=v5,{addUpdateNodeValidator:B5}=Kd(),Uu=Y(),zM=M(),QM=nt(),wfe=J(),MT=yt(),Pu=Is(),H5=j(),{cloneDeep:x5}=require("lodash"),F5=wT(),{Node:q5,NodeSubscription:G5}=Ta(),{broadcast:k5}=tt(),V5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",$5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Y5=H5.get(zM.CONFIG_PARAMS.CLUSTERING_NODENAME);JM.exports=K5;async function K5(e){Uu.trace("updateNode called with:",e),Pu.checkClusteringEnabled();let t=B5(e);if(t)throw DT(t,t.message,LT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Pu.getNodeRecord(r);s.length>0&&(n=x5(s));let{added:i,skipped:o}=await F5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=V5,c;let u=Pu.buildNodePayloads(i,Y5,zM.OPERATIONS_ENUM.UPDATE_NODE,await Pu.getSystemInfo());Uu.trace("updateNode sending remote payload:",u);let _;try{_=await MT.request(`${r}.${QM.REQUEST_SUFFIX}`,u)}catch(l){Uu.error(`updateNode received error from request: ${l}`);let d=MT.requestErrorHandler(l,"update_node",r);throw DT(new Error,d,LT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===QM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw DT(new Error,l,LT.INTERNAL_SERVER_ERROR,"error",l)}Uu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];Uu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await MT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return n||(n=[new q5(r,[],_.system_info)]),await W5(n[0],i,_.system_info),o.length>0?c.message=$5:c.message=`Successfully updated '${r}'`,c}a(K5,"updateNode");async function W5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new G5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Pu.upsertNodeRecord(n),k5({type:"nats_update"})}a(W5,"updateNodeTable")});var tU=T((Lfe,eU)=>{"use strict";var ZM=require("joi"),{string:XM}=ZM.types(),Q5=rt(),jM=M(),z5=j(),J5=nt();eU.exports=X5;function X5(e){let t=XM.invalid(z5.get(jM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(J5.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=ZM.object({operation:XM.valid(jM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Q5.validateBySchema(e,r)}a(X5,"removeNodeValidator")});var af=T((Ufe,aU)=>{"use strict";var{handleHDBError:rU,hdb_errors:j5}=Z(),{HTTP_STATUS_CODES:nU}=j5,Z5=tU(),vu=Y(),sU=Is(),e8=J(),of=M(),iU=nt(),oU=yt(),t8=j(),{RemotePayloadObject:r8}=Du(),{NodeSubscription:n8}=Ta(),s8=xc(),i8=Ki(),{broadcast:o8}=tt(),a8=t8.get(of.CONFIG_PARAMS.CLUSTERING_NODENAME);aU.exports=c8;async function c8(e){vu.trace("removeNode called with:",e),sU.checkClusteringEnabled();let t=Z5(e);if(t)throw rU(t,t.message,nU.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await sU.getNodeRecord(r);if(e8.isEmptyOrZeroLength(n))throw rU(new Error,`Node '${r}' was not found.`,nU.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new r8(of.OPERATIONS_ENUM.REMOVE_NODE,a8,[]),i,o=!1;try{i=await oU.request(`${r}.${iU.REQUEST_SUFFIX}`,s),vu.trace("Remove node reply from remote node:",r,i)}catch(u){vu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];vu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new n8(l.schema,l.table,!1,!1);await oU.updateWorkStream(d,r)}let c=new s8(of.SYSTEM_SCHEMA_NAME,of.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await i8.deleteRecord(c),o8({type:"nats_update"}),i?.status===iU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(vu.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(c8,"removeNode")});var lU=T((vfe,uU)=>{"use strict";var cU=require("joi"),{string:u8,array:l8}=cU.types(),_8=rt(),d8=Kd();uU.exports=f8;function f8(e){let t=cU.object({operation:u8.valid("configure_cluster").required(),connections:l8.items(d8.validation_schema).required()});return _8.validateBySchema(e,t)}a(f8,"configureClusterValidator")});var PT=T((Hfe,hU)=>{"use strict";var E8=M(),cf=Y(),h8=J(),m8=af(),p8=sf(),_U=Is(),S8=lU(),{handleHDBError:dU,hdb_errors:T8}=Z(),{HTTP_STATUS_CODES:fU}=T8,g8="Configure cluster complete.",R8="Failed to configure the cluster. Check the logs for more details.",A8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";hU.exports=O8;async function O8(e){cf.trace("configure cluster called with:",e),_U.checkClusteringEnabled();let t=S8(e);if(t)throw dU(t,t.message,fU.BAD_REQUEST,void 0,void 0,!0);let r=await _U.getAllNodeRecords(),n=[];for(let f=0,E=r.length;f<E;f++)n.push(EU(m8,{operation:E8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let s=await Promise.allSettled(n);cf.trace("All results from configure_cluster remove node:",s);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(EU(p8,E,E.node_name))}let c=await Promise.allSettled(i);cf.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=s.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(cf.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let S=h?.value?.result;typeof S=="string"&&S.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(h8.isEmptyOrZeroLength(u))return{message:g8,connections:_};if(l)return{message:A8,failed_nodes:u,connections:_};throw dU(new Error,R8,fU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(O8,"configureCluster");async function EU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){throw{node_name:r,error:n}}}a(EU,"functionWrapper")});var pU=T((Ffe,mU)=>{"use strict";var uf=require("joi"),b8=rt(),{validateSchemaExists:N8,validateTableExists:y8,validateSchemaName:I8}=Yn(),w8=uf.object({operation:uf.string().valid("purge_stream"),schema:uf.string().custom(N8).custom(I8).required(),table:uf.string().custom(y8).required()});function C8(e){return b8.validateBySchema(e,w8)}a(C8,"purgeStreamValidator");mU.exports=C8});var vT=T((Gfe,SU)=>{"use strict";var{handleHDBError:D8,hdb_errors:L8}=Z(),{HTTP_STATUS_CODES:M8}=L8,U8=pU(),P8=yt(),v8=Is();SU.exports=B8;async function B8(e){if(e.purge_ingest!==!0){let s=U8(e);if(s)throw D8(s,s.message,M8.BAD_REQUEST,void 0,void 0,!0)}v8.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:n}=e;return await P8.purgeTableStream(t,r,n),n?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(B8,"purgeStream")});var xT=T((Vfe,bU)=>{"use strict";var HT=Is(),H8=yt(),RU=j(),lf=M(),fo=nt(),x8=J(),BT=Y(),{RemotePayloadObject:F8}=Du(),{ErrorCode:TU}=require("nats"),gU=RU.get(lf.CONFIG_PARAMS.CLUSTERING_ENABLED),AU=RU.get(lf.CONFIG_PARAMS.CLUSTERING_NODENAME);bU.exports={clusterStatus:q8,buildNodeStatus:OU};async function q8(){let e={node_name:AU,is_enabled:gU,connections:[]};if(!gU)return e;let t=await HT.getAllNodeRecords();if(x8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(OU(t[n],e.connections));return await Promise.allSettled(r),e}a(q8,"clusterStatus");async function OU(e,t){let r=e.name,n=new F8(lf.OPERATIONS_ENUM.CLUSTER_STATUS,AU,void 0,await HT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await H8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,BT.error(`Error getting node status from ${r} `,s))}catch(u){BT.warn(`Error getting node status from ${r}`,u),u.code===TU.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===TU.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new G8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==lf.PRE_4_0_0_VERSION&&await HT.upsertNodeRecord(u)}catch(u){BT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(OU,"buildNodeStatus");function G8(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(G8,"NodeStatusObject")});var qT=T((Yfe,NU)=>{"use strict";var{handleHDBError:k8,hdb_errors:V8}=Z(),{HTTP_STATUS_CODES:$8}=V8,Y8=yt(),K8=Is(),FT=J(),_f=require("joi"),W8=rt(),Q8=2e3,z8=_f.object({timeout:_f.number().min(1),connected_nodes:_f.boolean(),routes:_f.boolean()});NU.exports=J8;async function J8(e){K8.checkClusteringEnabled();let t=W8.validateBySchema(e,z8);if(t)throw k8(t,t.message,$8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||FT.autoCastBoolean(n),o=s===void 0||FT.autoCastBoolean(s),c={nodes:[]},u=await Y8.getServerList(r??Q8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(S=>{h.connected_nodes.includes(S.name.slice(0,-4))||h.connected_nodes.push(S.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(S=>({host:S.split(":")[0],port:FT.autoCast(S.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(J8,"clusterNetwork")});var CU=T((Wfe,wU)=>{"use strict";var GT=require("joi"),yU=rt(),{route_constraints:IU}=Pp();wU.exports={setRoutesValidator:X8,deleteRoutesValidator:j8};function X8(e){let t=GT.object({server:GT.valid("hub","leaf").required(),routes:IU.required()});return yU.validateBySchema(e,t)}a(X8,"setRoutesValidator");function j8(e){let t=GT.object({routes:IU.required()});return yU.validateBySchema(e,t)}a(j8,"deleteRoutesValidator")});var VT=T((zfe,UU)=>{"use strict";var Eo=xr(),kT=J(),df=M(),DU=CU(),{handleHDBError:LU,hdb_errors:Z8}=Z(),{HTTP_STATUS_CODES:MU}=Z8,e6="cluster routes successfully set",t6="cluster routes successfully deleted";UU.exports={setRoutes:r6,getRoutes:n6,deleteRoutes:s6};function r6(e){let t=DU.setRoutesValidator(e);if(t)throw LU(t,t.message,MU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=kT.autoCast(_.port);let l=n.some(f=>f.host===_.host&&f.port===_.port),d=s.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(df.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(df.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:e6,set:o,skipped:i}}a(r6,"setRoutes");function n6(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(n6,"getRoutes");function s6(e){let t=DU.deleteRoutesValidator(e);if(t)throw LU(t,t.message,MU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=n.length;E<h;E++){let S=n[E];if(d.host===S.host&&d.port===S.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,S=s.length;h<S;h++){let p=s[h];if(d.host===p.host&&d.port===p.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=kT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(df.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=kT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(df.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:t6,deleted:i,skipped:o}}a(s6,"deleteRoutes")});var vU=T((Xfe,PU)=>{"use strict";var Bu=require("alasql"),ho=require("recursive-iterator"),Bn=Y(),i6=J(),Hu=M(),$T=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,a6(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Hu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Hu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Hu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=o6(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!Hu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Bu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function o6(e){return e.filter(t=>t[Hu.PERMS_CRUD_ENUM.READ])}a(o6,"filterReadRestrictedAttrs");function a6(e,t,r,n,s){c6(e,t,r,n,s)}a(a6,"interpretAST");function xu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(xu,"addSchemaTableToMap");function c6(e,t,r,n,s){if(!e){Bn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Bu.yy.Insert?d6(e,t,r):e instanceof Bu.yy.Select?u6(e,t,r,n,s):e instanceof Bu.yy.Update?l6(e,t,r):e instanceof Bu.yy.Delete?_6(e,t,r):Bn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(c6,"getRecordAttributesAST");function u6(e,t,r,n,s){if(!e){Bn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(i6.isEmptyOrZeroLength(i)){Bn.error("No schema specified");return}e.from.forEach(c=>{xu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),xu(c.table,t,r,n,s)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Bn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Bn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Bn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Bn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(u6,"getSelectAttributes");function l6(e,t,r){if(!e){Bn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;xu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.table.tableid,s,i.columnid,t,r)}a(l6,"getUpdateAttributes");function _6(e,t,r){if(!e){Bn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;xu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.table.tableid,s,i.columnid,t,r)}a(_6,"getDeleteAttributes");function d6(e,t,r){if(!e){Bn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;xu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.into.tableid,s,i.columnid,t,r)}a(d6,"getInsertAttributes");function YT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(YT,"pushAttribute");PU.exports=$T});var QT=T((Zfe,FU)=>{var ff=Ji(),BU=require("chalk"),Qr=Y(),HU=require("prompt"),{promisify:f6}=require("util"),KT=M(),E6=require("fs-extra"),h6=require("path"),m6=J(),p6=Zd(),xU=j();xU.initSync();var S6=require("moment"),T6=f6(HU.get),g6=h6.join(xU.getHdbBasePath(),KT.LICENSE_KEY_DIR_NAME,KT.LICENSE_FILE_NAME,KT.LICENSE_FILE_NAME);FU.exports={getFingerprint:A6,setLicense:R6,parseLicense:WT,register:O6,getRegistrationInfo:N6};async function R6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await WT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Qr.error(r),Qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(R6,"setLicense");async function A6(){let e={};try{e=await ff.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(A6,"getFingerprint");async function WT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=ff.validateLicense(e,t);if(Qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Qr.info("writing license to disk"),await E6.writeFile(g6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(WT,"parseLicense");async function O6(){let e=await b6();return WT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(O6,"register");async function b6(){let e=await ff.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:BU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:BU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{HU.start()}catch(n){Qr.error(n)}let r;try{r=await T6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(b6,"promptForRegistration");async function N6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await ff.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(m6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=p6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=S6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(N6,"getRegistrationInfo")});var GU=T((tEe,qU)=>{"use strict";var y6=nt(),zT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+y6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};qU.exports=zT});var $U=T((nEe,VU)=>{"use strict";var kU=nt(),JT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+kU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+kU.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,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"}};VU.exports=JT});var KU=T((iEe,YU)=>{"use strict";var XT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};YU.exports=XT});var QU=T((aEe,WU)=>{"use strict";var I6=nt(),jT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+I6.SERVER_SUFFIX.ADMIN,this.password=r}};WU.exports=jT});var tg=T((uEe,XU)=>{"use strict";var Ra=require("path"),mf=require("fs-extra"),w6=GU(),C6=$U(),D6=KU(),L6=QU(),ZT=cn(),Oa=J(),mr=xr(),hf=M(),Fu=nt(),{CONFIG_PARAMS:ft}=hf,qu=Y(),Gu=j(),zU=bs(),eg=yt(),Aa="clustering",M6=1e4,JU=5;XU.exports={generateNatsConfig:P6,removeNatsConfig:v6,getHubConfigPath:U6};function U6(){let e=Gu.get(ft.ROOTPATH);return Ra.join(e,Aa,Fu.NATS_CONFIG_FILES.HUB_SERVER)}a(U6,"getHubConfigPath");async function P6(e=!1,t=void 0){Gu.initSync();let r=Gu.get(ft.ROOTPATH),n=Ra.join(r,Aa,Fu.PID_FILES.HUB),s=Ra.join(r,Aa,Fu.PID_FILES.LEAF),i=mr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ra.join(r,Aa,Fu.NATS_CONFIG_FILES.HUB_SERVER),c=Ra.join(r,Aa,Fu.NATS_CONFIG_FILES.LEAF_SERVER),u=mr.getConfigFromFile(ft.CLUSTERING_TLS_CERTIFICATE),_=mr.getConfigFromFile(ft.CLUSTERING_TLS_PRIVATEKEY),l=mr.getConfigFromFile(ft.CLUSTERING_TLS_CERT_AUTH),d=mr.getConfigFromFile(ft.CLUSTERING_TLS_INSECURE),f=mr.getConfigFromFile(ft.CLUSTERING_TLS_VERIFY),E=mr.getConfigFromFile(ft.CLUSTERING_NODENAME),h=mr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await eg.checkNATSServerInstalled()||pf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let S=await ZT.listUsers(),p=mr.getConfigFromFile(ft.CLUSTERING_USER),g=await ZT.getClusterUser();(Oa.isEmpty(g)||g.active!==!0)&&pf(`Invalid cluster user '${p}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Ef(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Ef(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Ef(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),await Ef(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],b=[];for(let[Q,se]of S.entries())se.role.role===hf.ROLE_TYPES_ENUM.CLUSTER_USER&&se.active&&(A.push(new L6(se.username,zU.decrypt(se.hash))),b.push(new D6(se.username,zU.decrypt(se.hash))));let v=[],{hub_routes:G}=mr.getClusteringRoutes();if(!Oa.isEmptyOrZeroLength(G))for(let Q of G)v.push(`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@${Q.host}:${Q.port}`);let H=new w6(mr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,mr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NAME),mr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),v,A,b);l==null&&(delete H.tls.ca_file,delete H.leafnodes.tls.ca_file),t=Oa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===hf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await mf.writeJson(o,H),qu.trace(`Hub server config written to ${o}`));let P=`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,z=`tls://${g.uri_encoded_name}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,W=new C6(mr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[P],[z],A,b,u,_,l,d);l==null&&delete W.tls.ca_file,(t===void 0||t===hf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await mf.writeJson(c,W),qu.trace(`Leaf server config written to ${c}`))}a(P6,"generateNatsConfig");async function Ef(e){let t=Gu.get(e);return Oa.isEmpty(t)&&pf(`port undefined for '${e}'`),await Oa.isPortTaken(t)&&pf(`'${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(Ef,"isPortAvailable");function pf(e){let t=`Error generating clustering config: ${e}`;qu.error(t),console.error(t),process.exit(1)}a(pf,"generateNatsConfigError");async function v6(e){let{port:t,config_file:r}=eg.getServerConfig(e),{username:n,decrypt_hash:s}=await ZT.getClusterUser(),i=0,o=2e3;for(;i<JU;){try{let _=await eg.createConnection(t,n,s,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){qu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=JU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await Oa.async_set_timeout(o*(i*2))}let c="0".repeat(M6),u=Ra.join(Gu.get(ft.ROOTPATH),Aa,r);await mf.writeFile(u,c),await mf.remove(u),qu.notify(e,"started.")}a(v6,"removeNatsConfig")});var nP=T((_Ee,rP)=>{"use strict";var zr=j(),B6=Ji(),me=M(),ku=nt(),ws=require("path"),{PACKAGE_ROOT:Tf}=M(),jU=j(),Sf=J(),ba="/dev/null",H6=ws.join(Tf,"launchServiceScripts"),ZU=ws.join(Tf,"utility/scripts"),x6=ws.join(ZU,me.HDB_RESTART_SCRIPT),eP=ws.resolve(Tf,"dependencies",`${process.platform}-${process.arch}`,ku.NATS_BINARY_NAME);function tP(){let t=B6.licenseSearch().ram_allocation||me.RAM_ALLOCATION_ENUM.DEFAULT,r=me.MEM_SETTING_KEY+t,n={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Sf.noBootFile()&&(n[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Sf.getEnvCliRootPath()),{name:me.PROCESS_DESCRIPTORS.HDB,script:me.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:Tf}}a(tP,"generateMainServerConfig");var F6=9930;function q6(){zr.initSync(!0);let e=zr.get(me.CONFIG_PARAMS.ROOTPATH),t=ws.join(e,"clustering",ku.NATS_CONFIG_FILES.HUB_SERVER),r=ws.join(zr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),n=jU.get(me.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[zr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==F6?"-"+n:""),script:eP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(q6,"generateNatsHubServerConfig");var G6=9940;function k6(){zr.initSync(!0);let e=zr.get(me.CONFIG_PARAMS.ROOTPATH),t=ws.join(e,"clustering",ku.NATS_CONFIG_FILES.LEAF_SERVER),r=ws.join(zr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),n=jU.get(me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[zr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==G6?"-"+n:""),script:eP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(k6,"generateNatsLeafServerConfig");function V6(){zr.initSync();let e=ws.join(zr.get(me.CONFIG_PARAMS.LOGGING_ROOT),me.LOG_NAMES.HDB),t={name:me.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:me.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:H6,autorestart:!1};return zr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ba,t.error_file=ba),t}a(V6,"generateClusteringUpgradeV4ServiceConfig");function $6(){let e={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.RESTART_HDB};return Sf.noBootFile()&&(e[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Sf.getEnvCliRootPath()),{...{name:me.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:ZU},script:x6}}a($6,"generateRestart");function Y6(){return{apps:[tP()]}}a(Y6,"generateAllServiceConfigs");rP.exports={generateAllServiceConfigs:Y6,generateMainServerConfig:tP,generateRestart:$6,generateNatsHubServerConfig:q6,generateNatsLeafServerConfig:k6,generateClusteringUpgradeV4ServiceConfig:V6}});var pP=T((EEe,mP)=>{"use strict";var Le=M(),K6=J(),Cs=tg(),Vu=yt(),ts=nt(),hi=nP(),gf=j(),mi=Y(),W6=Is(),{startWorker:sP,onMessageFromWorkers:Q6}=tt(),z6=ga(),fEe=require("util"),J6=require("child_process"),X6=require("fs"),{execFile:j6}=J6,ye;mP.exports={enterPM2Mode:Z6,start:pi,stop:rg,reload:oP,restart:aP,list:ng,describe:uP,connect:Ds,kill:s9,startAllServices:i9,startService:sg,getUniqueServicesList:lP,restartAllServices:o9,isServiceRegistered:_P,reloadStopStart:dP,restartHdb:cP,deleteProcess:r9,startClusteringProcesses:EP,startClusteringThreads:hP,isHdbRestartRunning:n9,isClusteringRunning:c9,stopClustering:a9,reloadClustering:u9};var $u=!1;Q6(e=>{e.type==="restart"&&gf.initSync(!0)});function Z6(){$u=!0}a(Z6,"enterPM2Mode");function Ds(){return ye||(ye=require("pm2")),new Promise((e,t)=>{ye.connect((r,n)=>{mi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ds,"connect");var pr,e9=10,iP;function pi(e,t=!1){if($u)return t9(e);let r=j6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=pr.indexOf(r);o>-1&&pr.splice(o,1),!iP&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<e9&&(X6.existsSync(Cs.getHubConfigPath())?pi(e):(await Cs.generateNatsConfig(!0),pi(e),await new Promise(c=>setTimeout(c,3e3)),await Cs.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Cs.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=gf.get(Le.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&ts.LOG_LEVEL_HIERARCHY[o]>=ts.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===ts.LOG_LEVELS.ERR||l===ts.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=ts.LOG_LEVELS[f]}if(ts.LOG_LEVEL_HIERARCHY[o]>=ts.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===ts.LOG_LEVELS.ERR||l===ts.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),pr=[],!pr&&!t){let i=a(()=>{iP=!0,pr&&(pr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}pr.push(r)}a(pi,"start");function t9(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.start(e,(n,s)=>{n&&(ye.disconnect(),r(n)),ye.disconnect(),t(s)})})}a(t9,"startWithPM2");function rg(e){if(!$u){for(let t of pr||[])t.name===e&&(pr.splice(pr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.stop(e,async(n,s)=>{n&&(ye.disconnect(),r(n)),ye.delete(e,(i,o)=>{i&&(ye.disconnect(),r(n)),ye.disconnect(),t(o)})})})}a(rg,"stop");function oP(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.reload(e,(n,s)=>{n&&(ye.disconnect(),r(n)),ye.disconnect(),t(s)})})}a(oP,"reload");function aP(e){if(!$u)for(let t of pr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.restart(e,(n,s)=>{ye.disconnect(),t(s)})})}a(aP,"restart");function r9(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.delete(e,(n,s)=>{n&&(ye.disconnect(),r(n)),ye.disconnect(),t(s)})})}a(r9,"deleteProcess");async function cP(){await pi(hi.generateRestart())}a(cP,"restartHdb");async function n9(){let e=await ng();for(let t in e)if(e[t].name===Le.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(n9,"isHdbRestartRunning");function ng(){return new Promise(async(e,t)=>{try{await Ds()}catch(r){t(r)}ye.list((r,n)=>{r&&(ye.disconnect(),t(r)),ye.disconnect(),e(n)})})}a(ng,"list");function uP(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.describe(e,(n,s)=>{n&&(ye.disconnect(),r(n)),ye.disconnect(),t(s)})})}a(uP,"describe");function s9(){if(!$u){for(let e of pr||[])e.kill();pr=[];return}return new Promise(async(e,t)=>{try{await Ds()}catch(r){t(r)}ye.killDaemon((r,n)=>{r&&(ye.disconnect(),t(r)),ye.disconnect(),e(n)})})}a(s9,"kill");async function i9(){try{await EP(),await hP(),await pi(hi.generateAllServiceConfigs())}catch(e){throw ye?.disconnect(),e}}a(i9,"startAllServices");async function sg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Le.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=hi.generateMainServerConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=hi.generateNatsIngestServiceConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=hi.generateNatsReplyServiceConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=hi.generateNatsHubServerConfig(),await pi(r,t),await Cs.removeNatsConfig(e);return;case Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=hi.generateNatsLeafServerConfig(),await pi(r,t),await Cs.removeNatsConfig(e);return;case Le.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=hi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await pi(r)}catch(r){throw ye?.disconnect(),r}}a(sg,"startService");async function lP(){try{let e=await ng(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw ye?.disconnect(),e}}a(lP,"getUniqueServicesList");async function o9(e=[]){try{let t=!1,r=await lP();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Le.PROCESS_DESCRIPTORS.HDB?t=!0:await aP(o))}t&&await dP(Le.PROCESS_DESCRIPTORS.HDB)}catch(t){throw ye?.disconnect(),t}}a(o9,"restartAllServices");async function _P(e){if(pr?.find(r=>r.name===e))return!0;let t=await z6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(_P,"isServiceRegistered");async function dP(e){let t=e===Le.PROCESS_DESCRIPTORS.HDB?gf.get(Le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):gf.get(Le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await uP(e),n=K6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await rg(e),await sg(e)):e===Le.PROCESS_DESCRIPTORS.HDB?await cP():await oP(e)}a(dP,"reloadStopStart");var fP;async function EP(e=!1){for(let t in Le.CLUSTERING_PROCESSES){let r=Le.CLUSTERING_PROCESSES[t];await sg(r,e)}}a(EP,"startClusteringProcesses");async function hP(){fP=sP(Le.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Le.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Vu.createWorkQueueStream(ts.WORK_QUEUE_CONSUMER_NAMES),await Vu.updateIngestStreamConsumer(),await Vu.updateLocalStreams();let e=await W6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Le.PRE_4_0_0_VERSION){mi.info("Starting clustering upgrade 4.0.0 process"),sP(Le.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(hP,"startClusteringThreads");async function a9(){for(let e in Le.CLUSTERING_PROCESSES)if(e!==Le.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Le.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await fP.terminate();else{let t=Le.CLUSTERING_PROCESSES[e];await rg(t)}}a(a9,"stopClustering");async function c9(){for(let e in Le.CLUSTERING_PROCESSES){let t=Le.CLUSTERING_PROCESSES[e];if(await _P(t)===!1)return!1}return!0}a(c9,"isClusteringRunning");async function u9(){await Cs.generateNatsConfig(!0),await Vu.reloadNATSHub(),await Vu.reloadNATSLeaf(),await Cs.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Cs.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(u9,"reloadClustering")});var bf=T((mEe,bP)=>{"use strict";var l9=require("minimist"),{isMainThread:ag,parentPort:gP}=require("worker_threads"),ot=M(),{PROCESS_DESCRIPTORS_VALIDATE:Yu}=ot,rs=Y(),cg=J(),Rf=tg(),Na=yt(),ig=nt(),RP=xr(),ns=pP(),SP=ga(),_9=ih(),{restartWorkers:Af,onMessageByType:d9}=tt(),{handleHDBError:f9,hdb_errors:E9}=Z(),{HTTP_STATUS_CODES:h9}=E9,Of=j();Of.initSync();var Ku=`Restarting HarperDB. This may take up to ${ot.RESTART_TIMEOUT_MS/1e3} seconds.`,m9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",TP="Clustering is not enabled so cannot be restarted",p9="Invalid service",ya,En;bP.exports={restart:AP,restartService:ug};ag&&d9(ot.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?ug({service:e.workerType}):AP({operation:"restart"})});async function AP(e){En=Object.keys(e).length===0,ya=await ns.isServiceRegistered(ot.HDB_PROC_DESCRIPTOR);let t=l9(process.argv);if(t.service){await ug(t);return}if(En&&!ya){console.error(m9);return}if(En&&console.log(Ku),ya){ns.enterPM2Mode(),rs.notify(Ku);let r=_9(Object.keys(ot.CONFIG_PARAM_MAP),!0);return cg.isEmptyOrZeroLength(Object.keys(r))||RP.updateConfigValue(void 0,void 0,r,!0,!0),T9(),Ku}return ag?(rs.notify(Ku),setTimeout(()=>{Af()},50)):gP.postMessage({type:ot.ITC_EVENT_TYPES.RESTART}),Ku}a(AP,"restart");async function ug(e){let{service:t}=e;if(ot.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw f9(new Error,p9,h9.BAD_REQUEST,void 0,void 0,!0);if(ya=await ns.isServiceRegistered(ot.HDB_PROC_DESCRIPTOR),!ag)return gP.postMessage({type:ot.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Yu.clustering:if(!Of.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=TP;break}En&&console.log("Restarting clustering"),rs.notify("Restarting clustering"),await OP();break;case Yu.clustering_config:case Yu["clustering config"]:if(!Of.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=TP;break}En&&console.log("Restarting clustering_config"),rs.notify("Restarting clustering_config"),await ns.reloadClustering();break;case"custom_functions":case"custom functions":case Yu.harperdb:case Yu.http_workers:if(En&&!ya){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}En&&console.log("Restarting http_workers"),rs.notify("Restarting http_workers"),En?await ns.restart(ot.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Af("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(rs.error(r),En&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(ug,"restartService");async function S9(){await Na.publishToStream(`${ig.SUBJECT_PREFIXES.TXN}.${ig.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,ig.WORK_QUEUE_CONSUMER_NAMES.stream_name,Na.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(S9,"postDummyNatsMsg");async function T9(){await OP(),await ns.restart(ot.HDB_PROC_DESCRIPTOR),await cg.async_set_timeout(2e3),Of.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await og(),En&&(await Na.closeConnection(),process.exit(0))}a(T9,"restartPM2Mode");async function OP(){if(!RP.getConfigFromFile(ot.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await SP.getHDBProcessInfo()).clustering.length===0)rs.trace("Clustering not running, restart will start clustering services"),await Rf.generateNatsConfig(!0),await ns.startClusteringProcesses(),await ns.startClusteringThreads(),await og(),En&&await Na.closeConnection();else{await S9(),await Rf.generateNatsConfig(!0),ya?(rs.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await ns.restart(ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ns.restart(ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await SP.getHDBProcessInfo()).clustering.forEach(s=>{rs.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await cg.async_set_timeout(3e3),await og(),await Na.updateLocalStreams(),En&&await Na.closeConnection(),rs.trace("Restart clustering restarting ingest and reply service threads");let t=Af(ot.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Af(ot.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(OP,"restartClustering");async function og(){await Rf.removeNatsConfig(ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Rf.removeNatsConfig(ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(og,"removeNatsConfig")});var vP=T((TEe,PP)=>{"use strict";var SEe=require("lodash"),Sr=M(),{handleHDBError:NP,hdb_errors:g9}=Z(),{HDB_ERROR_MSGS:R9,HTTP_STATUS_CODES:A9}=g9,lg=Y();PP.exports={getRolePermissions:b9};var mo=Object.create(null),O9=a(e=>({key:e,perms:{}}),"perms_template_obj"),CP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),DP=a((e=!1,t=!1,r=!1,n=!1)=>({[Sr.PERMS_CRUD_ENUM.READ]:e,[Sr.PERMS_CRUD_ENUM.INSERT]:t,[Sr.PERMS_CRUD_ENUM.UPDATE]:r,[Sr.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),_g=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...DP(t,r,n,s)}),"table_perms_template"),yP=a((e,t=DP())=>({attribute_name:e,describe:UP(t),[Wu]:t[Wu],[dg]:t[dg],[fg]:t[fg]}),"attr_perms_template"),IP=a((e,t=!1)=>({attribute_name:e,describe:t,[Wu]:t}),"timestamp_attr_perms_template"),{READ:Wu,INSERT:dg,UPDATE:fg}=Sr.PERMS_CRUD_ENUM,LP=Object.values(Sr.PERMS_CRUD_ENUM),MP=[Wu,dg,fg];function b9(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[Sr.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(mo[t]&&mo[t].key===n)return mo[t].perms;let s=N9(e,r);return mo[t]?mo[t].key=n:mo[t]=O9(n),mo[t].perms=s,s}catch(r){if(!e[Sr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Sr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Sr.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw lg.error(n),lg.debug(r),NP(new Error,R9.OUTDATED_PERMS_TRANSLATION_ERROR,A9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
11
+ ${r.stack}`;throw lg.error(n),NP(new Error)}}}a(b9,"getRolePermissions");function N9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Sr.SYSTEM_SCHEMA_NAME]=n[Sr.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=y9(t[i]);return}r[i]=CP(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=I9(c,u);r[i].describe||LP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=_g()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=_g()})}),r}a(N9,"translateRolePermissions");function y9(e){let t=CP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=_g(!0,!0,!0,!0,!0)}),t}a(y9,"createStructureUserPermissions");function I9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return Sr.TIME_STAMP_NAMES.includes(d)&&(f=IP(d,l[Wu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=yP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=UP(l),s.attribute_permissions.push(l),c||w9(l,u)}else if(_!==o){let l;Sr.TIME_STAMP_NAMES.includes(_)?l=IP(_):l=yP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=wP(s),s}else return e.describe=wP(e),e}a(I9,"getTableAttrPerms");function wP(e){return LP.filter(t=>e[t]).length>0}a(wP,"getSchemaTableDescribePerm");function UP(e){return MP.filter(t=>e[t]).length>0}a(UP,"getAttributeDescribePerm");function w9(e,t){MP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(w9,"checkForHashPerms")});var BP={};qe(BP,{Headers:()=>Si});var Si,Nf=Re(()=>{Si=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]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];n?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var Qu={};qe(Qu,{authentication:()=>$P,bypassAuth:()=>v9,login:()=>H9,logout:()=>x9,start:()=>B9});function v9(){VP=!0}async function $P(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?M9?L9:[]:D9?C9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Si([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return yf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),yf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(yf){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let S=s.indexOf(";",h),p=s.indexOf("=",h);u=s.slice(p+1,S===-1?s.length:S),_=await xP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,S)=>{let p=new wf.AuthAuditLog(E,h,kt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);p.auth_strategy=S,u&&(p.session_id=u),r.referer&&(p.referer=r.referer),r.origin&&(p.origin=r.origin),h===kt.AUTH_AUDIT_STATUS.SUCCESS?HP.notify(p):HP.error(p)},"authAuditLog"),d;if(n){if(d=po.get(n),!d){let[E,h]=n.split(" "),S,p;try{switch(E){case"Basic":[S,p]=atob(h).split(":"),d=S||p?await ut.getUser(S,p,e):null;break;case"Bearer":try{d=await(0,If.validateOperationToken)(h)}catch(g){if(g.message==="invalid token")try{return await(0,If.validateRefreshToken)(h),c({status:-1})}catch{throw g}}break}}catch(g){return P9&&(po.get(h)||(po.set(h,h),l(S,kt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ti({error:g.message},e)})}po.set(n,d),U9&&l(d.username,kt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await ut.getUser(_.user,null,e):(VP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,qP.getSuperUser)());yf&&(e.session.update=function(E){if(!u){u=(0,GP.v4)();let S=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",S):f?.headers?.set&&f.headers.set("Set-Cookie",S)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,xP.put(E)},e.login=async function(E,h){e.user=await ut.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&Js.loginPath?(f.status=302,f.headers.set("Location",Js.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new Si);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function B9({server:e,port:t}){e.request($P,{port:t||"all"}),FP||(FP=!0,setInterval(()=>{po=new Map},hn.get(kt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),kP.user.addListener(()=>{po=new Map}))}async function H9(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 x9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var qP,If,GP,hn,kt,wf,kP,HP,C9,D9,L9,M9,xP,yf,VP,U9,P9,po,FP,Cf=Re(()=>{qP=B(cn());Zt();pc();If=B(Cu());Oe();GP=require("uuid"),hn=B(j()),kt=B(M()),wf=B(Y()),kP=B(Jc());Nf();Ia();HP=(0,wf.loggerWithTag)("auth-event");hn.initSync();C9=hn.get(kt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),D9=hn.get(kt.CONFIG_PARAMS.HTTP_CORS),L9=hn.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),M9=hn.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),xP=_t({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),yf=hn.get(kt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,VP=hn.get(kt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,U9=hn.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,P9=hn.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,po=new Map;ut.onInvalidatedUser(()=>{po=new Map});a(v9,"bypassAuth");a($P,"authentication");a(B9,"start");a(H9,"login");a(x9,"logout")});var XP=T((wEe,JP)=>{"use strict";var Ie=require("joi"),YP=require("fs-extra"),KP=require("path"),Ms=rt(),WP=j(),QP=M(),zP=Y(),{hdb_errors:F9}=Z(),{HDB_ERROR_MSGS:jt}=F9,Ls=/^[a-zA-Z0-9-_]+$/;JP.exports={getDropCustomFunctionValidator:G9,setCustomFunctionValidator:k9,addComponentValidator:K9,dropCustomFunctionProjectValidator:W9,packageComponentValidator:Q9,deployComponentValidator:z9,setComponentFileValidator:V9,getComponentFileValidator:Y9,dropComponentFileValidator:$9};function Df(e,t,r){try{let n=WP.get(QP.CONFIG_PARAMS.COMPONENTSROOT),s=KP.join(n,t);return YP.existsSync(s)?e?t:r.message(jt.PROJECT_EXISTS):e?r.message(jt.NO_PROJECT):t}catch(n){return zP.error(n),r.message(jt.VALIDATION_ERR)}}a(Df,"checkProjectExists");function zu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(zu,"checkFilePath");function q9(e,t,r,n){try{let s=WP.get(QP.CONFIG_PARAMS.COMPONENTSROOT),i=KP.join(s,e,t,r+".js");return YP.existsSync(i)?r:n.message(jt.NO_FILE)}catch(s){return zP.error(s),n.message(jt.VALIDATION_ERR)}}a(q9,"checkFileExists");function G9(e){let t=Ie.object({project:Ie.string().pattern(Ls).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(Ls).custom(q9.bind(null,e.project,e.type)).custom(zu).required().messages({"string.pattern.base":jt.BAD_FILE_NAME})});return Ms.validateBySchema(e,t)}a(G9,"getDropCustomFunctionValidator");function k9(e){let t=Ie.object({project:Ie.string().pattern(Ls).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(zu).required(),function_content:Ie.string().required()});return Ms.validateBySchema(e,t)}a(k9,"setCustomFunctionValidator");function V9(e){let t=Ie.object({project:Ie.string().pattern(Ls).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ms.validateBySchema(e,t)}a(V9,"setComponentFileValidator");function $9(e){let t=Ie.object({project:Ie.string().pattern(Ls).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).optional()});return Ms.validateBySchema(e,t)}a($9,"dropComponentFileValidator");function Y9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(zu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ms.validateBySchema(e,t)}a(Y9,"getComponentFileValidator");function K9(e){let t=Ie.object({project:Ie.string().pattern(Ls).custom(Df.bind(null,!1)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME})});return Ms.validateBySchema(e,t)}a(K9,"addComponentValidator");function W9(e){let t=Ie.object({project:Ie.string().pattern(Ls).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME})});return Ms.validateBySchema(e,t)}a(W9,"dropCustomFunctionProjectValidator");function Q9(e){let t=Ie.object({project:Ie.string().pattern(Ls).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Ms.validateBySchema(e,t)}a(Q9,"packageComponentValidator");function z9(e){let t=Ie.object({project:Ie.string().pattern(Ls).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":jt.BAD_PACKAGE}),package:Ie.string().optional()});return Ms.validateBySchema(e,t)}a(z9,"deployComponentValidator")});var Pf=T((DEe,sv)=>{"use strict";var Lf=require("joi"),Mf=require("path"),jP=require("fs-extra"),{exec:J9}=require("child_process"),X9=require("util"),ZP=X9.promisify(J9),Ju=M(),{handleHDBError:wa,hdb_errors:j9}=Z(),{HTTP_STATUS_CODES:Ca}=j9,Xu=j(),Z9=rt(),Da=Y();Xu.initSync();var Eg=Xu.get(Ju.CONFIG_PARAMS.COMPONENTSROOT),ev="npm install --omit=dev --json",e7=`${ev} --dry-run`;sv.exports={installModules:s7,auditModules:i7,installAllRootModules:t7,uninstallRootModule:r7,linkHarperdb:n7};async function t7(e=!1){await Uf(),await ju(e?"npm install --ignore-scripts":"npm install",Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(t7,"installAllRootModules");async function r7(e){await ju(`npm uninstall ${e}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(r7,"uninstallRootModule");async function n7(){await Uf(),await ju(`npm link ${Ju.PACKAGE_ROOT}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(n7,"linkHarperdb");async function ju(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await ZP(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
12
+ `,""))}return n&&!n.includes("Debugger listening")&&Da.error("Error running NPM command:",e,n),Da.trace(r,n),r?.replace(`
13
+ `,"")}a(ju,"runCommand");async function s7(e){Da.info(`starting installModules for request: ${e}`);let t=nv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?e7:ev;await Uf(),await rv(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 _=Mf.join(Eg,u),l,d=null;try{let{stdout:f,stderr:E}=await ZP(s,{cwd:_});l=f?f.replace(`
14
14
  `,""):null,d=E?E.replace(`
15
- `,""):null}catch(f){f.stderr?i[u].npm_error=VP(f.stderr):i[u].npm_error=f.message;continue}try{i[u].npm_output=JSON.parse(l)}catch{i[u].npm_output=l}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return wa.info(`finished installModules with response ${i}`),i}a(L9,"installModules");function VP(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
16
- `);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(VP,"parseNPMStdErr");async function D9(e){wa.info(`starting auditModules for request: ${e}`);let t=YP(e);if(t)throw ya(t,t.message,Ia.BAD_REQUEST);let{projects:r}=e;await wf(),await $P(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=If.join(rg,o);s[o]={npm_output:null,npm_error:null};try{let u=await rl("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=VP(u.stderr)}}return wa.info(`finished auditModules with response ${s}`),s}a(D9,"auditModules");async function wf(){try{return await rl("npm -v"),!0}catch{throw ya(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ia.BAD_REQUEST,void 0,void 0,!0)}}a(wf,"checkNPMInstalled");async function $P(e){if(!Array.isArray(e)||e.length===0)throw ya(new Error,"projects argument must be an array with at least 1 element",Ia.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=If.join(rg,i.toString());if(!await GP.pathExists(o)){t.push(i);continue}let u=If.join(o,"package.json");await GP.pathExists(u)||r.push(i)}if(t.length>0)throw ya(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ia.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw ya(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ia.BAD_REQUEST,void 0,void 0,!0)}a($P,"checkProjectPaths");function YP(e){let t=yf.object({projects:yf.array().min(1).items(yf.string()).required(),dry_run:yf.boolean().default(!1)});return N9.validateBySchema(e,t)}a(YP,"modulesValidator")});var ng=T((Jfe,XP)=>{"use strict";var Ca=require("fs-extra"),sg=require("path"),Lf=q(),WP=z(),Df=w(),JP=j(),M9=xr();XP.exports=U9;async function U9(){let e=P9(),t=JP.get(Df.CONFIG_PARAMS.ROOTPATH),r=sg.join(t,"package.json"),s={dependencies:{harperdb:"file:"+Df.PACKAGE_ROOT}},n=sg.join(t,"node_modules");await Ca.ensureDir(n);let i,o=!0,c=!1;try{i=await Ca.readJson(r)}catch(u){if(WP.isEmptyOrZeroLength(e))return;if(u.code!==Df.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!WP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await QP(_);s.dependencies[u]=l+_}if(!o){Lf.notify("Installing components"),await zP(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await QP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(Lf.notify("Removing component",u),c=!0);c&&(Lf.notify("Updating components."),await zP(r,s,i))}a(U9,"installComponents");function P9(){let e=M9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(P9,"getComponentsConfig");async function QP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":sg.extname(e)||await Ca.pathExists(e)?"file:":"github:"}a(QP,"getPkgPrefix");async function zP(e,t,r){Lf.trace("npm installing components package.json",t),await Ca.writeFile(e,JSON.stringify(t,null," "));try{await Cf().installAllRootModules(JP.get(Df.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(s){throw r?await Ca.writeFile(e,JSON.stringify(r,null," ")):await Ca.unlink(e),s}}a(zP,"installPackages")});var ag=T((Zfe,tv)=>{"use strict";var qe=require("fs-extra"),ig=require("fast-glob"),fe=require("path"),ZP=require("tar-fs"),jfe=require("uuid").v4,og=require("normalize-path"),_n=FP(),It=q(),Ke=w(),St=j(),sl=xr(),v9=z(),{PACKAGE_ROOT:B9}=w(),{handleHDBError:vt,hdb_errors:H9}=Z(),{basename:x9}=require("path"),F9=ng(),ev=j(),G9=w(),{Readable:q9}=require("stream"),{isMainThread:k9}=require("worker_threads"),{HDB_ERROR_MSGS:So,HTTP_STATUS_CODES:Bt}=H9,V9=fe.join(B9,"application-template"),jP=fe.join(St.get(Ke.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function $9(){It.trace("getting custom api status");let e={};try{e={port:St.get(Ke.CONFIG_PARAMS.HTTP_PORT),directory:St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw vt(new Error,So.FUNCTION_STATUS,Bt.INTERNAL_SERVER_ERROR,It.ERR,t)}return e}a($9,"customFunctionsStatus");function Y9(){It.trace("getting custom api endpoints");let e={},t=St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT);try{ig.sync(og(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:ig.sync(og(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:ig.sync(og(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw vt(new Error,So.GET_FUNCTIONS,Bt.INTERNAL_SERVER_ERROR,It.ERR,r)}return e}a(Y9,"getCustomFunctions");function K9(e){e.project&&(e.project=fe.parse(e.project).name),e.file&&(e.file=fe.parse(e.file).name);let t=_n.getDropCustomFunctionValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);It.trace("getting custom api endpoint file content");let r=St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e,o=fe.join(r,s,n,i+".js");try{return qe.readFileSync(o,{encoding:"utf8"})}catch(c){throw vt(new Error,So.GET_FUNCTION,Bt.INTERNAL_SERVER_ERROR,It.ERR,c)}}a(K9,"getCustomFunction");function W9(e){e.project&&(e.project=fe.parse(e.project).name),e.file&&(e.file=fe.parse(e.file).name);let t=_n.setCustomFunctionValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);It.trace("setting custom function file content");let r=St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i,function_content:o}=e;try{return qe.outputFileSync(fe.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw vt(new Error,So.SET_FUNCTION,Bt.INTERNAL_SERVER_ERROR,It.ERR,c)}}a(W9,"setCustomFunction");function Q9(e){e.project&&(e.project=fe.parse(e.project).name),e.file&&(e.file=fe.parse(e.file).name);let t=_n.getDropCustomFunctionValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);It.trace("dropping custom function file");let r=St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e;try{return qe.unlinkSync(fe.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw vt(new Error,So.DROP_FUNCTION,Bt.INTERNAL_SERVER_ERROR,It.ERR,o)}}a(Q9,"dropCustomFunction");function z9(e){e.project&&(e.project=fe.parse(e.project).name);let t=_n.addComponentValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);It.trace("adding component");let r=St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;try{let n=fe.join(r,s);return qe.mkdirSync(n,{recursive:!0}),qe.copySync(V9,n),`Successfully added project: ${s}`}catch(n){throw vt(new Error,So.ADD_FUNCTION,Bt.INTERNAL_SERVER_ERROR,It.ERR,n)}}a(z9,"addComponent");function J9(e){e.project&&(e.project=fe.parse(e.project).name);let t=_n.dropCustomFunctionProjectValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);It.trace("dropping custom function project");let r=St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=St.get(Ke.CONFIG_PARAMS.APPS);if(!v9.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 sl.updateConfigValue(Ke.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=fe.join(r,s);return qe.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw vt(new Error,So.DROP_FUNCTION_PROJECT,Bt.INTERNAL_SERVER_ERROR,It.ERR,i)}}a(J9,"dropCustomFunctionProject");async function X9(e){e.project&&(e.project=fe.parse(e.project).name);let t=_n.packageComponentValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let r=St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;It.trace("packaging component",s);let n;try{n=await qe.realpath(fe.join(r,s))}catch(u){if(u.code!==Ke.NODE_ERROR_CODES.ENOENT)throw u;try{n=await qe.realpath(fe.join(St.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(_){if(_.code===Ke.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await qe.ensureDir(jP);let i=fe.join(jP,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(fe.join(n,"node_modules"))}),ZP.pack(n,o).pipe(qe.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=qe.readFileSync(i,{encoding:"base64"});return await qe.remove(i),{project:s,payload:c}}a(X9,"packageComponent");async function j9(e){e.project&&(e.project=fe.parse(e.project).name);let t=_n.deployComponentValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let r=St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{project:s,payload:n,package:i}=e;if(It.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(n){o=fe.join(r,s),i="file:"+o,await qe.ensureDir(o);let f=q9.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe(ZP.extract(o,{finish:h})).on("error",p)});let E=await qe.readdir(o);E.length===1&&E[0]==="package"&&(await qe.copy(fe.join(o,"package"),o),await qe.remove(fe.join(o,"package")))}if(await sl.addConfig(s,{package:i}),!n){await F9();let f=ev.get(G9.CONFIG_PARAMS.ROOTPATH);o=fe.join(f,"node_modules",s)}if(k9)return;let c=new Map;c.isWorker=!0;let u=(Uf(),ee(Mf)),_;u.setErrorReporter(f=>_=f);let l=x9(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return It.info("Installed component"),`Successfully deployed: ${s}`}a(j9,"deployComponent");async function Z9(){let e=sl.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await qe.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=fe.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await qe.stat(d),E={name:fe.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return It.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),s=await r(St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),{name:St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT).split(fe.sep).slice(-1).pop(),entries:t});for(let o of s.entries)if(o.package){let c=await r(fe.join(St.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(Uf(),ee(Mf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return s}a(Z9,"getComponents");async function e7(e){let t=_n.getComponentFileValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let s=sl.getConfigObj()[e.project]||e.project==="harperdb"?fe.join(ev.get(Ke.CONFIG_PARAMS.ROOTPATH),"node_modules"):St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),n=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await qe.stat(fe.join(s,e.project,e.file));return{message:await qe.readFile(fe.join(s,e.project,e.file),n),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Ke.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${fe.join(e.project,e.file)}'`):i}}a(e7,"getComponentFile");async function t7(e){let t=_n.setComponentFileValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=fe.join(St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await qe.ensureFile(s),await qe.outputFile(s,e.payload,r)):await qe.ensureDir(s),"Successfully set component: "+e.file}a(t7,"setComponentFile");async function r7(e){let t=_n.dropComponentFileValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let r=e.file?fe.join(e.project,e.file):e.project,s=fe.join(St.get(Ke.CONFIG_PARAMS.COMPONENTSROOT),r);return await qe.pathExists(s)&&await qe.remove(s),sl.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(r7,"dropComponent");tv.exports={customFunctionsStatus:$9,getCustomFunctions:Y9,getCustomFunction:K9,setCustomFunction:W9,dropCustomFunction:Q9,addComponent:z9,dropCustomFunctionProject:J9,packageComponent:X9,deployComponent:j9,getComponents:Z9,getComponentFile:e7,setComponentFile:t7,dropComponent:r7}});var cg=T((tEe,sv)=>{"use strict";var dn=require("joi"),rv=et();sv.exports={readTransactionLogValidator:s7,deleteTransactionLogsBeforeValidator:n7};function s7(e){let t=dn.object({schema:dn.string().required(),table:dn.string().required(),from:dn.date().timestamp(),to:dn.date().timestamp(),limit:dn.number().min(1)});return rv.validateBySchema(e,t)}a(s7,"readTransactionLogValidator");function n7(e){let t=dn.object({schema:dn.string().required(),table:dn.string().required(),timestamp:dn.date().timestamp().required()});return rv.validateBySchema(e,t)}a(n7,"deleteTransactionLogsBeforeValidator")});var vf=T((sEe,cv)=>{"use strict";var ug=w(),Pf=yt(),nv=z(),iv=j(),ov=wn(),{handleHDBError:La,hdb_errors:i7}=Z(),{HTTP_STATUS_CODES:Da}=i7,{readTransactionLogValidator:o7,deleteTransactionLogsBeforeValidator:a7}=cg(),av="This operation relies on clustering and cannot run with it disable.",c7="Logs successfully deleted from transaction log.",u7="All logs successfully deleted from transaction log.";cv.exports={readTransactionLog:l7,deleteTransactionLogsBefore:_7};async function*l7(e){let t=o7(e);if(t)throw La(t,t.message,Da.BAD_REQUEST,void 0,void 0,!0);if(!iv.get(ug.CONFIG_PARAMS.CLUSTERING_ENABLED))throw La(new Error,av,Da.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=nv.checkSchemaTableExist(r,s);if(n)throw La(new Error,n,Da.NOT_FOUND,void 0,void 0,!0);let i=ov.createNatsTableStreamName(r,s),o=await Pf.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 _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===ug.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(l7,"readTransactionLog");async function _7(e){let t=a7(e);if(t)throw La(t,t.message,Da.BAD_REQUEST,void 0,void 0,!0);if(!iv.get(ug.CONFIG_PARAMS.CLUSTERING_ENABLED))throw La(new Error,av,Da.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=nv.checkSchemaTableExist(r,s);if(i)throw La(new Error,i,Da.NOT_FOUND,void 0,void 0,!0);let o=ov.createNatsTableStreamName(r,s),{jsm:c}=await Pf.getNATSReferences(),u=await Pf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(n<=_)return`No transactions exist before: ${n}`;let l=c7,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=u7):d=(await Pf.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(_7,"deleteTransactionLogsBefore")});var lv=T((iEe,uv)=>{"use strict";var lg=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}};uv.exports=lg});var dv=T((aEe,_v)=>{"use strict";var _g=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};_v.exports=_g});var fg=T((uEe,Ev)=>{"use strict";var fv=lv(),d7=dv(),{HDB_ERROR_MSGS:f7}=Cr(),dg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=f7.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 fv(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new d7(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 fv(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}};Ev.exports=dg});var Ff=T((_Ee,Lv)=>{"use strict";var Eg=cs(),Bf=as(),gs=Hd(),ol=Vi(),hg=Qi(),E7=yS(),h7=yD(),al=ls(),Hf=vS(),wt=q(),m7=xS(),p7=Zd(),S7=RT(),T7=tf(),g7=AT(),R7=OT(),A7=yT(),O7=wT(),mg=DT(),Hn=z(),b7=OU(),pg=BT(),pv=Tf(),Ts=w(),Sv=OP(),N7=Sa(),Tv=Uu(),gv=(bf(),ee(ju)),Rv=xr(),zr=ag(),y7=require("alasql"),Av=vf(),Ov=Cf(),bv=fg(),{handleHDBError:Rr,hdb_errors:Nv}=Z(),{HDB_ERROR_MSGS:Vt,HTTP_STATUS_CODES:nl}=Nv,F=new Map,yv="delete",Oi="insert",xn="read",To="update",il="describe",hv=ol.describeSchema.name,mv=ol.describeTable.name,Iv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},I7="catchup",w7="handleGetJob",C7="handleGetJobsByStartDate",xf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},L7=[gs.createTable.name,gs.createAttribute.name,gs.dropTable.name,gs.dropAttribute.name],wv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},k=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};F.set(Eg.insert.name,new k(!1,[Oi]));F.set(Eg.update.name,new k(!1,[To]));F.set(Eg.upsert.name,new k(!1,[Oi,To]));F.set(Bf.searchByConditions.name,new k(!1,[xn]));F.set(Bf.searchByHash.name,new k(!1,[xn]));F.set(Bf.searchByValue.name,new k(!1,[xn]));F.set(Bf.search.name,new k(!1,[xn]));F.set(gs.createSchema.name,new k(!0,[]));F.set(gs.createTable.name,new k(!0,[]));F.set(gs.createAttribute.name,new k(!1,[Oi]));F.set(gs.dropSchema.name,new k(!0,[]));F.set(gs.dropTable.name,new k(!0,[]));F.set(gs.dropAttribute.name,new k(!0,[]));F.set(ol.describeSchema.name,new k(!1,[xn]));F.set(ol.describeTable.name,new k(!1,[xn]));F.set(hg.deleteRecord.name,new k(!1,[yv]));F.set(al.addUser.name,new k(!0,[]));F.set(al.alterUser.name,new k(!0,[]));F.set(al.dropUser.name,new k(!0,[]));F.set(al.listUsersExternal.name,new k(!0,[]));F.set(Hf.listRoles.name,new k(!0,[]));F.set(Hf.addRole.name,new k(!0,[]));F.set(Hf.alterRole.name,new k(!0,[]));F.set(Hf.dropRole.name,new k(!0,[]));F.set(m7.name,new k(!0,[]));F.set(p7.name,new k(!0,[]));F.set(S7.name,new k(!0,[]));F.set(T7.name,new k(!0,[]));F.set(g7.name,new k(!0,[]));F.set(R7.name,new k(!0,[]));F.set(mg.setRoutes.name,new k(!0,[]));F.set(mg.getRoutes.name,new k(!0,[]));F.set(mg.deleteRoutes.name,new k(!0,[]));F.set(Rv.setConfiguration.name,new k(!0,[]));F.set(A7.clusterStatus.name,new k(!0,[]));F.set(O7.name,new k(!0,[]));F.set(pg.getFingerprint.name,new k(!0,[]));F.set(pg.setLicense.name,new k(!0,[]));F.set(hg.deleteFilesBefore.name,new k(!0,[]));F.set(hg.deleteAuditLogsBefore.name,new k(!0,[]));F.set(pv.restart.name,new k(!0,[]));F.set(pv.restartService.name,new k(!0,[]));F.set(E7.name,new k(!0,[]));F.set(h7.name,new k(!0,[xn]));F.set(N7.systemInformation.name,new k(!0,[]));F.set(Rv.getConfiguration.name,new k(!0,[]));F.set(Av.readTransactionLog.name,new k(!0,[]));F.set(Av.deleteTransactionLogsBefore.name,new k(!0,[]));F.set(Ov.installModules.name,new k(!0,[]));F.set(Ov.auditModules.name,new k(!0,[]));F.set(Tv.createTokens.name,new k(!1,[]));F.set(Tv.refreshOperationToken.name,new k(!1,[]));F.set(gv.login.name,new k(!1,[]));F.set(gv.logout.name,new k(!1,[]));F.set(zr.customFunctionsStatus.name,new k(!0,[]));F.set(zr.getCustomFunctions.name,new k(!0,[]));F.set(zr.getComponents.name,new k(!0,[]));F.set(zr.getComponentFile.name,new k(!0,[]));F.set(zr.setComponentFile.name,new k(!0,[]));F.set(zr.dropComponent.name,new k(!0,[]));F.set(zr.getCustomFunction.name,new k(!0,[]));F.set(zr.setCustomFunction.name,new k(!0,[]));F.set(zr.dropCustomFunction.name,new k(!0,[]));F.set(zr.addComponent.name,new k(!0,[]));F.set(zr.dropCustomFunctionProject.name,new k(!0,[]));F.set(zr.packageComponent.name,new k(!0,[]));F.set(zr.deployComponent.name,new k(!0,[]));F.set(pg.getRegistrationInfo.name,new k(!1,[]));F.set(al.userInfo.name,new k(!1,[]));F.set(ol.describeAll.name,new k(!1,[]));F.set(w7,new k(!1,[]));F.set(C7,new k(!0,[]));F.set(I7,new k(!0,[]));F.set(xf.CSV_DATA_LOAD,new k(!1,[Oi,To]));F.set(xf.CSV_URL_LOAD,new k(!1,[Oi,To]));F.set(xf.CSV_FILE_LOAD,new k(!1,[Oi,To]));F.set(xf.IMPORT_FROM_S3,new k(!1,[Oi,To]));F.set(wv.EXPORT_TO_S3,new k(!0,[]));F.set(wv.EXPORT_LOCAL,new k(!0,[]));F.set(Ts.VALID_SQL_OPS_ENUM.DELETE,new k(!1,[yv]));F.set(Ts.VALID_SQL_OPS_ENUM.SELECT,new k(!1,[xn]));F.set(Ts.VALID_SQL_OPS_ENUM.INSERT,new k(!1,[Oi]));F.set(Ts.VALID_SQL_OPS_ENUM.UPDATE,new k(!1,[To]));Lv.exports={verifyPerms:M7,verifyPermsAst:D7,verifyBulkLoadAttributePerms:P7};function D7(e,t,r){if(Hn.isEmptyOrZeroLength(e))throw wt.info("verify_perms_ast has an empty user parameter"),Rr(new Error);if(Hn.isEmptyOrZeroLength(t))throw wt.info("verify_perms_ast has an empty user parameter"),Rr(new Error);if(Hn.isEmptyOrZeroLength(r))throw wt.info("verify_perms_ast has a null operation parameter"),Rr(new Error);try{let s=new bv,n=new b7(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw wt.info("No schemas defined in verifyPermsAst(), will not continue."),Rr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Iv[r])throw Rr(new Error,Vt.DROP_SYSTEM,nl.FORBIDDEN);if(c&&!u)return null;let _=Sv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof y7.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=n.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=Cv(t,r,o,s);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=n.getAttributesBySchemaTableName(f,d[E]),p=Tg(t.role.permission,f,d[E]);Sg(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw Rr(s)}}a(D7,"verifyPermsAst");function M7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw wt.info("null required parameter in verifyPerms"),Rr(new Error,Vt.DEFAULT_INVALID_REQUEST,nl.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema??e.database,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new bv;if(Hn.isEmptyOrZeroLength(e.hdb_user.role)||Hn.isEmptyOrZeroLength(e.hdb_user.role.permission))return wt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Vt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(Ts.SYSTEM_SCHEMA_NAME)||n===Ts.SYSTEM_SCHEMA_NAME;if(l&&Iv[r])throw Rr(new Error,Vt.DROP_SYSTEM,nl.FORBIDDEN);if(u&&!l||_===!0&&(r===gs.createSchema.name||r===gs.dropSchema.name))return null;if(L7.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=Sv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===hv||r===mv){if(n===Ts.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Vt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===hv&&(!d[n]||!d[n][il]))return c.handleInvalidItem(Vt.SCHEMA_NOT_FOUND(n));if(r===mv&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][il]))return c.handleInvalidItem(Vt.TABLE_NOT_FOUND(n,i))}}let f=Cv(e.hdb_user,r,o,c,s);if(f)return f;if(F.get(r)&&F.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&Ts.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[n].tables[i];S[Ts.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(O=>O[Ts.PERMS_CRUD_ENUM.READ]).forEach(O=>{p.push(O.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(R=>R.attribute),e.get_attributes=p)}let E=U7(e),h=Tg(e.hdb_user.role.permission,n,i);return Sg(E,h,r,i,n,c,s),c.getPermsResponse()}a(M7,"verifyPerms");function Cv(e,t,r,s,n){if(Hn.arrayHasEmptyValues([e,t,r]))throw wt.info("hasPermissions has an invalid parameter"),Rr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||F.get(t).requires_su))return null;if(!F.get(t))throw wt.info(`operation ${t} not found.`),Rr(new Error,Vt.OP_NOT_FOUND(t),nl.BAD_REQUEST);if(F.get(t)&&F.get(t).requires_su)return wt.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Vt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][il]===!1){s.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[il]===!1)s.addInvalidItem(Vt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=F.get(t).perms;!Hn.isEmpty(n)&&E.includes(n)&&(E=[n]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(wt.info(`Required ${p} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&s.addUnauthorizedTable(u,l,f)}catch(f){let E=Vt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw wt.error(E),wt.error(f),Rr(Nv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(Cv,"hasPermissions");function Sg(e,t,r,s,n,i,o){if(!e||!t)throw wt.info("no attributes specified in checkAttributePerms."),Rr(new Error);let c=F.get(r).perms;if(!c||c==="")throw wt.info(`no permissions found for ${r} in checkAttributePerms().`),Rr(new Error);if(Hn.isEmptyOrZeroLength(t))return wt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[il]===!1){i.addInvalidItem(Vt.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let f of c){if(Ts.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==xn)throw Rr(new Error,Vt.SYSTEM_TIMESTAMP_PERMS_ERR,nl.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(Vt.ATTR_NOT_FOUND(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(Sg,"checkAttributePerms");function U7(e){let t=new Set;try{if(e.action)return t;if(e.operation===Ts.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){wt.info(r)}return t}a(U7,"getRecordAttributes");function Tg(e,t,r){let s=new Map;if(Hn.isEmpty(e))return wt.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{wt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(Tg,"getAttributePermissions");function P7(e,t,r,s,n,i,o){let c=new Set(i),u=Tg(e,s,n);Sg(c,u,t,n,s,o,r)}a(P7,"verifyBulkLoadAttributePerms")});var qf=T((fEe,vv)=>{"use strict";vv.exports={evaluateSQL:W7,processAST:Pv,convertSQLToAST:Uv,checkASTPermissions:Mv};var v7=cs(),Dv=require("util"),B7=Dv.callbackify(v7.insert),H7=as().search,x7=HL().update,F7=Dv.callbackify(x7),G7=FL().convertDelete,bi=require("alasql"),q7=Ff(),Gf=q(),k7=x_(),V7=z(),cl=w(),{hdb_errors:$7,handleHDBError:gg}=Z(),{HTTP_STATUS_CODES:Rg}=$7;k7(bi);var Y7=403,K7="There was a problem performing this insert. Please check the logs and try again.",Ag=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function W7(e,t){let r=e.parsed_sql_object;if(!r){r=Uv(e.sql);let s,n=r.ast.statements[0];if(n instanceof bi.yy.Insert?s=n.into.databaseid:n instanceof bi.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof bi.yy.Update||n instanceof bi.yy.Delete?s=n.table.databaseid:Gf.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof bi.yy.Select)&&V7.isEmptyOrZeroLength(s))return t("No schema specified",null)}Pv(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(W7,"evaluateSQL");function Mv(e,t){let r;try{r=q7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(Mv,"checkASTPermissions");function Uv(e){let t=new Ag;if(!e)throw gg(new Error,"The 'sql' parameter is missing from the request body",Rg.BAD_REQUEST);try{let r=e.trim(),s=bi.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
17
- `);throw s[1]?gg(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Rg.BAD_REQUEST):gg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Rg.BAD_REQUEST)}return t}a(Uv,"convertSQLToAST");function Pv(e,t,r){try{let s=Q7;if(!e.bypass_auth&&!t.permissions_checked){let i=Mv(e,t);if(i&&i.length>0)return r(Y7,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case cl.VALID_SQL_OPS_ENUM.SELECT:s=H7,n=t.ast.statements[0];break;case cl.VALID_SQL_OPS_ENUM.INSERT:s=z7;break;case cl.VALID_SQL_OPS_ENUM.UPDATE:s=F7;break;case cl.VALID_SQL_OPS_ENUM.DELETE:s=G7;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(Pv,"processAST");function Q7(e,t){Gf.info(e),t("unknown sql statement")}a(Q7,"nullFunction");function z7({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=J7(i,e.values)}catch(o){return r(o)}B7(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Gf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(z7,"convertInsert");function J7(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]]=bi.compile(`SELECT ${n.toString()} AS [${cl.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw Gf.error(r),new Error(K7)}}a(J7,"createDataObjects")});var Og=T((hEe,Hv)=>{"use strict";var{S3:X7,GetObjectCommand:j7}=require("@aws-sdk/client-s3");Hv.exports={getFileStreamFromS3:Z7,getS3AuthObj:Bv};async function Z7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Bv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new j7(r))).Body}a(Z7,"getFileStreamFromS3");function Bv(e,t,r){return new X7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Bv,"getS3AuthObj")});var kf=T((pEe,Kv)=>{"use strict";var Ng=as(),eee=qf(),tee=Og(),{AsyncParser:ree,Transform:see}=require("json2csv"),ll=require("stream"),Jr=z(),bg=require("fs-extra"),nee=require("path"),Rs=q(),{promisify:Gv}=require("util"),ul=z(),{handleHDBError:Tt,hdb_errors:iee}=Z(),{HDB_ERROR_MSGS:Ar,HTTP_STATUS_CODES:gt}=iee,{streamAsJSON:oee}=(_S(),ee(ML)),{Upload:aee}=require("@aws-sdk/lib-storage"),xv=["search_by_value","search_by_hash","sql","search_by_conditions"],Fv=["json","csv"],qv="json",kv="csv",cee="Successfully exported JSON locally.",uee="Successfully exported CSV locally.",lee=1e3,_ee=Ng.searchByHash,dee=Ng.searchByValue,fee=Gv(eee.evaluateSQL),Eee=Gv(ll.finished);Kv.exports={export_to_s3:See,export_local:hee,toCsvStream:Vv};async function hee(e){Rs.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=$v(e);if(!Jr.isEmpty(t))throw Rs.error(t),Tt(new Error,t,gt.BAD_REQUEST,void 0,void 0,!0);if(Jr.isEmpty(e.path))throw Rs.error(Ar.MISSING_VALUE("path")),Tt(new Error,Ar.MISSING_VALUE("path"),gt.BAD_REQUEST,void 0,void 0,!0);let r=(Jr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(nee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Jr.buildFolderPath(e.path,r);await mee(e.path);let n=await Yv(e);return await pee(s,e.format,n)}a(hee,"export_local");async function mee(e){if(Rs.trace("in confirmPath"),Jr.isEmptyOrZeroLength(e))throw Tt(new Error,`Invalid path: ${e}`,gt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await bg.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,Rs.error(s),Tt(new Error,s,gt.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 Rs.error(r),Tt(new Error,r,gt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(mee,"confirmPath");async function pee(e,t,r){if(Rs.trace("in saveToLocal"),ul.isEmptyOrZeroLength(e))throw Tt(new Error,Ar.INVALID_VALUE("file_path"),gt.BAD_REQUEST,void 0,void 0,!0);if(ul.isEmptyOrZeroLength(t))throw Tt(new Error,Ar.INVALID_VALUE("Source format"),gt.BAD_REQUEST,void 0,void 0,!0);if(ul.isEmpty(r))throw Tt(new Error,Ar.NOT_FOUND("Data"),gt.BAD_REQUEST,void 0,void 0,!0);if(t===qv){let s=bg.createWriteStream(e);return oee(r).pipe(s),await Eee(s),{message:cee,path:e}}else if(t===kv){let s=bg.createWriteStream(e),n=ll.Readable.from(r),i={},o={objectMode:!0};return await new ree(i,o).fromInput(n).toOutput(s).promise(!1),{message:uee,path:e}}throw Tt(new Error,Ar.INVALID_VALUE("format"),gt.BAD_REQUEST)}a(pee,"saveToLocal");async function See(e){if(!e.s3||Object.keys(e.s3).length===0)throw Tt(new Error,Ar.MISSING_VALUE("S3 object"),gt.BAD_REQUEST);if(Jr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Tt(new Error,Ar.MISSING_VALUE("aws_access_key_id"),gt.BAD_REQUEST);if(Jr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Tt(new Error,Ar.MISSING_VALUE("aws_secret_access_key"),gt.BAD_REQUEST);if(Jr.isEmptyOrZeroLength(e.s3.bucket))throw Tt(new Error,Ar.MISSING_VALUE("bucket"),gt.BAD_REQUEST);if(Jr.isEmptyOrZeroLength(e.s3.key))throw Tt(new Error,Ar.MISSING_VALUE("key"),gt.BAD_REQUEST);if(Jr.isEmptyOrZeroLength(e.s3.region))throw Tt(new Error,Ar.MISSING_VALUE("region"),gt.BAD_REQUEST);let t=$v(e);if(!Jr.isEmpty(t))throw Tt(new Error,t,gt.BAD_REQUEST);Rs.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await Yv(e)}catch(u){throw Rs.error(u),u}let s,n=await tee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new ll.PassThrough;if(e.format===kv){i=e.s3.key+".csv";let u=Vv(r);u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===qv){i=e.s3.key+".json";let u=new ll.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%lee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Tt(new Error,Ar.INVALID_VALUE("format"),gt.BAD_REQUEST);return new aee({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(See,"export_to_s3");function Vv(e){let t=ll.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),r={},s={objectMode:!0},n=new see(r,s);return t.pipe(n)}a(Vv,"toCsvStream");function $v(e){if(Rs.trace("in exportCoreValidation"),Jr.isEmpty(e.format))return"format missing";if(Fv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${Fv.join(", ")}`;let t=e.search_operation.operation;if(Jr.isEmpty(t))return"search_operation.operation missing";if(xv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${xv.join(", ")}`}a($v,"exportCoreValidation");async function Yv(e){Rs.trace("in getRecords");let t,r;if(ul.isEmpty(e.search_operation)||ul.isEmptyOrZeroLength(e.search_operation.operation))throw Tt(new Error,Ar.INVALID_VALUE("Search operation"),gt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=dee;break;case"search_by_hash":t=_ee;break;case"search_by_conditions":t=Ng.searchByConditions;break;case"sql":t=fee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Rs.error(r),Tt(new Error,r,gt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(Yv,"getRecords")});var Zv={};$e(Zv,{contentTypes:()=>Lg,findBestSerializer:()=>$f,getDeserializer:()=>Ro,registerContentHandlers:()=>Dg,serialize:()=>Yf,serializeMessage:()=>Ai});function Tee(e){try{return e?.[0]===123?Cg(e):e}catch{return e}}function Dg(e){e.register(Ree,{serializers:[{regex:/^application\/json$/,serializer:gu},{regex:/^application\/cbor$/,serializer:function(t){return new go.EncoderStream(dl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Vf.Readable.from((0,fn.encodeIter)(t,dl)):(0,fn.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,yg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,fn.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,go.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function $f(e){let r=(e.headers.asObject||e.headers).accept,s,n=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=$t.get(_);if(E){let h=(E.q||1)*d;h>n&&(s=E,i=E.type||_,n=h,o=f)}}if(!s){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from($t.keys()).join(", "))}};s=$t.get("application/json"),i="application/json"}return{serializer:s,type:i,parameters:o}}function Yf(e,t,r){let s=Qv&&t.headers.asObject?.["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;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=$f(t);if(i.serializer.compressible===!1&&(s=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e);return s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Fn.createBrotliCompress)({params:{[Fn.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Fn.constants.BROTLI_MODE_TEXT:Fn.constants.BROTLI_MODE_GENERIC,[Fn.constants.BROTLI_PARAM_QUALITY]:2}}))),o}n=i.serializer.serialize(e)}return s&&n?.length>Qv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Fn.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ai(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return _l(e);let r=t.serialize;if(r)return r(e);let s=$f(t);return r=t.serialize=s.serializer.serialize,r(e)}function Aee(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 Ro(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=$t.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=$t.get(e)?.deserialize||zv(e,s);return o=>Aee(o).then(i)}return e&&$t.get(e)?.deserialize||zv(e,s)}function zv(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=>{if(!e)try{if(r?.[0]===123)return Cg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Oee(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 yg,fn,go,Fn,Vf,Jv,Ig,wg,Xv,_l,Cg,dl,$t,Lg,Wv,jv,gee,Ree,Qv,Na=ge(()=>{_S();yg=U(kf()),fn=require("msgpackr"),go=require("cbor-x"),Fn=require("zlib"),Vf=require("stream");wr();Jv=require("../index"),Ig=U(j()),wg=U(w()),Xv=Ig.default.get(wg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,_l=Xv?no:JSON.stringify,Cg=Xv?lS:JSON.parse,dl={useRecords:!1,useToJSON:!0},$t=new Map,Lg=$t;At.contentTypes=Lg;(0,Jv._assignPackageExport)("contentTypes",Lg);$t.set("application/json",{serializeStream:gu,serialize:_l,deserialize:Cg,q:.8});Wv=new go.Encoder(dl);$t.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new go.EncoderStream(dl).end(e)},serialize:Wv.encode,deserialize:Wv.decode,q:1});$t.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Vf.Readable.from((0,fn.encodeIter)(e,dl)):(0,fn.pack)(e)},serialize:fn.pack,deserialize:fn.unpack,q:.9});$t.set("text/csv",{serializeStream(e){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,yg.toCsvStream)(e)},q:.1});$t.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});$t.set("text/event-stream",{serializeStream:function(e){return Vf.Readable.from(Oee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
18
- `),e.data){let r=e.data;typeof r=="object"&&(r=_l(r)),t+="data: "+r+`
15
+ `,""):null}catch(f){f.stderr?i[u].npm_error=tv(f.stderr):i[u].npm_error=f.message;continue}try{i[u].npm_output=JSON.parse(l)}catch{i[u].npm_output=l}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return Da.info(`finished installModules with response ${i}`),i}a(s7,"installModules");function tv(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
16
+ `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(tv,"parseNPMStdErr");async function i7(e){Da.info(`starting auditModules for request: ${e}`);let t=nv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r}=e;await Uf(),await rv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Mf.join(Eg,o);n[o]={npm_output:null,npm_error:null};try{let u=await ju("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=tv(u.stderr)}}return Da.info(`finished auditModules with response ${n}`),n}a(i7,"auditModules");async function Uf(){try{return await ju("npm -v"),!0}catch{throw wa(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ca.BAD_REQUEST,void 0,void 0,!0)}}a(Uf,"checkNPMInstalled");async function rv(e){if(!Array.isArray(e)||e.length===0)throw wa(new Error,"projects argument must be an array with at least 1 element",Ca.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Mf.join(Eg,i.toString());if(!await jP.pathExists(o)){t.push(i);continue}let u=Mf.join(o,"package.json");await jP.pathExists(u)||r.push(i)}if(t.length>0)throw wa(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ca.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw wa(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ca.BAD_REQUEST,void 0,void 0,!0)}a(rv,"checkProjectPaths");function nv(e){let t=Lf.object({projects:Lf.array().min(1).items(Lf.string()).required(),dry_run:Lf.boolean().default(!1)});return Z9.validateBySchema(e,t)}a(nv,"modulesValidator")});var mg=T((MEe,uv)=>{"use strict";var La=require("fs-extra"),hg=require("path"),vf=Y(),iv=J(),Bf=M(),cv=j(),o7=xr();uv.exports=a7;async function a7(){let e=c7(),t=cv.get(Bf.CONFIG_PARAMS.ROOTPATH),r=hg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Bf.PACKAGE_ROOT}},s=hg.join(t,"node_modules");await La.ensureDir(s);let i,o=!0,c=!1;try{i=await La.readJson(r)}catch(u){if(iv.isEmptyOrZeroLength(e))return;if(u.code!==Bf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!iv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await ov(_);n.dependencies[u]=l+_}if(!o){vf.notify("Installing components"),await av(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await ov(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(vf.notify("Removing component",u),c=!0);c&&(vf.notify("Updating components."),await av(r,n,i))}a(a7,"installComponents");function c7(){let e=o7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(c7,"getComponentsConfig");async function ov(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":hg.extname(e)||await La.pathExists(e)?"file:":"github:"}a(ov,"getPkgPrefix");async function av(e,t,r){vf.trace("npm installing components package.json",t),await La.writeFile(e,JSON.stringify(t,null," "));try{await Pf().installAllRootModules(cv.get(Bf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await La.writeFile(e,JSON.stringify(r,null," ")):await La.unlink(e),n}}a(av,"installPackages")});var Tg=T((vEe,fv)=>{"use strict";var ke=require("fs-extra"),pg=require("fast-glob"),Te=require("path"),_v=require("tar-fs"),PEe=require("uuid").v4,Sg=require("normalize-path"),ss=XP(),It=Y(),Qe=M(),St=j(),Zu=xr(),u7=J(),{PACKAGE_ROOT:l7}=M(),{handleHDBError:Bt,hdb_errors:_7}=Z(),{basename:d7}=require("path"),f7=mg(),dv=j(),E7=M(),{Readable:h7}=require("stream"),{isMainThread:m7}=require("worker_threads"),{HDB_ERROR_MSGS:So,HTTP_STATUS_CODES:Ht}=_7,p7=Te.join(l7,"application-template"),lv=Te.join(St.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function S7(){It.trace("getting custom api status");let e={};try{e={port:St.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Bt(new Error,So.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,It.ERR,t)}return e}a(S7,"customFunctionsStatus");function T7(){It.trace("getting custom api endpoints");let e={},t=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{pg.sync(Sg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:pg.sync(Sg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:pg.sync(Sg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Bt(new Error,So.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,It.ERR,r)}return e}a(T7,"getCustomFunctions");function g7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=ss.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("getting custom api endpoint file content");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw Bt(new Error,So.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,It.ERR,c)}}a(g7,"getCustomFunction");function R7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=ss.setCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("setting custom function file content");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return ke.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Bt(new Error,So.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,It.ERR,c)}}a(R7,"setCustomFunction");function A7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=ss.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("dropping custom function file");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return ke.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Bt(new Error,So.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,It.ERR,o)}}a(A7,"dropCustomFunction");function O7(e){e.project&&(e.project=Te.parse(e.project).name);let t=ss.addComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("adding component");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return ke.mkdirSync(s,{recursive:!0}),ke.copySync(p7,s),`Successfully added project: ${n}`}catch(s){throw Bt(new Error,So.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,It.ERR,s)}}a(O7,"addComponent");function b7(e){e.project&&(e.project=Te.parse(e.project).name);let t=ss.dropCustomFunctionProjectValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("dropping custom function project");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=St.get(Qe.CONFIG_PARAMS.APPS);if(!u7.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return Zu.updateConfigValue(Qe.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Bt(new Error,So.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,It.ERR,i)}}a(b7,"dropCustomFunctionProject");async function N7(e){e.project&&(e.project=Te.parse(e.project).name);let t=ss.packageComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;It.trace("packaging component",n);let s;try{s=await ke.realpath(Te.join(r,n))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{s=await ke.realpath(Te.join(St.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await ke.ensureDir(lv);let i=Te.join(lv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),_v.pack(s,o).pipe(ke.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=ke.readFileSync(i,{encoding:"base64"});return await ke.remove(i),{project:n,payload:c}}a(N7,"packageComponent");async function y7(e){e.project&&(e.project=Te.parse(e.project).name);let t=ss.deployComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(It.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await ke.ensureDir(o);let f=h7.from(Buffer.from(s,"base64"));await new Promise((h,S)=>{f.pipe(_v.extract(o,{finish:h})).on("error",S)});let E=await ke.readdir(o);E.length===1&&E[0]==="package"&&(await ke.copy(Te.join(o,"package"),o),await ke.remove(Te.join(o,"package")))}if(await Zu.addConfig(n,{package:i}),!s){await f7();let f=dv.get(E7.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",n)}if(m7)return;let c=new Map;c.isWorker=!0;let u=(xf(),ee(Hf)),_;u.setErrorReporter(f=>_=f);let l=d7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return It.info("Installed component"),`Successfully deployed: ${n}`}a(y7,"deployComponent");async function I7(){let e=Zu.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await ke.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Te.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await ke.stat(d),E={name:Te.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return It.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(St.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(xf(),ee(Hf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(I7,"getComponents");async function w7(e){let t=ss.getComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let n=Zu.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(dv.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(Te.join(n,e.project,e.file));return{message:await ke.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(w7,"getComponentFile");async function C7(e){let t=ss.setComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(n),await ke.outputFile(n,e.payload,r)):await ke.ensureDir(n),"Successfully set component: "+e.file}a(C7,"setComponentFile");async function D7(e){let t=ss.dropComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(n)&&await ke.remove(n),Zu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(D7,"dropComponent");fv.exports={customFunctionsStatus:S7,getCustomFunctions:T7,getCustomFunction:g7,setCustomFunction:R7,dropCustomFunction:A7,addComponent:O7,dropCustomFunctionProject:b7,packageComponent:N7,deployComponent:y7,getComponents:I7,getComponentFile:w7,setComponentFile:C7,dropComponent:D7}});var gg=T((HEe,hv)=>{"use strict";var is=require("joi"),Ev=rt();hv.exports={readTransactionLogValidator:L7,deleteTransactionLogsBeforeValidator:M7};function L7(e){let t=is.object({schema:is.string().required(),table:is.string().required(),from:is.date().timestamp(),to:is.date().timestamp(),limit:is.number().min(1)});return Ev.validateBySchema(e,t)}a(L7,"readTransactionLogValidator");function M7(e){let t=is.object({schema:is.string().required(),table:is.string().required(),timestamp:is.date().timestamp().required()});return Ev.validateBySchema(e,t)}a(M7,"deleteTransactionLogsBeforeValidator")});var qf=T((FEe,gv)=>{"use strict";var Rg=M(),Ff=yt(),mv=J(),pv=j(),Sv=bs(),{handleHDBError:Ma,hdb_errors:U7}=Z(),{HTTP_STATUS_CODES:Ua}=U7,{readTransactionLogValidator:P7,deleteTransactionLogsBeforeValidator:v7}=gg(),Tv="This operation relies on clustering and cannot run with it disable.",B7="Logs successfully deleted from transaction log.",H7="All logs successfully deleted from transaction log.";gv.exports={readTransactionLog:x7,deleteTransactionLogsBefore:F7};async function*x7(e){let t=P7(e);if(t)throw Ma(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!pv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,Tv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=mv.checkSchemaTableExist(r,n);if(s)throw Ma(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=Sv.createNatsTableStreamName(r,n),o=await Ff.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 _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===Rg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(x7,"readTransactionLog");async function F7(e){let t=v7(e);if(t)throw Ma(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!pv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,Tv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=mv.checkSchemaTableExist(r,n);if(i)throw Ma(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=Sv.createNatsTableStreamName(r,n),{jsm:c}=await Ff.getNATSReferences(),u=await Ff.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=B7,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=H7):d=(await Ff.viewStream(o,parseInt(s),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(F7,"deleteTransactionLogsBefore")});var Av=T((GEe,Rv)=>{"use strict";var Ag=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};Rv.exports=Ag});var bv=T((VEe,Ov)=>{"use strict";var Og=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Ov.exports=Og});var Ng=T((YEe,yv)=>{"use strict";var Nv=Av(),q7=bv(),{HDB_ERROR_MSGS:G7}=wr(),bg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=G7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new Nv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new q7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Nv(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};yv.exports=bg});var $f=T((WEe,kv)=>{"use strict";var yg=on(),Gf=sn(),pn=Gd(),rl=Gi(),Ig=Ki(),k7=FS(),V7=xL(),nl=cn(),kf=QS(),wt=Y(),$7=XS(),Y7=sf(),K7=UT(),W7=af(),Q7=PT(),z7=vT(),J7=xT(),X7=qT(),wg=VT(),Us=J(),j7=vU(),Cg=QT(),Cv=bf(),mn=M(),Dv=vP(),Z7=ga(),Lv=Cu(),Mv=(Cf(),ee(Qu)),Uv=xr(),Jr=Tg(),eee=require("alasql"),Pv=qf(),vv=Pf(),Bv=Ng(),{handleHDBError:Tr,hdb_errors:Hv}=Z(),{HDB_ERROR_MSGS:Vt,HTTP_STATUS_CODES:el}=Hv,q=new Map,xv="delete",gi="insert",Ps="read",To="update",tl="describe",Iv=rl.describeSchema.name,wv=rl.describeTable.name,Fv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},tee="catchup",ree="handleGetJob",nee="handleGetJobsByStartDate",Vf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},see=[pn.createTable.name,pn.createAttribute.name,pn.dropTable.name,pn.dropAttribute.name],qv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},K=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};q.set(yg.insert.name,new K(!1,[gi]));q.set(yg.update.name,new K(!1,[To]));q.set(yg.upsert.name,new K(!1,[gi,To]));q.set(Gf.searchByConditions.name,new K(!1,[Ps]));q.set(Gf.searchByHash.name,new K(!1,[Ps]));q.set(Gf.searchByValue.name,new K(!1,[Ps]));q.set(Gf.search.name,new K(!1,[Ps]));q.set(pn.createSchema.name,new K(!0,[]));q.set(pn.createTable.name,new K(!0,[]));q.set(pn.createAttribute.name,new K(!1,[gi]));q.set(pn.dropSchema.name,new K(!0,[]));q.set(pn.dropTable.name,new K(!0,[]));q.set(pn.dropAttribute.name,new K(!0,[]));q.set(rl.describeSchema.name,new K(!1,[Ps]));q.set(rl.describeTable.name,new K(!1,[Ps]));q.set(Ig.deleteRecord.name,new K(!1,[xv]));q.set(nl.addUser.name,new K(!0,[]));q.set(nl.alterUser.name,new K(!0,[]));q.set(nl.dropUser.name,new K(!0,[]));q.set(nl.listUsersExternal.name,new K(!0,[]));q.set(kf.listRoles.name,new K(!0,[]));q.set(kf.addRole.name,new K(!0,[]));q.set(kf.alterRole.name,new K(!0,[]));q.set(kf.dropRole.name,new K(!0,[]));q.set($7.name,new K(!0,[]));q.set(Y7.name,new K(!0,[]));q.set(K7.name,new K(!0,[]));q.set(W7.name,new K(!0,[]));q.set(Q7.name,new K(!0,[]));q.set(z7.name,new K(!0,[]));q.set(wg.setRoutes.name,new K(!0,[]));q.set(wg.getRoutes.name,new K(!0,[]));q.set(wg.deleteRoutes.name,new K(!0,[]));q.set(Uv.setConfiguration.name,new K(!0,[]));q.set(J7.clusterStatus.name,new K(!0,[]));q.set(X7.name,new K(!0,[]));q.set(Cg.getFingerprint.name,new K(!0,[]));q.set(Cg.setLicense.name,new K(!0,[]));q.set(Ig.deleteFilesBefore.name,new K(!0,[]));q.set(Ig.deleteAuditLogsBefore.name,new K(!0,[]));q.set(Cv.restart.name,new K(!0,[]));q.set(Cv.restartService.name,new K(!0,[]));q.set(k7.name,new K(!0,[]));q.set(V7.name,new K(!0,[Ps]));q.set(Z7.systemInformation.name,new K(!0,[]));q.set(Uv.getConfiguration.name,new K(!0,[]));q.set(Pv.readTransactionLog.name,new K(!0,[]));q.set(Pv.deleteTransactionLogsBefore.name,new K(!0,[]));q.set(vv.installModules.name,new K(!0,[]));q.set(vv.auditModules.name,new K(!0,[]));q.set(Lv.createTokens.name,new K(!1,[]));q.set(Lv.refreshOperationToken.name,new K(!1,[]));q.set(Mv.login.name,new K(!1,[]));q.set(Mv.logout.name,new K(!1,[]));q.set(Jr.customFunctionsStatus.name,new K(!0,[]));q.set(Jr.getCustomFunctions.name,new K(!0,[]));q.set(Jr.getComponents.name,new K(!0,[]));q.set(Jr.getComponentFile.name,new K(!0,[]));q.set(Jr.setComponentFile.name,new K(!0,[]));q.set(Jr.dropComponent.name,new K(!0,[]));q.set(Jr.getCustomFunction.name,new K(!0,[]));q.set(Jr.setCustomFunction.name,new K(!0,[]));q.set(Jr.dropCustomFunction.name,new K(!0,[]));q.set(Jr.addComponent.name,new K(!0,[]));q.set(Jr.dropCustomFunctionProject.name,new K(!0,[]));q.set(Jr.packageComponent.name,new K(!0,[]));q.set(Jr.deployComponent.name,new K(!0,[]));q.set(Cg.getRegistrationInfo.name,new K(!1,[]));q.set(nl.userInfo.name,new K(!1,[]));q.set(rl.describeAll.name,new K(!1,[]));q.set(ree,new K(!1,[]));q.set(nee,new K(!0,[]));q.set(tee,new K(!0,[]));q.set(Vf.CSV_DATA_LOAD,new K(!1,[gi,To]));q.set(Vf.CSV_URL_LOAD,new K(!1,[gi,To]));q.set(Vf.CSV_FILE_LOAD,new K(!1,[gi,To]));q.set(Vf.IMPORT_FROM_S3,new K(!1,[gi,To]));q.set(qv.EXPORT_TO_S3,new K(!0,[]));q.set(qv.EXPORT_LOCAL,new K(!0,[]));q.set(mn.VALID_SQL_OPS_ENUM.DELETE,new K(!1,[xv]));q.set(mn.VALID_SQL_OPS_ENUM.SELECT,new K(!1,[Ps]));q.set(mn.VALID_SQL_OPS_ENUM.INSERT,new K(!1,[gi]));q.set(mn.VALID_SQL_OPS_ENUM.UPDATE,new K(!1,[To]));kv.exports={verifyPerms:oee,verifyPermsAst:iee,verifyBulkLoadAttributePerms:cee};function iee(e,t,r){if(Us.isEmptyOrZeroLength(e))throw wt.info("verify_perms_ast has an empty user parameter"),Tr(new Error);if(Us.isEmptyOrZeroLength(t))throw wt.info("verify_perms_ast has an empty user parameter"),Tr(new Error);if(Us.isEmptyOrZeroLength(r))throw wt.info("verify_perms_ast has a null operation parameter"),Tr(new Error);try{let n=new Bv,s=new j7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw wt.info("No schemas defined in verifyPermsAst(), will not continue."),Tr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Fv[r])throw Tr(new Error,Vt.DROP_SYSTEM,el.FORBIDDEN);if(c&&!u)return null;let _=Dv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof eee.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=s.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=Gv(t,r,o,n);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=s.getAttributesBySchemaTableName(f,d[E]),S=Lg(t.role.permission,f,d[E]);Dg(h,S,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw Tr(n)}}a(iee,"verifyPermsAst");function oee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw wt.info("null required parameter in verifyPerms"),Tr(new Error,Vt.DEFAULT_INVALID_REQUEST,el.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new Bv;if(Us.isEmptyOrZeroLength(e.hdb_user.role)||Us.isEmptyOrZeroLength(e.hdb_user.role.permission))return wt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Vt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(mn.SYSTEM_SCHEMA_NAME)||s===mn.SYSTEM_SCHEMA_NAME;if(l&&Fv[r])throw Tr(new Error,Vt.DROP_SYSTEM,el.FORBIDDEN);if(u&&!l||_===!0&&(r===pn.createSchema.name||r===pn.dropSchema.name))return null;if(see.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=Dv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Iv||r===wv){if(s===mn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Vt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Iv&&(!d[s]||!d[s][tl]))return c.handleInvalidItem(Vt.SCHEMA_NOT_FOUND(s));if(r===wv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][tl]))return c.handleInvalidItem(Vt.TABLE_NOT_FOUND(s,i))}}let f=Gv(e.hdb_user,r,o,c,n);if(f)return f;if(q.get(r)&&q.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&mn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let S=[],p=d[s].tables[i];p[mn.PERMS_CRUD_ENUM.READ]&&(p.attribute_permissions.length>0?p.attribute_permissions.filter(A=>A[mn.PERMS_CRUD_ENUM.READ]).forEach(A=>{S.push(A.attribute_name)}):S=global.hdb_schema[s][i].attributes.map(g=>g.attribute),e.get_attributes=S)}let E=aee(e),h=Lg(e.hdb_user.role.permission,s,i);return Dg(E,h,r,i,s,c,n),c.getPermsResponse()}a(oee,"verifyPerms");function Gv(e,t,r,n,s){if(Us.arrayHasEmptyValues([e,t,r]))throw wt.info("hasPermissions has an invalid parameter"),Tr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||q.get(t).requires_su))return null;if(!q.get(t))throw wt.info(`operation ${t} not found.`),Tr(new Error,Vt.OP_NOT_FOUND(t),el.BAD_REQUEST);if(q.get(t)&&q.get(t).requires_su)return wt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Vt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][tl]===!1){n.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[tl]===!1)n.addInvalidItem(Vt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=q.get(t).perms;!Us.isEmpty(s)&&E.includes(s)&&(E=[s]);for(let h=0;h<E.length;h++){let S=E[h],p=d[S];(p==null||p===!1)&&(wt.info(`Required ${S} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(S))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=Vt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw wt.error(E),wt.error(f),Tr(Hv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Gv,"hasPermissions");function Dg(e,t,r,n,s,i,o){if(!e||!t)throw wt.info("no attributes specified in checkAttributePerms."),Tr(new Error);let c=q.get(r).perms;if(!c||c==="")throw wt.info(`no permissions found for ${r} in checkAttributePerms().`),Tr(new Error);if(Us.isEmptyOrZeroLength(t))return wt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[tl]===!1){i.addInvalidItem(Vt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(mn.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Ps)throw Tr(new Error,Vt.SYSTEM_TIMESTAMP_PERMS_ERR,el.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(Vt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Dg,"checkAttributePerms");function aee(e){let t=new Set;try{if(e.action)return t;if(e.operation===mn.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 n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){wt.info(r)}return t}a(aee,"getRecordAttributes");function Lg(e,t,r){let n=new Map;if(Us.isEmpty(e))return wt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{wt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Lg,"getAttributePermissions");function cee(e,t,r,n,s,i,o){let c=new Set(i),u=Lg(e,n,s);Dg(c,u,t,s,n,o,r)}a(cee,"verifyBulkLoadAttributePerms")});var Kf=T((zEe,Wv)=>{"use strict";Wv.exports={evaluateSQL:Ree,processAST:Kv,convertSQLToAST:Yv,checkASTPermissions:$v};var uee=on(),Vv=require("util"),lee=Vv.callbackify(uee.insert),_ee=sn().search,dee=zD().update,fee=Vv.callbackify(dee),Eee=XD().convertDelete,Ri=require("alasql"),hee=$f(),Yf=Y(),mee=V_(),pee=J(),sl=M(),{hdb_errors:See,handleHDBError:Mg}=Z(),{HTTP_STATUS_CODES:Ug}=See;mee(Ri);var Tee=403,gee="There was a problem performing this insert. Please check the logs and try again.",Pg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Ree(e,t){let r=e.parsed_sql_object;if(!r){r=Yv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ri.yy.Insert?n=s.into.databaseid:s instanceof Ri.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ri.yy.Update||s instanceof Ri.yy.Delete?n=s.table.databaseid:Yf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ri.yy.Select)&&pee.isEmptyOrZeroLength(n))return t("No schema specified",null)}Kv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Ree,"evaluateSQL");function $v(e,t){let r;try{r=hee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a($v,"checkASTPermissions");function Yv(e){let t=new Pg;if(!e)throw Mg(new Error,"The 'sql' parameter is missing from the request body",Ug.BAD_REQUEST);try{let r=e.trim(),n=Ri.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
17
+ `);throw n[1]?Mg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ug.BAD_REQUEST):Mg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ug.BAD_REQUEST)}return t}a(Yv,"convertSQLToAST");function Kv(e,t,r){try{let n=Aee;if(!e.bypass_auth&&!t.permissions_checked){let i=$v(e,t);if(i&&i.length>0)return r(Tee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case sl.VALID_SQL_OPS_ENUM.SELECT:n=_ee,s=t.ast.statements[0];break;case sl.VALID_SQL_OPS_ENUM.INSERT:n=Oee;break;case sl.VALID_SQL_OPS_ENUM.UPDATE:n=fee;break;case sl.VALID_SQL_OPS_ENUM.DELETE:n=Eee;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(Kv,"processAST");function Aee(e,t){Yf.info(e),t("unknown sql statement")}a(Aee,"nullFunction");function Oee({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=bee(i,e.values)}catch(o){return r(o)}lee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Yf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Oee,"convertInsert");function bee(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 n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ri.compile(`SELECT ${s.toString()} AS [${sl.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Yf.error(r),new Error(gee)}}a(bee,"createDataObjects")});var vg=T((XEe,zv)=>{"use strict";var{S3:Nee,GetObjectCommand:yee}=require("@aws-sdk/client-s3");zv.exports={getFileStreamFromS3:Iee,getS3AuthObj:Qv};async function Iee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Qv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new yee(r))).Body}a(Iee,"getFileStreamFromS3");function Qv(e,t,r){return new Nee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Qv,"getS3AuthObj")});var Wf=T((ZEe,s0)=>{"use strict";var Hg=sn(),wee=Kf(),Cee=vg(),{AsyncParser:Dee,Transform:Lee}=require("json2csv"),ol=require("stream"),Xr=J(),Bg=require("fs-extra"),Mee=require("path"),Sn=Y(),{promisify:jv}=require("util"),il=J(),{handleHDBError:Tt,hdb_errors:Uee}=Z(),{HDB_ERROR_MSGS:gr,HTTP_STATUS_CODES:gt}=Uee,{streamAsJSON:Pee}=(bS(),ee($D)),{Upload:vee}=require("@aws-sdk/lib-storage"),Jv=["search_by_value","search_by_hash","sql","search_by_conditions"],Xv=["json","csv"],Zv="json",e0="csv",Bee="Successfully exported JSON locally.",Hee="Successfully exported CSV locally.",xee=1e3,Fee=Hg.searchByHash,qee=Hg.searchByValue,Gee=jv(wee.evaluateSQL),kee=jv(ol.finished);s0.exports={export_to_s3:Kee,export_local:Vee,toCsvStream:t0};async function Vee(e){Sn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=r0(e);if(!Xr.isEmpty(t))throw Sn.error(t),Tt(new Error,t,gt.BAD_REQUEST,void 0,void 0,!0);if(Xr.isEmpty(e.path))throw Sn.error(gr.MISSING_VALUE("path")),Tt(new Error,gr.MISSING_VALUE("path"),gt.BAD_REQUEST,void 0,void 0,!0);let r=(Xr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Mee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Xr.buildFolderPath(e.path,r);await $ee(e.path);let s=await n0(e);return await Yee(n,e.format,s)}a(Vee,"export_local");async function $ee(e){if(Sn.trace("in confirmPath"),Xr.isEmptyOrZeroLength(e))throw Tt(new Error,`Invalid path: ${e}`,gt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Bg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,Sn.error(n),Tt(new Error,n,gt.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 Sn.error(r),Tt(new Error,r,gt.BAD_REQUEST,void 0,void 0,!0)}return!0}a($ee,"confirmPath");async function Yee(e,t,r){if(Sn.trace("in saveToLocal"),il.isEmptyOrZeroLength(e))throw Tt(new Error,gr.INVALID_VALUE("file_path"),gt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmptyOrZeroLength(t))throw Tt(new Error,gr.INVALID_VALUE("Source format"),gt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmpty(r))throw Tt(new Error,gr.NOT_FOUND("Data"),gt.BAD_REQUEST,void 0,void 0,!0);if(t===Zv){let n=Bg.createWriteStream(e);return Pee(r).pipe(n),await kee(n),{message:Bee,path:e}}else if(t===e0){let n=Bg.createWriteStream(e),s=ol.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Dee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Hee,path:e}}throw Tt(new Error,gr.INVALID_VALUE("format"),gt.BAD_REQUEST)}a(Yee,"saveToLocal");async function Kee(e){if(!e.s3||Object.keys(e.s3).length===0)throw Tt(new Error,gr.MISSING_VALUE("S3 object"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Tt(new Error,gr.MISSING_VALUE("aws_access_key_id"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Tt(new Error,gr.MISSING_VALUE("aws_secret_access_key"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.bucket))throw Tt(new Error,gr.MISSING_VALUE("bucket"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.key))throw Tt(new Error,gr.MISSING_VALUE("key"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.region))throw Tt(new Error,gr.MISSING_VALUE("region"),gt.BAD_REQUEST);let t=r0(e);if(!Xr.isEmpty(t))throw Tt(new Error,t,gt.BAD_REQUEST);Sn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await n0(e)}catch(u){throw Sn.error(u),u}let n,s=await Cee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new ol.PassThrough;if(e.format===e0){i=e.s3.key+".csv";let u=t0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===Zv){i=e.s3.key+".json";let u=new ol.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%xee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Tt(new Error,gr.INVALID_VALUE("format"),gt.BAD_REQUEST);return new vee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Kee,"export_to_s3");function t0(e,t){let r=ol.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new Lee(n,s);return r.pipe(i)}a(t0,"toCsvStream");function r0(e){if(Sn.trace("in exportCoreValidation"),Xr.isEmpty(e.format))return"format missing";if(Xv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${Xv.join(", ")}`;let t=e.search_operation.operation;if(Xr.isEmpty(t))return"search_operation.operation missing";if(Jv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${Jv.join(", ")}`}a(r0,"exportCoreValidation");async function n0(e){Sn.trace("in getRecords");let t,r;if(il.isEmpty(e.search_operation)||il.isEmptyOrZeroLength(e.search_operation.operation))throw Tt(new Error,gr.INVALID_VALUE("Search operation"),gt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=qee;break;case"search_by_hash":t=Fee;break;case"search_by_conditions":t=Hg.searchByConditions;break;case"sql":t=Gee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Sn.error(r),Tt(new Error,r,gt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(n0,"getRecords")});var d0={};qe(d0,{contentTypes:()=>kg,findBestSerializer:()=>zf,getDeserializer:()=>Ro,registerContentHandlers:()=>Vg,serialize:()=>Jf,serializeMessage:()=>Ti});function Wee(e){try{return e?.[0]===123?Gg(e):e}catch{return e}}function Vg(e){e.register(zee,{serializers:[{regex:/^application\/json$/,serializer:mu},{regex:/^application\/cbor$/,serializer:function(t){return new go.EncoderStream(cl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Qf.Readable.from((0,os.encodeIter)(t,cl)):(0,os.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,os.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,go.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function zf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let S=h.indexOf("=");f[h.substring(0,S)]=h.substring(S+1)}d=+f.q;let E=xt.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(xt.keys()).join(", "))}};n=xt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Jf(e,t,r){let n=o0&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=zf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,vs.createBrotliCompress)({params:{[vs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?vs.constants.BROTLI_MODE_TEXT:vs.constants.BROTLI_MODE_GENERIC,[vs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>o0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,vs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function Ti(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return al(e);let r=t.serialize;if(r)return r(e);let n=zf(t);return r=t.serialize=n.serializer.serialize,r(e)}function Jee(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function Ro(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=xt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=xt.get(e)?.deserialize||a0(e,n);return o=>Jee(o).then(i)}return e&&xt.get(e)?.deserialize||a0(e,n)}function a0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Gg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Xee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var xg,os,go,vs,Qf,c0,Fg,qg,u0,l0,al,Gg,cl,xt,kg,i0,_0,Qee,zee,o0,Ia=Re(()=>{bS();xg=B(Wf()),os=require("msgpackr"),go=require("cbor-x"),vs=require("zlib"),Qf=require("stream");Zt();c0=require("../index"),Fg=B(j()),qg=B(M()),u0=B(require("yaml")),l0=Fg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,al=l0?so:JSON.stringify,Gg=l0?OS:JSON.parse,cl={useRecords:!1,useToJSON:!0},xt=new Map,kg=xt;ut.contentTypes=kg;(0,c0._assignPackageExport)("contentTypes",kg);xt.set("application/json",{serializeStream:mu,serialize:al,deserialize:Gg,q:.8});i0=new go.Encoder(cl);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new go.EncoderStream(cl).end(e)},serialize:i0.encode,deserialize:i0.decode,q:1});xt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Qf.Readable.from((0,os.encodeIter)(e,cl)):(0,os.pack)(e)},serialize:os.pack,deserialize:os.unpack,q:.9});xt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(e,e?.getColumns?.())},q:.1});xt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});xt.set("text/yaml",{serialize(e){return u0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});xt.set("text/event-stream",{serializeStream:function(e){return Qf.Readable.from(Xee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
18
+ `),e.data){let r=e.data;typeof r=="object"&&(r=al(r)),t+="data: "+r+`
19
19
  `}return e.id&&(t+="id: "+e.id+`
20
20
  `),e.retry&&(t+="retry: "+e.retry+`
21
21
  `),t+`
22
- `}else return typeof e=="object"?`data: ${_l(e)}
22
+ `}else return typeof e=="object"?`data: ${al(e)}
23
23
 
24
24
  `:`data: ${e}
25
25
 
26
- `},compressible:!1,q:.8});$t.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()}});jv={type:"application/json",serializeStream:gu,serialize:_l,deserialize:Tee,q:.8};$t.set("*/*",jv);$t.set("",jv);a(Tee,"tryJSONParse");a(Dg,"registerContentHandlers");gee=require("fastify-plugin"),Ree=gee(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=$f(s.raw);n.type(c),n.serializer(o.serializeStream||o.serialize)}),r()},{name:"content-type-negotiation"});a($f,"findBestSerializer");Qv=Ig.default.get(wg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Yf,"serialize");a(Ai,"serializeMessage");a(Aee,"streamToBuffer");a(Ro,"getDeserializer");a(zv,"deserializerUnknownType");a(Oee,"transformIterable")});var Kf={};$e(Kf,{start:()=>yee});async function Nee(e,t){let r=e.headers.asObject,s=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&e_(e);let n=new Ri;try{e.responseHeaders=n;let i=e.url.slice(1),o=Ug.getMatch(i);if(!o)return t(e);e.handlerPath=o.path;let c={url:o.relativeURL,async:!0},u=o.Resource,_=r["cache-control"];if(_){_=_.toLowerCase();let p=_.match(/max-age=(\d+)/)?.[1];p&&(e.expiresAt=p*1e3+Date.now()),_.includes("only-if-cached")&&(e.onlyIfCached=!0),_.includes("no-cache")&&(e.noCache=!0),_.includes("no-store")&&(e.noCacheStore=!0),_.includes("stale-if-error")&&(e.staleIfError=!0),_.includes("must-revalidate")&&(e.mustRevalidate=!0)}let l=await Qe(e,()=>{if(s==="POST"||s==="PUT"||s==="PATCH"||s==="QUERY")try{e.data=Ro(r["content-type"],!0)(e.body)}catch(p){throw new El.ClientError(p,400)}switch(e.authorize=!0,s){case"GET":case"HEAD":return u.get(c,e);case"POST":return u.post(c,e.data,e);case"PUT":return u.put(c,e.data,e);case"DELETE":return u.delete(c,e);case"PATCH":return u.patch(c,e.data,e);case"OPTIONS":n.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return u.connect(c,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return u.query(c,e.data,e);case"COPY":return u.copy(c,r.destination,e);case"MOVE":return u.move(c,r.destination,e);case"BREW":throw new El.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new El.ServerError(`Method ${s} is not recognized`,501)}}),d=200,f;if(l==null)d=s==="GET"||s==="HEAD"?404:204,Mg.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(f=e.lastModified){bee[0]=f;let p=String.fromCharCode(34,(Yt[0]&63)+62,(Yt[0]>>6)+(Yt[1]<<2&63)+62,(Yt[1]>>4)+(Yt[2]<<4&63)+62,(Yt[2]>>2)+62,(Yt[3]&63)+62,(Yt[3]>>6)+(Yt[4]<<2&63)+62,(Yt[4]>>4)+(Yt[5]<<4&63)+62,(Yt[5]>>2)+62,(Yt[6]&63)+62,(Yt[6]>>6)+(Yt[7]<<2&63)+62,34),S=r["if-none-match"];S&&p==S?(l?.onDone&&l.onDone(),d=304,l=void 0):n.setIfNone("ETag",p),Mg.lastModified&&n.setIfNone("Last-Modified",new Date(f).toUTCString())}e.createdResource&&(d=201),e.newLocation&&n.setIfNone("Location",e.newLocation);let E={status:d,headers:n,body:void 0},h=l?.wasLoadedFromSource?.();return h!==void 0&&(E.wasCacheMiss=h,!h&&f&&n.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||f))/1e3))),l!==void 0&&(E.body=Yf(l,e,E),s==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?Ao.warn(i):Ao.info(i):Ao.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),n.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:n,body:void 0};return o.body=Yf(i.contentType?i:i.toString(),e,o),o}}function yee(e){Mg=e,!e0&&(e0=!0,Ug=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Nee(t,r)}),e.server.ws(async(t,r,s)=>{fl++;let n=new ys;t0||(t0=!0,nu(l=>{fl>0&&l.push({metric:"ws-connections",connections:fl,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ao.warn(l)});let o;t.on("message",a(function(d){o||(o=Ro(r.headers.asObject["content-type"]));let f=o(d);n.push(f)},"message"));let c;t.on("close",()=>{fl--,_s(!i,"connection","ws","disconnect"),n.emit("close"),c&&c.return()}),await s;let u=r.url.slice(1),_=Ug.getMatch(u);if(_s(!!_,"connection","ws","connect"),!_)t.send(Ai(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,qr(h=>({count:h.count,total:fl}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Qe(r,()=>d.connect(l,n,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ai(E.value,r);t.send(h),qr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var Ao,El,Yt,bee,Mg,e0,Ug,t0,fl,r0=ge(()=>{Na();Cn();Ao=U(q()),El=U(Z());t_();uc();Ui();gf();Yt=new Uint8Array(8),bee=new Float64Array(Yt.buffer,0,1),Mg={};a(Nee,"http");fl=0;a(yee,"start")});var Pg=T((CEe,s0)=>{var{recordAction:Wf,recordActionBinary:Iee}=(Cn(),ee(iu)),wee=require("fastify-plugin"),Cee=200;s0.exports=wee(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.request.routeOptions,_,l,d;u.config?.isOperation?(_=s.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Wf(o,"duration",_,d,l),Iee(n.raw.statusCode<400,"success",_,d,l);let f=Cee;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Wf(performance.now()-c,"transfer",_,d,l),Wf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Wf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);n.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var xg=T((LEe,c0)=>{var jf=require("clone"),Zf=et(),Lee=z(),Jf=w(),Dee=q(),Qf=require("fs"),vg=require("joi"),{string:Xf}=vg.types(),{hdb_errors:Mee,handleHDBError:hl}=Z(),{HDB_ERROR_MSGS:Uee,HTTP_STATUS_CODES:zf}=Mee,{common_validators:Ma}=Js(),n0=1e9,i0=" is required",Pee=["insert","update","upsert"],Bg={database:{presence:!1,format:Ma.schema_format,length:Ma.schema_length},schema:{presence:!1,format:Ma.schema_format,length:Ma.schema_length},table:{presence:!0,format:Ma.schema_format,length:Ma.schema_length},action:{inclusion:{within:Pee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},vee={schema:Xf.required(),table:Xf.required(),action:Xf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Bee,AWS_SECRET:Hee,AWS_BUCKET:xee,AWS_FILE_KEY:Fee,REGION:Gee}=Jf.S3_BUCKET_AUTH_KEYS,qee={s3:{presence:!0},[`s3.${Bee}`]:{presence:!0,type:"String"},[`s3.${Hee}`]:{presence:!0,type:"String"},[`s3.${xee}`]:{presence:!0,type:"String"},[`s3.${Fee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Gee}`]:{presence:!0,type:"String"}},o0=jf(Bg);o0.data.presence={message:i0};var a0=jf(Bg);a0.file_path.presence={message:i0};var kee=Object.assign(jf(Bg),qee),Hg=jf(vee);Hg.csv_url=Xf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Hg.passthrough_headers=vg.object();function Vee(e){let t=Zf.validateObject(e,o0);return eE(e,t)}a(Vee,"dataObject");function $ee(e){let t=Zf.validateBySchema(e,vg.object(Hg));return eE(e,t)}a($ee,"urlObject");function Yee(e){let t=Zf.validateObject(e,a0);return eE(e,t)}a(Yee,"fileObject");function Kee(e){let t=Zf.validateObject(e,kee);return eE(e,t)}a(Kee,"s3FileObject");function eE(e,t){if(!t){let r=Lee.checkGlobalSchemaTable(e.schema,e.table);if(r)return hl(new Error,r,zf.BAD_REQUEST);if(e.operation===Jf.OPERATIONS_ENUM.CSV_FILE_LOAD){try{Qf.accessSync(e.file_path,Qf.constants.R_OK|Qf.constants.F_OK)}catch(s){return s.code===Jf.NODE_ERROR_CODES.ENOENT?hl(s,`No such file or directory ${s.path}`,zf.BAD_REQUEST):s.code===Jf.NODE_ERROR_CODES.EACCES?hl(s,`Permission denied ${s.path}`,zf.BAD_REQUEST):hl(s)}try{let s=Qf.statSync(e.file_path).size;if(s>n0)return hl(new Error,Uee.MAX_FILE_SIZE_ERR(s,n0),zf.BAD_REQUEST)}catch(s){Dee.error(s),console.error(s)}}}return t}a(eE,"postValidateChecks");c0.exports={dataObject:Vee,urlObject:$ee,fileObject:Yee,s3FileObject:Kee}});var Fg=T((MEe,u0)=>{"use strict";var ml=q(),tE=w();async function Wee(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===tE.OPERATIONS_ENUM.INSERT||t.operation===tE.OPERATIONS_ENUM.UPDATE||t.operation===tE.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===tE.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ml.info(i.message),i):i.http_resp_msg?(ml.error(`Error calling operation: ${e.name}`),ml.error(i.http_resp_msg),i):(ml.error(`Error calling operation: ${e.name}`),ml.error(i),i)}}a(Wee,"callOperationFunctionAsAwait");u0.exports={callOperationFunctionAsAwait:Wee}});var _0=T((PEe,l0)=>{"use strict";var Gg=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}},qg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};l0.exports={BulkLoadFileObject:Gg,BulkLoadDataObject:qg}});var f0=T((BEe,d0)=>{"use strict";var kg=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};d0.exports=kg});var Qg=T((kEe,L0)=>{"use strict";var rE=cs(),nE=xg(),Qee=require("needle"),qs=w(),xEe=tt(),Ua=z(),{handleHDBError:ot,hdb_errors:A0}=Z(),{HTTP_STATUS_CODES:Kt,HDB_ERROR_MSGS:Ct,CHECK_LOGS_WRAPPER:bo}=A0,Pa=q(),Vg=require("papaparse");Ua.promisifyPapaParse();var ks=require("fs-extra"),zee=require("path"),{chain:E0}=require("stream-chain"),h0=require("stream-json/streamers/StreamArray"),m0=require("stream-json/utils/Batch"),p0=require("stream-chain/utils/comp"),{finished:S0}=require("stream"),Jee=j(),O0=Fg(),Xee=Og(),{BulkLoadFileObject:Yg,BulkLoadDataObject:jee}=_0(),Kg=fg(),{verifyBulkLoadAttributePerms:b0}=Ff(),FEe=f0(),GEe=yt(),qEe=wn(),{databases:Zee}=(pe(),ee(Ge)),{coerceType:ete}=(hd(),ee(Kp)),T0="No records parsed from csv file.",Oo=`${Jee.get("HDB_ROOT")}/tmp`,{schema_regex:tte}=Js(),g0=1024*1024*2,R0=5e3,rte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};L0.exports={csvDataLoad:ste,csvURLLoad:nte,csvFileLoad:ite,importFromS3:ote};async function ste(e,t){let r=nE.dataObject(e);if(r)throw ot(r,r.message,Kt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=I0(e.schema,e.table),i=Vg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:$g.bind(null,n),dynamicTyping:!1}),o=new Kg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&b0(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 ot(new Error,c,Kt.BAD_REQUEST,void 0,void 0,!0);let u=new jee(e.action,e.schema,e.table,i.data);return s=await O0.callOperationFunctionAsAwait(w0,u,null),s.message===T0?T0:C0(s.records,s.number_written)}catch(n){throw No(n)}}a(ste,"csvDataLoad");async function nte(e){let t=nE.urlObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${Oo}/${r}`;try{await ate(e,r)}catch(n){throw Pa.error(Ct.DOWNLOAD_FILE_ERR(r)+" - "+n),ot(n,bo(Ct.DOWNLOAD_FILE_ERR(r)))}try{let n=new Yg(this.job_operation_function.name,e.action,e.schema,e.table,s,qs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Wg(n);return await sE(s),i}catch(n){throw await sE(s),No(n)}}a(nte,"csvURLLoad");async function ite(e){let t=nE.fileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=new Yg(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,qs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Wg(r)}catch(s){throw No(s)}}a(ite,"csvFileLoad");async function ote(e){let t=nE.s3FileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=zee.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${Oo}/${n}`;let i=new Yg(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await cte(n,e);let o=await Wg(i);return await sE(r),o}catch(s){throw await sE(r),No(s)}}a(ote,"importFromS3");async function ate(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Qee("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 ot(s,n,s.statusCode,qs.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}lte(r,e.csv_url),await ute(t,r.raw)}a(ate,"downloadCSVFile");async function cte(e,t){try{let r=`${Oo}/${e}`;await ks.mkdirp(Oo),await ks.writeFile(`${Oo}/${e}`,"",{flag:"a+"});let s=await ks.createWriteStream(r),n=await Xee.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(){Pa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Pa.error(Ct.S3_DOWNLOAD_ERR+" - "+r),ot(r,bo(Ct.S3_DOWNLOAD_ERR))}}a(cte,"downloadFileFromS3");async function ute(e,t){try{await ks.mkdirp(Oo),await ks.writeFile(`${Oo}/${e}`,t)}catch(r){throw Pa.error(Ct.WRITE_TEMP_FILE_ERR),ot(r,bo(Ct.DEFAULT_BULK_LOAD_ERR))}}a(ute,"writeFileToTempFolder");async function sE(e){if(e)try{await ks.access(e),await ks.unlink(e)}catch{Pa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(sE,"deleteTempFile");function lte(e,t){if(e.statusCode!==A0.HTTP_STATUS_CODES.OK)throw ot(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Kt.BAD_REQUEST);if(!rte[e.headers["content-type"]])throw ot(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Kt.BAD_REQUEST);if(!e.raw)throw ot(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Kt.BAD_REQUEST)}a(lte,"validateURLResponse");async function Wg(e){try{let t;switch(e.file_type){case qs.VALID_S3_FILE_TYPES.CSV:t=await _te(e);break;case qs.VALID_S3_FILE_TYPES.JSON:t=await dte(e);break;default:throw ot(new Error,Ct.DEFAULT_BULK_LOAD_ERR,Kt.BAD_REQUEST,qs.LOG_LEVELS.ERROR,Ct.INVALID_FILE_EXT_ERR(e))}return C0(t.records,t.number_written)}catch(t){throw No(t)}}a(Wg,"fileLoad");async function N0(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 rE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&b0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=ot(c);r(u)}}a(N0,"validateChunk");async function y0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;Ua.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!Ua.isEmpty(c)&&!Ua.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await O0.callOperationFunctionAsAwait(w0,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=ot(c,bo(Ct.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,Ct.INSERT_CSV_ERR+" - "+c);r(u)}}a(y0,"insertChunk");async function _te(e){let t={records:0,number_written:0},r=I0(e.schema,e.table);try{let s=new Kg,n=ks.createReadStream(e.file_path,{highWaterMark:g0});n.setEncoding("utf8"),await Vg.parsePromise(n,N0.bind(null,e,s),$g.bind(null,r));let i=s.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);return n=ks.createReadStream(e.file_path,{highWaterMark:g0}),n.setEncoding("utf8"),await Vg.parsePromise(n,y0.bind(null,e,t),$g.bind(null,r)),n.destroy(),t}catch(s){throw ot(s,bo(Ct.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,Ct.PAPA_PARSE_ERR+s)}}a(_te,"callPapaParse");function I0(e,t){let r=Zee[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>ete(i,n));return s}a(I0,"createTransformMap");function $g(e,t,r){let s=e.get(r);return s?s(t):Ua.autoCast(t)}a($g,"typeFunction");async function dte(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Kg,n=E0([ks.createReadStream(e.file_path,{encoding:"utf-8"}),h0.withParser(),c=>c.value,new m0({batchSize:R0}),p0(async c=>{await N0(e,s,r,c)})]);await new Promise((c,u)=>{S0(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);let o=E0([ks.createReadStream(e.file_path,{encoding:"utf-8"}),h0.withParser(),c=>c.value,new m0({batchSize:R0}),p0(async c=>{await y0(e,t,r,c)})]);return await new Promise((c,u)=>{S0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw ot(s,bo(Ct.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,Ct.INSERT_JSON_ERR+s)}}a(dte,"insertJson");async function w0(e){let t={};try{e.data&&e.data.length>0&&fte(e.data[0])?t=await Ete(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Pa.info(t.message))}catch(r){throw No(r)}return t}a(w0,"callBulkFileLoad");function fte(e){let t=Object.keys(e);for(let r of t)if(!tte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(fte,"validateColumnNames");async function Ete(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=rE.insert;break;case"update":i=rE.update;break;case"upsert":i=rE.upsert;break;default:throw ot(new Error,Ct.INVALID_ACTION_PARAM_ERR(s),Kt.BAD_REQUEST,qs.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 l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Ua.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw No(o)}}a(Ete,"bulkFileLoad");function C0(e,t){return`successfully loaded ${t} of ${e} records`}a(C0,"buildResponseMsg");function No(e){return ot(e,bo(Ct.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,Ct.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(No,"buildTopLevelErrMsg")});var M0=T(($Ee,D0)=>{"use strict";var zg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};D0.exports=zg});var v0=T((KEe,P0)=>{"use strict";var hte=w(),U0=require("moment"),mte=require("uuid").v4,Jg=class{static{a(this,"JobObject")}constructor(){this.id=mte(),this.type=void 0,this.start_datetime=U0().valueOf(),this.created_datetime=U0().valueOf(),this.end_datetime=void 0,this.status=hte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};P0.exports=Jg});var Xg=T((QEe,q0)=>{"use strict";var pte=require("uuid").v4,x0=cs(),F0=as(),Ste=js(),Tte=Xo(),gte=M0(),at=w(),Rte=v0(),Ate=qS(),As=q(),Ote=Lc(),va=z(),{promisify:bte}=require("util"),yo=require("moment"),Nte=qf(),iE=xg(),B0=up(),{deleteTransactionLogsBeforeValidator:yte}=cg(),{handleHDBError:Ite,hdb_errors:wte}=Z(),{HTTP_STATUS_CODES:Cte}=wte,H0=F0.searchByValue,Lte=F0.searchByHash,Dte=x0.insert,Mte=bte(Nte.evaluateSQL),Ute=x0.update;q0.exports={addJob:Bte,updateJob:xte,handleGetJob:Pte,handleGetJobsByStartDate:vte,getJobById:G0};async function Pte(e){try{let t=await G0(e.id);return va.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 As.error("There was an error getting job",t),new Error(r)}}a(Pte,"handleGetJob");async function vte(e){try{let t=await Hte(e);if(As.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=yo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=yo(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 As.error(r),new Error(r)}}a(vte,"handleGetJobsByStartDate");async function Bte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||va.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return As.info(l),t.error=l,t}if(!at.JOB_TYPE_ENUM[e.operation])return As.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case at.OPERATIONS_ENUM.CSV_FILE_LOAD:s=iE.fileObject(e);break;case at.OPERATIONS_ENUM.CSV_URL_LOAD:s=iE.urlObject(e);break;case at.OPERATIONS_ENUM.CSV_DATA_LOAD:s=iE.dataObject(e);break;case at.OPERATIONS_ENUM.IMPORT_FROM_S3:s=iE.s3FileObject(e);break;case at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=B0(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=B0(e,"timestamp");break;case at.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=yte(e);break;default:break}if(s)throw Ite(s,s.message,Cte.BAD_REQUEST,void 0,void 0,!0);let n=new Rte;n.type=e.operation===at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new Ste(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await H0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return As.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=pte();try{o=await H0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return As.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return As.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new Ote(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await Dte(u)}catch(l){return As.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,As.trace(l)}return t}a(Bte,"addJob");async function Hte(e){let t=yo(e.from_date,yo.ISO_8601),r=yo(e.to_date,yo.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 gte(s,e.hdb_user);try{return await Mte(n)}catch(i){throw As.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(Hte,"getJobsInDateRange");async function G0(e){if(va.isEmptyOrZeroLength(e))return va.errorizeMessage("Invalid job ID specified.");let t=new Tte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Lte(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return As.error(s),va.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(G0,"getJobById");async function xte(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(va.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===at.JOB_STATUS_ENUM.COMPLETE||e.status===at.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=yo().valueOf());let t=new Ate(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Ute(t),r}a(xte,"updateJob")});var W0=T((JEe,K0)=>{"use strict";var k0=z(),Or=w(),Fte=require("moment"),oE=Qg(),aE=q(),V0=Xg(),$0=kf(),Y0=Qi(),Gte=Ze(),qte=vf(),jg=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function kte(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(k0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(k0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Or.JOB_TYPE_ENUM.csv_file_load:await Gn(e,oE.csvFileLoad);break;case Or.JOB_TYPE_ENUM.csv_url_load:await Gn(e,oE.csvURLLoad);break;case Or.JOB_TYPE_ENUM.csv_data_load:await Gn(e,oE.csvDataLoad);break;case Or.JOB_TYPE_ENUM.import_from_s3:await Gn(e,oE.importFromS3);break;case Or.JOB_TYPE_ENUM.empty_trash:break;case Or.JOB_TYPE_ENUM.export_local:await Gn(e,$0.export_local);break;case Or.JOB_TYPE_ENUM.export_to_s3:await Gn(e,$0.export_to_s3);break;case Or.JOB_TYPE_ENUM.delete_files_before:case Or.JOB_TYPE_ENUM.delete_records_before:await Gn(e,Y0.deleteFilesBefore);break;case Or.JOB_TYPE_ENUM.delete_audit_logs_before:await Gn(e,Y0.deleteAuditLogsBefore);break;case Or.JOB_TYPE_ENUM.delete_transaction_logs_before:await Gn(e,qte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(kte,"parseMessage");async function Gn(e,t){try{e.job.status=Or.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Fte().valueOf(),await V0.updateJob(e.job),await Vte(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):aE.error(`There was an error running ${t.name} job with id ${e.job.id}`),aE.error(s),e.job.message=s,e.job.status=Or.JOB_STATUS_ENUM.ERROR;try{await V0.updateJob(e.job)}catch(n){throw aE.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Gn,"runJob");async function Vte(e){aE.trace("launching job thread:",e),Gte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Or.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Vte,"launchJobThread");K0.exports={parseMessage:kte,RunnerMessage:jg}});var z0=T((jEe,Q0)=>{"use strict";var Zg=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};Q0.exports=Zg});var dB=T((ehe,iR)=>{"use strict";var _E=as(),rR=qf(),cE=Qg(),qn=Hd(),uE=Vi(),Sl=Qi(),$te=yS(),pl=ls(),lE=vS(),Wt=ag(),Lt=q(),Yte=xS(),Kte=Zd(),J0=RT(),Wte=tf(),Qte=AT(),zte=OT(),Jte=yT(),Xte=wT(),eR=DT(),X0=kf(),jte=Ff(),sR=Xg(),v=w(),{hdb_errors:gl,handleHDBError:Tl}=Z(),{HTTP_STATUS_CODES:j0}=gl,tR=BT(),Z0=Tf(),cB=require("util"),Ba=cs(),Zte=ni(),ere=Sa(),eB=W0(),tB=Uu(),rB=(bf(),ee(ju)),sB=xr(),nB=vf(),iB=Cf(),{setServerUtilities:tre}=(hd(),ee(Kp)),{CONTEXT:rre}=(Is(),ee(mh)),{_assignPackageExport:sre}=require("../index"),{transformReq:nre}=z(),{server:ire}=(wr(),ee(Ci)),ore=Fg(),oB=_E.searchByHash,are=_E.searchByValue,cre=cB.promisify(_E.search),ure=cB.promisify(rR.evaluateSQL),lre={[v.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[v.OPERATIONS_ENUM.CREATE_TABLE]:!0,[v.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[v.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[v.OPERATIONS_ENUM.DROP_TABLE]:!0,[v.OPERATIONS_ENUM.DROP_SCHEMA]:!0},G=z0();async function uB(e,t){try{if(e.body.operation!=="read_log"&&(Lt.log_level===v.LOG_LEVELS.INFO||Lt.log_level===v.LOG_LEVELS.DEBUG||Lt.log_level===v.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;Lt.info(o)}}catch(s){Lt.error(s)}let r=await ore.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return lre[e.body.operation]&&Zte.setSchemaDataToGlobal(s=>{s&&Lt.error(s)}),r}a(uB,"processLocalTransaction");var aB=dre();iR.exports={chooseOperation:lB,getOperationFunction:_B,operation:nR,processLocalTransaction:uB};tre(iR.exports);ire.operation=nR;function lB(e){let t;try{t=_B(e)}catch(n){throw Lt.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=rR.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=rR.checkASTPermissions(e,i);if(o)throw Lt.error(`${j0.FORBIDDEN} from operation ${e.operation}`),Lt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),Tl(new Error,o,gl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==v.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==v.OPERATIONS_ENUM.LOGIN&&e.operation!==v.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=jte.verifyPerms(i,n);if(o)throw Lt.error(`${j0.FORBIDDEN} from operation ${e.operation}`),Lt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),Tl(new Error,o,gl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw Tl(n,"There was an error when trying to choose an operation path")}return r}a(lB,"chooseOperation");function _B(e){if(Lt.trace(`getOperationFunction with operation: ${e.operation}`),aB.has(e.operation))return aB.get(e.operation);throw Tl(new Error,gl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),gl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(_B,"getOperationFunction");sre("operation",nR);function nR(e,t){e.hdb_user=this[rre]?.user,e.bypass_auth=!t;let r=lB(e);return uB({body:e},r)}a(nR,"operation");async function _re(e){Lt.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[v.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case v.OPERATIONS_ENUM.INSERT:o=await Ba.insert(i);break;case v.OPERATIONS_ENUM.UPDATE:o=await Ba.update(i);break;case v.OPERATIONS_ENUM.UPSERT:o=await Ba.upsert(i);break;case v.OPERATIONS_ENUM.DELETE:o=await Sl.deleteRecord(i);break;default:Lt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Lt.info("Invalid operation in transaction"),Lt.error(o)}}a(_re,"catchup");async function En(e){nre(e);let t,r;try{r=await sR.addJob(e),t=r.createdJob,Lt.info("addJob result",r);let s=new eB.RunnerMessage(t,e);return await eB.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 Lt.error(n),Tl(s,n)}}a(En,"executeJob");function dre(){let e=new Map;return e.set(v.OPERATIONS_ENUM.INSERT,new G(Ba.insert)),e.set(v.OPERATIONS_ENUM.UPDATE,new G(Ba.update)),e.set(v.OPERATIONS_ENUM.UPSERT,new G(Ba.upsert)),e.set(v.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new G(_E.searchByConditions)),e.set(v.OPERATIONS_ENUM.SEARCH_BY_HASH,new G(oB)),e.set(v.OPERATIONS_ENUM.SEARCH_BY_ID,new G(oB)),e.set(v.OPERATIONS_ENUM.SEARCH_BY_VALUE,new G(are)),e.set(v.OPERATIONS_ENUM.SEARCH,new G(cre)),e.set(v.OPERATIONS_ENUM.SQL,new G(ure)),e.set(v.OPERATIONS_ENUM.CSV_DATA_LOAD,new G(En,cE.csvDataLoad)),e.set(v.OPERATIONS_ENUM.CSV_FILE_LOAD,new G(En,cE.csvFileLoad)),e.set(v.OPERATIONS_ENUM.CSV_URL_LOAD,new G(En,cE.csvURLLoad)),e.set(v.OPERATIONS_ENUM.IMPORT_FROM_S3,new G(En,cE.importFromS3)),e.set(v.OPERATIONS_ENUM.CREATE_SCHEMA,new G(qn.createSchema)),e.set(v.OPERATIONS_ENUM.CREATE_DATABASE,new G(qn.createSchema)),e.set(v.OPERATIONS_ENUM.CREATE_TABLE,new G(qn.createTable)),e.set(v.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new G(qn.createAttribute)),e.set(v.OPERATIONS_ENUM.DROP_SCHEMA,new G(qn.dropSchema)),e.set(v.OPERATIONS_ENUM.DROP_DATABASE,new G(qn.dropSchema)),e.set(v.OPERATIONS_ENUM.DROP_TABLE,new G(qn.dropTable)),e.set(v.OPERATIONS_ENUM.DROP_ATTRIBUTE,new G(qn.dropAttribute)),e.set(v.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new G(uE.describeSchema)),e.set(v.OPERATIONS_ENUM.DESCRIBE_DATABASE,new G(uE.describeSchema)),e.set(v.OPERATIONS_ENUM.DESCRIBE_TABLE,new G(uE.describeTable)),e.set(v.OPERATIONS_ENUM.DESCRIBE_ALL,new G(uE.describeAll)),e.set(v.OPERATIONS_ENUM.DELETE,new G(Sl.deleteRecord)),e.set(v.OPERATIONS_ENUM.ADD_USER,new G(pl.addUser)),e.set(v.OPERATIONS_ENUM.ALTER_USER,new G(pl.alterUser)),e.set(v.OPERATIONS_ENUM.DROP_USER,new G(pl.dropUser)),e.set(v.OPERATIONS_ENUM.LIST_USERS,new G(pl.listUsersExternal)),e.set(v.OPERATIONS_ENUM.LIST_ROLES,new G(lE.listRoles)),e.set(v.OPERATIONS_ENUM.ADD_ROLE,new G(lE.addRole)),e.set(v.OPERATIONS_ENUM.ALTER_ROLE,new G(lE.alterRole)),e.set(v.OPERATIONS_ENUM.DROP_ROLE,new G(lE.dropRole)),e.set(v.OPERATIONS_ENUM.USER_INFO,new G(pl.userInfo)),e.set(v.OPERATIONS_ENUM.READ_LOG,new G(Yte)),e.set(v.OPERATIONS_ENUM.ADD_NODE,new G(Kte)),e.set(v.OPERATIONS_ENUM.UPDATE_NODE,new G(J0)),e.set(v.OPERATIONS_ENUM.SET_NODE_REPLICATION,new G(J0)),e.set(v.OPERATIONS_ENUM.REMOVE_NODE,new G(Wte)),e.set(v.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new G(Qte)),e.set(v.OPERATIONS_ENUM.PURGE_STREAM,new G(zte)),e.set(v.OPERATIONS_ENUM.SET_CONFIGURATION,new G(sB.setConfiguration)),e.set(v.OPERATIONS_ENUM.CLUSTER_STATUS,new G(Jte.clusterStatus)),e.set(v.OPERATIONS_ENUM.CLUSTER_NETWORK,new G(Xte)),e.set(v.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new G(eR.setRoutes)),e.set(v.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new G(eR.getRoutes)),e.set(v.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new G(eR.deleteRoutes)),e.set(v.OPERATIONS_ENUM.EXPORT_TO_S3,new G(En,X0.export_to_s3)),e.set(v.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new G(En,Sl.deleteFilesBefore)),e.set(v.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new G(En,Sl.deleteFilesBefore)),e.set(v.OPERATIONS_ENUM.EXPORT_LOCAL,new G(En,X0.export_local)),e.set(v.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new G(sR.handleGetJobsByStartDate)),e.set(v.OPERATIONS_ENUM.GET_JOB,new G(sR.handleGetJob)),e.set(v.OPERATIONS_ENUM.GET_FINGERPRINT,new G(tR.getFingerprint)),e.set(v.OPERATIONS_ENUM.SET_LICENSE,new G(tR.setLicense)),e.set(v.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new G(tR.getRegistrationInfo)),e.set(v.OPERATIONS_ENUM.RESTART,new G(Z0.restart)),e.set(v.OPERATIONS_ENUM.RESTART_SERVICE,new G(Z0.restartService)),e.set(v.OPERATIONS_ENUM.CATCHUP,new G(_re)),e.set(v.OPERATIONS_ENUM.SYSTEM_INFORMATION,new G(ere.systemInformation)),e.set(v.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new G(En,Sl.deleteAuditLogsBefore)),e.set(v.OPERATIONS_ENUM.READ_AUDIT_LOG,new G($te)),e.set(v.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new G(tB.createTokens)),e.set(v.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new G(tB.refreshOperationToken)),e.set(v.OPERATIONS_ENUM.LOGIN,new G(rB.login)),e.set(v.OPERATIONS_ENUM.LOGOUT,new G(rB.logout)),e.set(v.OPERATIONS_ENUM.GET_CONFIGURATION,new G(sB.getConfiguration)),e.set(v.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new G(Wt.customFunctionsStatus)),e.set(v.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new G(Wt.getCustomFunctions)),e.set(v.OPERATIONS_ENUM.GET_COMPONENT_FILE,new G(Wt.getComponentFile)),e.set(v.OPERATIONS_ENUM.GET_COMPONENTS,new G(Wt.getComponents)),e.set(v.OPERATIONS_ENUM.SET_COMPONENT_FILE,new G(Wt.setComponentFile)),e.set(v.OPERATIONS_ENUM.DROP_COMPONENT,new G(Wt.dropComponent)),e.set(v.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new G(Wt.getCustomFunction)),e.set(v.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new G(Wt.setCustomFunction)),e.set(v.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new G(Wt.dropCustomFunction)),e.set(v.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new G(Wt.addComponent)),e.set(v.OPERATIONS_ENUM.ADD_COMPONENT,new G(Wt.addComponent)),e.set(v.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new G(Wt.dropCustomFunctionProject)),e.set(v.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new G(Wt.packageComponent)),e.set(v.OPERATIONS_ENUM.PACKAGE_COMPONENT,new G(Wt.packageComponent)),e.set(v.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new G(Wt.deployComponent)),e.set(v.OPERATIONS_ENUM.DEPLOY_COMPONENT,new G(Wt.deployComponent)),e.set(v.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new G(nB.readTransactionLog)),e.set(v.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new G(En,nB.deleteTransactionLogsBefore)),e.set(v.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new G(iB.installModules)),e.set(v.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new G(iB.auditModules)),e.set(v.OPERATIONS_ENUM.GET_BACKUP,new G(qn.getBackup)),e}a(dre,"initializeOperationFunctionMap")});var fE=T((rhe,hB)=>{"use strict";var oR=w(),fre=z(),Rl=q(),{handleHDBError:aR,hdb_errors:dE}=Z(),{isMainThread:Ere}=require("worker_threads"),{Readable:hre}=require("stream"),fB=require("os"),mre=require("util"),pre=zS(),Sre=mre.promisify(pre.authorize),EB=dB(),{createGzip:Tre,constants:gre}=require("zlib");function Rre(e){let t=`Found an uncaught exception with message: ${e.message}. ${fB.EOL}Stack: ${e.stack} ${fB.EOL}Terminating ${Ere?"HDB":"thread"}.`;console.error(t),Rl.fatal(t),process.exit(1)}a(Rre,"handleServerUncaughtException");function Are(e,t,r){if(Rl[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:dE.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(Are,"serverErrorHandler");function Ore(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=aR(new Error,"Invalid JSON.",dE.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(fre.isEmpty(e.body.operation)){let s=aR(new Error,"Request body must include an 'operation' property.",dE.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(Ore,"reqBodyValidationHandler");function bre(e,t,r){let s;e.body.operation!==oR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==oR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==oR.OPERATIONS_ENUM.LOGOUT?Sre(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{Rl.warn(n),Rl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(aR(n,i,dE.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(bre,"authHandler");async function Nre(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=EB.chooseOperation(e.body);let n=await EB.processLocalTransaction(e,s);if(n instanceof hre&&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(Tre({level:gre.Z_BEST_SPEED})))}return n}catch(n){throw Rl.error(n),n}}a(Nre,"handlePostRequest");hB.exports={authHandler:bre,handlePostRequest:Nre,handleServerUncaughtException:Rre,serverErrorHandler:Are,reqBodyValidationHandler:Ore}});var TB=T((nhe,SB)=>{"use strict";var yre=require("fastify-plugin"),{handlePostRequest:mB,authHandler:Ire,reqBodyValidationHandler:wre}=fE();async function Cre(e){e.decorate("hdbCore",{preValidation:[wre,Ire],request:t=>pB(mB(t,response)),requestWithoutAuthentication:(t,r)=>pB(mB(t,r,!0))})}a(Cre,"hdbCore");async function pB(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(pB,"convertAsyncIterators");SB.exports=yre(Cre)});var AB=T((ahe,RB)=>{"use strict";var ohe=require("fs"),cR=j();cR.initSync();var{CONFIG_PARAMS:gB}=w(),Lre=1024*1024*1024;function Dre(e){let t=cR.get(gB.HTTP_TIMEOUT),r=cR.get(gB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:Lre,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Dre,"getServerOptions");RB.exports=Dre});var NB=T((uhe,bB)=>{"use strict";var uR=j();uR.initSync();var{CONFIG_PARAMS:OB}=w();function Mre(){let e=uR.get(OB.HTTP_CORSACCESSLIST),t=uR.get(OB.HTTP_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(Mre,"getCORSOptions");bB.exports=Mre});var wB=T((_he,IB)=>{"use strict";var yB=j();yB.initSync();var Ure=w();function Pre(){return yB.get(Ure.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Pre,"getHeaderTimeoutConfig");IB.exports=Pre});var lR={};$e(lR,{customFunctionsServer:()=>Hre,ready:()=>Gre,start:()=>Bre});function Bre(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){kn||(kn=VB(t),At.http((await kn).server));let o=await kn,c=(0,LB.dirname)(n),u=s.replace(/\/routes\/.*/g,"");if(u.startsWith("/")&&(u=u.slice(1)),!CB.has(c)){CB.add(c);try{o.register(Fre(c,u))}catch(_){if(_.message==="Root plugin has already booted")ke.warn(`Could not load root fastify route for ${n}, this may require a restart to install properly`);else throw _}}}}}async function Hre(){try{ke.info("In Custom Functions Fastify server"+process.cwd()),ke.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),ke.debug(`Custom Functions server process ${process.pid} starting up.`),await xre();let e=BB.get(HB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=kn=await VB(e)}catch(r){throw ke.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw ke.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){ke.error(`Custom Functions ${process.pid} Error: ${e}`),ke.error(e),process.exit(1)}}async function xre(){try{ke.info("Custom Functions starting configuration."),await xB.setUsersToGlobal(),ke.info("Custom Functions completed configuration.")}catch(e){ke.error(e)}}function Fre(e,t){return async function(r){try{ke.info("Custom Functions starting buildRoutes"),ke.trace("Loading fastify routes folder "+e),(0,DB.existsSync)(e)&&r.register(vB.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:ke.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?ke.error(n.message):n&&ke.error(n),o()})}catch(s){ke.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function VB(e){ke.info("Custom Functions starting buildServer.");let t=(0,FB.default)(e),r=(0,MB.default)(t);r.server.headersTimeout=(0,qB.default)(),r.setErrorHandler(kB.serverErrorHandler);let s=(0,GB.default)();return s&&r.register(UB.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(PB.default),await r.register(vre),await r.after(),Dg(r),ke.info("Custom Functions completed buildServer."),r}function Gre(){if(kn)return kn.then?kn.then(e=>e.ready()):kn.ready()}var LB,DB,MB,UB,PB,vB,BB,HB,ke,vre,xB,FB,GB,qB,kB,kn,CB,$B=ge(()=>{LB=require("path"),DB=require("fs"),MB=U(require("fastify")),UB=U(require("@fastify/cors")),PB=U(Pg()),vB=U(require("@fastify/autoload")),BB=U(j()),HB=U(w()),ke=U(q()),vre=U(TB()),xB=U(ls()),FB=U(AB()),GB=U(NB()),qB=U(wB()),kB=U(fE());Na();wr();CB=new Set;a(Bre,"start");a(Hre,"customFunctionsServer");a(xre,"setUp");a(Fre,"buildRouteFolder");a(VB,"buildServer");a(Gre,"ready")});var _R={};$e(_R,{start:()=>qre});function qre(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,zB.default)(r,e);return e.server.http(async(n,i)=>{if(!n.isWebSocket)return new Promise(o=>s(n._nodeRequest,n._nodeResponse,()=>{o(i(n))}))}),!0}},handleFile(t,r,s){KB||(KB=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=YB.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,WB.default)(n,(0,QB.realpathSync)(o))}}return i(n)},{runFirst:!0})),YB.set(r,s)}}}var WB,QB,zB,YB,KB,JB=ge(()=>{WB=U(require("send")),QB=require("fs"),zB=U(require("serve-static")),YB=new Map;a(qre,"start")});var hR={};$e(hR,{Request:()=>dR,createReuseportFd:()=>EE});var XB,dR,fR,ER,EE,hE=ge(()=>{XB=require("os"),dR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let s=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=s,this.headers=new ER(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get body(){return this.#e||(this.#e=new fR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},fR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},ER=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,s]of this)t(s,r,this)}};(0,XB.platform)()!="win32"&&(EE=require("node-unix-socket").createReuseportFd)});var tH=T((Ohe,eH)=>{"use strict";var kre=require("cluster"),Io=j();Io.initSync();var ZB=w(),She=require("util"),Vn=q(),The=require("fs"),Vre=require("fastify"),ghe=Ru(),$re=require("@fastify/cors"),Yre=require("@fastify/compress"),Kre=require("@fastify/static"),Wre=Pg(),Qre=require("path"),{PACKAGE_ROOT:zre}=w(),Jre=ni(),Xre=z(),jre=ls(),Zre=ji(),{server:ese}=(wr(),ee(Ci)),{node_request_key:Rhe}=(hE(),ee(hR)),{authHandler:tse,handlePostRequest:rse,serverErrorHandler:sse,reqBodyValidationHandler:nse}=fE(),Ahe=require("net"),{registerContentHandlers:ise}=(Na(),ee(Zv)),ose=6e4,ase=1024*1024*1024,cse="TRUE",{CONFIG_PARAMS:Al}=ZB,Ha;eH.exports={hdbServer:jB,start:jB};async function jB(e){try{Vn.info("In Fastify server"+process.cwd()),Vn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=kre.isMaster,await use();let t=e.securePort>0;Ha=lse(t),await Ha.ready(),e||(e={}),e.isOperationsServer=!0;try{ese.http(Ha.server,e),Ha.server.closeIdleConnections||await Ha.listen({port:0,host:"::"})}catch(r){throw Ha.close(),Vn.error(r),Vn.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vn.fatal(t),process.exit(1)}}a(jB,"operationsServer");async function use(){Vn.trace("Configuring HarperDB process."),Jre.setSchemaDataToGlobal(),await jre.setUsersToGlobal(),await Zre.getLicense()}a(use,"setUp");function lse(e){Vn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=_se(e),r=Vre(t);r.server.headersTimeout=fse(),r.setErrorHandler(sse);let s=dse();s&&r.register($re,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Wre),r.register(Yre),r.register(Kre,{root:Qre.join(zre,"studio/build-local")}),ise(r);let n=Io.get(ZB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Xre.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[nse,tse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),rse(i,o)}),r.get("/health",()=>"HarperDB is running."),Vn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(lse,"buildServer");function _se(e){let t=Io.get(Al.OPERATIONSAPI_NETWORK_TIMEOUT),r=Io.get(Al.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:ase,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(_se,"getServerOptions");function dse(){let e=Io.get(Al.OPERATIONSAPI_NETWORK_CORS),t=Io.get(Al.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===cse)&&(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(dse,"getCORSOpts");function fse(){return Io.get(Al.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??ose}a(fse,"getHeaderTimeoutConfig")});var _H=T((whe,lH)=>{"use strict";var{decode:Ese}=require("msgpackr"),{isMainThread:Nhe,parentPort:hse,threadId:yhe}=require("worker_threads"),pR=yt(),$n=tt(),mse=w(),Ni=q(),rH=j(),nH=w();Ze();var pse=wn(),{recordAction:Sse,recordActionBinary:Tse}=(Cn(),ee(iu)),{publishToStream:gse}=pR,{ConsumerEvents:Rse}=require("nats"),Ihe={durable:$n.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:$n.WORK_QUEUE_CONSUMER_NAMES.deliver_group},Ase,Ose,bse,iH,oH;lH.exports={initialize:SR,workQueueListener:uH,setSubscription:Nse,setIgnoreOrigin:Ise,getDatabaseSubscriptions:yse};async function SR(){oH=!0,Ni.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await pR.getNATSReferences();Ase=e,Ose=e.info.server_name,bse=t,iH=r}a(SR,"initialize");var pE=new Map;function Nse(e,t,r){let s=pE.get(e);s||pE.set(e,s=new Map),s.set(t,r),oH||SR().then(uH)}a(Nse,"setSubscription");function yse(){return pE}a(yse,"getDatabaseSubscriptions");var aH;function Ise(e){aH=e}a(Ise,"setIgnoreOrigin");var cH=100,sH=new Array(cH),mE=0;async function uH(){let e=await iH.consumers.get($n.WORK_QUEUE_CONSUMER_NAMES.stream_name,$n.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(hse?.on("message",async s=>{let{type:n}=s;n===nH.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let s of await r.status())if(s.type===Rse.HeartbeatsMissed){let n=s.data;Ni.trace(`${n} clustering ingest consumer heartbeats missed`),n===2&&(Ni.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let s of r)await sH[mE],sH[mE]=wse(s).catch(n=>{Ni.error(n)}),++mE>=cH&&(mE=0)}catch(s){Ni.error("Error consuming clustering ingest, restarting consumer",s)}pR.clearClientCache(),await SR()}}a(uH,"workQueueListener");async function wse(e){let t=Ese(e.data);Sse(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,s=!1,n=rH.get(mse.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has($n.MSG_HEADERS.TRANSACTED_NODES)&&r.values($n.MSG_HEADERS.TRANSACTED_NODES).indexOf(n)>-1&&(s=!0);let i=r.get($n.MSG_HEADERS.ORIGIN);if(s||(s=i===n&&!aH),Tse(s,"echo",e.subject,t.operation,"ingest"),s){e.ack();return}r.append($n.MSG_HEADERS.TRANSACTED_NODES,n);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Ni.trace("processing message:",o,c,_,(l?"records: "+l.map(b=>b?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Ni.trace(`messageProcessor nats msg id: ${e.headers.get($n.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:R}=f||{},O=pE.get(c)?.get(_);if(!O)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,O.send(t);else if(l.length===1&&!u)O.send({type:mR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:R});else{let b=l.map((P,$)=>({type:mR(o),value:P,expiresAt:E,id:d?.[$],table:_}));for(;u;)b.push({type:mR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;O.send({type:"transaction",writes:b,table:_,timestamp:p,onCommit:h,user:S,nodeName:R})}rH.get(nH.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&gse(e.subject.split(".").slice(0,-1).join("."),pse.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Ni.error(o)}e.ack()}a(wse,"messageProcessor");function mR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(mR,"convertOperation")});var bR={};$e(bR,{disableNATS:()=>Lse,publishToStream:()=>AE,setNATSReplicator:()=>TR,setPublishToStream:()=>Dse,setSubscription:()=>OR,start:()=>Cse});function Cse(){TE.default.get(gE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Use()}function Lse(e=!0){mH=e}function Dse(e,t){AE=e,OR=t}function Use(){if(mH||process.env._DISABLE_NATS)return;let e=Ms(),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];TR(n,r,i)}}Xp((r,s)=>{TR(r.tableName,r.databaseName,r),s&&SH(r)}),!dH&&(dH=!0)}function TR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(n=>n?.isNATSReplicator))return;r.sourcedFrom(class extends Ft{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){SH(i)}static subscribe(){let i=new ys;return OR(t,e,i),i}static subscribeOnThisThread(i){return i<Mse}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function s(n){let i=n?.transaction?.nats;if(!i)if(n?.transaction){n.transaction.nats=i=new SE(n.transaction,n);let o=n.transaction;for(;o.next;)o=o.next;o.next=n.transaction.nats,i.user=n.user,i.context=n}else i=pH;return i}a(s,"getNATSTransaction")}function SH(e){let t=TE.default.get(gE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);AE(`${RR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,AR.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 fH,RR,AR,EH,hH,TE,gE,RE,mH,AE,OR,Mse,pH,dH,SE,gR,TH=ge(()=>{pe();Is();fH=U(yt()),RR=U(tt()),AR=U(wn());uc();EH=U(_H()),hH=U(Lr()),TE=U(j()),gE=U(w()),RE=U(q());a(Cse,"start");a(Lse,"disableNATS");AE=fH.publishToStream,OR=EH.setSubscription;a(Dse,"setPublishToStream");Mse=2;a(Use,"assignReplicationSource");a(TR,"setNATSReplicator");a(SH,"publishSchema");SE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let s=this.writes_by_db.get(t);s||this.writes_by_db.set(t,s=[]),s.push(r)}commit({timestamp:t}){let r=TE.default.get(gE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(RE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&s.push(AE(`${RR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,AR.createNatsTableStreamName)(n,u.table),void 0,u)?.catch(l=>{throw RE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(s)}},gR=class extends SE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,hH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};pH=new gR});async function AH({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await NR.getResource(e,{});n=new wR(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await NR.get(e);i&&i.delete()}n=new bE(e,t)}return s&&(s.id=e,s.user={username:t?.username},Ol.put(s)),n}function yR(){return OE++,OE>65500&&(OE=1),OE}function IR(e,t,r=e){let{topic:s,retain:n}=e;e.data=t,e.async=!0,e.authorize=!0;let i=Zn.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`);e.url=i.relativeURL;let o=i.Resource;return Qe(r,()=>n?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var gH,wo,RH,NR,Ol,OE,bE,wR,OH=ge(()=>{pe();hc();gH=U(Lr()),wo=U(q());Ui();RH=U(Ze()),NR=lt({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"}]}}]}),Ol=lt({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,RH.getWorkerIndex)()===0&&(async()=>{for await(let e of Ol.search({})){let t=e.data,r=Object.assign({},e);Qe(r,()=>{IR(r,t),Ol.delete(e.id,r)})}})();a(AH,"getSession");OE=1;a(yR,"getNextMessageId");bE=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,rh:i,startTime:o}=t,c=n.indexOf("?"),u,_;if(c>-1?(u=n.slice(c),_=n.slice(0,c)):_=n,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(R=>R.topic===n),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,wo.trace)("Resuming subscription from",n,"from",o);let E=Zn.getMatch(_);if(!E){let R=new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);throw R.statusCode=404,R}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let R=f.url.slice(1);if(R.indexOf("#")>-1&&R.indexOf("#")!==R.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,R.indexOf("+")===R.length-1)f.onlyChildren=!0,f.url="/"+R.slice(0,R.length-1);else{let O=R.split("/"),b;for(let x=0;x<O.length;x++)if(O[x].indexOf("+")>-1)if(O[x]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(s&&b)throw new Error("Filters can not be combined");let P=!0;O[O.length-1]==="#"&&(O.length--,P=!1),b&&(s=a(x=>{let D=x.id;if(!Array.isArray(D)||P&&D.length!==O.length)return!1;for(let Y=0;Y<O.length;Y++)if(O[Y]!=="+"&&O[Y]!==D[Y])return!1;return!0},"filter"));let $=O.indexOf("+");f.url="/"+($>-1?O.slice(0,$):O).concat("").join("/")}}let h=E.path,p=E.Resource,S=await Qe(f,async()=>{let R=await p.subscribe(f);if(!R)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!R[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let O of R)try{let b;if(O.type&&O.type!=="put"&&O.type!=="delete"&&O.type!=="message"||s&&!s(O))continue;r?(O.topic=n,b=this.needsAcknowledge(O)):(O.acknowledge?.(),b=yR());let P=O.id;Array.isArray(P)&&(P=Bo(P)),P==null&&(P=""),this.listener(h+"/"+P,O.value,b,t)}catch(b){(0,wo.warn)(b)}})(),R});return S.topic=n,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=yR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,IR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Qe(r,async()=>{if(!t){let s=await Ol.get(this.sessionId,r);s.doesExist()&&await IR(s,s.data,r)}await Ol.delete(this.sessionId,r)}).catch(s=>{(0,wo.warn)(`Error publishing MQTT will for ${this.sessionId}`,s)});for(let s of this.subscriptions)s.end();this.subscriptions=[]}};a(IR,"publish");wR=class extends bE{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=yR(),s={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(s.acknowledge=t.acknowledge),this.awaitingAcks.set(r,s),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();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,wo.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,gH.getNextMonotonicTime)()),(0,wo.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),NR.put(this.sessionRecord)),t.qos}}});var CR={};$e(CR,{start:()=>vse});function vse({server:e,port:t,network:r,webSocket:s,securePort:n,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i},c,u=r?.mtls;return s&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=yH(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,br.info)("WebSocket error",h)})}},{subProtocol:"mqtt"})),(t||n)&&(c=e.socket(async _=>{let l;if(u)if(_.authorized)try{let E=u.user;l!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,br.error)(E)}else return(0,br.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end();!l&&Pse&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,IH.getSuperUser)());let{onMessage:d,onClose:f}=yH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,br.info)("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function yH(e,t,r,s,n){NH||(NH=!0,nu(d=>{NE>0&&d.push({metric:"mqtt-connections",connections:NE,byThread:!0})}));let i;NE++;let o,c={protocolVersion:4},u=(0,IE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){NE--,i||(i=!0,o?.disconnect(),_s(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{s?.then&&(s=await s),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{s=await At.getUser(d.username,d.password.toString(),r),(0,yE.get)(hn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&bH.notify({username:s.username,status:hn.AUTH_AUDIT_STATUS.SUCCESS,type:hn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,yE.get)(hn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&bH.error({username:s.username,status:hn.AUTH_AUDIT_STATUS.FAILURE,type:hn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!s&&n.requireAuthentication)return _s(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(n.authorizeClient?.(d,s),d.will){let b=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?b(d.will.payload):void 0,delete d.will.payload}o=AH({user:s,...d}),o=await o}catch(b){return(0,br.error)(b),_s(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:b.code||5,returnCode:b.code||128})}_s(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((b,P,$,x)=>{try{let D=b.indexOf("/",1),Y=D>0?b.slice(0,D):b;f({cmd:"publish",topic:b,payload:E(P),messageId:$||Math.floor(Math.random()*1e8),qos:x.qos},Y)}catch(D){(0,br.error)(D),o?.disconnect()}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let b of d.subscriptions){let P;try{P=(await o.addSubscription(b,b.qos>=1)).qos||0}catch($){(0,br.error)($),P=c.protocolVersion<5?128:$.statusCode===403?135:$.statusCode===404?143:128}h.push(P)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let b=[];for(let P of d.unsubscriptions)b.push(o.removeSubscription(P)?0:17);f({cmd:"unsuback",granted:b,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let p=d.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type"))),R=d.payload?.length>0?S(d.payload):void 0,O;try{O=await o.publish(d,R)}catch(b){(0,br.warn)(b),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:O===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),_s(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,br.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,IE.generate)(h,c);t(S),qr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ai(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var IE,IH,yE,hn,br,bH,Pse,NH,NE,wH=ge(()=>{IE=require("mqtt-packet");OH();IH=U(ls());Na();Cn();wr();yE=U(j()),hn=U(w()),br=U(q()),bH=(0,br.loggerWithTag)("auth-event"),Pse=(0,yE.get)(hn.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(vse,"start");NE=0;a(yH,"onSocket")});var Mf={};$e(Mf,{component_errors:()=>Fa,loadComponent:()=>wE,loadComponentDirectories:()=>HH,setErrorReporter:()=>Fse});function HH(e,t){t&&(DR=t),e&&(MR=e);let r=[];if((0,Vs.existsSync)(LR)){let n=(0,Vs.readdirSync)(LR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Rt.join)(LR,o);r.push(wE(c,DR,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(wE(s,DR,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{BH=!0})}function Fse(e){Nl=e}async function wE(e,t,r,s,n,i){if(!LH.has(e)){LH.set(e,!0),n&&(MR=n);try{let o;s&&(Fa=new Map);let c=(0,Rt.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Vs.existsSync)(c)?o=s?(0,vH.getConfigObj)():(0,DH.parseDocument)((0,Vs.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=UR;let u=[],_=s;for(let l in o){let d=o[l];if(Fa.set(s?l:(0,Rt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let O=e,b;for(;!(0,Vs.existsSync)(b=(0,Rt.join)(O,"node_modules",l));)if(O=(0,Rt.dirname)(O),O.length<(0,PH.getHdbBasePath)().length){b=null;break}if(b)f=await wE(b,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=xse[l];if(!f)continue;u.push(f);let h=a(O=>(O.origin=r,lt(O)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,R=!p?.https&&p?.port;if(xa.isMainThread&&(f=await f.startOnMainThread?.({server:At,ensureTable:h,port:R,securePort:S,resources:t,...d})||f,s&&p))for(let O of[R,S])try{if(+O&&!CH.includes(O)){let b=PR.get(vR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);b&&bl.default.warn("Session affinity is not recommended and may cause memory leaks"),(b||!EE)&&(CH.push(O),BR(O,b))}}catch(b){console.error("Error listening on socket",O,b,l)}if(t.isWorker&&(f=await f.start?.({server:At,ensureTable:h,port:R,securePort:S,resources:t,...d})||f),MR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,UH.handleHDBError)("Can not reference parent directories");let O=(0,Rt.join)(e,d.files).replace(/\\/g,"/"),b=O.indexOf("/*");if(b>-1&&d.files!==UR[l]?.files&&!(0,Vs.existsSync)(O.slice(0,b)))throw new Error(`The path '${O.slice(0,b)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let P=(0,Rt.basename)(e),$=d.path||"/";$=$.startsWith("/")?$:$.startsWith("./")?"/"+P+$.slice(2):$==="."?"/"+P:"/"+P+"/"+$;let x,D,Y;if(d.root){let W=d.root;W.startsWith("/")&&(W=W.slice(1)),W.endsWith("/")&&(W=W.slice(0,-1)),W+="/",D=(0,Rt.join)(e,W)}else(Y=O.indexOf("/*"))>-1&&(D=O.slice(0,Y+1),x=(0,Rt.relative)(e,D));let V=!1;if(xa.isMainThread&&f.setupDirectory&&(V=await f.setupDirectory?.($,D,t)),t.isWorker&&f.handleDirectory&&(V=await f.handleDirectory?.($,D,t)),V)continue;for(let W of await(0,MH.default)(O,{onlyFiles:!1,objectMode:!0})){let{path:re,dirent:be}=W;_=!0;let ne=(0,Rt.relative)(e,re).replace(/\\/g,"/");if(x)if(ne.startsWith(x))ne=ne.slice(x.length);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${ne}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let ct=$+($.endsWith("/")?"":"/")+ne;try{if(be.isFile()){let Te=await Hse(re);xa.isMainThread&&await f.setupFile?.(Te,ct,re,t),t.isWorker&&await f.handleFile?.(Te,ct,re,t)}else xa.isMainThread&&await f.setupDirectory?.(ct,re,t),t.isWorker&&await f.handleDirectory?.(ct,re,t)}catch(Te){Te.message=`Could not load ${be.isFile()?"file":"directory"} '${re}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${Te.message}`,Nl?.(Te),((0,Ga.getWorkerIndex)()===0?console:bl.default).error(Te),t.set(d.path||"/",new yl(Te)),Fa.set(s?l:(0,Rt.basename)(e),Te.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Rt.basename)(e)}' due to: ${h.message}`,Nl?.(h),((0,Ga.getWorkerIndex)()===0?console:bl.default).error(h),t.set(d.path||"/",new yl(h),null,!0),Fa.set(s?l:(0,Rt.basename)(e),h.message)}}if(xa.isMainThread&&!BH&&i&&(0,Ga.watchDir)(e,async()=>HH()),o.extensionModule)return await wd((0,Rt.join)(e,o.extensionModule));if(!_){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;Nl?.(new Error(l)),((0,Ga.getWorkerIndex)()===0?console:bl.default).error(l),Fa.set((0,Rt.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Nl?.(o),t.set("",new yl(o))}}}var Vs,Rt,xa,DH,PR,vR,MH,Ga,bl,UH,PH,Bse,vH,Hse,LR,MR,BH,DR,Fa,xse,UR,CH,LH,Nl,yl,Uf=ge(()=>{Vs=require("fs"),Rt=require("path"),xa=require("worker_threads"),DH=require("yaml"),PR=U(j()),vR=U(w());gL();bL();NL();r0();$B();JB();MH=U(require("fast-glob")),Ga=U(Ze()),bl=U(q());nS();wr();UH=U(Z());Is();pe();HR();PH=U(j()),Bse=U(tH());bf();TH();wH();vH=U(xr());hE();({readFile:Hse}=Vs.promises),LR=PR.get(vR.CONFIG_PARAMS.COMPONENTSROOT),MR=new Map,Fa=new Map;a(HH,"loadComponentDirectories");xse={REST:Kf,rest:Kf,graphqlSchema:sS,jsResource:oS,fastifyRoutes:lR,login:cS,static:_R,operationsApi:Bse,customFunctions:{},http:{},clustering:bR,authentication:ju,mqtt:CR},UR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(UR,"static",{value:{files:"web/**"}});CH=[],LH=new Map;a(Fse,"setErrorReporter");a(wE,"loadComponent");yl=class extends Ft{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 CE=T((sme,FH)=>{var{isMainThread:xH}=require("worker_threads"),{getTables:Gse}=(pe(),ee(Ge)),{loadComponentDirectories:qse,loadComponent:kse}=(Uf(),ee(Mf)),{resetResources:Vse}=(hc(),ee(LO)),$se=ng(),Yse=xr(),{dirname:Kse}=require("path"),{getConnection:Wse}=yt(),Qse=j(),zse=w(),xR=new Map;async function Jse(e=!1){!xH&&Qse.get(zse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Wse();try{xH&&await $se()}catch(s){console.error(s)}let t=Vse();Gse(),t.isWorker=e,await kse(Kse(Yse.getConfigFilePath()),t,"hdb",!0,xR),await qse(xR,t);let r=[];for(let[s]of xR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(Jse,"loadRootComponents");FH.exports.loadRootComponents=Jse});var Ze=T((ime,Ii)=>{"use strict";var{Worker:Xse,MessageChannel:jse,parentPort:mn,isMainThread:VR,threadId:Zse,workerData:Yn}=require("worker_threads"),{PACKAGE_ROOT:ene}=w(),{join:VH,isAbsolute:tne,extname:rne}=require("path"),{server:$H}=(wr(),ee(Ci)),{watch:sne,readdir:nne}=require("fs/promises"),{totalmem:GH}=require("os"),Il=w(),YH=j(),Kn=q(),{randomBytes:ine}=require("crypto"),{_assignPackageExport:one}=require("../index"),ane=w(),qH=1024*1024,yi=[],Os=[],cne=50,$R=1e4,une="restart",KH="request_thread_info",WH="resource_report",QH="thread_info",zH="added-port",lne="ack",FR;one("threads",Os);Ii.exports={startWorker:GR,restartWorkers:KR,shutdownWorkers:hne,workers:yi,setMonitorListener:One,onMessageFromWorkers:mne,onMessageByType:tx,broadcast:Sne,broadcastWithAcknowledgement:gne,setChildListenerByType:Ene,getWorkerIndex:JH,getWorkerCount:XH,getTicketKeys:jH,setMainIsWorker:dne,setTerminateTimeout:_ne,restartNumber:Yn?.restartNumber||1};Os.onMessageByType=tx;Os.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Os.find(s=>s.threadId===e);if(r)return r.postMessage(t),!0};var YR;function _ne(e){$R=e}a(_ne,"setTerminateTimeout");function JH(){return Yn?Yn.workerIndex:YR?0:void 0}a(JH,"getWorkerIndex");function XH(){return Yn?Yn.workerCount:YR?1:void 0}a(XH,"getWorkerCount");function dne(e){YR=e}a(dne,"setMainIsWorker");var LE;function jH(){return LE||(LE=VR?ine(48):Yn.ticketKeys,LE)}a(jH,"getTicketKeys");Object.defineProperty($H,"workerIndex",{get(){return JH()}});Object.defineProperty($H,"workerCount",{get(){return XH()}});var ZH={[KH](e,t){Rne(t)},[WH](e,t){Ane(t,e)}};function GR(e,t={}){let r=process.constrainedMemory?.()||GH();r=Math.min(r,GH(),2e4*qH);let s=YH.get(Il.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/qH/(10+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>6,16),64),i=[],o=[];for(let u of Os){let _=new jse;_.existingPort=u,i.push(_),o.push(_.port2)}rne(e)||(e+=".js");let c=new Xse(tne(e)?e:VH(ene,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:t.threadCount,name:t.name,restartNumber:Ii.exports.restartNumber,ticketKeys:jH()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:zH,port:u,threadId:c.threadId},[u]);return ME(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>GR(e,t),c.on("error",u=>{console.error("Worker error:",u),Kn.error("Worker error:",u)}),c.on("exit",u=>{yi.splice(yi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<cne?(t.unexpectedRestarts=c.unexpectedRestarts+1,GR(e,t)):Kn.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{ZH[u.type]?.(u,c)}),yi.push(c),Nne(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(GR,"startWorker");var fne=[Il.THREAD_TYPES.HTTP];async function KR(e=null,t=2,r=!0){if(VR){if(r){let{loadRootComponents:o}=CE();await o()}Ii.exports.restartNumber++,t<1&&(t=t*yi.length);let s=[],n=[];for(let o of yi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Kn.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ii.exports.restartNumber,type:Il.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=fne.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),$R*2).unref();o.on("exit",()=>{clearTimeout(l),s.splice(s.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(s.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===ane.ITC_EVENT_TYPES.CHILD_STARTED&&(Kn.trace("Worker has started",_.threadId),d(),n.splice(n.indexOf(l)),_.off("message",f))},"startListener");Kn.trace("Waiting for worker to start",_.threadId),_.on("message",f)});n.push(l),s.length>=t&&await Promise.race(s),n.length>=t&&await Promise.race(n)}}await Promise.all(s),await Promise.all(n);let{restartService:i}=Tf();r&&(e==="http"||!e)&&YH.get(Il.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else mn.postMessage({type:une,workerType:e})}a(KR,"restartWorkers");function Ene(e,t){ZH[e]=t}a(Ene,"setChildListenerByType");function hne(e){return KR(e,1/0,!1)}a(hne,"shutdownWorkers");var ex=[];function mne(e){ex.push(e)}a(mne,"onMessageFromWorkers");var qR=new Map;function tx(e,t){let r=qR.get(e);r||qR.set(e,r=[]),r.push(t)}a(tx,"onMessageByType");var pne=10;async function Sne(e){let t=0;for(let r of Os)try{r.postMessage(e),t++>pne&&(t=0,await new Promise(setImmediate))}catch(s){Kn.error("Unable to send message to worker",s)}}a(Sne,"broadcast");var DE=new Map,Tne=1;function gne(e){return new Promise(t=>{let r=0;for(let s of Os)try{let n=Tne++,i=a(()=>{DE.delete(n),--r===0&&t(),s!==mn&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,DE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of DE)o.port===s&&o()})),s.postMessage(e),r++}catch(n){Kn.error("Unable to send message to worker",n)}r===0&&t()})}a(gne,"broadcastWithAcknowledgement");function Rne(e){e.postMessage({type:QH,workers:rx()})}a(Rne,"sendThreadInfo");function rx(){let e=Date.now();return yi.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(rx,"getChildWorkerInfo");function Ane(e,t){e.resources=t,e.resources.updated=Date.now()}a(Ane,"recordResourceReport");var kR;function One(e){kR=e}a(One,"setMonitorListener");var bne=1e3,kH=!1;function Nne(){kH||(kH=!0,setInterval(()=>{for(let e of yi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}kR&&kR()},bne).unref())}a(Nne,"startMonitoring");var yne=1e3;if(mn){ME(mn);for(let e=0,t=Yn.addPorts.length;e<t;e++){let r=Yn.addPorts[e];r.threadId=Yn.addThreadIds[e],ME(r)}setInterval(()=>{let e=process.memoryUsage();mn.postMessage({type:WH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},yne).unref(),FR=a(()=>new Promise((e,t)=>{mn.on("message",r),mn.postMessage({type:KH});function r(s){s.type===QH&&(mn.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else FR=rx;Ii.exports.getThreadInfo=FR;function ME(e,t){Os.push(e),e.on("message",r=>{if(r.type===zH)r.port.threadId=r.threadId,ME(r.port);else if(r.type===lne){let s=DE.get(r.id);s&&s()}else{for(let n of ex)n(r,e);let s=qR.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){Kn.error(i)}}}).on("close",()=>{Os.splice(Os.indexOf(e),1)}).on("exit",()=>{Os.splice(Os.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(ME,"addPort");if(VR){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await nne(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(VH(s,i.name));try{for await(let{filename:i}of sne(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await KR(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",s,i)}},"watch_dir");Ii.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else mn.on("message",async e=>{let{type:t}=e;t===Il.ITC_EVENT_TYPES.SHUTDOWN&&(Ii.exports.restartNumber=e.restartNumber,mn.unref(),setTimeout(()=>{Kn.warn("Thread did not voluntarily terminate",Zse),process.exit(0)},$R).unref())})});var mx=T(Dl=>{"use strict";var{isMainThread:Ine,parentPort:Ll,threadId:wl}=require("worker_threads"),{Socket:wne,createServer:Cne}=require("net"),{createServer:Lne,IncomingMessage:Dne}=require("http"),{createServer:Mne}=require("https"),{readFileSync:qa,unlinkSync:sx,existsSync:Une}=require("fs"),$s=q(),Ve=j(),Nr=w(),{server:vE}=(wr(),ee(Ci)),{WebSocketServer:Pne}=require("ws"),{createServer:vne}=require("tls"),{getTicketKeys:Bne,restartNumber:Hne,getWorkerIndex:nx}=Ze(),{Headers:ux}=(gf(),ee(bP)),{recordAction:Cl,recordActionBinary:xne}=(Cn(),ee(iu)),{Request:lx,createReuseportFd:ix}=(hE(),ee(hR)),{checkMemoryLimit:Fne}=ji(),_x=require("tls"),ox=_x.createSecureContext;_x.createSecureContext=function(e){if(!e.cert||!e.key)return ox(e);let t={...e};delete t.key,delete t.cert;let r=ox(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){Hne<=1&&$s.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:ame,CONFIG_PARAMS:Gne}=Nr;Ve.initSync();var qne=Ve.get(Gne.HTTP_SESSIONAFFINITY),pn={};Dl.registerServer=XR;Dl.httpServer=jR;Dl.deliverSocket=JR;Dl.startServers=dx;vE.http=jR;vE.request=Yne;vE.socket=Kne;vE.ws=Wne;var WR=[],UE=[],kne,Co={},PE={},Vne=[],QR=[];function dx(){return CE().loadRootComponents(!0).then(()=>{Ll?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)JR(s,r,n);else if(t.requestId)$ne(t);else if(t.type===Nr.ITC_EVENT_TYPES.SHUTDOWN){$s.trace("received shutdown request",wl);for(let i in pn){let o=pn[i],c;o.closeIdleConnections&&(setInterval(()=>{o.closeIdleConnections()},25).unref(),setTimeout(()=>{o.closeAllConnections(),$s.info("Closed all http connections",i,wl)},4e3).unref()),o.close?.(()=>{if(Ve.get(Nr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&nx()==0)try{sx(Ve.get(Nr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,wl),o.cantCleanupProperly||$s.warn("Had to forcefully exit the thread",wl),process.exit(0)},5e3).unref()})}if(process.env.DEV_MODE)try{require("inspector").close()}catch(i){console.error("Could not close debugger",i)}}}).ref();let e=[];if(ix&&!qne)for(let t in pn){let r=pn[t];if(isNaN(t)&&nx()==0){Une(t)&&sx(t),e.push(new Promise((n,i)=>{r.listen({path:t},()=>{n(),$s.info("Domain socket listening on "+t)}).on("error",i)}));continue}let s;try{s=ix(+t,"::")}catch(n){console.error(`Unable to bind to port ${t}`,n);continue}e.push(new Promise((n,i)=>{r.listen({fd:s},()=>{n(),$s.trace("Listening on port "+t,wl)}).on("error",i)}))}Promise.all(e).then(()=>{Ll?.postMessage({type:Nr.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(dx,"startServers");Ine||dx();function JR(e,t,r){let s=e?.read?e:new wne({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),n=pn[t];if(n.isSecure&&(s.startTime=performance.now()),n)typeof n=="function"?n(s):n.emit("connection",s),r&&s.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=pn[t];c?(typeof c=="function"?c(s):c.emit("connection",s),r&&s.emit("data",r)):o<5?i(o+1):($s.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(JR,"deliverSocket");var ax=new Map;function $ne(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=ax.get(n),r){case"connection":i=JR(void 0,t),ax.set(n,i),i.write=(c,u,_)=>(Ll.postMessage({requestId:n,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Ll.postMessage({requestId:n,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Ll.postMessage({requestId:n,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(s,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a($ne,"proxyRequest");function XR(e,t){!+t&&t!==Ve.get(Nr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(Ve.get(Nr.CONFIG_PARAMS.HTTP_PORT),10));let r=pn[t];if(r){let s=r.lastServer||r;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",cx),s.on("unhandled",(n,i)=>{e.cantCleanupProperly&&(r.cantCleanupProperly=!0),e.emit("request",n,i)}),r.lastServer=e}else pn[t]=e;e.on("unhandled",cx)}a(XR,"registerServer");function fx(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],Ve.get(Nr.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:Ve.get(Nr.CONFIG_PARAMS.HTTP_PORT),secure:Ve.get(Nr.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),Ve.get(Nr.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:Ve.get(Nr.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&Ve.get(Nr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:Ve.get(Nr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(fx,"getPorts");function jR(e,t){for(let{port:r,secure:s}of fx(t))Ex(r,s,t?.isOperationsServer),typeof e=="function"?QR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=s,XR(e,r)),PE[r]=zR(QR,r),kne=zR(Vne,r)}a(jR,"httpServer");function Ex(e,t,r){if(!Co[e]){let s=r?"operationsApi_network":"http",n={keepAliveTimeout:Ve.get(s+"_keepAliveTimeout"),headersTimeout:Ve.get(s+"_headersTimeout"),requestTimeout:Ve.get(s+"_timeout")},i=Ve.get(s+"_mtls");if(t){s=r?"operationsApi_":"";let c=Ve.get(s+"tls_privateKey"),u=Ve.get(s+"tls_certificate"),_=Ve.get(s+"tls_certificateAuthority");Object.assign(n,{allowHTTP1:!0,key:qa(c),ciphers:Ve.get("tls_ciphers"),cert:qa(u),ca:_&&qa(_),requestCert:!!i,ticketKeys:Bne()})}let o=Fne();Co[e]=(t?Mne:Lne)(n,async(c,u)=>{try{let l=performance.now(),d=new lx(c,u);r&&(d.isOperationsServer=!0);let f=await PE[e](d);if(!f){if(d._nodeResponse.statusCode)return;f=hx(d)}if(o?f.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):f.headers?.set?.("Server","HarperDB"),f.status===-1){for(let P of f.headers||[])u.setHeader(P[0],P[1]);return c.baseRequest=d,u.baseResponse=f,Co[e].emit("unhandled",c,u)}let E=f.status||200,h=performance.now(),p=h-l,S=f.body,R;if(!f.handlesHeaders){let P=f.headers||new ux;if(S?S.length>=0&&(typeof S=="string"?P.set("Content-Length",Buffer.byteLength(S)):P.set("Content-Length",S.length),R=!0):(P.set("Content-Length","0"),R=!0),P.append){let $=`hdb;dur=${p.toFixed(2)}`;f.wasCacheMiss&&($+=", miss"),P.append("Server-Timing",$,!0)}u.writeHead(E,P&&(P[Symbol.iterator]?Array.from(P):P)),R&&u.end(S)}let O=d.handlerPath,b=d.method;if(Cl(p,"duration",O,b,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),xne(E<400,"success",O,b),!R)if(S?.pipe){S.pipe(u),S.destroy&&u.on("close",()=>{S.destroy()});let P=0;S.on("data",$=>{P+=$.length}),S.on("end",()=>{Cl(performance.now()-h,"transfer",O,b),Cl(P,"bytes-sent",O,b)})}else S?.then?S.then(P=>{u.end(P)},_):u.end(S)}catch(l){_(l)}function _(l){let d=l.headers;u.writeHead(l.statusCode||500,d&&(d[Symbol.iterator]?Array.from(d):d)),u.end(l.toString()),l.statusCode?l.statusCode===500?$s.warn(l):$s.info(l):$s.error(l)}a(_,"onError")}),t&&(Co[e].on("secureConnection",c=>{c._parent.startTime&&Cl(performance.now()-c._parent.startTime,"tls-handshake",e),Cl(c.isSessionReused(),"tls-reused",e)}),Co[e].isSecure=!0),XR(Co[e],e)}return Co[e]}a(Ex,"getHTTPServer");function zR(e,t){let r=hx;for(let s=e.length;s>0;){let{listener:n,port:i}=e[--s];if(i===t||i==="all"){let o=r;r=a(c=>n(c,o),"next_callback")}}return r}a(zR,"makeCallbackChain");function hx(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new ux}}a(hx,"unhandled");function Yne(e,t){jR(e,{requestOnly:!0,...t})}a(Yne,"onRequest");function Kne(e,t){let r;if(t.securePort){let s=Ve.get("tls_privateKey"),n=Ve.get("tls_certificate"),i=t.mtls?.certificateAuthority||Ve.get("tls_certificateAuthority");r=vne({ciphers:Ve.get("tls_ciphers"),key:qa(s),cert:qa(n),ca:i&&qa(i),requestCert:!!t.mtls},e),pn[t.securePort]=r}return t.port&&(r=Cne(e),pn[t.port]=r),r}a(Kne,"onSocket");Object.defineProperty(Dne.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function Wne(e,t){for(let{port:r,secure:s}of fx(t)){UE[r]||(UE[r]=new Pne({server:Ex(r,s)}),UE[r].on("connection",async(i,o)=>{try{let c=new lx(o);c.isWebSocket=!0;let u=PE[r](c),_=o.headers["sec-websocket-protocol"]||"";for(let l=0;l<WR.length;l++){let d=WR[l];if(d.protocol){if(d.protocol===_){d.listener(i,c,u);break}}else d.listener(i,c,u)}}catch(c){$s.warn("Error handling WebSocket connection",c)}}),UE[r].on("error",i=>{console.log("Error in setting up WebSocket server",i)}));let n=t?.subProtocol||"";WR.push({listener:e,protocol:n}),PE[r]=zR(QR,r)}}a(Wne,"onWebSocket");function cx(e,t){t.writeHead(404),t.end(`Not found
27
- `)}a(cx,"defaultNotFound")});var bx={};$e(bx,{startHTTPThreads:()=>zne,startSocketServer:()=>BR,updateWorkerIdleness:()=>Ox});async function zne(e=2,t){if(t)eA(0,1,!0);else{let{loadRootComponents:s}=CE();if(e===0)return(0,wi.setMainIsWorker)(!0),await mx().startServers(),Promise.resolve([]);await s()}let r=(0,gx.checkMemoryLimit)();r&&!process.env.DEV_MODE&&(console.error(r),setInterval(()=>{FE.notify(r)},Qne).unref());for(let s=0;s<e;s++)eA(s,e);return Promise.all(Ax)}function eA(e,t=1,r){if(ZR++,(0,wi.startWorker)("server/threads/threadServer.js",{name:xE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(_){_.type===xE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});Ax.push(n),await n,ka.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=HE.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=ka.indexOf(s);o>-1&&ka.splice(o,1)}if(a(i,"removeWorker"),Va){let o=Va;Va=[];for(let c of o)Rx[c.localPort](null,c)}}}),r){let s=setInterval(()=>{tA?tA=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,wi.shutdownWorkers)(),ZR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function BR(e=0,t){if(typeof e=="string")try{(0,GE.existsSync)(e)&&(0,GE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Jne:r=Xne(t):r=rA;let s=(0,$a.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=Rx[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),tA=!0,r(o,(c,u)=>{if(!c){if(px){let l=o._socket||new $a.Socket({handle:o,writable:!0,readable:!0});px.deliverSocket(l,e,u),l.resume()}else ZR>0?(Va.length===0&&setTimeout(()=>{Va.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(),o.localPort=e,Va.push(o)):(console.log("start up a dynamic thread to handle request"),eA(0));qr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new $a.Socket({handle:o,writable:!0,readable:!0});eie(l,c,e)}qr(!0,"socket-routed")})};let n=Ru();FE.info(`HarperDB ${n.version} Server running on port ${e}`)}return s.on("error",n=>{console.error("Error in socket server",n)}),process.env._UNREF_SERVER&&s.unref(),s}function rA(e,t){let r,s=0;for(let n of ka){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=BE)return BE=i,t(r);s=i}BE=0,t(r)}function Jne(e,t){let r={};e.getpeername(r);let s=r.address,n=Ya.get(s),i=Date.now();if(n&&n.worker.threadId!==-1)return n.lastUsed=i,t(n.worker);rA(e,o=>{Ya.set(s,{worker:o,lastUsed:i}),t(o)})}function Xne(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){let i=new $a.Socket({handle:s,readable:!0,writable:!0});s._socket=i,i.on("data",o=>{s.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ya.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,n(_.worker);rA(s,d=>{Ya.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function Ox(){BE=0;for(let e of ka)e.expectedIdle=e.recentELU.idle+jne,e.requests=1;ka.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function eie(e,t,r){let s=Zne++;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(),HE.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")),HE.delete(s)),n.event=="destroy"&&(e.destroy(),HE.delete(s))})}var wi,$a,xE,FE,GE,Tx,gx,ka,Va,Rx,px,ZR,Ax,Qne,tA,BE,Sx,Ya,jne,HE,Zne,HR=ge(()=>{wi=U(Ze()),$a=require("net"),xE=U(w()),FE=U(q()),GE=require("fs");Cn();Tx=require("worker_threads"),gx=U(ji()),ka=[],Va=[],Rx=[],ZR=0,Ax=[];Tx.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});Qne=6e5;a(zne,"startHTTPThreads");a(eA,"startHTTPWorker");a(BR,"startSocketServer");BE=0;a(rA,"findMostIdleWorker");Sx=36e5,Ya=new Map;a(Jne,"findByRemoteAddressAffinity");a(Xne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ya)r.lastUsed+Sx<e&&Ya.delete(t)},Sx).unref();jne=1e3;a(Ox,"updateWorkerIdleness");(0,wi.setMonitorListener)(Ox);HE=new Map,Zne=1;a(eie,"proxySocket")});QE();var{startHTTPThreads:tie,startSocketServer:Nx}=(HR(),ee(bx));tie(0,!0);Nx(9925);Nx(9926);
26
+ `},compressible:!1,q:.8});xt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});_0={type:"application/json",serializeStream:mu,serialize:al,deserialize:Wee,q:.8};xt.set("*/*",_0);xt.set("",_0);a(Wee,"tryJSONParse");a(Vg,"registerContentHandlers");Qee=require("fastify-plugin"),zee=Qee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=zf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(zf,"findBestSerializer");o0=Fg.default.get(qg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Jf,"serialize");a(Ti,"serializeMessage");a(Jee,"streamToBuffer");a(Ro,"getDeserializer");a(a0,"deserializerUnknownType");a(Xee,"transformIterable")});function S0(e){let t={openapi:jee,info:{title:"HarperDB HTTP REST interface",version:(0,p0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,{attributes:i,primaryKey:o,prototype:c}=n.Resource;if(o=o??"id",!o)continue;let u={},_=[];if(i)for(let{type:A,name:b}of i)u[b]=new m0(f0[A],A),_.push(new Kg(b,"query",u[b]));let l=Object.keys(u),d=new Kg(o,"path",new m0(f0.ID,"ID"));d.required=!0,d.description="primary key of record";let f=new Kg("property","path",{enum:l});f.required=!0,t.components.schemas[s]=new tte(u);let E=c.post!==Resource.prototype.post||c.update,h=c.hasOwnProperty("put"),S=c.hasOwnProperty("get"),p=c.hasOwnProperty("delete"),g="/"+s+"/";E&&(t.paths[g]={},t.paths[g].post=new Zee(s,r,"create a new record auto-assigning a primary key")),S&&(t.paths[g]||(t.paths[g]={}),t.paths[g].get=new $g(_,r,{200:new Yg({$ref:Xf+s})},"search for records by the specified property name and value")),p&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new h0(_,r,"delete all the records that match the provided query",{204:new E0})),g="/"+s+"/{"+o+"}",S&&(t.paths[g]={},t.paths[g].get=new $g([d],r,{200:new Yg({$ref:Xf+s})},"retrieve a record by its primary key")),h&&(t.paths[g]||(t.paths[g]={}),t.paths[g].put=new ete([d],r,s,"create or update the record with the URL path that maps to the record's primary key")),p&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new h0([d],r,"delete a record with the given primary key",{204:new E0})),S&&f.schema.enum.length>0&&(g="/"+s+"/{"+o+"}.{property}",t.paths[g]={},t.paths[g].get=new $g([d,f],r,{200:new Yg({enum:l})},"used to retrieve the specified property of the specified record"))}return t}function Zee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Xf+e}}}},this.security=t,this.responses={200:{description:Wg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function $g(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Yg(e){this.description=Wg,this.content={"application/json":{schema:e}}}function E0(){this.description="successfully processed request, no content returned to client"}function ete(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Xf+r}}}},this.responses={200:{description:Wg}}}function h0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function tte(e){this.type="object",this.properties=e}function m0(e,t){this.type=e,this.format=t}function Kg(e,t,r){this.name=e,this.in=t,this.schema=r}var p0,jee,f0,Xf,Wg,T0=Re(()=>{p0=B(Zd()),jee="3.0.3",f0={ID:"string",Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",Any:"string",BigInt:"integer"},Xf="#/components/schemas/",Wg="successful operation";a(S0,"generateJsonApi");a(Zee,"Post");a($g,"Get");a(Yg,"Response200");a(E0,"Response204");a(ete,"Put");a(h0,"Delete");a(tte,"ResourceSchema");a(m0,"Type");a(Kg,"Parameter")});var Zf={};qe(Zf,{start:()=>ste});async function nte(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&__(e);let s=new Si;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==g0){let h=jf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Xe(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=Ro(r["content-type"],!0)(e.body)}catch(h){throw new ll.ClientError(h,400)}if(e.authorize=!0,i===g0&&n==="GET")return S0(jf);switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new ll.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new ll.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,Qg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){rte[0]=d;let h=String.fromCharCode(34,($t[0]&63)+62,($t[0]>>6)+($t[1]<<2&63)+62,($t[1]>>4)+($t[2]<<4&63)+62,($t[2]>>2)+62,($t[3]&63)+62,($t[3]>>6)+($t[4]<<2&63)+62,($t[4]>>4)+($t[5]<<4&63)+62,($t[5]>>2)+62,($t[6]&63)+62,($t[6]>>6)+($t[7]<<2&63)+62,34),S=r["if-none-match"];S&&h==S?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),Qg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let f={status:l,headers:s,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=Jf(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?Ao.warn(i):Ao.info(i):Ao.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Jf(i.contentType?i:i.toString(),e,o),o}}function ste(e){Qg=e,!R0&&(R0=!0,jf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return nte(t,r)}),e.server.ws(async(t,r,n)=>{ul++;let s=new An;A0||(A0=!0,eu(l=>{ul>0&&l.push({metric:"ws-connections",connections:ul,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ao.warn(l)});let o;t.on("message",a(function(d){o||(o=Ro(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{ul--,un(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=jf.getMatch(u);if(un(!!_,"connection","ws","connect"),!_)t.send(Ti(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Gr(h=>({count:h.count,total:ul}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Xe(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ti(E.value,r);t.send(h),Gr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var Ao,ll,$t,rte,Qg,g0,R0,jf,A0,ul,O0=Re(()=>{Ia();Ns();Ao=B(Y()),ll=B(Z());d_();uc();Ui();Nf();T0();$t=new Uint8Array(8),rte=new Float64Array($t.buffer,0,1),Qg={},g0="openapi";a(nte,"http");ul=0;a(ste,"start")});var zg=T((Ehe,b0)=>{var{recordAction:eE,recordActionBinary:ite}=(Ns(),ee(tu)),ote=require("fastify-plugin"),ate=200;b0.exports=ote(function(e,t,r){e.addHook("onResponse",async(n,s)=>{s.getResponseTime()}),e.addHook("onSend",async(n,s,i)=>{let o=s.getResponseTime(),c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),eE(o,"duration",_,d,l),ite(s.raw.statusCode<400,"success",_,d,l);let f=ate;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{eE(performance.now()-c,"transfer",_,d,l),eE(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,eE(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Zg=T((hhe,C0)=>{var iE=require("clone"),oE=rt(),cte=J(),nE=M(),ute=Y(),tE=require("fs"),Jg=require("joi"),{string:sE}=Jg.types(),{hdb_errors:lte,handleHDBError:_l}=Z(),{HDB_ERROR_MSGS:_te,HTTP_STATUS_CODES:rE}=lte,{common_validators:Pa}=Yn(),N0=1e9,y0=" is required",dte=["insert","update","upsert"],Xg={database:{presence:!1,format:Pa.schema_format,length:Pa.schema_length},schema:{presence:!1,format:Pa.schema_format,length:Pa.schema_length},table:{presence:!0,format:Pa.schema_format,length:Pa.schema_length},action:{inclusion:{within:dte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},fte={schema:sE.required(),table:sE.required(),action:sE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Ete,AWS_SECRET:hte,AWS_BUCKET:mte,AWS_FILE_KEY:pte,REGION:Ste}=nE.S3_BUCKET_AUTH_KEYS,Tte={s3:{presence:!0},[`s3.${Ete}`]:{presence:!0,type:"String"},[`s3.${hte}`]:{presence:!0,type:"String"},[`s3.${mte}`]:{presence:!0,type:"String"},[`s3.${pte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Ste}`]:{presence:!0,type:"String"}},I0=iE(Xg);I0.data.presence={message:y0};var w0=iE(Xg);w0.file_path.presence={message:y0};var gte=Object.assign(iE(Xg),Tte),jg=iE(fte);jg.csv_url=sE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();jg.passthrough_headers=Jg.object();function Rte(e){let t=oE.validateObject(e,I0);return aE(e,t)}a(Rte,"dataObject");function Ate(e){let t=oE.validateBySchema(e,Jg.object(jg));return aE(e,t)}a(Ate,"urlObject");function Ote(e){let t=oE.validateObject(e,w0);return aE(e,t)}a(Ote,"fileObject");function bte(e){let t=oE.validateObject(e,gte);return aE(e,t)}a(bte,"s3FileObject");function aE(e,t){if(!t){let r=cte.checkGlobalSchemaTable(e.schema,e.table);if(r)return _l(new Error,r,rE.BAD_REQUEST);if(e.operation===nE.OPERATIONS_ENUM.CSV_FILE_LOAD){try{tE.accessSync(e.file_path,tE.constants.R_OK|tE.constants.F_OK)}catch(n){return n.code===nE.NODE_ERROR_CODES.ENOENT?_l(n,`No such file or directory ${n.path}`,rE.BAD_REQUEST):n.code===nE.NODE_ERROR_CODES.EACCES?_l(n,`Permission denied ${n.path}`,rE.BAD_REQUEST):_l(n)}try{let n=tE.statSync(e.file_path).size;if(n>N0)return _l(new Error,_te.MAX_FILE_SIZE_ERR(n,N0),rE.BAD_REQUEST)}catch(n){ute.error(n),console.error(n)}}}return t}a(aE,"postValidateChecks");C0.exports={dataObject:Rte,urlObject:Ate,fileObject:Ote,s3FileObject:bte}});var eR=T((phe,D0)=>{"use strict";var dl=Y(),cE=M();async function Nte(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===cE.OPERATIONS_ENUM.INSERT||t.operation===cE.OPERATIONS_ENUM.UPDATE||t.operation===cE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===cE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(dl.info(i.message),i):i.http_resp_msg?(dl.error(`Error calling operation: ${e.name}`),dl.error(i.http_resp_msg),i):(dl.error(`Error calling operation: ${e.name}`),dl.error(i),i)}}a(Nte,"callOperationFunctionAsAwait");D0.exports={callOperationFunctionAsAwait:Nte}});var M0=T((The,L0)=>{"use strict";var tR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},rR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};L0.exports={BulkLoadFileObject:tR,BulkLoadDataObject:rR}});var P0=T((Rhe,U0)=>{"use strict";var nR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};U0.exports=nR});var uR=T((Ihe,X0)=>{"use strict";var uE=on(),_E=Zg(),yte=require("needle"),Hn=M(),Ohe=nt(),va=J(),{handleHDBError:at,hdb_errors:V0}=Z(),{HTTP_STATUS_CODES:Yt,HDB_ERROR_MSGS:Ct,CHECK_LOGS_WRAPPER:bo}=V0,Ba=Y(),sR=require("papaparse");va.promisifyPapaParse();var xn=require("fs-extra"),Ite=require("path"),{chain:v0}=require("stream-chain"),B0=require("stream-json/streamers/StreamArray"),H0=require("stream-json/utils/Batch"),x0=require("stream-chain/utils/comp"),{finished:F0}=require("stream"),wte=j(),$0=eR(),Cte=vg(),{BulkLoadFileObject:oR,BulkLoadDataObject:Dte}=M0(),aR=Ng(),{verifyBulkLoadAttributePerms:Y0}=$f(),bhe=P0(),Nhe=yt(),yhe=bs(),{databases:Lte}=(Oe(),ee(Ge)),{coerceType:Mte}=(Td(),ee(iS)),q0="No records parsed from csv file.",Oo=`${wte.get("HDB_ROOT")}/tmp`,{schema_regex:Ute}=Yn(),G0=1024*1024*2,k0=5e3,Pte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};X0.exports={csvDataLoad:vte,csvURLLoad:Bte,csvFileLoad:Hte,importFromS3:xte};async function vte(e,t){let r=_E.dataObject(e);if(r)throw at(r,r.message,Yt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=Q0(e.schema,e.table),i=sR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:iR.bind(null,s),dynamicTyping:!1}),o=new aR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&Y0(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 at(new Error,c,Yt.BAD_REQUEST,void 0,void 0,!0);let u=new Dte(e.action,e.schema,e.table,i.data);return n=await $0.callOperationFunctionAsAwait(z0,u,null),n.message===q0?q0:J0(n.records,n.number_written)}catch(s){throw No(s)}}a(vte,"csvDataLoad");async function Bte(e){let t=_E.urlObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Oo}/${r}`;try{await Fte(e,r)}catch(s){throw Ba.error(Ct.DOWNLOAD_FILE_ERR(r)+" - "+s),at(s,bo(Ct.DOWNLOAD_FILE_ERR(r)))}try{let s=new oR(this.job_operation_function.name,e.action,e.schema,e.table,n,Hn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await cR(s);return await lE(n),i}catch(s){throw await lE(n),No(s)}}a(Bte,"csvURLLoad");async function Hte(e){let t=_E.fileObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r=new oR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Hn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await cR(r)}catch(n){throw No(n)}}a(Hte,"csvFileLoad");async function xte(e){let t=_E.s3FileObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Ite.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Oo}/${s}`;let i=new oR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await qte(s,e);let o=await cR(i);return await lE(r),o}catch(n){throw await lE(r),No(n)}}a(xte,"importFromS3");async function Fte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await yte("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw at(n,s,n.statusCode,Hn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}kte(r,e.csv_url),await Gte(t,r.raw)}a(Fte,"downloadCSVFile");async function qte(e,t){try{let r=`${Oo}/${e}`;await xn.mkdirp(Oo),await xn.writeFile(`${Oo}/${e}`,"",{flag:"a+"});let n=await xn.createWriteStream(r),s=await Cte.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){Ba.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ba.error(Ct.S3_DOWNLOAD_ERR+" - "+r),at(r,bo(Ct.S3_DOWNLOAD_ERR))}}a(qte,"downloadFileFromS3");async function Gte(e,t){try{await xn.mkdirp(Oo),await xn.writeFile(`${Oo}/${e}`,t)}catch(r){throw Ba.error(Ct.WRITE_TEMP_FILE_ERR),at(r,bo(Ct.DEFAULT_BULK_LOAD_ERR))}}a(Gte,"writeFileToTempFolder");async function lE(e){if(e)try{await xn.access(e),await xn.unlink(e)}catch{Ba.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(lE,"deleteTempFile");function kte(e,t){if(e.statusCode!==V0.HTTP_STATUS_CODES.OK)throw at(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Yt.BAD_REQUEST);if(!Pte[e.headers["content-type"]])throw at(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Yt.BAD_REQUEST);if(!e.raw)throw at(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Yt.BAD_REQUEST)}a(kte,"validateURLResponse");async function cR(e){try{let t;switch(e.file_type){case Hn.VALID_S3_FILE_TYPES.CSV:t=await Vte(e);break;case Hn.VALID_S3_FILE_TYPES.JSON:t=await $te(e);break;default:throw at(new Error,Ct.DEFAULT_BULK_LOAD_ERR,Yt.BAD_REQUEST,Hn.LOG_LEVELS.ERROR,Ct.INVALID_FILE_EXT_ERR(e))}return J0(t.records,t.number_written)}catch(t){throw No(t)}}a(cR,"fileLoad");async function K0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await uE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&Y0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=at(c);r(u)}}a(K0,"validateChunk");async function W0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;va.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!va.isEmpty(c)&&!va.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await $0.callOperationFunctionAsAwait(z0,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=at(c,bo(Ct.INSERT_CSV_ERR),Yt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Ct.INSERT_CSV_ERR+" - "+c);r(u)}}a(W0,"insertChunk");async function Vte(e){let t={records:0,number_written:0},r=Q0(e.schema,e.table);try{let n=new aR,s=xn.createReadStream(e.file_path,{highWaterMark:G0});s.setEncoding("utf8"),await sR.parsePromise(s,K0.bind(null,e,n),iR.bind(null,r));let i=n.getPermsResponse();if(i)throw at(new Error,i,Yt.BAD_REQUEST);return s=xn.createReadStream(e.file_path,{highWaterMark:G0}),s.setEncoding("utf8"),await sR.parsePromise(s,W0.bind(null,e,t),iR.bind(null,r)),s.destroy(),t}catch(n){throw at(n,bo(Ct.PAPA_PARSE_ERR),Yt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Ct.PAPA_PARSE_ERR+n)}}a(Vte,"callPapaParse");function Q0(e,t){let r=Lte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Mte(i,s));return n}a(Q0,"createTransformMap");function iR(e,t,r){let n=e.get(r);return n?n(t):va.autoCast(t)}a(iR,"typeFunction");async function $te(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new aR,s=v0([xn.createReadStream(e.file_path,{encoding:"utf-8"}),B0.withParser(),c=>c.value,new H0({batchSize:k0}),x0(async c=>{await K0(e,n,r,c)})]);await new Promise((c,u)=>{F0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw at(new Error,i,Yt.BAD_REQUEST);let o=v0([xn.createReadStream(e.file_path,{encoding:"utf-8"}),B0.withParser(),c=>c.value,new H0({batchSize:k0}),x0(async c=>{await W0(e,t,r,c)})]);return await new Promise((c,u)=>{F0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw at(n,bo(Ct.INSERT_JSON_ERR),Yt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Ct.INSERT_JSON_ERR+n)}}a($te,"insertJson");async function z0(e){let t={};try{e.data&&e.data.length>0&&Yte(e.data[0])?t=await Kte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ba.info(t.message))}catch(r){throw No(r)}return t}a(z0,"callBulkFileLoad");function Yte(e){let t=Object.keys(e);for(let r of t)if(!Ute.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Yte,"validateColumnNames");async function Kte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=uE.insert;break;case"update":i=uE.update;break;case"upsert":i=uE.upsert;break;default:throw at(new Error,Ct.INVALID_ACTION_PARAM_ERR(n),Yt.BAD_REQUEST,Hn.LOG_LEVELS.ERROR,Ct.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=va.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw No(o)}}a(Kte,"bulkFileLoad");function J0(e,t){return`successfully loaded ${t} of ${e} records`}a(J0,"buildResponseMsg");function No(e){return at(e,bo(Ct.DEFAULT_BULK_LOAD_ERR),Yt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Ct.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(No,"buildTopLevelErrMsg")});var Z0=T((Che,j0)=>{"use strict";var lR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};j0.exports=lR});var rB=T((Lhe,tB)=>{"use strict";var Wte=M(),eB=require("moment"),Qte=require("uuid").v4,_R=class{static{a(this,"JobObject")}constructor(){this.id=Qte(),this.type=void 0,this.start_datetime=eB().valueOf(),this.created_datetime=eB().valueOf(),this.end_datetime=void 0,this.status=Wte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};tB.exports=_R});var dR=T((Uhe,cB)=>{"use strict";var zte=require("uuid").v4,iB=on(),oB=sn(),Jte=Wn(),Xte=jo(),jte=Z0(),ct=M(),Zte=rB(),ere=eT(),Tn=Y(),tre=yc(),Ha=J(),{promisify:rre}=require("util"),yo=require("moment"),nre=Kf(),dE=Zg(),nB=Op(),{deleteTransactionLogsBeforeValidator:sre}=gg(),{handleHDBError:ire,hdb_errors:ore}=Z(),{HTTP_STATUS_CODES:are}=ore,sB=oB.searchByValue,cre=oB.searchByHash,ure=iB.insert,lre=rre(nre.evaluateSQL),_re=iB.update;cB.exports={addJob:Ere,updateJob:mre,handleGetJob:dre,handleGetJobsByStartDate:fre,getJobById:aB};async function dre(e){try{let t=await aB(e.id);return Ha.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 Tn.error("There was an error getting job",t),new Error(r)}}a(dre,"handleGetJob");async function fre(e){try{let t=await hre(e);if(Tn.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=yo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=yo(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 Tn.error(r),new Error(r)}}a(fre,"handleGetJobsByStartDate");async function Ere(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ha.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Tn.info(l),t.error=l,t}if(!ct.JOB_TYPE_ENUM[e.operation])return Tn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case ct.OPERATIONS_ENUM.CSV_FILE_LOAD:n=dE.fileObject(e);break;case ct.OPERATIONS_ENUM.CSV_URL_LOAD:n=dE.urlObject(e);break;case ct.OPERATIONS_ENUM.CSV_DATA_LOAD:n=dE.dataObject(e);break;case ct.OPERATIONS_ENUM.IMPORT_FROM_S3:n=dE.s3FileObject(e);break;case ct.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ct.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=nB(e,"date");break;case ct.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=nB(e,"timestamp");break;case ct.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=sre(e);break;default:break}if(n)throw ire(n,n.message,are.BAD_REQUEST,void 0,void 0,!0);let s=new Zte;s.type=e.operation===ct.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ct.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new Jte(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await sB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Tn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=zte();try{o=await sB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Tn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Tn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new tre(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await ure(u)}catch(l){return Tn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,Tn.trace(l)}return t}a(Ere,"addJob");async function hre(e){let t=yo(e.from_date,yo.ISO_8601),r=yo(e.to_date,yo.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 n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new jte(n,e.hdb_user);try{return await lre(s)}catch(i){throw Tn.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(hre,"getJobsInDateRange");async function aB(e){if(Ha.isEmptyOrZeroLength(e))return Ha.errorizeMessage("Invalid job ID specified.");let t=new Xte(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await cre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Tn.error(n),Ha.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(aB,"getJobById");async function mre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ha.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ct.JOB_STATUS_ENUM.COMPLETE||e.status===ct.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=yo().valueOf());let t=new ere(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await _re(t),r}a(mre,"updateJob")});var EB=T((vhe,fB)=>{"use strict";var uB=J(),Rr=M(),pre=require("moment"),fE=uR(),EE=Y(),lB=dR(),_B=Wf(),dB=Ki(),Sre=tt(),Tre=qf(),fR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function gre(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(uB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(uB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Rr.JOB_TYPE_ENUM.csv_file_load:await Bs(e,fE.csvFileLoad);break;case Rr.JOB_TYPE_ENUM.csv_url_load:await Bs(e,fE.csvURLLoad);break;case Rr.JOB_TYPE_ENUM.csv_data_load:await Bs(e,fE.csvDataLoad);break;case Rr.JOB_TYPE_ENUM.import_from_s3:await Bs(e,fE.importFromS3);break;case Rr.JOB_TYPE_ENUM.empty_trash:break;case Rr.JOB_TYPE_ENUM.export_local:await Bs(e,_B.export_local);break;case Rr.JOB_TYPE_ENUM.export_to_s3:await Bs(e,_B.export_to_s3);break;case Rr.JOB_TYPE_ENUM.delete_files_before:case Rr.JOB_TYPE_ENUM.delete_records_before:await Bs(e,dB.deleteFilesBefore);break;case Rr.JOB_TYPE_ENUM.delete_audit_logs_before:await Bs(e,dB.deleteAuditLogsBefore);break;case Rr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Bs(e,Tre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(gre,"parseMessage");async function Bs(e,t){try{e.job.status=Rr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=pre().valueOf(),await lB.updateJob(e.job),await Rre(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):EE.error(`There was an error running ${t.name} job with id ${e.job.id}`),EE.error(n),e.job.message=n,e.job.status=Rr.JOB_STATUS_ENUM.ERROR;try{await lB.updateJob(e.job)}catch(s){throw EE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Bs,"runJob");async function Rre(e){EE.trace("launching job thread:",e),Sre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Rr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Rre,"launchJobThread");fB.exports={parseMessage:gre,RunnerMessage:fR}});var mB=T((Hhe,hB)=>{"use strict";var ER=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};hB.exports=ER});var UB=T((Fhe,gR)=>{"use strict";var SE=sn(),pR=Kf(),hE=uR(),Hs=Gd(),mE=Gi(),El=Ki(),Are=FS(),fl=cn(),pE=QS(),Kt=Tg(),Dt=Y(),Ore=XS(),bre=sf(),pB=UT(),Nre=af(),yre=PT(),Ire=vT(),wre=xT(),Cre=qT(),hR=VT(),SB=Wf(),Dre=$f(),SR=dR(),F=M(),{hdb_errors:ml,handleHDBError:hl}=Z(),{HTTP_STATUS_CODES:TB}=ml,mR=QT(),gB=bf(),CB=require("util"),xa=on(),Lre=ti(),Mre=ga(),RB=EB(),AB=Cu(),OB=(Cf(),ee(Qu)),bB=xr(),NB=qf(),yB=Pf(),{setServerUtilities:Ure}=(Td(),ee(iS)),{CONTEXT:Pre}=(On(),ee(Vh)),{_assignPackageExport:vre}=require("../index"),{transformReq:Bre}=J(),{server:Hre}=(Zt(),ee(yi)),xre=eR(),IB=SE.searchByHash,Fre=SE.searchByValue,qre=CB.promisify(SE.search),Gre=CB.promisify(pR.evaluateSQL),kre={[F.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.CREATE_TABLE]:!0,[F.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[F.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.DROP_TABLE]:!0,[F.OPERATIONS_ENUM.DROP_SCHEMA]:!0},V=mB();async function DB(e,t){try{if(e.body.operation!=="read_log"&&(Dt.log_level===F.LOG_LEVELS.INFO||Dt.log_level===F.LOG_LEVELS.DEBUG||Dt.log_level===F.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;Dt.info(o)}}catch(n){Dt.error(n)}let r=await xre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return kre[e.body.operation]&&Lre.setSchemaDataToGlobal(n=>{n&&Dt.error(n)}),r}a(DB,"processLocalTransaction");var wB=$re();gR.exports={chooseOperation:LB,getOperationFunction:MB,operation:TR,processLocalTransaction:DB};Ure(gR.exports);Hre.operation=TR;function LB(e){let t;try{t=MB(e)}catch(s){throw Dt.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=pR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=pR.checkASTPermissions(e,i);if(o)throw Dt.error(`${TB.FORBIDDEN} from operation ${e.operation}`),Dt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),hl(new Error,o,ml.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==F.OPERATIONS_ENUM.LOGIN&&e.operation!==F.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Dre.verifyPerms(i,s);if(o)throw Dt.error(`${TB.FORBIDDEN} from operation ${e.operation}`),Dt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),hl(new Error,o,ml.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw hl(s,"There was an error when trying to choose an operation path")}return r}a(LB,"chooseOperation");function MB(e){if(Dt.trace(`getOperationFunction with operation: ${e.operation}`),wB.has(e.operation))return wB.get(e.operation);throw hl(new Error,ml.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),ml.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(MB,"getOperationFunction");vre("operation",TR);function TR(e,t){e.hdb_user=this[Pre]?.user,e.bypass_auth=!t;let r=LB(e);return DB({body:e},r)}a(TR,"operation");async function Vre(e){Dt.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await xa.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await xa.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await xa.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await El.deleteRecord(i);break;default:Dt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Dt.info("Invalid operation in transaction"),Dt.error(o)}}a(Vre,"catchup");async function as(e){Bre(e);let t,r;try{r=await SR.addJob(e),t=r.createdJob,Dt.info("addJob result",r);let n=new RB.RunnerMessage(t,e);return await RB.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw Dt.error(s),hl(n,s)}}a(as,"executeJob");function $re(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new V(xa.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new V(xa.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new V(xa.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new V(SE.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new V(IB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new V(IB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new V(Fre)),e.set(F.OPERATIONS_ENUM.SEARCH,new V(qre)),e.set(F.OPERATIONS_ENUM.SQL,new V(Gre)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new V(as,hE.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new V(as,hE.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new V(as,hE.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new V(as,hE.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new V(Hs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new V(Hs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new V(Hs.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new V(Hs.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new V(Hs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new V(Hs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new V(Hs.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new V(Hs.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new V(mE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new V(mE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new V(mE.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new V(mE.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new V(El.deleteRecord)),e.set(F.OPERATIONS_ENUM.ADD_USER,new V(fl.addUser)),e.set(F.OPERATIONS_ENUM.ALTER_USER,new V(fl.alterUser)),e.set(F.OPERATIONS_ENUM.DROP_USER,new V(fl.dropUser)),e.set(F.OPERATIONS_ENUM.LIST_USERS,new V(fl.listUsersExternal)),e.set(F.OPERATIONS_ENUM.LIST_ROLES,new V(pE.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new V(pE.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new V(pE.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new V(pE.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new V(fl.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new V(Ore)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new V(bre)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new V(pB)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new V(pB)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new V(Nre)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new V(yre)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new V(Ire)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new V(bB.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new V(wre.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new V(Cre)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new V(hR.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new V(hR.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new V(hR.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new V(as,SB.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new V(as,El.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new V(as,El.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new V(as,SB.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new V(SR.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new V(SR.handleGetJob)),e.set(F.OPERATIONS_ENUM.GET_FINGERPRINT,new V(mR.getFingerprint)),e.set(F.OPERATIONS_ENUM.SET_LICENSE,new V(mR.setLicense)),e.set(F.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new V(mR.getRegistrationInfo)),e.set(F.OPERATIONS_ENUM.RESTART,new V(gB.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new V(gB.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new V(Vre)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new V(Mre.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new V(as,El.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new V(Are)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new V(AB.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new V(AB.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new V(OB.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new V(OB.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new V(bB.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new V(Kt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new V(Kt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new V(Kt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new V(Kt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new V(Kt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new V(Kt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new V(Kt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new V(Kt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new V(Kt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new V(Kt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new V(Kt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new V(Kt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new V(Kt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new V(Kt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new V(Kt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new V(Kt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new V(NB.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new V(as,NB.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new V(yB.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new V(yB.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new V(Hs.getBackup)),e}a($re,"initializeOperationFunctionMap")});var gE=T((Ghe,BB)=>{"use strict";var RR=M(),Yre=J(),pl=Y(),{handleHDBError:AR,hdb_errors:TE}=Z(),{isMainThread:Kre}=require("worker_threads"),{Readable:Wre}=require("stream"),PB=require("os"),Qre=require("util"),zre=cT(),Jre=Qre.promisify(zre.authorize),vB=UB(),{createGzip:Xre,constants:jre}=require("zlib");function Zre(e){let t=`Found an uncaught exception with message: ${e.message}. ${PB.EOL}Stack: ${e.stack} ${PB.EOL}Terminating ${Kre?"HDB":"thread"}.`;console.error(t),pl.fatal(t),process.exit(1)}a(Zre,"handleServerUncaughtException");function ene(e,t,r){if(pl[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 n=e.statusCode?e.statusCode:TE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(ene,"serverErrorHandler");function tne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=AR(new Error,"Invalid JSON.",TE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Yre.isEmpty(e.body.operation)){let n=AR(new Error,"Request body must include an 'operation' property.",TE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(tne,"reqBodyValidationHandler");function rne(e,t,r){let n;e.body.operation!==RR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==RR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==RR.OPERATIONS_ENUM.LOGOUT?Jre(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{pl.warn(s),pl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(AR(s,i,TE.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(rne,"authHandler");async function nne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=vB.chooseOperation(e.body);let s=await vB.processLocalTransaction(e,n);if(s instanceof Wre&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(Xre({level:jre.Z_BEST_SPEED})))}return s}catch(s){throw pl.error(s),s}}a(nne,"handlePostRequest");BB.exports={authHandler:rne,handlePostRequest:nne,handleServerUncaughtException:Zre,serverErrorHandler:ene,reqBodyValidationHandler:tne}});var qB=T((Vhe,FB)=>{"use strict";var sne=require("fastify-plugin"),{handlePostRequest:HB,authHandler:ine,reqBodyValidationHandler:one}=gE();async function ane(e){e.decorate("hdbCore",{preValidation:[one,ine],request:t=>xB(HB(t,response)),requestWithoutAuthentication:(t,r)=>xB(HB(t,r,!0))})}a(ane,"hdbCore");async function xB(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(xB,"convertAsyncIterators");FB.exports=sne(ane)});var VB=T((Khe,kB)=>{"use strict";var Yhe=require("fs"),OR=j();OR.initSync();var{CONFIG_PARAMS:GB}=M(),cne=1024*1024*1024;function une(e){let t=OR.get(GB.HTTP_TIMEOUT),r=OR.get(GB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:cne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(une,"getServerOptions");kB.exports=une});var KB=T((Qhe,YB)=>{"use strict";var bR=j();bR.initSync();var{CONFIG_PARAMS:$B}=M();function lne(){let e=bR.get($B.HTTP_CORSACCESSLIST),t=bR.get($B.HTTP_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=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(lne,"getCORSOptions");YB.exports=lne});var zB=T((Jhe,QB)=>{"use strict";var WB=j();WB.initSync();var _ne=M();function dne(){return WB.get(_ne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(dne,"getHeaderTimeoutConfig");QB.exports=dne});var yR={};qe(yR,{customFunctionsServer:()=>hne,ready:()=>lH,start:()=>Ene});function Ene(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){xs||(xs=uH(t),ut.http((await xs).server));let o=await xs,c=(0,NR.dirname)(s),u=(0,NR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!JB.has(c)){JB.add(c);try{o.register(pne(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:lH}}async function hne(){try{Ve.info("In Custom Functions Fastify server"+process.cwd()),Ve.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ve.debug(`Custom Functions server process ${process.pid} starting up.`),await mne();let e=rH.get(nH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=xs=await uH(e)}catch(r){throw Ve.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ve.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ve.error(`Custom Functions ${process.pid} Error: ${e}`),Ve.error(e),process.exit(1)}}async function mne(){try{Ve.info("Custom Functions starting configuration."),await sH.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function pne(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,XB.existsSync)(e)&&r.register(tH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ve.error(s.message):s&&Ve.error(s),o()})}catch(n){Ve.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function uH(e){Ve.info("Custom Functions starting buildServer.");let t=(0,iH.default)(e),r=(0,jB.default)(t);r.server.headersTimeout=(0,aH.default)(),r.setErrorHandler(cH.serverErrorHandler);let n=(0,oH.default)();return n&&r.register(ZB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(eH.default),await r.register(fne),await r.after(),Vg(r),Ve.info("Custom Functions completed buildServer."),r}function lH(){if(xs)return xs.then?xs.then(e=>e.ready()):xs.ready()}var NR,XB,jB,ZB,eH,tH,rH,nH,Ve,fne,sH,iH,oH,aH,cH,xs,JB,_H=Re(()=>{NR=require("path"),XB=require("fs"),jB=B(require("fastify")),ZB=B(require("@fastify/cors")),eH=B(zg()),tH=B(require("@fastify/autoload")),rH=B(j()),nH=B(M()),Ve=B(Y()),fne=B(qB()),sH=B(cn()),iH=B(VB()),oH=B(KB()),aH=B(zB()),cH=B(gE());Ia();Zt();JB=new Set;a(Ene,"start");a(hne,"customFunctionsServer");a(mne,"setUp");a(pne,"buildRouteFolder");a(uH,"buildServer");a(lH,"ready")});var IR={};qe(IR,{start:()=>Sne});function Sne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,mH.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){fH||(fH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=dH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,EH.default)(s,(0,hH.realpathSync)(o))}}return i(s)},{runFirst:!0})),dH.set(r,n)}}}var EH,hH,mH,dH,fH,pH=Re(()=>{EH=B(require("send")),hH=require("fs"),mH=B(require("serve-static")),dH=new Map;a(Sne,"start")});var LR={};qe(LR,{Request:()=>wR,createReuseportFd:()=>RE});var SH,wR,CR,DR,RE,AE=Re(()=>{SH=require("os"),wR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new DR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get body(){return this.#e||(this.#e=new CR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},CR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},DR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,SH.platform)()!="win32"&&(RE=require("node-unix-socket").createReuseportFd)});var AH=T((cme,RH)=>{"use strict";var Tne=require("cluster"),Io=j();Io.initSync();var gH=M(),nme=require("util"),Fs=Y(),sme=require("fs"),gne=require("fastify"),ime=pu(),Rne=require("@fastify/cors"),Ane=require("@fastify/compress"),One=require("@fastify/static"),bne=zg(),Nne=require("path"),{PACKAGE_ROOT:yne}=M(),Ine=ti(),wne=J(),Cne=cn(),Dne=Ji(),{server:Lne}=(Zt(),ee(yi)),{node_request_key:ome}=(AE(),ee(LR)),{authHandler:Mne,handlePostRequest:Une,serverErrorHandler:Pne,reqBodyValidationHandler:vne}=gE(),ame=require("net"),{registerContentHandlers:Bne}=(Ia(),ee(d0)),Hne=6e4,xne=1024*1024*1024,Fne="TRUE",{CONFIG_PARAMS:Sl}=gH,Fa;RH.exports={hdbServer:TH,start:TH};async function TH(e){try{Fs.info("In Fastify server"+process.cwd()),Fs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Fs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Tne.isMaster,await qne();let t=e.securePort>0;Fa=Gne(t),await Fa.ready(),e||(e={}),e.isOperationsServer=!0;try{Lne.http(Fa.server,e),Fa.server.closeIdleConnections||await Fa.listen({port:0,host:"::"})}catch(r){throw Fa.close(),Fs.error(r),Fs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Fs.fatal(t),process.exit(1)}}a(TH,"operationsServer");async function qne(){Fs.trace("Configuring HarperDB process."),Ine.setSchemaDataToGlobal(),await Cne.setUsersToGlobal(),await Dne.getLicense()}a(qne,"setUp");function Gne(e){Fs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=kne(e),r=gne(t);r.server.headersTimeout=$ne(),r.setErrorHandler(Pne);let n=Vne();n&&r.register(Rne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(bne),r.register(Ane),r.register(One,{root:Nne.join(yne,"studio/build-local")}),Bne(r);let s=Io.get(gH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!wne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[vne,Mne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Une(i,o)}),r.get("/health",()=>"HarperDB is running."),Fs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Gne,"buildServer");function kne(e){let t=Io.get(Sl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Io.get(Sl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:xne,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(kne,"getServerOptions");function Vne(){let e=Io.get(Sl.OPERATIONSAPI_NETWORK_CORS),t=Io.get(Sl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Fne)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(Vne,"getCORSOpts");function $ne(){return Io.get(Sl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Hne}a($ne,"getHeaderTimeoutConfig")});var MH=T((fme,LH)=>{"use strict";var{decode:Yne}=require("msgpackr"),{isMainThread:lme,parentPort:Kne,threadId:_me}=require("worker_threads"),UR=yt(),qs=nt(),Wne=M(),Ai=Y(),OH=j(),NH=M();tt();var Qne=bs(),{recordAction:zne,recordActionBinary:Jne}=(Ns(),ee(tu)),{publishToStream:Xne}=UR,{ConsumerEvents:jne}=require("nats"),dme={durable:qs.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:qs.WORK_QUEUE_CONSUMER_NAMES.deliver_group},Zne,ese,tse,yH,IH;LH.exports={initialize:PR,workQueueListener:DH,setSubscription:rse,setIgnoreOrigin:sse,getDatabaseSubscriptions:nse};async function PR(){IH=!0,Ai.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await UR.getNATSReferences();Zne=e,ese=e.info.server_name,tse=t,yH=r}a(PR,"initialize");var bE=new Map;function rse(e,t,r){let n=bE.get(e);n||bE.set(e,n=new Map),n.set(t,r),IH||PR().then(DH)}a(rse,"setSubscription");function nse(){return bE}a(nse,"getDatabaseSubscriptions");var wH;function sse(e){wH=e}a(sse,"setIgnoreOrigin");var CH=100,bH=new Array(CH),OE=0;async function DH(){let e=await yH.consumers.get(qs.WORK_QUEUE_CONSUMER_NAMES.stream_name,qs.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(Kne?.on("message",async n=>{let{type:s}=n;s===NH.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let n of await r.status())if(n.type===jne.HeartbeatsMissed){let s=n.data;Ai.trace(`${s} clustering ingest consumer heartbeats missed`),s===2&&(Ai.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let n of r)await bH[OE],bH[OE]=ise(n).catch(s=>{Ai.error(s)}),++OE>=CH&&(OE=0)}catch(n){Ai.error("Error consuming clustering ingest, restarting consumer",n)}UR.clearClientCache(),await PR()}}a(DH,"workQueueListener");async function ise(e){let t=Yne(e.data);zne(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,n=!1,s=OH.get(Wne.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(qs.MSG_HEADERS.TRANSACTED_NODES)&&r.values(qs.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(qs.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!wH),Jne(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(qs.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Ai.trace("processing message:",o,c,_,(l?"records: "+l.map(b=>b?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Ai.trace(`messageProcessor nats msg id: ${e.headers.get(qs.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:S,user:p,node_name:g}=f||{},A=bE.get(c)?.get(_);if(!A)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,A.send(t);else if(l.length===1&&!u)A.send({type:MR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:S,table:_,onCommit:h,user:p,nodeName:g});else{let b=l.map((v,G)=>({type:MR(o),value:v,expiresAt:E,id:d?.[G],table:_}));for(;u;)b.push({type:MR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;A.send({type:"transaction",writes:b,table:_,timestamp:S,onCommit:h,user:p,nodeName:g})}OH.get(NH.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Xne(e.subject.split(".").slice(0,-1).join("."),Qne.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Ai.error(o)}e.ack()}a(ise,"messageProcessor");function MR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(MR,"convertOperation")});var qR={};qe(qR,{disableNATS:()=>ase,publishToStream:()=>CE,setNATSReplicator:()=>vR,setPublishToStream:()=>cse,setSubscription:()=>FR,start:()=>ose});function ose(){yE.default.get(IE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&lse()}function ase(e=!0){HH=e}function cse(e,t){CE=e,FR=t}function lse(){if(HH||process.env._DISABLE_NATS)return;let e=Cn(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];vR(s,r,i)}}lS((r,n)=>{vR(r.tableName,r.databaseName,r),n&&FH(r)}),!UH&&(UH=!0)}function vR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Ft{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Ce],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Ce]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Ce],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Ce],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Ce]})}static defineSchema(i){FH(i)}static subscribe(){let i=new An;return FR(t,e,i),i}static subscribeOnThisThread(i){return i<use}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new NE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=xH;return i}a(n,"getNATSTransaction")}function FH(e){let t=yE.default.get(IE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);CE(`${HR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,xR.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 PH,HR,xR,vH,BH,yE,IE,wE,HH,CE,FR,use,xH,UH,NE,BR,qH=Re(()=>{Oe();On();PH=B(yt()),HR=B(nt()),xR=B(bs());uc();vH=B(MH()),BH=B(Cr()),yE=B(j()),IE=B(M()),wE=B(Y());a(ose,"start");a(ase,"disableNATS");CE=PH.publishToStream,FR=vH.setSubscription;a(cse,"setPublishToStream");use=2;a(lse,"assignReplicationSource");a(vR,"setNATSReplicator");a(FH,"publishSchema");NE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=yE.default.get(IE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(wE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(CE(`${HR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,xR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw wE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},BR=class extends NE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,BH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};xH=new BR});var WR=T(Co=>{"use strict";var{isMainThread:_se,parentPort:Rl,threadId:Tl}=require("worker_threads"),{Socket:dse,createServer:fse}=require("net"),{createServer:Ese,IncomingMessage:hse}=require("http"),{createServer:mse}=require("https"),{readFileSync:qa,unlinkSync:GH,existsSync:pse}=require("fs"),Fn=Y(),$e=j(),Ar=M(),{server:ME}=(Zt(),ee(yi)),{WebSocketServer:Sse}=require("ws"),{createServer:Tse}=require("tls"),{getTicketKeys:gse,restartNumber:Rse,getWorkerIndex:kH}=tt(),{Headers:WH}=(Nf(),ee(BP)),{recordAction:gl,recordActionBinary:Ase}=(Ns(),ee(tu)),{Request:QH,createReuseportFd:VH}=(AE(),ee(LR)),{checkMemoryLimit:Ose}=Ji(),zH=require("tls"),$H=zH.createSecureContext;zH.createSecureContext=function(e){if(!e.cert||!e.key)return $H(e);let t={...e};delete t.key,delete t.cert;let r=$H(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){Rse<=1&&Fn.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:gme,CONFIG_PARAMS:bse}=Ar;$e.initSync();var Nse=$e.get(bse.HTTP_SESSIONAFFINITY),cs={};Co.registerServer=YR;Co.httpServer=KR;Co.deliverSocket=$R;Co.startServers=JH;Co.when_components_loaded=null;ME.http=KR;ME.request=Cse;ME.socket=Dse;ME.ws=Lse;var GR=[],DE=[],yse,wo={},LE={},Ise=[],kR=[];function JH(){return Co.when_components_loaded=UE().loadRootComponents(!0).then(()=>{Rl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)$R(n,r,s);else if(t.requestId)wse(t);else if(t.type===Ar.ITC_EVENT_TYPES.SHUTDOWN){Fn.trace("received shutdown request",Tl);for(let i in cs){let o=cs[i],c;o.closeIdleConnections&&(setInterval(()=>{o.closeIdleConnections()},25).unref(),setTimeout(()=>{o.closeAllConnections(),Fn.info("Closed all http connections",i,Tl)},4e3).unref()),o.close?.(()=>{if($e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&kH()==0)try{GH($e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,Tl),o.cantCleanupProperly||Fn.warn("Had to forcefully exit the thread",Tl),process.exit(0)},5e3).unref()})}if(process.env.DEV_MODE)try{require("inspector").close()}catch(i){console.error("Could not close debugger",i)}}}).ref();let e=[];if(VH&&!Nse)for(let t in cs){let r=cs[t];if(isNaN(t)&&kH()==0){pse(t)&&GH(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),Fn.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=VH(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),Fn.trace("Listening on port "+t,Tl)}).on("error",i)}))}Promise.all(e).then(()=>{Rl?.postMessage({type:Ar.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(JH,"startServers");_se||JH();function $R(e,t,r){let n=e?.read?e:new dse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=cs[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=cs[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Fn.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a($R,"deliverSocket");var YH=new Map;function wse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=YH.get(s),r){case"connection":i=$R(void 0,t),YH.set(s,i),i.write=(c,u,_)=>(Rl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Rl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Rl.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(wse,"proxyRequest");function YR(e,t,r=!0){!+t&&t!==$e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt($e.get(Ar.CONFIG_PARAMS.HTTP_PORT),10));let n=cs[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",KH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else cs[t]=e;e.on("unhandled",KH)}a(YR,"registerServer");function XH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],$e.get(Ar.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:$e.get(Ar.CONFIG_PARAMS.HTTP_PORT),secure:$e.get(Ar.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),$e.get(Ar.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:$e.get(Ar.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&$e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:$e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(XH,"getPorts");function KR(e,t){for(let{port:r,secure:n}of XH(t))jH(r,n,t?.isOperationsServer),typeof e=="function"?kR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,YR(e,r,!1)),LE[r]=VR(kR,r),yse=VR(Ise,r)}a(KR,"httpServer");function jH(e,t,r){if(!wo[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:$e.get(n+"_keepAliveTimeout"),headersTimeout:$e.get(n+"_headersTimeout"),requestTimeout:$e.get(n+"_timeout")},i=$e.get(n+"_mtls");if(t){n=r?"operationsApi_":"";let c=$e.get(n+"tls_privateKey"),u=$e.get(n+"tls_certificate"),_=$e.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:qa(c),ciphers:$e.get("tls_ciphers"),cert:qa(u),ca:_&&qa(_),requestCert:!!i,ticketKeys:gse()})}let o=Ose();wo[e]=(t?mse:Ese)(s,async(c,u)=>{try{let l=performance.now(),d=new QH(c,u);r&&(d.isOperationsServer=!0);let f=await LE[e](d);if(!f){if(d._nodeResponse.statusCode)return;f=ZH(d)}if(o?f.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):f.headers?.set?.("Server","HarperDB"),f.status===-1){for(let v of f.headers||[])u.setHeader(v[0],v[1]);return c.baseRequest=d,u.baseResponse=f,wo[e].emit("unhandled",c,u)}let E=f.status||200,h=performance.now(),S=h-l,p=f.body,g;if(!f.handlesHeaders){let v=f.headers||new WH;if(p?p.length>=0&&(typeof p=="string"?v.set("Content-Length",Buffer.byteLength(p)):v.set("Content-Length",p.length),g=!0):(v.set("Content-Length","0"),g=!0),v.append){let G=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(G+=", miss"),v.append("Server-Timing",G,!0)}u.writeHead(E,v&&(v[Symbol.iterator]?Array.from(v):v)),g&&u.end(p)}let A=d.handlerPath,b=d.method;if(gl(S,"duration",A,b,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),Ase(E<400,"success",A,b),!g)if(p?.pipe){p.pipe(u),p.destroy&&u.on("close",()=>{p.destroy()});let v=0;p.on("data",G=>{v+=G.length}),p.on("end",()=>{gl(performance.now()-h,"transfer",A,b),gl(v,"bytes-sent",A,b)})}else p?.then?p.then(v=>{u.end(v)},_):u.end(p)}catch(l){_(l)}function _(l){let d=l.headers;u.writeHead(l.statusCode||500,d&&(d[Symbol.iterator]?Array.from(d):d)),u.end(l.toString()),l.statusCode?l.statusCode===500?Fn.warn(l):Fn.info(l):Fn.error(l)}a(_,"onError")}),t&&(wo[e].on("secureConnection",c=>{c._parent.startTime&&gl(performance.now()-c._parent.startTime,"tls-handshake",e),gl(c.isSessionReused(),"tls-reused",e)}),wo[e].isSecure=!0),YR(wo[e],e)}return wo[e]}a(jH,"getHTTPServer");function VR(e,t){let r=ZH;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(VR,"makeCallbackChain");function ZH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new WH}}a(ZH,"unhandled");function Cse(e,t){KR(e,{requestOnly:!0,...t})}a(Cse,"onRequest");function Dse(e,t){let r;if(t.securePort){let n=$e.get("tls_privateKey"),s=$e.get("tls_certificate"),i=t.mtls?.certificateAuthority||$e.get("tls_certificateAuthority");r=Tse({ciphers:$e.get("tls_ciphers"),key:qa(n),cert:qa(s),ca:i&&qa(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),cs[t.securePort]=r}return t.port&&(r=fse(e),cs[t.port]=r),r}a(Dse,"onSocket");Object.defineProperty(hse.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function Lse(e,t){for(let{port:r,secure:n}of XH(t)){DE[r]||(DE[r]=new Sse({server:jH(r,n)}),DE[r].on("connection",async(i,o)=>{try{let c=new QH(o);c.isWebSocket=!0;let u=LE[r](c),_=o.headers["sec-websocket-protocol"]||"";for(let l=0;l<GR.length;l++){let d=GR[l];if(d.protocol){if(d.protocol===_){d.listener(i,c,u);break}}else d.listener(i,c,u)}}catch(c){Fn.warn("Error handling WebSocket connection",c)}}),DE[r].on("error",i=>{console.log("Error in setting up WebSocket server",i)}));let s=t?.subProtocol||"";GR.push({listener:e,protocol:s}),LE[r]=VR(kR,r)}}a(Lse,"onWebSocket");function KH(e,t){t.writeHead(404),t.end(`Not found
27
+ `)}a(KH,"defaultNotFound")});async function nx({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await QR.getResource(e,{});s=new XR(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await QR.get(e);i&&i.delete()}s=new vE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Al.put(n)),s}function zR(){return PE++,PE>65500&&(PE=1),PE}function JR(e,t,r=e){let{topic:n,retain:s}=e;e.data=t,e.async=!0,e.authorize=!0;let i=Js.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Xe(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var ex,Do,tx,rx,QR,Al,PE,vE,XR,sx=Re(()=>{Oe();pc();ex=B(Cr()),Do=B(Y());Ui();tx=B(tt()),rx=B(WR());Zt();QR=_t({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"}]}}]}),Al=_t({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,tx.getWorkerIndex)()===0&&(async()=>{await rx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Al.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await ut.getUser(r.user.username)),Xe(r,()=>{try{JR(r,t)}finally{Al.delete(e.id,r)}})}})();a(nx,"getSession");PE=1;a(zR,"getNextMessageId");vE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(g=>g.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Do.trace)("Resuming subscription from",s,"from",o);let E=Js.getMatch(_);if(!E){let g=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw g.statusCode=404,g}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let g=f.url.slice(1);if(g.indexOf("#")>-1&&g.indexOf("#")!==g.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,g.indexOf("+")===g.length-1)f.onlyChildren=!0,f.url="/"+g.slice(0,g.length-1);else{let A=g.split("/"),b;for(let H=0;H<A.length;H++)if(A[H].indexOf("+")>-1)if(A[H]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&b)throw new Error("Filters can not be combined");let v=!0;A[A.length-1]==="#"&&(A.length--,v=!1),b&&(n=a(H=>{let P=H.id;if(!Array.isArray(P)||v&&P.length!==A.length)return!1;for(let z=0;z<A.length;z++)if(A[z]!=="+"&&A[z]!==P[z])return!1;return!0},"filter"));let G=A.indexOf("+");f.url="/"+(G>-1?A.slice(0,G):A).concat("").join("/")}}let h=E.path,S=E.Resource,p=await Xe(f,async()=>{let g=await S.subscribe(f);if(!g)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!g[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let A of g)try{let b;if(A.type&&A.type!=="put"&&A.type!=="delete"&&A.type!=="message"&&A.type!=="patch"||n&&!n(A))continue;r?(A.topic=s,b=this.needsAcknowledge(A)):(A.acknowledge?.(),b=zR());let v=A.id;Array.isArray(v)&&(v=ko(v)),v==null&&(v=""),this.listener(h+"/"+v,A.value,b,t)}catch(b){(0,Do.warn)(b)}})(),g});return p.topic=s,p.qos=t.qos,this.subscriptions.push(p),p}resume(){}needsAcknowledge(t){let r=zR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,JR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Xe(r,async()=>{if(!t){let n=await Al.get(this.sessionId,r);n?.doesExist()&&await JR(n,n.data,r)}await Al.delete(this.sessionId,r)}).catch(n=>{(0,Do.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(JR,"publish");XR=class extends vE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{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,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=zR(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Do.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,ex.getNextMonotonicTime)()),(0,Do.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),QR.put(this.sessionRecord)),t.qos}}});var jR={};qe(jR,{bypassAuth:()=>Mse,start:()=>Use});function Mse(){ux=!0}function Use({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=ax(_,(h,S)=>{if(_.send(h),S&&_._socket.writableNeedDrain)return new Promise(p=>this._socket.once("drain",p))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,Or.info)("WebSocket error",h)})}},{subProtocol:"mqtt"})),(t||s)&&(c=e.socket(async _=>{let l;if(u){if(_.authorized)try{let E=u.user;l!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,Or.error)(E)}else if(u.required)return(0,Or.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&ux&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,cx.getSuperUser)());let{onMessage:d,onClose:f}=ax(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Or.info)("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function ax(e,t,r,n,s){ox||(ox=!0,eu(d=>{BE>0&&d.push({metric:"mqtt-connections",connections:BE,byThread:!0})}));let i;BE++;let o,c={protocolVersion:4},u=(0,xE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){BE--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),un(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await ut.getUser(d.username,d.password.toString(),r),(0,HE.get)(us.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ix.notify({username:n.username,status:us.AUTH_AUDIT_STATUS.SUCCESS,type:us.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,HE.get)(us.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&ix.error({username:n.username,status:us.AUTH_AUDIT_STATUS.FAILURE,type:us.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return un(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let b=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?b(d.will.payload):void 0,delete d.will.payload}o=nx({user:n,...d}),o=await o,s.sessions.add(o)}catch(b){return(0,Or.error)(b),un(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:b.code||5,returnCode:b.code||128})}un(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((b,v,G,H)=>{try{let P=b.indexOf("/",1),z=P>0?b.slice(0,P):b;f({cmd:"publish",topic:b,payload:E(v),messageId:G||Math.floor(Math.random()*1e8),qos:H.qos},z)}catch(P){(0,Or.error)(P),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let b of d.subscriptions){let v;try{v=(await o.addSubscription(b,b.qos>=1)).qos||0}catch(G){(0,Or.error)(G),v=c.protocolVersion<5?128:G.statusCode===403?135:G.statusCode===404?143:128}h.push(v)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let b=[];for(let v of d.unsubscriptions)b.push(o.removeSubscription(v)?0:17);f({cmd:"unsuback",granted:b,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let S=d.qos===2?"pubrec":"puback",p=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type"))),g=d.payload?.length>0?p(d.payload):void 0,A;try{A=await o.publish(d,g)}catch(b){(0,Or.warn)(b),d.qos>0&&f({cmd:S,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:S,messageId:d.messageId,reasonCode:A===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),un(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Or.error)(h),f({cmd:"disconnect"})}function f(h,S){let p=(0,xE.generate)(h,c);t(p),Gr(p.length,"bytes-sent",S,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ti(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var xE,cx,HE,us,Or,ix,ux,ox,BE,lx=Re(()=>{xE=require("mqtt-packet");sx();cx=B(cn());Ia();Ns();Zt();HE=B(j()),us=B(M()),Or=B(Y()),ix=(0,Or.loggerWithTag)("auth-event"),ux=(0,HE.get)(us.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Mse,"bypassAuth");a(Use,"start");BE=0;a(ax,"onSocket")});var Hf={};qe(Hf,{component_errors:()=>ka,loadComponent:()=>FE,loadComponentDirectories:()=>Tx,setErrorReporter:()=>Hse});function Tx(e,t){t&&(eA=t),e&&(tA=e);let r=[];if((0,qn.existsSync)(ZR)){let s=(0,qn.readdirSync)(ZR,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Rt.join)(ZR,o);r.push(FE(c,eA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(FE(n,eA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{Sx=!0})}function Hse(e){bl=e}async function FE(e,t,r,n,s,i){if(!dx.has(e)){dx.set(e,!0),s&&(tA=s);try{let o;n&&(ka=new Map);let c=(0,Rt.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,qn.existsSync)(c)?o=n?(0,px.getConfigObj)():(0,fx.parseDocument)((0,qn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=rA;let u=[],_=n;for(let l in o){let d=o[l];if(ka.set(n?l:(0,Rt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let A=e,b;for(;!(0,qn.existsSync)(b=(0,Rt.join)(A,"node_modules",l));)if(A=(0,Rt.dirname)(A),A.length<(0,mx.getHdbBasePath)().length){b=null;break}if(b)f=await FE(b,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=Bse[l];if(!f)continue;u.push(f);let h=a(A=>(A.origin=r,_t(A)),"ensureTable"),S=d.network||(d.port||d.securePort)&&d,p=S?.securePort||S?.https&&S.port,g=!S?.https&&S?.port;if(Ga.isMainThread&&(f=await f.startOnMainThread?.({server:ut,ensureTable:h,port:g,securePort:p,resources:t,...d})||f,n&&S))for(let A of[g,p])try{if(+A&&!_x.includes(A)){let b=nA.get(sA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);b&&Ol.default.warn("Session affinity is not recommended and may cause memory leaks"),(b||!RE)&&(_x.push(A),iA(A,b))}}catch(b){console.error("Error listening on socket",A,b,l)}if(t.isWorker&&(f=await f.start?.({server:ut,ensureTable:h,port:g,securePort:p,resources:t,...d})||f),tA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,hx.handleHDBError)("Can not reference parent directories");let A=(0,Rt.join)(e,d.files).replace(/\\/g,"/"),b=A.indexOf("/*");if(b>-1&&d.files!==rA[l]?.files&&!(0,qn.existsSync)(A.slice(0,b)))throw new Error(`The path '${A.slice(0,b)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let v=(0,Rt.basename)(e),G=d.path||"/";G=G.startsWith("/")?G:G.startsWith("./")?"/"+v+G.slice(2):G==="."?"/"+v:"/"+v+"/"+G;let H,P,z;if(d.root){let Q=d.root;Q.startsWith("/")&&(Q=Q.slice(1)),Q.endsWith("/")&&(Q=Q.slice(0,-1)),Q+="/",P=(0,Rt.join)(e,Q)}else(z=A.indexOf("/*"))>-1&&(P=A.slice(0,z+1),H=(0,Rt.relative)(e,P));let W=!1;if(Ga.isMainThread&&f.setupDirectory&&(W=await f.setupDirectory?.(G,P,t)),t.isWorker&&f.handleDirectory&&(W=await f.handleDirectory?.(G,P,t)),W)continue;for(let Q of await(0,Ex.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:se,dirent:pe}=Q;_=!0;let oe=(0,Rt.relative)(e,se).replace(/\\/g,"/");if(H)if(oe.startsWith(H))oe=oe.slice(H.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${oe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let Fe=G+(G.endsWith("/")?"":"/")+oe;try{if(pe.isFile()){let ce=await vse(se);Ga.isMainThread&&await f.setupFile?.(ce,Fe,se,t),t.isWorker&&await f.handleFile?.(ce,Fe,se,t)}else Ga.isMainThread&&await f.setupDirectory?.(Fe,se,t),t.isWorker&&await f.handleDirectory?.(Fe,se,t)}catch(ce){ce.message=`Could not load ${pe.isFile()?"file":"directory"} '${se}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${ce.message}`,bl?.(ce),((0,Va.getWorkerIndex)()===0?console:Ol.default).error(ce),t.set(d.path||"/",new Nl(ce)),ka.set(n?l:(0,Rt.basename)(e),ce.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Rt.basename)(e)}' due to: ${h.message}`,bl?.(h),((0,Va.getWorkerIndex)()===0?console:Ol.default).error(h),t.set(d.path||"/",new Nl(h),null,!0),ka.set(n?l:(0,Rt.basename)(e),h.message)}}if(Ga.isMainThread&&!Sx&&i&&(0,Va.watchDir)(e,async()=>Tx()),o.extensionModule)return await Md((0,Rt.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;bl?.(new Error(l)),((0,Va.getWorkerIndex)()===0?console:Ol.default).error(l),ka.set((0,Rt.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,bl?.(o),t.set("",new Nl(o))}}}var qn,Rt,Ga,fx,nA,sA,Ex,Va,Ol,hx,mx,Pse,px,vse,ZR,tA,Sx,eA,ka,Bse,rA,_x,dx,bl,Nl,xf=Re(()=>{qn=require("fs"),Rt=require("path"),Ga=require("worker_threads"),fx=require("yaml"),nA=B(j()),sA=B(M());MD();BD();HD();O0();_H();pH();Ex=B(require("fast-glob")),Va=B(tt()),Ol=B(Y());pS();Zt();hx=B(Z());On();Oe();oA();mx=B(j()),Pse=B(AH());Cf();qH();lx();px=B(xr());AE();({readFile:vse}=qn.promises),ZR=nA.get(sA.CONFIG_PARAMS.COMPONENTSROOT),tA=new Map,ka=new Map;a(Tx,"loadComponentDirectories");Bse={REST:Zf,rest:Zf,graphqlSchema:mS,jsResource:TS,fastifyRoutes:yR,login:RS,static:IR,operationsApi:Pse,customFunctions:{},http:{},clustering:qR,authentication:Qu,mqtt:jR},rA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(rA,"static",{value:{files:"web/**"}});_x=[],dx=new Map;a(Hse,"setErrorReporter");a(FE,"loadComponent");Nl=class extends Ft{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 UE=T((Kme,Rx)=>{var{isMainThread:gx}=require("worker_threads"),{getTables:xse}=(Oe(),ee(Ge)),{loadComponentDirectories:Fse,loadComponent:qse}=(xf(),ee(Hf)),{resetResources:Gse}=(pc(),ee(ob)),kse=mg(),Vse=xr(),{dirname:$se}=require("path"),{getConnection:Yse}=yt(),Kse=j(),Wse=M(),aA=new Map;async function Qse(e=!1){!gx&&Kse.get(Wse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Yse();try{gx&&await kse()}catch(n){console.error(n)}let t=Gse();xse(),t.isWorker=e,await qse($se(Vse.getConfigFilePath()),t,"hdb",!0,aA),await Fse(aA,t);let r=[];for(let[n]of aA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Qse,"loadRootComponents");Rx.exports.loadRootComponents=Qse});var tt=T((Qme,bi)=>{"use strict";var{Worker:zse,MessageChannel:Jse,parentPort:ls,isMainThread:dA,threadId:Xse,workerData:Gs}=require("worker_threads"),{PACKAGE_ROOT:jse}=M(),{join:Nx,isAbsolute:Zse,extname:eie}=require("path"),{server:yx}=(Zt(),ee(yi)),{watch:tie,readdir:rie}=require("fs/promises"),{totalmem:Ax}=require("os"),yl=M(),Ix=j(),ks=Y(),{randomBytes:nie}=require("crypto"),{_assignPackageExport:sie}=require("../index"),iie=M(),Ox=1024*1024,Oi=[],gn=[],oie=50,fA=1e4,aie="restart",wx="request_thread_info",Cx="resource_report",Dx="thread_info",Lx="added-port",cie="ack",cA;sie("threads",gn);bi.exports={startWorker:uA,restartWorkers:hA,shutdownWorkers:fie,workers:Oi,setMonitorListener:Rie,onMessageFromWorkers:Eie,onMessageByType:Hx,broadcast:mie,broadcastWithAcknowledgement:Sie,setChildListenerByType:die,getWorkerIndex:Mx,getWorkerCount:Ux,getTicketKeys:Px,setMainIsWorker:lie,setTerminateTimeout:uie,restartNumber:Gs?.restartNumber||1};gn.onMessageByType=Hx;gn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=gn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var EA;function uie(e){fA=e}a(uie,"setTerminateTimeout");function Mx(){return Gs?Gs.workerIndex:EA?0:void 0}a(Mx,"getWorkerIndex");function Ux(){return Gs?Gs.workerCount:EA?1:void 0}a(Ux,"getWorkerCount");function lie(e){EA=e}a(lie,"setMainIsWorker");var qE;function Px(){return qE||(qE=dA?nie(48):Gs.ticketKeys,qE)}a(Px,"getTicketKeys");Object.defineProperty(yx,"workerIndex",{get(){return Mx()}});Object.defineProperty(yx,"workerCount",{get(){return Ux()}});var vx={[wx](e,t){Tie(t)},[Cx](e,t){gie(t,e)}};function uA(e,t={}){let r=process.constrainedMemory?.()||Ax();r=Math.min(r,Ax(),2e4*Ox);let n=Ix.get(yl.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/Ox/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of gn){let _=new Jse;_.existingPort=u,i.push(_),o.push(_.port2)}eie(e)||(e+=".js");let c=new zse(Zse(e)?e:Nx(jse,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:t.threadCount,name:t.name,restartNumber:bi.exports.restartNumber,ticketKeys:Px()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Lx,port:u,threadId:c.threadId},[u]);return kE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>uA(e,t),c.on("error",u=>{console.error("Worker error:",u),ks.error("Worker error:",u)}),c.on("exit",u=>{Oi.splice(Oi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<oie?(t.unexpectedRestarts=c.unexpectedRestarts+1,uA(e,t)):ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{vx[u.type]?.(u,c)}),Oi.push(c),Oie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(uA,"startWorker");var _ie=[yl.THREAD_TYPES.HTTP];async function hA(e=null,t=2,r=!0){if(dA){if(r){let{loadRootComponents:o}=UE();await o()}bi.exports.restartNumber++,t<1&&(t=t*Oi.length);let n=[],s=[];for(let o of Oi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:bi.exports.restartNumber,type:yl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=_ie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),fA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===iie.ITC_EVENT_TYPES.CHILD_STARTED&&(ks.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");ks.trace("Waiting for worker to start",_.threadId),_.on("message",f)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=bf();r&&(e==="http"||!e)&&Ix.get(yl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ls.postMessage({type:aie,workerType:e})}a(hA,"restartWorkers");function die(e,t){vx[e]=t}a(die,"setChildListenerByType");function fie(e){return hA(e,1/0,!1)}a(fie,"shutdownWorkers");var Bx=[];function Eie(e){Bx.push(e)}a(Eie,"onMessageFromWorkers");var lA=new Map;function Hx(e,t){let r=lA.get(e);r||lA.set(e,r=[]),r.push(t)}a(Hx,"onMessageByType");var hie=10;async function mie(e){let t=0;for(let r of gn)try{r.postMessage(e),t++>hie&&(t=0,await new Promise(setImmediate))}catch(n){ks.error("Unable to send message to worker",n)}}a(mie,"broadcast");var GE=new Map,pie=1;function Sie(e){return new Promise(t=>{let r=0;for(let n of gn)try{let s=pie++,i=a(()=>{GE.delete(s),--r===0&&t(),n!==ls&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,GE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of GE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){ks.error("Unable to send message to worker",s)}r===0&&t()})}a(Sie,"broadcastWithAcknowledgement");function Tie(e){e.postMessage({type:Dx,workers:xx()})}a(Tie,"sendThreadInfo");function xx(){let e=Date.now();return Oi.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(xx,"getChildWorkerInfo");function gie(e,t){e.resources=t,e.resources.updated=Date.now()}a(gie,"recordResourceReport");var _A;function Rie(e){_A=e}a(Rie,"setMonitorListener");var Aie=1e3,bx=!1;function Oie(){bx||(bx=!0,setInterval(()=>{for(let e of Oi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}_A&&_A()},Aie).unref())}a(Oie,"startMonitoring");var bie=1e3;if(ls){kE(ls);for(let e=0,t=Gs.addPorts.length;e<t;e++){let r=Gs.addPorts[e];r.threadId=Gs.addThreadIds[e],kE(r)}setInterval(()=>{let e=process.memoryUsage();ls.postMessage({type:Cx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},bie).unref(),cA=a(()=>new Promise((e,t)=>{ls.on("message",r),ls.postMessage({type:wx});function r(n){n.type===Dx&&(ls.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else cA=xx;bi.exports.getThreadInfo=cA;function kE(e,t){gn.push(e),e.on("message",r=>{if(r.type===Lx)r.port.threadId=r.threadId,kE(r.port);else if(r.type===cie){let n=GE.get(r.id);n&&n()}else{for(let s of Bx)s(r,e);let n=lA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){ks.error(i)}}}).on("close",()=>{gn.splice(gn.indexOf(e),1)}).on("exit",()=>{gn.splice(gn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(kE,"addPort");if(dA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await rie(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(Nx(n,i.name));try{for await(let{filename:i}of tie(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await hA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");bi.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else ls.on("message",async e=>{let{type:t}=e;t===yl.ITC_EVENT_TYPES.SHUTDOWN&&(bi.exports.restartNumber=e.restartNumber,ls.unref(),setTimeout(()=>{ks.warn("Thread did not voluntarily terminate",Xse),process.exit(0)},fA).unref())})});var Kx={};qe(Kx,{startHTTPThreads:()=>yie,startSocketServer:()=>iA,updateWorkerIdleness:()=>Yx});async function yie(e=2,t){if(t)pA(0,1,!0);else{let{loadRootComponents:n}=UE();if(e===0)return(0,Ni.setMainIsWorker)(!0),await WR().startServers(),Promise.resolve([]);await n()}let r=(0,kx.checkMemoryLimit)();r&&!process.env.DEV_MODE&&(console.error(r),setInterval(()=>{KE.notify(r)},Nie).unref());for(let n=0;n<e;n++)pA(n,e);return Promise.all($x)}function pA(e,t=1,r){if(mA++,(0,Ni.startWorker)("server/threads/threadServer.js",{name:YE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===YE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});$x.push(s),await s,$a.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=$E.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=$a.indexOf(n);o>-1&&$a.splice(o,1)}if(a(i,"removeWorker"),Ya){let o=Ya;Ya=[];for(let c of o)Vx[c.localPort](null,c)}}}),r){let n=setInterval(()=>{SA?SA=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Ni.shutdownWorkers)(),mA=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function iA(e=0,t){if(typeof e=="string")try{(0,WE.existsSync)(e)&&(0,WE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Iie:r=wie(t):r=TA;let n=(0,Ka.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=Vx[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),SA=!0,r(o,(c,u)=>{if(!c){if(Fx){let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});Fx.deliverSocket(l,e,u),l.resume()}else mA>0?(Ya.length===0&&setTimeout(()=>{Ya.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(),o.localPort=e,Ya.push(o)):(console.log("start up a dynamic thread to handle request"),pA(0));Gr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});Lie(l,c,e)}Gr(!0,"socket-routed")})};let s=pu();KE.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function TA(e,t){let r,n=0;for(let s of $a){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=VE)return VE=i,t(r);n=i}VE=0,t(r)}function Iie(e,t){let r={};e.getpeername(r);let n=r.address,s=Wa.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);TA(e,o=>{Wa.set(n,{worker:o,lastUsed:i}),t(o)})}function wie(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Ka.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Wa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);TA(n,d=>{Wa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Yx(){VE=0;for(let e of $a)e.expectedIdle=e.recentELU.idle+Cie,e.requests=1;$a.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Lie(e,t,r){let n=Die++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),$E.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),$E.delete(n)),s.event=="destroy"&&(e.destroy(),$E.delete(n))})}var Ni,Ka,YE,KE,WE,Gx,kx,$a,Ya,Vx,Fx,mA,$x,Nie,SA,VE,qx,Wa,Cie,$E,Die,oA=Re(()=>{Ni=B(tt()),Ka=require("net"),YE=B(M()),KE=B(Y()),WE=require("fs");Ns();Gx=require("worker_threads"),kx=B(Ji()),$a=[],Ya=[],Vx=[],mA=0,$x=[];Gx.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});Nie=6e5;a(yie,"startHTTPThreads");a(pA,"startHTTPWorker");a(iA,"startSocketServer");VE=0;a(TA,"findMostIdleWorker");qx=36e5,Wa=new Map;a(Iie,"findByRemoteAddressAffinity");a(wie,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Wa)r.lastUsed+qx<e&&Wa.delete(t)},qx).unref();Cie=1e3;a(Yx,"updateWorkerIdleness");(0,Ni.setMonitorListener)(Yx);$E=new Map,Die=1;a(Lie,"proxySocket")});th();var{startHTTPThreads:Mie,startSocketServer:Wx}=(oA(),ee(Kx));Mie(0,!0);Wx(9925);Wx(9926);