harperdb 4.3.16 → 4.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,32 +1,32 @@
1
- "use strict";var Oq=Object.create;var ac=Object.defineProperty;var bq=Object.getOwnPropertyDescriptor;var Nq=Object.getOwnPropertyNames;var yq=Object.getPrototypeOf,Iq=Object.prototype.hasOwnProperty;var a=(e,t)=>ac(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qe=(e,t)=>{for(var r in t)ac(e,r,{get:t[r],enumerable:!0})},lO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Nq(t))!Iq.call(e,s)&&s!==r&&ac(e,s,{get:()=>t[s],enumerable:!(n=bq(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Oq(yq(e)):{},lO(t||!e||!e.__esModule?ac(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>lO(ac({},"__esModule",{value:!0}),e);var fO=R((Xae,dO)=>{var wq=require("fast-glob"),{statSync:wh,existsSync:Ch,readFileSync:Cq,writeFileSync:Dq}=require("fs"),{spawnSync:Lq,spawn:Mq,execFileSync:jae}=require("child_process"),{isMainThread:Uq}=require("worker_threads"),{join:Xs,relative:_O}=require("path"),{PACKAGE_ROOT:On}=M(),{tmpdir:Pq,platform:vq}=require("os");require("source-map-support").install();var Bq=["resources","server","dataLayer","components"],cc="ts-build",Dh,Hq=__filename.endsWith("tsBuild.js");if(Hq){if(Uq){let r;try{wh(Xs(On,cc)),r=!0}catch{}if(r)for(let n of wq.sync(Bq.map(s=>s+"/**/*.ts"),{cwd:On})){let s=0,i=0;try{s=wh(Xs(On,n)).mtimeMs-5e3,i=wh(Xs(On,cc,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."),Dh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Dh=!0;if(Dh){let n=Xs(On,"node_modules/.bin/tsc");vq()==="win32"&&(n+=".cmd");let s=Lq(n,{cwd:On});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=Xs(Pq(),"harperdb-tsc.pid"),o;if(Ch(i))try{process.kill(+Cq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Mq(n,["--watch"],{cwd:On,detached:!0,stdio:"ignore"});Dq(i,c.pid.toString()),c.unref()}}}}let e=dO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(On)&&!n[0].includes("node_modules")){let i=_O(On,n[0]),o;i.startsWith(cc)?o=Xs(On,_O(cc,i)):o=Xs(On,cc,i);let c=Xs(o,r),u=c+".js";if(Ch(u))return u;if(c.includes(".")&&Ch(c))return c}return t(r,n,s)}}});var M=R((tce,IO)=>{"use strict";var on=require("path"),xq=require("fs"),{relative:Zae,join:ece}=on,{existsSync:Gq}=xq;function qq(){let e=__dirname;for(;!Gq(on.join(e,"package.json"));){let t=on.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(qq,"getHDBPackageRoot");var Zs=qq(),EO="js",Xl=EO,Fq="harperdb-config.yaml",kq="defaultConfig.yaml",Vq="hdb",hO=`harperdb.${Xl}`,mO=`customFunctionsServer.${Xl}`,$q=`restartHdb.${Xl}`,Mh="HarperDB",jl="Custom Functions",Zl="Clustering Hub",e_="Clustering Leaf",Yq="Clustering Ingest Service",Kq="Clustering Reply Service",Wq="foreground.pid",Qq="hdb.pid",zq="data",Jq={HDB:Mh,CLUSTERING_HUB:Zl,CLUSTERING_LEAF:e_,CLUSTERING_INGEST_SERVICE:Yq,CLUSTERING_REPLY_SERVICE:Kq,CUSTOM_FUNCTIONS:jl,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"},jq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Xq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Zq={harperdb:Mh,"clustering hub":Zl,"clustering leaf":e_,"custom functions":jl,custom_functions:jl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},eF={CLUSTERING_HUB_PROC_DESCRIPTOR:Zl,CLUSTERING_LEAF_PROC_DESCRIPTOR:e_},Lh={HDB:on.join(Zs,"server/harperdb"),CUSTOM_FUNCTIONS:on.join(Zs,"server/customFunctions"),CLUSTERING_HUB:on.join(Zs,"server/nats"),CLUSTERING_LEAF:on.join(Zs,"server/nats")},tF={HDB:on.join(Lh.HDB,hO),CUSTOM_FUNCTIONS:on.join(Lh.CUSTOM_FUNCTIONS,mO)},rF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:on.join(Zs,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:on.join(Zs,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:on.join(Zs,"launchServiceScripts/launchUpdateNodes4-0-0.js")},nF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},pO="support@harperdb.io",sF="customer-success@harperdb.io",SO=1,iF=4141,TO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",oF="https://www.harperdb.io/product",aF=`For support, please submit a request at ${TO} or contact ${pO}`,gO=`For license support, please contact ${sF}`,cF="None of the specified records were found.",uF="hash attribute not found",lF=`Your current license only supports ${SO} role. ${gO}`,_F="Your current license only supports 3 connections to a node.",dF="127.0.0.1",fF=1,EF=/^\.$/,hF=/^\.\.$/,mF="U+002E",pF=/\//g,SF="U+002F",TF=/U\+002F/g,gF=/^U\+002E$/,RF=/^U\+002EU\+002E$/,AF="d",OF=999999,bF="*",NF="--max-old-space-size=",yF="system",IF="__hdb_hash",wF=".harperdb",CF=".hdb",DF="keys",LF="hdb_boot_properties.file",MF=".updateConfig.json",UF="SIGTSTP",PF=24,vF=6e4,BF=448,HF="blob",xF="trash",GF="database",qF="schema",FF="transactions",kF=".count",VF="id",$F="PROCESS_NAME",RO={SETTINGS_PATH_KEY:"settings_path"},AO=require("lodash"),YF={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"},KF={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},WF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},QF={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"},zF={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"},Dr="hdb_internal:",JF={CREATE_SCHEMA:Dr+"create_schema",CREATE_TABLE:Dr+"create_table",CREATE_ATTRIBUTE:Dr+"create_attribute",ADD_USER:Dr+"add_user",ALTER_USER:Dr+"alter_user",DROP_USER:Dr+"drop_user",HDB_NODES:Dr+"hdb_nodes",HDB_USERS:Dr+"hdb_users",HDB_WORKERS:Dr+"hdb_workers",CATCHUP:Dr+"catchup",SCHEMA_CATCHUP:Dr+"schema_catchup",WORKER_ROOM:Dr+"cluster_workers"},jF={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"},XF="060493.ks",ZF=".license",ek={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},ee={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"},tk={CSV:".csv",JSON:".json"},rk={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},nk={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},uc={};uc[ee.INSERT]=ee.INSERT;uc[ee.UPDATE]=ee.UPDATE;uc[ee.UPSERT]=ee.UPSERT;uc[ee.DELETE]=ee.DELETE;var He=Object.create(null);He[ee.DESCRIBE_ALL]=ee.DESCRIBE_ALL;He[ee.DESCRIBE_TABLE]=ee.DESCRIBE_TABLE;He[ee.DESCRIBE_SCHEMA]=ee.DESCRIBE_SCHEMA;He[ee.READ_LOG]=ee.READ_LOG;He[ee.ADD_NODE]=ee.ADD_NODE;He[ee.LIST_USERS]=ee.LIST_USERS;He[ee.LIST_ROLES]=ee.LIST_ROLES;He[ee.USER_INFO]=ee.USER_INFO;He[ee.SQL]=ee.SQL;He[ee.GET_JOB]=ee.GET_JOB;He[ee.SEARCH_JOBS_BY_START_DATE]=ee.SEARCH_JOBS_BY_START_DATE;He[ee.DELETE_FILES_BEFORE]=ee.DELETE_FILES_BEFORE;He[ee.EXPORT_LOCAL]=ee.EXPORT_LOCAL;He[ee.EXPORT_TO_S3]=ee.EXPORT_TO_S3;He[ee.CLUSTER_STATUS]=ee.CLUSTER_STATUS;He[ee.REMOVE_NODE]=ee.REMOVE_NODE;He[ee.RESTART]=ee.RESTART;He[ee.CUSTOM_FUNCTIONS_STATUS]=ee.CUSTOM_FUNCTIONS_STATUS;He[ee.GET_CUSTOM_FUNCTIONS]=ee.GET_CUSTOM_FUNCTIONS;He[ee.GET_CUSTOM_FUNCTION]=ee.GET_CUSTOM_FUNCTION;He[ee.SET_CUSTOM_FUNCTION]=ee.SET_CUSTOM_FUNCTION;He[ee.DROP_CUSTOM_FUNCTION]=ee.DROP_CUSTOM_FUNCTION;He[ee.ADD_CUSTOM_FUNCTION_PROJECT]=ee.ADD_CUSTOM_FUNCTION_PROJECT;He[ee.DROP_CUSTOM_FUNCTION_PROJECT]=ee.DROP_CUSTOM_FUNCTION_PROJECT;He[ee.PACKAGE_CUSTOM_FUNCTION_PROJECT]=ee.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[ee.DEPLOY_CUSTOM_FUNCTION_PROJECT]=ee.DEPLOY_CUSTOM_FUNCTION_PROJECT;var sk={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",COPYDB:"copy-db"},ik={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},OO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},ok=AO.invert(OO),ak={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"},w={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_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",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",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_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",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",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:"operationsApi_tls",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_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",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_REQUIRED:"mqtt_network_mtls_required",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",TLS:"tls",CLONED:"cloned"},bO={settings_path:RO.SETTINGS_PATH_KEY,hdb_root_key:w.ROOTPATH,hdb_root:w.ROOTPATH,rootpath:w.ROOTPATH,server_port_key:w.OPERATIONSAPI_NETWORK_PORT,server_port:w.OPERATIONSAPI_NETWORK_PORT,cert_key:w.TLS_CERTIFICATE,certificate:w.TLS_CERTIFICATE,private_key_key:w.TLS_PRIVATEKEY,private_key:w.TLS_PRIVATEKEY,http_secure_enabled_key:w.OPERATIONSAPI_NETWORK_HTTPS,https_on:w.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:w.OPERATIONSAPI_NETWORK_CORS,cors_on:w.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:w.LOGGING_LEVEL,log_level:w.LOGGING_LEVEL,log_path_key:w.LOGGING_ROOT,log_path:w.LOGGING_ROOT,clustering_node_name_key:w.CLUSTERING_NODENAME,node_name:w.CLUSTERING_NODENAME,clustering_enabled_key:w.CLUSTERING_ENABLED,clustering:w.CLUSTERING_ENABLED,max_http_threads:w.THREADS_COUNT,max_hdb_processes:w.THREADS_COUNT,server_timeout_key:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:w.LOGGING_AUDITLOG,disable_transaction_log:w.LOGGING_AUDITLOG,operation_token_timeout_key:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:w.HTTP_PORT,custom_functions_port:w.HTTP_PORT,custom_functions_directory_key:w.COMPONENTSROOT,custom_functions_directory:w.COMPONENTSROOT,max_custom_function_processes:w.THREADS_COUNT,log_to_file:w.LOGGING_FILE,log_to_stdstreams:w.LOGGING_STDSTREAMS,local_studio_on:w.LOCALSTUDIO_ENABLED,clustering_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:w.CLUSTERING_USER,clustering_enabled:w.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:w.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:w.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:w.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:w.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:w.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:w.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:w.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:w.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:w.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:w.CLUSTERING_NODENAME,clustering_tls_certificate:w.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:w.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:w.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:w.CLUSTERING_TLS_INSECURE,clustering_tls_verify:w.CLUSTERING_TLS_VERIFY,clustering_loglevel:w.CLUSTERING_LOGLEVEL,clustering_republishmessages:w.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:w.CLUSTERING_DATABASELEVEL,customfunctions_network_port:w.HTTP_PORT,customfunctions_tls_certificate:w.TLS_CERTIFICATE,customfunctions_network_cors:w.HTTP_CORS,customfunctions_network_corsaccesslist:w.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:w.HTTP_HEADERSTIMEOUT,customfunctions_network_https:w.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:w.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:w.HTTP_TIMEOUT,customfunctions_tls:w.TLS,http_threads:w.THREADS_COUNT,threads:w.THREADS_COUNT,threads_count:w.THREADS_COUNT,threads_debug:w.THREADS_DEBUG,threads_debug_startingport:w.THREADS_DEBUG_STARTINGPORT,threads_debug_port:w.THREADS_DEBUG_PORT,threads_debug_host:w.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:w.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:w.THREADS_MAXHEAPMEMORY,http_session_affinity:w.HTTP_SESSIONAFFINITY,http_compressionthreshold:w.HTTP_COMPRESSIONTHRESHOLD,http_cors:w.HTTP_CORS,http_corsaccesslist:w.HTTP_CORSACCESSLIST,http_headerstimeout:w.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,http_timeout:w.HTTP_TIMEOUT,http_port:w.HTTP_PORT,http_secureport:w.HTTP_SECUREPORT,http_mtls:w.HTTP_MTLS,http_mtls_user:w.HTTP_MTLS_USER,http_mtls_required:w.HTTP_MTLS_REQUIRED,customfunctions_processes:w.THREADS_COUNT,customfunctions_root:w.COMPONENTSROOT,localstudio_enabled:w.LOCALSTUDIO_ENABLED,logging_file:w.LOGGING_FILE,logging_level:w.LOGGING_LEVEL,logging_root:w.LOGGING_ROOT,logging_rotation_enabled:w.LOGGING_ROTATION_ENABLED,logging_rotation_compress:w.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:w.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:w.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:w.LOGGING_ROTATION_PATH,logging_stdstreams:w.LOGGING_STDSTREAMS,logging_auditlog:w.LOGGING_AUDITLOG,logging_auditretention:w.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:w.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:w.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:w.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:w.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:w.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:w.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:w.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls:w.OPERATIONSAPI_TLS,operationsapi_tls_certificate:w.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:w.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:w.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:w.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:w.ROOTPATH,databases:w.DATABASES,storage_path:w.STORAGE_PATH,storage_maxtransactionqueuetime:w.STORAGE_MAXTRANSACTIONQUEUETIME,ignorescripts:w.IGNORE_SCRIPTS,mqtt_network_port:w.MQTT_NETWORK_PORT,mqtt_websocket:w.MQTT_WEBSOCKET,mqtt_network_secureport:w.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:w.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:w.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:w.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:w.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:w.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:w.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:w.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:w.AUTHENTICATION_CACHETTL,authentication_enablesessions:w.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:w.COMPONENTSROOT,tls:w.TLS,tls_certificate:w.TLS_CERTIFICATE,tls_privatekey:w.TLS_PRIVATEKEY,tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,tls_ciphers:w.TLS_CIPHERS};for(let e in w){let t=w[e];bO[t.toLowerCase()]=t}var ck={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},uk={csv_file_load:"csv_file_load",csv_data_load:ee.CSV_DATA_LOAD,csv_url_load:ee.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"},lk={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"},_k={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},dk={VERSION_DEFAULT:"2.2.0"},fk={DEVELOPMENT:8192,DEFAULT:512},Ek={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"},hk={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"},mk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},NO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},pk=Symbol("metadata"),Sk="__clustering__",Tk=Object.values(NO),gk=15984864e5,yO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Rk=AO.invert(yO),Ak={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"},Ok=111,bk=`\r
2
- `,Nk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},yk=["*","%"],Ik="unauthorized_access",wk="func_val",Ck={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Dk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Lk={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",NATS_CONSUMER_UPDATE:"nats_consumer_update"},Mk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Uk={HTTP:"http"},Pk={STOPPED:"stopped",ONLINE:"online"},vk="3.x.x",Bk={SUCCESS:"success",FAILURE:"failure"},Hk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};IO.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:pO,HDB_SUPPORT_URL:TO,HDB_PRICING_URL:oF,SUPPORT_HELP_MSG:aF,LICENSE_HELP_MSG:gO,HDB_PROC_NAME:hO,HDB_PROC_DESCRIPTOR:Mh,CLUSTERING_LEAF_PROC_DESCRIPTOR:e_,CLUSTERING_HUB_PROC_DESCRIPTOR:Zl,SYSTEM_SCHEMA_NAME:yF,HASH_FOLDER_NAME:IF,HDB_HOME_DIR_NAME:wF,UPDATE_FILE_NAME:MF,LICENSE_KEY_DIR_NAME:DF,BOOT_PROPS_FILE_NAME:LF,JOB_TYPE_ENUM:uk,JOB_STATUS_ENUM:ek,SYSTEM_TABLE_NAMES:QF,SYSTEM_TABLE_HASH_ATTRIBUTES:zF,OPERATIONS_ENUM:ee,VALID_S3_FILE_TYPES:tk,S3_BUCKET_AUTH_KEYS:rk,VALID_SQL_OPS_ENUM:nk,GEO_CONVERSION_ENUM:ik,HDB_SETTINGS_NAMES:OO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:ok,SERVICE_ACTIONS_ENUM:sk,CLUSTER_MESSAGE_TYPE_ENUM:lk,CLUSTER_CONNECTION_DIRECTION_ENUM:_k,CLUSTER_EVENTS_DEFS_ENUM:Ek,PERIOD_REGEX:EF,DOUBLE_PERIOD_REGEX:hF,UNICODE_PERIOD:mF,FORWARD_SLASH_REGEX:pF,UNICODE_FORWARD_SLASH:SF,ESCAPED_FORWARD_SLASH_REGEX:TF,ESCAPED_PERIOD_REGEX:gF,ESCAPED_DOUBLE_PERIOD_REGEX:RF,REG_KEY_FILE_NAME:XF,RESTART_TIMEOUT_MS:vF,HDB_FILE_PERMISSIONS:BF,DATABASES_DIR_NAME:GF,LEGACY_DATABASES_DIR_NAME:qF,TRANSACTIONS_DIR_NAME:FF,LIMIT_COUNT_NAME:kF,ID_ATTRIBUTE_STRING:VF,INSERT_MODULE_ENUM:KF,UPGRADE_JSON_FIELD_NAMES_ENUM:WF,RESTART_CODE:UF,RESTART_CODE_NUM:PF,CLUSTER_OPERATIONS:uc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:jF,HDB_INTERNAL_SC_CHANNEL_PREFIX:Dr,INTERNAL_SC_CHANNELS:JF,CLUSTERING_MESSAGE_TYPES:Ak,HDB_FILE_SUFFIX:CF,BLOB_FOLDER_NAME:HF,HDB_TRASH_DIR:xF,ORIGINATOR_SET_VALUE:Ok,LICENSE_VALUES:dk,RAM_ALLOCATION_ENUM:fk,TIME_STAMP_NAMES_ENUM:NO,TIME_STAMP_NAMES:Tk,PERMS_UPDATE_RELEASE_TIMESTAMP:gk,SEARCH_NOT_FOUND_MESSAGE:cF,SEARCH_ATTRIBUTE_NOT_FOUND:uF,LICENSE_ROLE_DENIED_RESPONSE:lF,LICENSE_MAX_CONNS_REACHED:_F,BASIC_LICENSE_MAX_NON_CU_ROLES:SO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:iF,VALUE_SEARCH_COMPARATORS:yO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Rk,LICENSE_FILE_NAME:ZF,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:hk,NEW_LINE:bk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:fF,MOMENT_DAYS_TAG:AF,API_TURNOVER_SEC:OF,LOOPBACK:dF,CODE_EXTENSION:Xl,WILDCARD_SEARCH_VALUE:bF,NODE_ERROR_CODES:mk,JAVASCRIPT_EXTENSION:EO,PERMS_CRUD_ENUM:Nk,UNAUTHORIZED_PERMISSION_NAME:Ik,SEARCH_WILDCARDS:yk,FUNC_VAL:wk,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Ck,JWT_ENUM:Dk,CLUSTERING_FLAG:Sk,ITC_EVENT_TYPES:Lk,CUSTOM_FUNCTION_PROC_NAME:mO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:jl,SERVICES:Mk,THREAD_TYPES:Uk,MEM_SETTING_KEY:NF,HDB_RESTART_SCRIPT:$q,PROCESS_DESCRIPTORS:Jq,SERVICE_SERVERS:tF,SERVICE_SERVERS_CWD:Lh,PROCESS_DESCRIPTORS_VALIDATE:Zq,LAUNCH_SERVICE_SCRIPTS:rF,LOG_LEVELS:Xq,PROCESS_NAME_ENV_PROP:$F,LOG_NAMES:jq,PM2_PROCESS_STATUSES:Pk,CONFIG_PARAM_MAP:bO,CONFIG_PARAMS:w,HDB_CONFIG_FILE:Fq,HDB_DEFAULT_CONFIG_FILE:kq,ROLE_TYPES_ENUM:nF,BOOT_PROP_PARAMS:RO,INSTALL_PROMPTS:YF,HDB_ROOT_DIR_NAME:Vq,CLUSTERING_PROCESSES:eF,FOREGROUND_PID_FILE:Wq,PACKAGE_ROOT:Zs,PRE_4_0_0_VERSION:vk,DATABASES_PARAM_CONFIG:ck,METADATA_PROPERTY:pk,AUTH_AUDIT_STATUS:Bk,AUTH_AUDIT_TYPES:Hk,HDB_PID_FILE:Qq,DEFAULT_DATABASE_NAME:zq,LEGACY_CONFIG_PARAMS:ak};fO()});var Uh=R((nce,DO)=>{"use strict";var wO=require("minimist");DO.exports=xk;function xk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=CO(process.env),n=CO(wO(process.argv))):(r=process.env,n=wO(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(xk,"assignCMDENVVariables");function CO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(CO,"objKeysToLowerCase")});var $=R((ice,qh)=>{"use strict";var Bi=require("fs-extra"),{workerData:Gk,threadId:qk}=require("worker_threads"),ps=require("path"),UO=require("yaml"),PO=require("properties-reader"),mt=M(),LO=Uh(),Fk=require("os"),{PACKAGE_ROOT:vh}=M(),{_assignPackageExport:kk}=require("../index"),_c={};for(let e in console)_c[e]||(_c[e]=console[e]);var ir={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},vO={STDOUT:"stdOut",STDERR:"stdErr"},Vk=ps.join(vh,"logs"),$k=ps.join(vh,"config/yaml/",mt.HDB_DEFAULT_CONFIG_FILE),Yk=1e4,ms,Kn,sr,t_,r_,dc,Fo,lc;lc===void 0&&BO();qh.exports={notify:GO,fatal:qO,error:fc,warn:Gh,info:n_,debug:xh,trace:Hh,setLogLevel:Xk,log_level:sr,loggerWithTag:Kk,suppressLogging:Wk,initLogSettings:BO,setupConsoleLogging:HO,logCustomLevel:Jk,closeLogFile:Bh,getLogFilePath:()=>dc,OUTPUTS:vO,AuthAuditLog:tV};kk("logger",qh.exports);function BO(e=!1){try{if(lc===void 0||e){Bh();let t=jk(),r=LO(["ROOTPATH"]);try{lc=PO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Bi.pathExistsSync(ps.join(r.ROOTPATH,mt.HDB_CONFIG_FILE)))throw n}({level:sr,config_log_path:r_,to_file:ms,to_stream:Kn}=Zk(r.ROOTPATH?ps.join(r.ROOTPATH,mt.HDB_CONFIG_FILE):lc.get("settings_path"))),t_=mt.LOG_NAMES.HDB,dc=ps.join(r_,t_)}}catch(t){if(lc=void 0,t.code===mt.NODE_ERROR_CODES.ENOENT||t.code===mt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=LO(Object.keys(mt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=mt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===mt.CONFIG_PARAMS.LOGGING_LEVEL){sr=u;continue}if(c===mt.CONFIG_PARAMS.LOGGING_STDSTREAMS){Kn=u;continue}c===mt.CONFIG_PARAMS.LOGGING_FILE&&(ms=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=eV();ms=ms===void 0?s:ms,ms=MO(ms),Kn=Kn===void 0?i:Kn,Kn=MO(Kn),sr=sr===void 0?n:sr,r_=Vk,t_=mt.LOG_NAMES.INSTALL,dc=ps.join(r_,t_);return}throw fc("Error initializing log settings"),fc(t),t}process.env.DEV_MODE&&(Kn=!0),HO()}a(BO,"initLogSettings");var Ph=!0;function HO(){qo("error",fc),qo("warn",Gh),qo("log",n_),qo("info",n_),qo("debug",xh),qo("trace",Hh)}a(HO,"setupConsoleLogging");function qo(e,t){console[e]=function(...r){if(Ph&&t(...r),!/PM2 log:|App \[/.test(r[0]))return _c[e](...r)}}a(qo,"logConsole");function Kk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(GO),fatal:r(qO),error:r(fc),warn:r(Gh),info:r(n_),debug:r(xh),trace:r(Hh)};function r(n){return function(...s){return n(t,...s)}}}a(Kk,"loggerWithTag");function Wk(e){try{Ph=!1,e()}finally{Ph=!0}}a(Wk,"suppressLogging");var Qk=Gk?.name?.replace(/ /g,"-")||"main";function Ss(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||Qk+"/"+qk);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(Ss,"createLogRecord");function Ec(e){ms&&xO(e),Kn&&process.stdout.write(e)}a(Ec,"logStdOut");function s_(e){ms&&xO(e),Kn&&process.stderr.write(e)}a(s_,"logStdErr");function xO(e){zk(),Fo?Bi.appendFileSync(Fo,e):_c.log(e)}a(xO,"logToFile");function Bh(){try{Bi.closeSync(Fo)}catch{}Fo=null}a(Bh,"closeLogFile");function zk(){if(!Fo){try{if(!dc)debugger;Fo=Bi.openSync(dc,"a")}catch(e){_c.error(e)}setTimeout(()=>{Bh()},Yk).unref()}}a(zk,"openLogFile");function n_(...e){ir[sr]<=ir.info&&Ec(Ss("info",e))}a(n_,"info");function Hh(...e){ir[sr]<=ir.trace&&Ec(Ss("trace",e))}a(Hh,"trace");function fc(...e){ir[sr]<=ir.error&&s_(Ss("error",e))}a(fc,"error");function xh(...e){ir[sr]<=ir.debug&&Ec(Ss("debug",e))}a(xh,"debug");function GO(...e){ir[sr]<=ir.notify&&Ec(Ss("notify",e))}a(GO,"notify");function qO(...e){ir[sr]<=ir.fatal&&s_(Ss("fatal",e))}a(qO,"fatal");function Gh(...e){ir[sr]<=ir.warn&&s_(Ss("warn",e))}a(Gh,"warn");function Jk(e,t,...r){t===vO.STDERR?s_(Ss(e,r)):Ec(Ss(e,r))}a(Jk,"logCustomLevel");function jk(){let e;try{e=Fk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ps.join(e,mt.HDB_HOME_DIR_NAME,mt.BOOT_PROPS_FILE_NAME);return Bi.existsSync(t)||(t=ps.join(vh,"utility/hdb_boot_properties.file")),t}a(jk,"getPropsFilePath");function Xk(e){sr=e}a(Xk,"setLogLevel");function MO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(MO,"autoCastBoolean");function Zk(e){try{if(e.includes("config/settings.js")){let o=PO(e);return{level:o.get(mt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ps.dirname(o.get(mt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(mt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(mt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=UO.parseDocument(Bi.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===mt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Zk,"getLogConfig");function eV(){try{let e=UO.parseDocument(Bi.readFileSync($k,"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(eV,"getDefaultConfig");function tV(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(tV,"AuthAuditLog")});var kO=R((ace,FO)=>{"use strict";var rV=require("util"),nV=require("path"),sV=require("child_process"),iV=rV.promisify(sV.execFile),oV=1e3*1e3*10;FO.exports={findPs:aV};async function aV(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await iV("ps",["wwxo",`pid,${r}`],{maxBuffer:oV});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:nV.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(aV,"findPs")});var ut=R((uce,$O)=>{"use strict";var cV="__dbis__",uV="__txns__",lV="__environment_name__",_V="__dbi_defintion__",dV={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"},fV=["__createdtime__","__updatedtime__"],EV="\uFFFF",VO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},hV=Object.values(VO);$O.exports={AUDIT_STORE_NAME:uV,INTERNAL_DBIS_NAME:cV,DBI_DEFINITION_NAME:_V,SEARCH_TYPES:dV,TIMESTAMP_NAMES:fV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:lV,TRANSACTIONS_DBI_NAMES_ENUM:VO,TRANSACTIONS_DBIS:hV,OVERFLOW_MARKER:EV}});var Lr=R((lce,ZO)=>{"use strict";var YO=M(),KO=ut(),WO={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},QO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),zO={500:QO("There was an error processing your request."),400:"Invalid request"},mV=zO[WO.INTERNAL_SERVER_ERROR],pV={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.`},SV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},TV={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"},gV={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 ${KO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${KO.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"},RV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${YO.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 ${YO.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"},JO={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"},AV={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."},OV={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`},bV={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"},NV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},yV={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`},jO={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.`},XO={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}`},IV={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."},wV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},CV={...JO,...TV,...pV,...AV,...OV,...bV,...NV,...yV,...RV,...jO,...XO,...IV,...wV,...SV};ZO.exports={CHECK_LOGS_WRAPPER:QO,HDB_ERROR_MSGS:CV,DEFAULT_ERROR_MSGS:zO,DEFAULT_ERROR_RESP:mV,HTTP_STATUS_CODES:WO,LMDB_ERRORS_ENUM:gV,AUTHENTICATION_ERROR_MSGS:JO,VALIDATION_ERROR_MSGS:jO,ITC_ERRORS:XO}});var ne=R((dce,rb)=>{"use strict";var ko=Lr(),DV=$(),LV=M(),i_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,eb),this.statusCode=n||ko.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(ko.DEFAULT_ERROR_MSGS[n]?ko.DEFAULT_ERROR_MSGS[n]:ko.DEFAULT_ERROR_MSGS[ko.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&&DV[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}},kh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function eb(e,t,r,n=LV.LOG_LEVELS.ERROR,s=null,i=!1){if(tb(e))return e;let o=new i_(e,t,r,n,s);return i&&delete o.stack,o}a(eb,"handleHDBError");function tb(e){return e.__proto__.constructor.name===i_.name}a(tb,"isHDBError");rb.exports={isHDBError:tb,handleHDBError:eb,ClientError:Fh,ServerError:kh,hdb_errors:ko}});var ze=R((Ece,ub)=>{"use strict";var Tc=M(),MV=Q(),or=Z(),gc=require("path"),UV=require("minimist"),nb=require("fs-extra"),sb=require("lodash");or.initSync();var{CONFIG_PARAMS:ei,DATABASES_PARAM_CONFIG:hc,SYSTEM_SCHEMA_NAME:o_}=Tc,mc,pc,Sc;function ib(){if(mc!==void 0)return mc;if(or.getHdbBasePath()!==void 0)return mc=or.get(ei.STORAGE_PATH)||gc.join(or.getHdbBasePath(),Tc.DATABASES_DIR_NAME),mc}a(ib,"getBaseSchemaPath");function ob(){if(pc!==void 0)return pc;if(or.getHdbBasePath()!==void 0)return pc=cb(o_),pc}a(ob,"getSystemSchemaPath");function ab(){if(Sc!==void 0)return Sc;if(or.getHdbBasePath()!==void 0)return Sc=or.get(Tc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||gc.join(or.getHdbBasePath(),Tc.TRANSACTIONS_DIR_NAME),Sc}a(ab,"getTransactionAuditStoreBasePath");function PV(e,t){let r=or.get(ei.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||gc.join(ab(),e.toString())}a(PV,"getTransactionAuditStorePath");function cb(e,t){e=e.toString(),t=t&&t.toString();let r=or.get(Tc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||gc.join(ib(),e)}a(cb,"getSchemaPath");function vV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,UV(process.argv));let n=r[ei.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!MV.isObject(n))throw o;i=n}for(let o of i){let c=o[o_];if(!c)continue;let u=or.get(ei.DATABASES);u=u??{};let _=c?.tables?.[t]?.[hc.PATH];if(_)return sb.set(u,[o_,hc.TABLES,t,hc.PATH],_),or.setProperty(ei.DATABASES,u),_;let l=c?.[hc.PATH];if(l)return sb.set(u,[o_,hc.PATH],l),or.setProperty(ei.DATABASES,u),l}}let s=r[ei.STORAGE_PATH.toUpperCase()];if(s){if(!nb.pathExistsSync(s))throw new Error(s+" does not exist");let i=gc.join(s,e);return nb.mkdirsSync(i),or.setProperty(ei.STORAGE_PATH,s),i}return ob()}a(vV,"initSystemSchemaPaths");function BV(){mc=void 0,pc=void 0,Sc=void 0}a(BV,"resetPaths");ub.exports={getBaseSchemaPath:ib,getSystemSchemaPath:ob,getTransactionAuditStorePath:PV,getTransactionAuditStoreBasePath:ab,getSchemaPath:cb,initSystemSchemaPaths:vV,resetPaths:BV}});var Mr=R((Sce,Eb)=>{"use strict";var HV=Lr().LMDB_ERRORS_ENUM,mce=require("lmdb"),xV=ut(),pce=require("buffer").Buffer,{OVERFLOW_MARKER:lb,MAX_SEARCH_KEY_LENGTH:a_}=xV,_b=["number","string","symbol","boolean","bigint"];function GV(e){if(e=e?.primaryStore||e,!e)throw new Error(HV.ENV_REQUIRED)}a(GV,"validateEnv");function qV(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(qV,"stringifyData");function FV(e){return e instanceof Date?e.valueOf():e}a(FV,"convertKeyValueToWrite");function kV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(_b.includes(typeof e))return e.length>a_?[e.slice(0,a_)+lb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(_b.includes(typeof i))i.length>a_?r.push(i.slice(0,a_)+lb):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(kV,"getIndexedValues");var c_=0,db=0;function fb(){db=Date.now()-performance.now()}a(fb,"adjustStartTime");fb();var VV=6e4;setInterval(fb,VV).unref();function $V(){let e=performance.now()+db;return e>c_?(c_=e,e):(c_+=488e-6,c_)}a($V,"getNextMonotonicTime");Eb.exports={validateEnv:GV,stringifyData:qV,convertKeyValueToWrite:FV,getNextMonotonicTime:$V,getIndexedValues:kV}});var hb,bn,Vh,Rc=Re(()=>{hb=require("events"),bn=class extends hb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Vh;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)}},Vh=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 Hi={};qe(Hi,{server:()=>nt});var mb,nt,ar=Re(()=>{mb=require("../index"),nt={};(0,mb._assignPackageExport)("server",nt)});var Kh={};qe(Kh,{loadGQLSchema:()=>WV,start:()=>Yh,startOnMainThread:()=>KV});function Yh({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 S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let v=function(P){if(P.kind==="NonNullType"){let j=v(P.type);return j.nullable=!1,j}if(P.kind==="ListType")return{type:"array",elements:v(P.type)};let H={type:P.name?.value};return Object.defineProperty(H,"location",{value:P.loc.startToken}),H};a(v,"getProperty");let T=S.name.value,A=[],g={table:null,database:null,properties:A};f.set(T,g);for(let P of S.directives){if(P.name.value==="table"){for(let k of P.arguments)g[k.name.value]=k.value.value;g.schema&&(g.database=g.schema),g.table||(g.table=T),g.audit&&(g.audit=g.audit!=="false"),g.attributes=g.properties,E.push(g)}if(P.name.value==="sealed"&&(g.sealed=!0),P.name.value==="export"){g.export=!0;for(let k of P.arguments)k.name.value==="name"&&(g.export={name:k.value.value})}}let L=!1;for(let P of S.fields){let k=v(P.type);k.name=P.name.value,A.push(k);for(let H of P.directives)if(H.name.value==="primaryKey")L?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,L=!0);else if(H.name.value==="indexed")k.indexed=!0;else if(H.name.value==="relationship"){let j={};for(let z of H.arguments)j[z.name.value]=z.value.value;k.relationship=j}else if(H.name.value==="createdTime")k.assignCreatedTime=!0;else if(H.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(H.name.value==="expiresAt")k.expiresAt=!0;else if(H.name.value==="allow"){let j=k.authorizedRoles=[];for(let z of H.arguments)z.name.value==="role"&&j.push(z.value.value)}}g.type=T,T==="Query"&&(h=g)}function p(S){let T=f.get(S.type);T?(Object.defineProperty(S,"properties",{value:T.properties}),Object.defineProperty(S,"definition",{value:T})):S.type==="array"?p(S.elements):YV.includes(S.type)||(0,pb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of f.values())for(let T of S.properties)p(T);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,$h.dirname)(n),S.tableClass):i.set((0,$h.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var $h,pb,YV,KV,WV,Sb=Re(()=>{$h=require("path");Ae();pb=B(Je()),YV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Yh,"start");KV=Yh,WV=Yh({ensureTable:lt}).handleFile});async function u_(e){return QV?(Ac||(Ac=zV(jV)),(await(await Ac).import(e)).namespace):import(e)}async function zV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Ac=new Compartment({console,Math,Date,fetch:JV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,gb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:kt,tables:Ur,databases:st})}};let n=await(0,Tb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Ac}function JV(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 jV(){return{Resource:kt,tables:Ur}}var Tb,gb,QV,Ac,Wh=Re(()=>{Nn();Ae();Tb=require("fs/promises"),gb=require("path"),QV=!1;a(u_,"secureImport");a(zV,"getCompartment");a(JV,"secureOnlyFetch");a(jV,"getGlobalVars")});var zh={};qe(zh,{handleFile:()=>XV});async function XV(e,t,r,n){let s=new Map,i=(0,Rb.pathToFileURL)(r).toString(),o=await u_(i);u(o.default)&&n.set((0,Qh.dirname)(t),o.default),c(o,(0,Qh.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 Rb,Qh,Ab=Re(()=>{Rb=require("url");Wh();Qh=require("path");a(XV,"handleFile")});var jh={};qe(jh,{start:()=>ZV});function ZV({resources:e}){e.set("login",Jh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Jh,Ob=Re(()=>{Nn();a(ZV,"start");Jh=class extends kt{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 Db={};qe(Db,{parse:()=>Zh,streamAsJSON:()=>Oc,stringify:()=>xi});function Oc(e){return new Xh({value:e})}function bb(e){return console.error(e),JSON.stringify(e.toString())}function Nb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function xi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===wb)return Cb(e);if(t.resolution)return t.resolution.then(()=>xi(e));throw t}}function Cb(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+=Cb(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+xi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Zh(e){return r$.test(e)?e$.parse(e):JSON.parse(e)}var yb,Ib,e$,t$,wb,Xh,r$,em=Re(()=>{yb=require("stream"),Ib=B(require("json-bigint-fixes")),e$=(0,Ib.default)({useNativeBigInt:!0}),t$=1e4,wb={};BigInt.prototype.toJSON=function(){throw wb};a(Oc,"streamAsJSON");Xh=class extends yb.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),bb)}catch(s){yield bb(s)}else yield xi(t)}else yield xi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Nb(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>t$?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 Nb(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(bb,"handleError");a(Nb,"when");a(xi,"stringify");a(Cb,"jsStringify");r$=/[[,:]\s*-?\d{16,}/;a(Zh,"parse")});var Vb=R((Pce,kb)=>{"use strict";var tm=require("recursive-iterator"),n$=require("alasql"),rm=require("clone"),Lb=Q(),{handleHDBError:Mb,hdb_errors:s$}=ne(),{HDB_ERROR_MSGS:Ub,HTTP_STATUS_CODES:Pb}=s$,{getDatabases:i$}=(Ae(),ie(Fe)),o$=["DISTINCT_ARRAY"],vb=Symbol("validateTables"),nm=Symbol("validateTable"),Uce=Symbol("getAllColumns"),Bb=Symbol("validateAllColumns"),l_=Symbol("findColumn"),Hb=Symbol("validateOrderBy"),bc=Symbol("validateSegment"),sm=Symbol("validateColumn"),xb=Symbol("setColumnsForTable"),Gb=Symbol("checkColumnsForAsterisk"),qb=Symbol("validateGroupBy"),Fb=Symbol("hasColumns"),im=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[vb](),this[Gb](),this[Bb]()}[vb](){if(this[Fb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[nm](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[nm](t.table)})}}[Fb](){let t=!1,r=new tm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[nm](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=i$();if(!r[t.databaseid])throw Mb(new Error,Ub.SCHEMA_NOT_FOUND(t.databaseid),Pb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Mb(new Error,Ub.TABLE_NOT_FOUND(t.databaseid,t.tableid),Pb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=rm(s);i.table=rm(t),this.attributes.push(i)})}[l_](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)}[Gb](){let t=new tm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[xb](r.tableid)}[xb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new n$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Bb](){this[bc](this.statement.columns,!1),this[bc](this.statement.joins,!1),this[bc](this.statement.where,!1),this[qb](this.statement.group,!1),this[bc](this.statement.order,!0)}[bc](t,r){if(!t)return;let n=new tm(t),s=[];for(let{node:i,path:o}of n)!Lb.isEmpty(i)&&!Lb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Hb](i):s.push(this[sm](i)));return s}[qb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&o$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=rm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[l_](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[l_](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`}[Hb](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[sm](t)}[sm](t){let r=this[l_](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]}};kb.exports=im});var Yb=R((Bce,$b)=>{"use strict";var om=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")}};$b.exports=om});var Wb=R((xce,Kb)=>{"use strict";var am=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Kb.exports=am});var jb={};qe(jb,{HAS_EXPIRATION:()=>Em,LAST_TIMESTAMP_PLACEHOLDER:()=>Ic,LOCAL_TIMESTAMP:()=>a$,METADATA:()=>Nc,NO_TIMESTAMP:()=>um,PENDING_LOCAL_TIME:()=>hm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>fm,RecordEncoder:()=>dm,TIMESTAMP_ASSIGN_LAST:()=>u$,TIMESTAMP_ASSIGN_NEW:()=>zb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Jb,TIMESTAMP_PLACEHOLDER:()=>__,TIMESTAMP_RECORD_PREVIOUS:()=>lm,getUpdateRecord:()=>mm,handleLocalTimeForGets:()=>h_});function _$(){return yc[0]=yc[0]^64,c$.getFloat64(0)}function h_(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?.[Nc];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?.[Nc]>=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[Nc];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(){this.timerTracked||(this.timerTracked=!0,Gi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Gi.length;u++){let _=Gi[u].deref();(!_||_.isDone||_.isCommitted)&&Gi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function mm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Vo=i?.localTime?lm|Jb:um:Vo=u?i?.localTime?lm|16384:zb|16384:um,l>0&&(c|=Em),f_=c,_m=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},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(E&&(d_=e.encoder.encode(E)),f&&i?.localTime){let A=i?.localTime,g=r.get(A);if(g){let L=Ut(g).previousLocalTime;return r.put(A,E_(o,t,n,L,T,d,d_),{ifVersion:p}),S}}r.put(Ic,E_(o,t,n,i?.localTime?1:0,T,d,d_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Qb,cm,__,Ic,fm,a$,Nc,yc,c$,um,zb,u$,Jb,lm,Em,hm,l$,d_,Vo,f_,_m,dm,Gi,wc=Re(()=>{Qb=require("msgpackr");ti();cm=B($()),__=new Uint8Array([1,1,1,1,4,64,0,0]),Ic=new Uint8Array([1,1,1,1,1,0,0,0]),fm=new Uint8Array([1,1,1,1,3,64,0,0]),a$=Symbol("local-timestamp"),Nc=Symbol("metadata"),yc=new Uint8Array(8),c$=new DataView(yc.buffer,0,8),um=0,zb=0,u$=1,Jb=3,lm=4,Em=16,hm=1,Vo=0,f_=-1,_m=0,dm=class extends Qb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(Vo||f_>=0){let i=0,o=Vo;o&&(i+=8,Vo=0);let c=f_,u=_m;c>=0&&(i+=2,f_=-1,u&&(i+=8,_m=0));let _=l$=r.call(this,n,s|2048|i);d_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(__[4]=o,__[5]=o>>8,_.set(__,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(yc,0,c),c+=8;else for(let d=0;d<8;d++)yc[d]=t[c++];u=_$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Em&&(_=(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,[Nc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(_$,"getTimestamp");a(h_,"handleLocalTimeForGets");Gi=[];setInterval(()=>{for(let e=0;e<Gi.length;e++){let t=Gi[e].deref();!t||t.isDone||t.isCommitted?Gi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(cm.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):cm.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(mm,"getUpdateRecord")});var Cc=R((Vce,Zb)=>{"use strict";var Xb=Z(),d$=M(),{RecordEncoder:f$}=(wc(),ie(jb)),kce=require("fs");Xb.initSync();var E$=Xb.get(d$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,pm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=E$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:f$})}};Zb.exports=pm});var Dc=R((Yce,eN)=>{"use strict";var Pr=Z(),an=M();Pr.initSync();var m_=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.eventTurnBatching=!1,this.noSync=Pr.get(an.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Pr.get(an.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Pr.get(an.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Pr.get(an.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Pr.get(an.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Pr.get(an.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Pr.get(an.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Pr.get(an.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Pr.get(an.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Pr.get(an.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Pr.get(an.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Pr.get(an.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};eN.exports=m_;m_.MAX_DBS=1e4});var Ke=R((Wce,lN)=>{"use strict";var Tm=require("lmdb"),yn=require("fs-extra"),vr=require("path"),p_=Mr(),nN=$(),cr=Lr().LMDB_ERRORS_ENUM,S_=Wb(),gm=Cc(),sN=Dc(),ri=ut(),tN=M(),{table:h$,resetDatabases:m$}=(Ae(),ie(Fe)),rN=Z(),In=ri.INTERNAL_DBIS_NAME,iN=ri.DBI_DEFINITION_NAME,p$="data.mdb",S$="lock.mdb",Lc=".mdb",T$="-lock",Sm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=cn(t,r),this.key_type=this.dbi[ri.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ri.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Tm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function T_(e,t){if(e===void 0)throw new Error(cr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(cr.ENV_NAME_REQUIRED)}a(T_,"pathEnvNameValidation");async function Rm(e,t,r=!0){try{await yn.access(e)}catch(n){throw n.code==="ENOENT"?new Error(cr.INVALID_BASE_PATH):n}try{let n=vr.join(e,t+Lc);return await yn.access(n,yn.constants.R_OK|yn.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await yn.access(vr.join(e,t,p$),yn.constants.R_OK|yn.constants.F_OK),vr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(cr.INVALID_ENVIRONMENT)}else throw new Error(cr.INVALID_ENVIRONMENT);throw n}}a(Rm,"validateEnvironmentPath");function g_(e,t){if(p_.validateEnv(e),t===void 0)throw new Error(cr.DBI_NAME_REQUIRED)}a(g_,"validateEnvDBIName");async function g$(e,t,r=!1,n=!1){T_(e,t);let s=vr.basename(e);t=t.toString();let i=rN.get(tN.CONFIG_PARAMS.DATABASES);i||rN.setProperty(tN.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Rm(e,t,n),oN(e,t,r)}catch(o){if(o.message===cr.INVALID_ENVIRONMENT){let c=vr.join(e,t);await yn.mkdirp(n?c:e);let u=new sN(n?c:c+Lc,!1),_=Tm.open(u);_.dbis=Object.create(null);let l=new gm(!1);_.openDB(In,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=Am(e,t,r);return _[ri.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(g$,"createEnvironment");async function R$(e,t,r,n=!0){T_(e,t),t=t.toString();let s=vr.join(e,t);return h$({table:t,database:vr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(R$,"copyEnvironment");async function oN(e,t,r=!1){T_(e,t),t=t.toString();let n=Am(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 Rm(e,t),i=vr.join(e,t+Lc),o=s!=i,c=new sN(s,o),u=Tm.open(c);u.dbis=Object.create(null);let _=cN(u);for(let l=0;l<_.length;l++)cn(u,_[l]);return u[ri.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(oN,"openEnvironment");async function A$(e,t,r=!1){T_(e,t),t=t.toString();let n=vr.join(e,t+Lc),s=await Rm(e,t);if(global.lmdb_map!==void 0){let i=Am(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await aN(o),delete global.lmdb_map[i]}}await yn.remove(s),await yn.remove(s===n?s+T$:vr.join(vr.dirname(s),S$))}a(A$,"deleteEnvironment");async function aN(e){p_.validateEnv(e);let t=e[ri.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(aN,"closeEnvironment");function Am(e,t,r=!1){let s=`${vr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(Am,"getCachedEnvironmentName");function O$(e){p_.validateEnv(e);let t=Object.create(null),r=cn(e,In);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==In)try{t[n]=Object.assign(new S_,s)}catch{nN.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(O$,"listDBIDefinitions");function cN(e){p_.validateEnv(e);let t=[],r=cn(e,In);for(let{key:n}of r.getRange({start:!1}))n!==In&&t.push(n);return t}a(cN,"listDBIs");function b$(e,t){let n=cn(e,In).getEntry(t),s=new S_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{nN.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(b$,"getDBIDefinition");function uN(e,t,r,n=!r){if(g_(e,t),t=t.toString(),t===In)throw new Error(cr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return cn(e,t)}catch(s){if(s.message===cr.DBI_DOES_NOT_EXIST){let i=new gm(r,n===!0),o=e.openDB(t,i),c=new S_(r===!0,n);return o[iN]=c,cn(e,In).putSync(t,c),e.dbis[t]=o,o}throw s}}a(uN,"createDBI");function cn(e,t){if(g_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==In?r=b$(e,t):r=new S_,r===void 0)throw new Error(cr.DBI_DOES_NOT_EXIST);let n;try{let s=new gm(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(cr.DBI_DOES_NOT_EXIST):s}return n[iN]=r,e.dbis[t]=n,n}a(cn,"openDBI");function N$(e,t){g_(e,t),t=t.toString();let r=cn(e,t),n=r.getStats();return r[ri.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(N$,"statDBI");async function y$(e,t){try{let r=vr.join(e,t+Lc);return(await yn.stat(r)).size}catch{throw new Error(cr.INVALID_ENVIRONMENT)}}a(y$,"environmentDataSize");function I$(e,t){if(g_(e,t),t=t.toString(),t===In)throw new Error(cr.CANNOT_DROP_INTERNAL_DBIS_NAME);cn(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],cn(e,In).removeSync(t)}a(I$,"dropDBI");function w$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{cn(e,i)}catch(o){if(o.message===cr.DBI_DOES_NOT_EXIST)uN(e,i,i!==t,i===t),n=!0;else throw o}}n&&m$()}a(w$,"initializeDBIs");lN.exports={openDBI:cn,openEnvironment:oN,createEnvironment:g$,listDBIs:cN,listDBIDefinitions:O$,createDBI:uN,dropDBI:I$,statDBI:N$,deleteEnvironment:A$,initializeDBIs:w$,TransactionCursor:Sm,environmentDataSize:y$,copyEnvironment:R$,closeEnvironment:aN}});var dN=R((zce,_N)=>{"use strict";var Om=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};_N.exports=Om});var EN=R((jce,fN)=>{"use strict";var bm=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}};fN.exports=bm});var mN=R((Zce,hN)=>{"use strict";var Nm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};hN.exports=Nm});var $o=R((sue,TN)=>{"use strict";var C$=Ke(),D$=dN(),L$=EN(),M$=mN(),Wn=Mr(),Mc=Lr().LMDB_ERRORS_ENUM,U$=ut(),Ts=M(),P$=Q(),v$=require("uuid"),tue=require("lmdb"),{handleHDBError:B$,hdb_errors:H$}=ne(),{OVERFLOW_MARKER:rue,MAX_SEARCH_KEY_LENGTH:nue}=U$,pN=Z();pN.initSync();var R_=pN.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),ym=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function x$(e,t,r,n,s=Wn.getNextMonotonicTime()){Dm(e,t,r,n),Im(e,t,r);let i=new D$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];SN(_,!0,s);let l=G$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return wm(o,c,n,i,s)}a(x$,"insertRecords");function G$(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][Ts.FUNC_VAL],n[o]=c)}let u=Wn.getIndexedValues(c),_=e.dbis[o];if(u){R_&&_.prefetch(u.map(l=>({key:l,value:s})),A_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}R_&&e.dbis[t].prefetch([s],A_),e.dbis[t].put(s,n,n[qi])})}a(G$,"insertRecord");function q$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(q$,"removeSkippedRecords");function SN(e,t,r){let n=r>0;(n||!Number.isInteger(e[qi]))&&(e[qi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[ym]))&&(e[ym]=r||Wn.getNextMonotonicTime()):delete e[ym]}a(SN,"setTimestamps");function Im(e,t,r){r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),C$.initializeDBIs(e,t,r)}a(Im,"initializeTransaction");async function F$(e,t,r,n,s=Wn.getNextMonotonicTime()){Dm(e,t,r,n),Im(e,t,r);let i=new L$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=Cm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return wm(c,u,n,i,s,o)}a(F$,"updateRecords");async function k$(e,t,r,n,s=Wn.getNextMonotonicTime()){try{Dm(e,t,r,n)}catch(u){throw B$(u,u.message,H$.HTTP_STATUS_CODES.BAD_REQUEST)}Im(e,t,r);let i=new M$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;P$.isEmpty(_[t])?(l=v$.v4(),_[t]=l):l=_[t];let d=Cm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return wm(o,c,n,i,s)}a(k$,"upsertRecords");async function wm(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||Wn.getNextMonotonicTime(),q$(r,i),n}a(wm,"finalizeWrite");function Cm(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(SN(r,!l,o),Number.isInteger(r[qi])&&_[qi]>r[qi])return!1;l&&s.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 T=_[h];if(typeof p=="function"){let g=p([[_]]);Array.isArray(g)&&(p=g[0][Ts.FUNC_VAL],r[h]=p)}if(p===T)continue;let A=Wn.getIndexedValues(T);if(A){R_&&S.prefetch(A.map(g=>({key:g,value:n})),A_);for(let g=0,L=A.length;g<L;g++)S.remove(A[g],n)}if(A=Wn.getIndexedValues(p),A){R_&&S.prefetch(A.map(g=>({key:g,value:n})),A_);for(let g=0,L=A.length;g<L;g++)S.put(A[g],n)}}let E=Object.assign({},_,r);c.put(n,E,E[qi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:Cm(e,t,r,n,s,i,o))}a(Cm,"updateUpsertRecord");function V$(e,t,r){if(Wn.validateEnv(e),t===void 0)throw new Error(Mc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Mc.WRITE_ATTRIBUTES_REQUIRED):new Error(Mc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(V$,"validateBasic");function Dm(e,t,r,n){if(V$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Mc.RECORDS_REQUIRED):new Error(Mc.RECORDS_MUST_BE_ARRAY)}a(Dm,"validateWrite");function A_(){}a(A_,"noop");TN.exports={insertRecords:x$,updateRecords:F$,upsertRecords:k$}});var Fi=R((oue,$$)=>{$$.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"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},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"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var zn=R((aue,AN)=>{"use strict";var RN=Q(),gN=M(),Yo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Qn=require("joi"),ni={schema_format:{pattern:Yo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},Y$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number(),Qn.array()).required(),K$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number()),W$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number()).required();function Q$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ni.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(Q$,"checkValidTable");function z$(e,t){return RN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(z$,"validateSchemaExists");function J$(e,t){let r=t.state.ancestors[0].schema;return RN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(J$,"validateTableExists");function j$(e,t){return e.toLowerCase()===gN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${gN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(j$,"validateSchemaName");AN.exports={common_validators:ni,schema_regex:Yo,hdb_schema_table:Y$,validateSchemaExists:z$,validateTableExists:J$,validateSchemaName:j$,checkValidTable:Q$,hdb_database:K$,hdb_table:W$}});var je=R((uue,ON)=>{"use strict";var ur=require("validate.js");ur.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||ur.validators.type.checks[t](e)?null:` must be a '${t}' value`};ur.validators.type.checks={Object:function(e){return ur.isObject(e)&&!ur.isArray(e)},Array:ur.isArray,Integer:ur.isInteger,Number:ur.isNumber,String:ur.isString,Date:ur.isDate,Boolean:function(e){return typeof e=="boolean"}};ur.validators.hasValidFileExt=function(e,t){return ur.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};ON.exports={validateObject:X$,validateObjectAsync:Z$,validateBySchema:e1};function X$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=ur(e,t,{format:"flat"});return r?new Error(r):null}a(X$,"validateObject");async function Z$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await ur.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(Z$,"validateObjectAsync");function e1(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(e1,"validateBySchema")});var O_=R((_ue,bN)=>{var{common_validators:Jn}=zn(),Pc=je(),Uc="is required",pt={database:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},schema:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},table:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},hash_attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length}};function vc(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(vc,"makeAttributesStrings");function t1(e){return e=vc(e),pt.table.presence=!1,pt.attribute.presence=!1,pt.hash_attribute.presence=!1,Pc.validateObject(e,pt)}a(t1,"schema_object");function r1(e){return e=vc(e),pt.table.presence={message:Uc},pt.attribute.presence=!1,pt.hash_attribute.presence=!1,Pc.validateObject(e,pt)}a(r1,"table_object");function n1(e){return e=vc(e),pt.table.presence={message:Uc},pt.attribute.presence=!1,Pc.validateObject(e,pt)}a(n1,"create_table_object");function s1(e){return e=vc(e),pt.table.presence={message:Uc},pt.attribute.presence={message:Uc},pt.hash_attribute.presence=!1,Pc.validateObject(e,pt)}a(s1,"attribute_object");function i1(e){return e=vc(e),pt.table.presence={message:Uc},pt.attribute.presence=!1,pt.hash_attribute.presence=!1,Pc.validateObject(e,pt)}a(i1,"describe_table");function o1(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(o1,"validateTableResidence");bN.exports={schema_object:t1,create_table_object:n1,table_object:r1,attribute_object:s1,describe_table:i1,validateTableResidence:o1}});var yN=R((fue,NN)=>{"use strict";var a1=require("uuid"),Lm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||a1.v4(),this.schema_table=`${this.schema}.${this.table}`}};NN.exports=Lm});var b_=R((hue,IN)=>{"use strict";var c1=yN(),Mm=class extends c1{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}};IN.exports=Mm});var CN=R((pue,wN)=>{"use strict";wN.exports=l1;var u1="inserted";function l1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===u1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(l1,"returnObject")});var N_=R((Tue,PN)=>{"use strict";var _1=M(),Um=Ke(),d1=$o(),{getSystemSchemaPath:f1,getSchemaPath:E1}=ze(),h1=Fi(),m1=O_(),p1=b_(),S1=CN(),{handleHDBError:DN,hdb_errors:MN}=ne(),LN=Q(),{HTTP_STATUS_CODES:T1}=MN,Pm=h1.hdb_attribute,UN=[];for(let e=0;e<Pm.attributes.length;e++)UN.push(Pm.attributes[e].attribute);var g1="inserted";PN.exports=R1;async function R1(e){let t=m1.attribute_object(e);if(t)throw DN(new Error,t.message,MN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&LN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw DN(new Error,r,T1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=LN.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 p1(e.schema,e.table,e.attribute,e.id);try{let i=await Um.openEnvironment(E1(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}`);Um.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Um.openEnvironment(f1(),_1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await d1.insertRecords(o,Pm.hash_attribute,UN,[s]);return S1(g1,c,{records:[s]},u)}catch(i){throw i}}a(R1,"lmdbCreateAttribute")});var Bm=R((Rue,BN)=>{var{hdb_table:A1,hdb_database:vN}=zn(),O1=je(),vm=require("joi"),b1={undefined:"undefined",null:"null"},N1=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||b1[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"),y1=vm.object({database:vN,schema:vN,table:A1,records:vm.array().items(vm.object().custom(N1)).required()});BN.exports=function(e){return O1.validateBySchema(e,y1)}});var Bc=R((bue,xN)=>{"use strict";var gs=Q(),HN=$(),Oue=Bm(),{getDatabases:I1}=(Ae(),ie(Fe)),{ClientError:ki}=ne();xN.exports=w1;function w1(e){if(gs.isEmpty(e))throw new ki("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new ki("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new ki("invalid table specified.");if(!Array.isArray(e.records))throw new ki("records must be an array");let t=I1()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new ki(`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&&gs.isEmptyOrZeroLength(o[r]))throw HN.error("a valid hash attribute must be provided with update record:",o),new ki("a valid hash attribute must be provided with update record, check log for more info");if(!gs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw HN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new ki(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gs.isEmpty(o[r])&&o[r]!==""&&n.has(gs.autoCast(o[r]))&&(o.skip=!0),n.add(gs.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(w1,"insertUpdateValidate")});var Hc=R((yue,GN)=>{"use strict";var C1=M().OPERATIONS_ENUM,Hm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=C1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};GN.exports=Hm});var xc=R((Cue,FN)=>{"use strict";var wue=Hc(),y_=M(),xm=Q(),qN=$(),D1=require("uuid"),{handleHDBError:I_,hdb_errors:L1}=ne(),{HDB_ERROR_MSGS:w_,HTTP_STATUS_CODES:C_}=L1;FN.exports=M1;function M1(e,t,r){for(let s=0;s<t.length;s++)U1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];P1(i,r,e.operation)}}a(M1,"processRows");function U1(e){if(Buffer.byteLength(String(e))>y_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw I_(new Error,w_.ATTR_NAME_LENGTH_ERR(e),C_.BAD_REQUEST,void 0,void 0,!0);if(xm.isEmptyOrZeroLength(e)||xm.isEmpty(e.trim()))throw I_(new Error,w_.ATTR_NAME_NULLISH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}a(U1,"validateAttribute");function P1(e,t,r){if(!e.hasOwnProperty(t)||xm.isEmptyOrZeroLength(e[t])){if(r===y_.OPERATIONS_ENUM.INSERT||r===y_.OPERATIONS_ENUM.UPSERT){e[t]=D1.v4();return}throw qN.error("Update transaction aborted due to record with no hash value:",e),I_(new Error,w_.RECORD_MISSING_HASH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>y_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw qN.error(e),I_(new Error,w_.HASH_VAL_LENGTH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}a(P1,"validateHash")});var VN=R((Lue,kN)=>{"use strict";var Gm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};kN.exports=Gm});var KN=R((Uue,YN)=>{"use strict";var qm=Ke(),v1=$(),$N=Lr().LMDB_ERRORS_ENUM;YN.exports=B1;async function B1(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 qm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==$N.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await qm.closeEnvironment(global.lmdb_map[n]),await qm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==$N.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){v1.error(t)}}a(B1,"cleanLMDBMap")});var Rs=R((vue,JN)=>{"use strict";var Gc=require("crypto"),H1=Z(),{CONFIG_PARAMS:x1}=M(),QN="aes-256-cbc",G1=32,q1=16,Fm=64,zN=32,F1=Fm+zN,WN=new Map;JN.exports={encrypt:k1,decrypt:V1,createNatsTableStreamName:$1};function k1(e){let t=Gc.randomBytes(G1),r=Gc.randomBytes(q1),n=Gc.createCipheriv(QN,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(k1,"encrypt");function V1(e){let t=e.substr(0,Fm),r=e.substr(Fm,zN),n=e.substr(F1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Gc.createDecipheriv(QN,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(V1,"decrypt");function $1(e,t){let r=H1.get(x1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=WN.get(r);return n||(n=Gc.createHash("md5").update(r).digest("hex"),WN.set(r,n)),n}a($1,"createNatsTableStreamName")});var As=R((xue,XN)=>{"use strict";var Hue=Br(),D_=$(),jN=O_(),Y1=Rs(),L_=Q(),{handleHDBError:M_,hdb_errors:K1}=ne(),{HDB_ERROR_MSGS:U_,HTTP_STATUS_CODES:km}=K1,W1=Z();W1.initSync();var{getDatabases:Vm}=(Ae(),ie(Fe));XN.exports={describeAll:Q1,describeTable:P_,describeSchema:z1};async function Q1(e){try{let t=L_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Vm(),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 P_({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 P_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){D_.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 D_.error("Got an error in describeAll"),D_.error(t),M_(new Error,U_.DESCRIBE_ALL_ERR)}}a(Q1,"describeAll");async function P_(e,t){L_.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=jN.describe_table(e);if(i)throw i;let c=Vm()[r];if(!c)throw M_(new Error,U_.SCHEMA_NOT_FOUND(e.schema),km.NOT_FOUND);let u=c[n];if(!u)throw M_(new Error,U_.TABLE_NOT_FOUND(e.schema,e.table),km.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=Y1.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){D_.warn(`unable to stat table dbi due to ${f}`)}return d}a(P_,"descTable");async function z1(e){L_.transformReq(e);let t=jN.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=Vm()[n];if(!i)throw M_(new Error,U_.SCHEMA_NOT_FOUND(e.schema),km.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),L_.isEmpty(u)||u.describe){let _=await P_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(z1,"describeSchema")});var Os=R((kue,ny)=>{var J1=Fi(),{callbackify:ey,promisify:j1}=require("util"),{getDatabases:ty}=(Ae(),ie(Fe));ny.exports={setSchemaDataToGlobal:ZN,getTableSchema:X1,getSystemSchema:Z1,setSchemaDataToGlobalAsync:j1(ZN)};var ry=As(),que=ey(ry.describeAll),Fue=ey(ry.describeTable);function ZN(e){global.hdb_schema=ty(),e&&e()}a(ZN,"setSchemaDataToGlobal");function X1(e,t,r){let n=ty()[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(X1,"getTableSchema");function Z1(){return J1}a(Z1,"getSystemSchema")});var Hr=R(($ue,ay)=>{"use strict";var B_=Bm(),Vt=Q(),eY=require("util"),H_=wn(),tY=Os(),sy=$(),{handleHDBError:Vi,hdb_errors:rY}=ne(),{HTTP_STATUS_CODES:$i}=rY,nY=eY.promisify(tY.getTableSchema),sY="updated",iy="inserted",oy="upserted";ay.exports={insert:oY,update:aY,upsert:cY,validation:iY,flush:uY};async function iY(e){if(Vt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Vt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Vt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await nY(e.schema,e.table),r=B_(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&&Vt.isEmptyOrZeroLength(c[n]))throw sy.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(!Vt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw sy.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Vt.isEmpty(c[n])&&c[n]!==""&&s.has(Vt.autoCast(c[n]))&&(c.skip=!0),s.add(Vt.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(iY,"validation");async function oY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=B_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);Vt.transformReq(e);let r=Vt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await H_.createRecords(e);return v_(iy,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(oY,"insertData");async function aY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=B_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);Vt.transformReq(e);let r=Vt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await H_.updateRecords(e);return Vt.isEmpty(n.existing_rows)?v_(sY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):v_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(aY,"updateData");async function cY(e){if(e.operation!=="upsert")throw Vi(new Error,"invalid operation, must be upsert",$i.INTERNAL_SERVER_ERROR);let t=B_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);Vt.transformReq(e);let r=Vt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await H_.upsertRecords(e);return v_(oy,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(cY,"upsertData");function v_(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===iy?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===oy?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(v_,"returnObject");function uY(e){return Vt.transformReq(e),H_.flush(e.schema,e.table)}a(uY,"flush")});var Ym=R((Kue,ly)=>{var lY=je(),$m=require("joi"),{hdb_table:_Y,hdb_database:cy}=zn(),uy={schema:cy,database:cy,table:_Y},dY={date:$m.date().iso().required()},fY={timestamp:$m.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};ly.exports=function(e,t){let r=t==="timestamp"?{...uy,...fY}:{...uy,...dY},n=$m.object(r);return lY.validateBySchema(e,n)}});var fy=R((Wue,dy)=>{var EY=je(),Km=require("joi"),{hdb_table:hY,hdb_database:_y}=zn(),mY=Km.object({schema:_y,database:_y,table:hY,hash_values:Km.array().required(),ids:Km.array()});dy.exports=function(e){return EY.validateBySchema(e,mY)}});var hy=R((Que,Ey)=>{"use strict";var Wm=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}},Qm=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}},zm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};Ey.exports={InsertObject:Wm,NoSQLSeachObject:Qm,DeleteResponseObject:zm}});var oi=R((Jue,gy)=>{"use strict";var py=Ym(),pY=fy(),Yi=Q(),my=require("moment"),Sy=$(),{promisify:SY,callbackify:TY}=require("util"),Ki=M(),gY=Os(),Jm=SY(gY.getTableSchema),jm=wn(),{DeleteResponseObject:RY}=hy(),{handleHDBError:si,hdb_errors:AY}=ne(),{HDB_ERROR_MSGS:x_,HTTP_STATUS_CODES:ii}=AY,OY="records successfully deleted",bY=TY(Ty);gy.exports={delete:bY,deleteRecord:Ty,deleteFilesBefore:NY,deleteAuditLogsBefore:yY};async function NY(e){let t=py(e,"date");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!my(e.date,my.ISO_8601).isValid())throw si(new Error,x_.INVALID_DATE,ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,x_.INVALID_DATE,!0);let n=Yi.checkSchemaTableExist(e.schema,e.table);if(n)throw si(new Error,n,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,n,!0);let s=await jm.deleteRecordsBefore(e);if(await Jm(e.schema,e.table),Sy.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(NY,"deleteFilesBefore");async function yY(e){let t=py(e,"timestamp");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),isNaN(e.timestamp))throw si(new Error,x_.INVALID_VALUE("Timestamp"),ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,x_.INVALID_VALUE("Timestamp"),!0);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);let n=await jm.deleteAuditLogsBefore(e);return await Jm(e.schema,e.table),Sy.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(yY,"deleteAuditLogsBefore");async function Ty(e){e.ids&&(e.hash_values=e.ids);let t=pY(e);if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);Yi.transformReq(e);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);try{await Jm(e.schema,e.table);let n=await jm.deleteRecords(e);return Yi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${OY}`),n}catch(n){if(n.message===Ki.SEARCH_NOT_FOUND_MESSAGE){let s=new RY;return s.message=Ki.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(Ty,"deleteRecord")});var G_=R((Xue,Oy)=>{var IY=require("crypto"),Ry=9;function wY(e){let t=DY(Ry),r=Ay(e+t);return t+r}a(wY,"createHash");function CY(e,t){let r=e?.substr(0,Ry),n=r+Ay(t+r);return e===n}a(CY,"validateHash");function DY(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(DY,"generateSalt");function Ay(e){return IY.createHash("md5").update(e).digest("hex")}a(Ay,"md5");Oy.exports={hash:wY,validate:CY}});var Ny=R((ele,by)=>{var Xm=je(),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 LY(e){return Jt.password.presence=!0,Jt.username.presence=!0,Jt.role.presence=!0,Jt.active.presence=!0,Xm.validateObject(e,Jt)}a(LY,"addUserValidation");function MY(e){return Jt.password.presence=!1,Jt.username.presence=!0,Jt.role.presence=!1,Jt.active.presence=!1,Xm.validateObject(e,Jt)}a(MY,"alterUserValidation");function UY(e){return Jt.password.presence=!1,Jt.username.presence=!0,Jt.role.presence=!1,Jt.active.presence=!1,Xm.validateObject(e,Jt)}a(UY,"dropUserValidation");by.exports={addUserValidation:LY,alterUserValidation:MY,dropUserValidation:UY}});var ke=R((nle,Iy)=>{"use strict";var{platform:rle}=require("os"),PY="nats-server.zip",Zm="nats-server",vY=process.platform==="win32"?`${Zm}.exe`:Zm,BY=/^[^\s.,*>]+$/,yy="__request__",HY=a(e=>`${e}.${yy}`,"REQUEST_SUBJECT"),xY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},GY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},qY={HUB:"hub.pid",LEAF:"leaf.pid"},FY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},kY={SUCCESS:"success",ERROR:"error"},VY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},$Y={TXN:"txn",MSGID:"msgid"},Ko={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},YY={[Ko.ERR]:1,[Ko.WRN]:2,[Ko.INF]:3,[Ko.DBG]:4,[Ko.TRC]:5},KY={debug:"-D",trace:"-DVV"};Iy.exports={NATS_SERVER_ZIP:PY,NATS_SERVER_NAME:Zm,NATS_BINARY_NAME:vY,PID_FILES:qY,NATS_CONFIG_FILES:GY,SERVER_SUFFIX:FY,NATS_TERM_CONSTRAINTS_RX:BY,REQUEST_SUFFIX:yy,UPDATE_REMOTE_RESPONSE_STATUSES:kY,CLUSTER_STATUS_STATUSES:VY,REQUEST_SUBJECT:HY,SUBJECT_PREFIXES:$Y,MSG_HEADERS:xY,LOG_LEVELS:Ko,LOG_LEVEL_FLAGS:KY,LOG_LEVEL_HIERARCHY:YY}});var Cy=R((ile,wy)=>{"use strict";var WY={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
+ "use strict";var Oq=Object.create;var cc=Object.defineProperty;var bq=Object.getOwnPropertyDescriptor;var yq=Object.getOwnPropertyNames;var Nq=Object.getPrototypeOf,Iq=Object.prototype.hasOwnProperty;var a=(e,t)=>cc(e,"name",{value:t,configurable:!0});var Ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qe=(e,t)=>{for(var r in t)cc(e,r,{get:t[r],enumerable:!0})},_O=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yq(t))!Iq.call(e,s)&&s!==r&&cc(e,s,{get:()=>t[s],enumerable:!(n=bq(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Oq(Nq(e)):{},_O(t||!e||!e.__esModule?cc(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>_O(cc({},"__esModule",{value:!0}),e);var EO=g((jae,fO)=>{var wq=require("fast-glob"),{statSync:Dh,existsSync:Lh,readFileSync:Cq,writeFileSync:Dq}=require("fs"),{spawnSync:Lq,spawn:Mq,execFileSync:Jae}=require("child_process"),{isMainThread:Pq}=require("worker_threads"),{join:Xs,relative:dO}=require("path"),{PACKAGE_ROOT:bn}=P(),{tmpdir:Uq,platform:vq}=require("os");require("source-map-support").install();var Bq=["resources","server","dataLayer","components"],uc="ts-build",Mh,Hq=__filename.endsWith("tsBuild.js");if(Hq){if(Pq){let r;try{Dh(Xs(bn,uc)),r=!0}catch{}if(r)for(let n of wq.sync(Bq.map(s=>s+"/**/*.ts"),{cwd:bn})){let s=0,i=0;try{s=Dh(Xs(bn,n)).mtimeMs-5e3,i=Dh(Xs(bn,uc,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."),Mh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Mh=!0;if(Mh){let n=Xs(bn,"node_modules/.bin/tsc");vq()==="win32"&&(n+=".cmd");let s=Lq(n,{cwd:bn});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Xs(Uq(),"harperdb-tsc.pid"),o;if(Lh(i))try{process.kill(+Cq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Mq(n,["--watch"],{cwd:bn,detached:!0,stdio:"ignore"});Dq(i,c.pid.toString()),c.unref()}}}}let e=fO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(bn)&&!n[0].includes("node_modules")){let i=dO(bn,n[0]),o;i.startsWith(uc)?o=Xs(bn,dO(uc,i)):o=Xs(bn,uc,i);let c=Xs(o,r),u=c+".js";if(Lh(u))return u;if(c.includes(".")&&Lh(c))return c}return t(r,n,s)}}});var P=g((ece,wO)=>{"use strict";var an=require("path"),xq=require("fs"),{relative:Xae,join:Zae}=an,{existsSync:Gq}=xq;function qq(){let e=__dirname;for(;!Gq(an.join(e,"package.json"));){let t=an.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(qq,"getHDBPackageRoot");var Zs=qq(),hO="js",e_=hO,Fq="harperdb-config.yaml",kq="defaultConfig.yaml",Vq="hdb",mO=`harperdb.${e_}`,pO=`customFunctionsServer.${e_}`,$q=`restartHdb.${e_}`,Uh="HarperDB",Zl="Custom Functions",t_="Clustering Hub",r_="Clustering Leaf",Yq="Clustering Ingest Service",Kq="Clustering Reply Service",Wq="foreground.pid",Qq="hdb.pid",zq="data",Jq={HDB:Uh,CLUSTERING_HUB:t_,CLUSTERING_LEAF:r_,CLUSTERING_INGEST_SERVICE:Yq,CLUSTERING_REPLY_SERVICE:Kq,CUSTOM_FUNCTIONS:Zl,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"},jq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Xq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Zq={harperdb:Uh,"clustering hub":t_,"clustering leaf":r_,"custom functions":Zl,custom_functions:Zl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},eF={CLUSTERING_HUB_PROC_DESCRIPTOR:t_,CLUSTERING_LEAF_PROC_DESCRIPTOR:r_},Ph={HDB:an.join(Zs,"server/harperdb"),CUSTOM_FUNCTIONS:an.join(Zs,"server/customFunctions"),CLUSTERING_HUB:an.join(Zs,"server/nats"),CLUSTERING_LEAF:an.join(Zs,"server/nats")},tF={HDB:an.join(Ph.HDB,mO),CUSTOM_FUNCTIONS:an.join(Ph.CUSTOM_FUNCTIONS,pO)},rF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:an.join(Zs,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:an.join(Zs,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:an.join(Zs,"launchServiceScripts/launchUpdateNodes4-0-0.js")},nF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},SO="support@harperdb.io",sF="customer-success@harperdb.io",TO=1,iF=4141,gO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",oF="https://www.harperdb.io/product",aF=`For support, please submit a request at ${gO} or contact ${SO}`,RO=`For license support, please contact ${sF}`,cF="None of the specified records were found.",uF="hash attribute not found",lF=`Your current license only supports ${TO} role. ${RO}`,_F="Your current license only supports 3 connections to a node.",dF="127.0.0.1",fF=1,EF=/^\.$/,hF=/^\.\.$/,mF="U+002E",pF=/\//g,SF="U+002F",TF=/U\+002F/g,gF=/^U\+002E$/,RF=/^U\+002EU\+002E$/,AF="d",OF=999999,bF="*",yF="--max-old-space-size=",NF="system",IF="__hdb_hash",wF=".harperdb",CF=".hdb",DF="keys",LF="hdb_boot_properties.file",MF=".updateConfig.json",PF="SIGTSTP",UF=24,vF=6e4,BF=448,HF="blob",xF="trash",GF="database",qF="schema",FF="transactions",kF=".count",VF="id",$F="PROCESS_NAME",AO={SETTINGS_PATH_KEY:"settings_path"},OO=require("lodash"),YF={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"},KF={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},WF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},QF={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"},zF={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"},Pr="hdb_internal:",JF={CREATE_SCHEMA:Pr+"create_schema",CREATE_TABLE:Pr+"create_table",CREATE_ATTRIBUTE:Pr+"create_attribute",ADD_USER:Pr+"add_user",ALTER_USER:Pr+"alter_user",DROP_USER:Pr+"drop_user",HDB_NODES:Pr+"hdb_nodes",HDB_USERS:Pr+"hdb_users",HDB_WORKERS:Pr+"hdb_workers",CATCHUP:Pr+"catchup",SCHEMA_CATCHUP:Pr+"schema_catchup",WORKER_ROOM:Pr+"cluster_workers"},jF={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"},XF="060493.ks",ZF=".license",ek={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},ee={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"},tk={CSV:".csv",JSON:".json"},rk={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},nk={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},lc={};lc[ee.INSERT]=ee.INSERT;lc[ee.UPDATE]=ee.UPDATE;lc[ee.UPSERT]=ee.UPSERT;lc[ee.DELETE]=ee.DELETE;var Be=Object.create(null);Be[ee.DESCRIBE_ALL]=ee.DESCRIBE_ALL;Be[ee.DESCRIBE_TABLE]=ee.DESCRIBE_TABLE;Be[ee.DESCRIBE_SCHEMA]=ee.DESCRIBE_SCHEMA;Be[ee.READ_LOG]=ee.READ_LOG;Be[ee.ADD_NODE]=ee.ADD_NODE;Be[ee.LIST_USERS]=ee.LIST_USERS;Be[ee.LIST_ROLES]=ee.LIST_ROLES;Be[ee.USER_INFO]=ee.USER_INFO;Be[ee.SQL]=ee.SQL;Be[ee.GET_JOB]=ee.GET_JOB;Be[ee.SEARCH_JOBS_BY_START_DATE]=ee.SEARCH_JOBS_BY_START_DATE;Be[ee.DELETE_FILES_BEFORE]=ee.DELETE_FILES_BEFORE;Be[ee.EXPORT_LOCAL]=ee.EXPORT_LOCAL;Be[ee.EXPORT_TO_S3]=ee.EXPORT_TO_S3;Be[ee.CLUSTER_STATUS]=ee.CLUSTER_STATUS;Be[ee.REMOVE_NODE]=ee.REMOVE_NODE;Be[ee.RESTART]=ee.RESTART;Be[ee.CUSTOM_FUNCTIONS_STATUS]=ee.CUSTOM_FUNCTIONS_STATUS;Be[ee.GET_CUSTOM_FUNCTIONS]=ee.GET_CUSTOM_FUNCTIONS;Be[ee.GET_CUSTOM_FUNCTION]=ee.GET_CUSTOM_FUNCTION;Be[ee.SET_CUSTOM_FUNCTION]=ee.SET_CUSTOM_FUNCTION;Be[ee.DROP_CUSTOM_FUNCTION]=ee.DROP_CUSTOM_FUNCTION;Be[ee.ADD_CUSTOM_FUNCTION_PROJECT]=ee.ADD_CUSTOM_FUNCTION_PROJECT;Be[ee.DROP_CUSTOM_FUNCTION_PROJECT]=ee.DROP_CUSTOM_FUNCTION_PROJECT;Be[ee.PACKAGE_CUSTOM_FUNCTION_PROJECT]=ee.PACKAGE_CUSTOM_FUNCTION_PROJECT;Be[ee.DEPLOY_CUSTOM_FUNCTION_PROJECT]=ee.DEPLOY_CUSTOM_FUNCTION_PROJECT;var sk={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",COPYDB:"copy-db"},ik={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},bO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},ok=OO.invert(bO),ak={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"},I={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_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",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",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_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",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",HTTP_THREADRANGE:"http_threadRange",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:"operationsApi_tls",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_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",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_REQUIRED:"mqtt_network_mtls_required",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",TLS:"tls",CLONED:"cloned"},yO={settings_path:AO.SETTINGS_PATH_KEY,hdb_root_key:I.ROOTPATH,hdb_root:I.ROOTPATH,rootpath:I.ROOTPATH,server_port_key:I.OPERATIONSAPI_NETWORK_PORT,server_port:I.OPERATIONSAPI_NETWORK_PORT,cert_key:I.TLS_CERTIFICATE,certificate:I.TLS_CERTIFICATE,private_key_key:I.TLS_PRIVATEKEY,private_key:I.TLS_PRIVATEKEY,http_secure_enabled_key:I.OPERATIONSAPI_NETWORK_HTTPS,https_on:I.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:I.OPERATIONSAPI_NETWORK_CORS,cors_on:I.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:I.LOGGING_LEVEL,log_level:I.LOGGING_LEVEL,log_path_key:I.LOGGING_ROOT,log_path:I.LOGGING_ROOT,clustering_node_name_key:I.CLUSTERING_NODENAME,node_name:I.CLUSTERING_NODENAME,clustering_enabled_key:I.CLUSTERING_ENABLED,clustering:I.CLUSTERING_ENABLED,max_http_threads:I.THREADS_COUNT,max_hdb_processes:I.THREADS_COUNT,server_timeout_key:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:I.LOGGING_AUDITLOG,disable_transaction_log:I.LOGGING_AUDITLOG,operation_token_timeout_key:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:I.HTTP_PORT,custom_functions_port:I.HTTP_PORT,custom_functions_directory_key:I.COMPONENTSROOT,custom_functions_directory:I.COMPONENTSROOT,max_custom_function_processes:I.THREADS_COUNT,log_to_file:I.LOGGING_FILE,log_to_stdstreams:I.LOGGING_STDSTREAMS,local_studio_on:I.LOCALSTUDIO_ENABLED,clustering_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:I.CLUSTERING_USER,clustering_enabled:I.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:I.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:I.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:I.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:I.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:I.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:I.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:I.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:I.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:I.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:I.CLUSTERING_NODENAME,clustering_tls_certificate:I.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:I.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:I.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:I.CLUSTERING_TLS_INSECURE,clustering_tls_verify:I.CLUSTERING_TLS_VERIFY,clustering_loglevel:I.CLUSTERING_LOGLEVEL,clustering_republishmessages:I.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:I.CLUSTERING_DATABASELEVEL,customfunctions_network_port:I.HTTP_PORT,customfunctions_tls_certificate:I.TLS_CERTIFICATE,customfunctions_network_cors:I.HTTP_CORS,customfunctions_network_corsaccesslist:I.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:I.HTTP_HEADERSTIMEOUT,customfunctions_network_https:I.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:I.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:I.HTTP_TIMEOUT,customfunctions_tls:I.TLS,http_threads:I.THREADS_COUNT,threads:I.THREADS_COUNT,threads_count:I.THREADS_COUNT,threads_debug:I.THREADS_DEBUG,threads_debug_startingport:I.THREADS_DEBUG_STARTINGPORT,threads_debug_port:I.THREADS_DEBUG_PORT,threads_debug_host:I.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:I.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:I.THREADS_MAXHEAPMEMORY,http_session_affinity:I.HTTP_SESSIONAFFINITY,http_compressionthreshold:I.HTTP_COMPRESSIONTHRESHOLD,http_cors:I.HTTP_CORS,http_corsaccesslist:I.HTTP_CORSACCESSLIST,http_headerstimeout:I.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,http_timeout:I.HTTP_TIMEOUT,http_port:I.HTTP_PORT,http_secureport:I.HTTP_SECUREPORT,http_mtls:I.HTTP_MTLS,http_mtls_user:I.HTTP_MTLS_USER,http_mtls_required:I.HTTP_MTLS_REQUIRED,http_maxheadersize:I.HTTP_MAXHEADERSIZE,http_threadrange:I.HTTP_THREADRANGE,customfunctions_processes:I.THREADS_COUNT,customfunctions_root:I.COMPONENTSROOT,localstudio_enabled:I.LOCALSTUDIO_ENABLED,logging_file:I.LOGGING_FILE,logging_level:I.LOGGING_LEVEL,logging_root:I.LOGGING_ROOT,logging_rotation_enabled:I.LOGGING_ROTATION_ENABLED,logging_rotation_compress:I.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:I.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:I.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:I.LOGGING_ROTATION_PATH,logging_stdstreams:I.LOGGING_STDSTREAMS,logging_auditlog:I.LOGGING_AUDITLOG,logging_auditretention:I.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:I.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:I.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:I.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:I.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:I.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:I.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:I.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls:I.OPERATIONSAPI_TLS,operationsapi_tls_certificate:I.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:I.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:I.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:I.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:I.ROOTPATH,databases:I.DATABASES,storage_path:I.STORAGE_PATH,storage_maxtransactionqueuetime:I.STORAGE_MAXTRANSACTIONQUEUETIME,ignorescripts:I.IGNORE_SCRIPTS,mqtt_network_port:I.MQTT_NETWORK_PORT,mqtt_websocket:I.MQTT_WEBSOCKET,mqtt_network_secureport:I.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:I.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:I.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:I.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:I.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:I.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:I.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:I.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:I.AUTHENTICATION_CACHETTL,authentication_enablesessions:I.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:I.COMPONENTSROOT,tls:I.TLS,tls_certificate:I.TLS_CERTIFICATE,tls_privatekey:I.TLS_PRIVATEKEY,tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,tls_ciphers:I.TLS_CIPHERS};for(let e in I){let t=I[e];yO[t.toLowerCase()]=t}var ck={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},uk={csv_file_load:"csv_file_load",csv_data_load:ee.CSV_DATA_LOAD,csv_url_load:ee.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"},lk={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"},_k={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},dk={VERSION_DEFAULT:"2.2.0"},fk={DEVELOPMENT:8192,DEFAULT:512},Ek={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"},hk={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"},mk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},NO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},pk=Symbol("metadata"),Sk="__clustering__",Tk=Object.values(NO),gk=15984864e5,IO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Rk=OO.invert(IO),Ak={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"},Ok=111,bk=`\r
2
+ `,yk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Nk=["*","%"],Ik="unauthorized_access",wk="func_val",Ck={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Dk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Lk={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",NATS_CONSUMER_UPDATE:"nats_consumer_update"},Mk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Pk={HTTP:"http"},Uk={STOPPED:"stopped",ONLINE:"online"},vk="3.x.x",Bk={SUCCESS:"success",FAILURE:"failure"},Hk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};wO.exports={LOCAL_HARPERDB_OPERATIONS:Be,HDB_SUPPORT_ADDRESS:SO,HDB_SUPPORT_URL:gO,HDB_PRICING_URL:oF,SUPPORT_HELP_MSG:aF,LICENSE_HELP_MSG:RO,HDB_PROC_NAME:mO,HDB_PROC_DESCRIPTOR:Uh,CLUSTERING_LEAF_PROC_DESCRIPTOR:r_,CLUSTERING_HUB_PROC_DESCRIPTOR:t_,SYSTEM_SCHEMA_NAME:NF,HASH_FOLDER_NAME:IF,HDB_HOME_DIR_NAME:wF,UPDATE_FILE_NAME:MF,LICENSE_KEY_DIR_NAME:DF,BOOT_PROPS_FILE_NAME:LF,JOB_TYPE_ENUM:uk,JOB_STATUS_ENUM:ek,SYSTEM_TABLE_NAMES:QF,SYSTEM_TABLE_HASH_ATTRIBUTES:zF,OPERATIONS_ENUM:ee,VALID_S3_FILE_TYPES:tk,S3_BUCKET_AUTH_KEYS:rk,VALID_SQL_OPS_ENUM:nk,GEO_CONVERSION_ENUM:ik,HDB_SETTINGS_NAMES:bO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:ok,SERVICE_ACTIONS_ENUM:sk,CLUSTER_MESSAGE_TYPE_ENUM:lk,CLUSTER_CONNECTION_DIRECTION_ENUM:_k,CLUSTER_EVENTS_DEFS_ENUM:Ek,PERIOD_REGEX:EF,DOUBLE_PERIOD_REGEX:hF,UNICODE_PERIOD:mF,FORWARD_SLASH_REGEX:pF,UNICODE_FORWARD_SLASH:SF,ESCAPED_FORWARD_SLASH_REGEX:TF,ESCAPED_PERIOD_REGEX:gF,ESCAPED_DOUBLE_PERIOD_REGEX:RF,REG_KEY_FILE_NAME:XF,RESTART_TIMEOUT_MS:vF,HDB_FILE_PERMISSIONS:BF,DATABASES_DIR_NAME:GF,LEGACY_DATABASES_DIR_NAME:qF,TRANSACTIONS_DIR_NAME:FF,LIMIT_COUNT_NAME:kF,ID_ATTRIBUTE_STRING:VF,INSERT_MODULE_ENUM:KF,UPGRADE_JSON_FIELD_NAMES_ENUM:WF,RESTART_CODE:PF,RESTART_CODE_NUM:UF,CLUSTER_OPERATIONS:lc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:jF,HDB_INTERNAL_SC_CHANNEL_PREFIX:Pr,INTERNAL_SC_CHANNELS:JF,CLUSTERING_MESSAGE_TYPES:Ak,HDB_FILE_SUFFIX:CF,BLOB_FOLDER_NAME:HF,HDB_TRASH_DIR:xF,ORIGINATOR_SET_VALUE:Ok,LICENSE_VALUES:dk,RAM_ALLOCATION_ENUM:fk,TIME_STAMP_NAMES_ENUM:NO,TIME_STAMP_NAMES:Tk,PERMS_UPDATE_RELEASE_TIMESTAMP:gk,SEARCH_NOT_FOUND_MESSAGE:cF,SEARCH_ATTRIBUTE_NOT_FOUND:uF,LICENSE_ROLE_DENIED_RESPONSE:lF,LICENSE_MAX_CONNS_REACHED:_F,BASIC_LICENSE_MAX_NON_CU_ROLES:TO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:iF,VALUE_SEARCH_COMPARATORS:IO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Rk,LICENSE_FILE_NAME:ZF,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:hk,NEW_LINE:bk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:fF,MOMENT_DAYS_TAG:AF,API_TURNOVER_SEC:OF,LOOPBACK:dF,CODE_EXTENSION:e_,WILDCARD_SEARCH_VALUE:bF,NODE_ERROR_CODES:mk,JAVASCRIPT_EXTENSION:hO,PERMS_CRUD_ENUM:yk,UNAUTHORIZED_PERMISSION_NAME:Ik,SEARCH_WILDCARDS:Nk,FUNC_VAL:wk,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Ck,JWT_ENUM:Dk,CLUSTERING_FLAG:Sk,ITC_EVENT_TYPES:Lk,CUSTOM_FUNCTION_PROC_NAME:pO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Zl,SERVICES:Mk,THREAD_TYPES:Pk,MEM_SETTING_KEY:yF,HDB_RESTART_SCRIPT:$q,PROCESS_DESCRIPTORS:Jq,SERVICE_SERVERS:tF,SERVICE_SERVERS_CWD:Ph,PROCESS_DESCRIPTORS_VALIDATE:Zq,LAUNCH_SERVICE_SCRIPTS:rF,LOG_LEVELS:Xq,PROCESS_NAME_ENV_PROP:$F,LOG_NAMES:jq,PM2_PROCESS_STATUSES:Uk,CONFIG_PARAM_MAP:yO,CONFIG_PARAMS:I,HDB_CONFIG_FILE:Fq,HDB_DEFAULT_CONFIG_FILE:kq,ROLE_TYPES_ENUM:nF,BOOT_PROP_PARAMS:AO,INSTALL_PROMPTS:YF,HDB_ROOT_DIR_NAME:Vq,CLUSTERING_PROCESSES:eF,FOREGROUND_PID_FILE:Wq,PACKAGE_ROOT:Zs,PRE_4_0_0_VERSION:vk,DATABASES_PARAM_CONFIG:ck,METADATA_PROPERTY:pk,AUTH_AUDIT_STATUS:Bk,AUTH_AUDIT_TYPES:Hk,HDB_PID_FILE:Qq,DEFAULT_DATABASE_NAME:zq,LEGACY_CONFIG_PARAMS:ak};EO()});var vh=g((rce,LO)=>{"use strict";var CO=require("minimist");LO.exports=xk;function xk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=DO(process.env),n=DO(CO(process.argv))):(r=process.env,n=CO(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(xk,"assignCMDENVVariables");function DO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(DO,"objKeysToLowerCase")});var $=g((sce,kh)=>{"use strict";var Bi=require("fs-extra"),{workerData:Gk,threadId:qk}=require("worker_threads"),ps=require("path"),UO=require("yaml"),vO=require("properties-reader"),pt=P(),MO=vh(),Fk=require("os"),{PACKAGE_ROOT:Hh}=P(),{_assignPackageExport:kk}=require("../index"),dc={};for(let e in console)dc[e]||(dc[e]=console[e]);var ar={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},BO={STDOUT:"stdOut",STDERR:"stdErr"},Vk=ps.join(Hh,"logs"),$k=ps.join(Hh,"config/yaml/",pt.HDB_DEFAULT_CONFIG_FILE),Yk=1e4,ms,Kn,or,n_,s_,fc,ko,_c;_c===void 0&&HO();kh.exports={notify:qO,fatal:FO,error:Ec,warn:Fh,info:i_,debug:qh,trace:Gh,setLogLevel:Xk,log_level:or,loggerWithTag:Kk,suppressLogging:Wk,initLogSettings:HO,setupConsoleLogging:xO,logCustomLevel:Jk,closeLogFile:xh,getLogFilePath:()=>fc,OUTPUTS:BO,AuthAuditLog:tV};kk("logger",kh.exports);function HO(e=!1){try{if(_c===void 0||e){xh();let t=jk(),r=MO(["ROOTPATH"]);try{_c=vO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Bi.pathExistsSync(ps.join(r.ROOTPATH,pt.HDB_CONFIG_FILE)))throw n}({level:or,config_log_path:s_,to_file:ms,to_stream:Kn}=Zk(r.ROOTPATH?ps.join(r.ROOTPATH,pt.HDB_CONFIG_FILE):_c.get("settings_path"))),n_=pt.LOG_NAMES.HDB,fc=ps.join(s_,n_)}}catch(t){if(_c=void 0,t.code===pt.NODE_ERROR_CODES.ENOENT||t.code===pt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=MO(Object.keys(pt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=pt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===pt.CONFIG_PARAMS.LOGGING_LEVEL){or=u;continue}if(c===pt.CONFIG_PARAMS.LOGGING_STDSTREAMS){Kn=u;continue}c===pt.CONFIG_PARAMS.LOGGING_FILE&&(ms=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=eV();ms=ms===void 0?s:ms,ms=PO(ms),Kn=Kn===void 0?i:Kn,Kn=PO(Kn),or=or===void 0?n:or,s_=Vk,n_=pt.LOG_NAMES.INSTALL,fc=ps.join(s_,n_);return}throw Ec("Error initializing log settings"),Ec(t),t}process.env.DEV_MODE&&(Kn=!0),xO()}a(HO,"initLogSettings");var Bh=!0;function xO(){Fo("error",Ec),Fo("warn",Fh),Fo("log",i_),Fo("info",i_),Fo("debug",qh),Fo("trace",Gh)}a(xO,"setupConsoleLogging");function Fo(e,t){console[e]=function(...r){if(Bh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return dc[e](...r)}}a(Fo,"logConsole");function Kk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(qO),fatal:r(FO),error:r(Ec),warn:r(Fh),info:r(i_),debug:r(qh),trace:r(Gh)};function r(n){return function(...s){return n(t,...s)}}}a(Kk,"loggerWithTag");function Wk(e){try{Bh=!1,e()}finally{Bh=!0}}a(Wk,"suppressLogging");var Qk=Gk?.name?.replace(/ /g,"-")||"main";function Ss(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||Qk+"/"+qk);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(Ss,"createLogRecord");function hc(e){ms&&GO(e),Kn&&process.stdout.write(e)}a(hc,"logStdOut");function o_(e){ms&&GO(e),Kn&&process.stderr.write(e)}a(o_,"logStdErr");function GO(e){zk(),ko?Bi.appendFileSync(ko,e):dc.log(e)}a(GO,"logToFile");function xh(){try{Bi.closeSync(ko)}catch{}ko=null}a(xh,"closeLogFile");function zk(){if(!ko){try{if(!fc)debugger;ko=Bi.openSync(fc,"a")}catch(e){dc.error(e)}setTimeout(()=>{xh()},Yk).unref()}}a(zk,"openLogFile");function i_(...e){ar[or]<=ar.info&&hc(Ss("info",e))}a(i_,"info");function Gh(...e){ar[or]<=ar.trace&&hc(Ss("trace",e))}a(Gh,"trace");function Ec(...e){ar[or]<=ar.error&&o_(Ss("error",e))}a(Ec,"error");function qh(...e){ar[or]<=ar.debug&&hc(Ss("debug",e))}a(qh,"debug");function qO(...e){ar[or]<=ar.notify&&hc(Ss("notify",e))}a(qO,"notify");function FO(...e){ar[or]<=ar.fatal&&o_(Ss("fatal",e))}a(FO,"fatal");function Fh(...e){ar[or]<=ar.warn&&o_(Ss("warn",e))}a(Fh,"warn");function Jk(e,t,...r){t===BO.STDERR?o_(Ss(e,r)):hc(Ss(e,r))}a(Jk,"logCustomLevel");function jk(){let e;try{e=Fk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ps.join(e,pt.HDB_HOME_DIR_NAME,pt.BOOT_PROPS_FILE_NAME);return Bi.existsSync(t)||(t=ps.join(Hh,"utility/hdb_boot_properties.file")),t}a(jk,"getPropsFilePath");function Xk(e){or=e}a(Xk,"setLogLevel");function PO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(PO,"autoCastBoolean");function Zk(e){try{if(e.includes("config/settings.js")){let o=vO(e);return{level:o.get(pt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ps.dirname(o.get(pt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(pt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(pt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=UO.parseDocument(Bi.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===pt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Zk,"getLogConfig");function eV(){try{let e=UO.parseDocument(Bi.readFileSync($k,"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(eV,"getDefaultConfig");function tV(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(tV,"AuthAuditLog")});var VO=g((oce,kO)=>{"use strict";var rV=require("util"),nV=require("path"),sV=require("child_process"),iV=rV.promisify(sV.execFile),oV=1e3*1e3*10;kO.exports={findPs:aV};async function aV(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await iV("ps",["wwxo",`pid,${r}`],{maxBuffer:oV});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:nV.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(aV,"findPs")});var _t=g((cce,YO)=>{"use strict";var cV="__dbis__",uV="__txns__",lV="__environment_name__",_V="__dbi_defintion__",dV={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"},fV=["__createdtime__","__updatedtime__"],EV="\uFFFF",$O={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},hV=Object.values($O);YO.exports={AUDIT_STORE_NAME:uV,INTERNAL_DBIS_NAME:cV,DBI_DEFINITION_NAME:_V,SEARCH_TYPES:dV,TIMESTAMP_NAMES:fV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:lV,TRANSACTIONS_DBI_NAMES_ENUM:$O,TRANSACTIONS_DBIS:hV,OVERFLOW_MARKER:EV}});var Ur=g((uce,eb)=>{"use strict";var KO=P(),WO=_t(),QO={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},zO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),JO={500:zO("There was an error processing your request."),400:"Invalid request"},mV=JO[QO.INTERNAL_SERVER_ERROR],pV={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.`},SV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},TV={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"},gV={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 ${WO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${WO.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"},RV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${KO.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 ${KO.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"},jO={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"},AV={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."},OV={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`},bV={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"},yV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},NV={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`},XO={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.`},ZO={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}`},IV={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."},wV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},CV={...jO,...TV,...pV,...AV,...OV,...bV,...yV,...NV,...RV,...XO,...ZO,...IV,...wV,...SV};eb.exports={CHECK_LOGS_WRAPPER:zO,HDB_ERROR_MSGS:CV,DEFAULT_ERROR_MSGS:JO,DEFAULT_ERROR_RESP:mV,HTTP_STATUS_CODES:QO,LMDB_ERRORS_ENUM:gV,AUTHENTICATION_ERROR_MSGS:jO,VALIDATION_ERROR_MSGS:XO,ITC_ERRORS:ZO}});var ne=g((_ce,nb)=>{"use strict";var Vo=Ur(),DV=$(),LV=P(),a_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,tb),this.statusCode=n||Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Vo.DEFAULT_ERROR_MSGS[n]?Vo.DEFAULT_ERROR_MSGS[n]:Vo.DEFAULT_ERROR_MSGS[Vo.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&&DV[s](i)}},Vh=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}},$h=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function tb(e,t,r,n=LV.LOG_LEVELS.ERROR,s=null,i=!1){if(rb(e))return e;let o=new a_(e,t,r,n,s);return i&&delete o.stack,o}a(tb,"handleHDBError");function rb(e){return e.__proto__.constructor.name===a_.name}a(rb,"isHDBError");nb.exports={isHDBError:rb,handleHDBError:tb,ClientError:Vh,ServerError:$h,hdb_errors:Vo}});var ze=g((fce,lb)=>{"use strict";var gc=P(),MV=J(),cr=Z(),Rc=require("path"),PV=require("minimist"),sb=require("fs-extra"),ib=require("lodash");cr.initSync();var{CONFIG_PARAMS:ei,DATABASES_PARAM_CONFIG:mc,SYSTEM_SCHEMA_NAME:c_}=gc,pc,Sc,Tc;function ob(){if(pc!==void 0)return pc;if(cr.getHdbBasePath()!==void 0)return pc=cr.get(ei.STORAGE_PATH)||Rc.join(cr.getHdbBasePath(),gc.DATABASES_DIR_NAME),pc}a(ob,"getBaseSchemaPath");function ab(){if(Sc!==void 0)return Sc;if(cr.getHdbBasePath()!==void 0)return Sc=ub(c_),Sc}a(ab,"getSystemSchemaPath");function cb(){if(Tc!==void 0)return Tc;if(cr.getHdbBasePath()!==void 0)return Tc=cr.get(gc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Rc.join(cr.getHdbBasePath(),gc.TRANSACTIONS_DIR_NAME),Tc}a(cb,"getTransactionAuditStoreBasePath");function UV(e,t){let r=cr.get(ei.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Rc.join(cb(),e.toString())}a(UV,"getTransactionAuditStorePath");function ub(e,t){e=e.toString(),t=t&&t.toString();let r=cr.get(gc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Rc.join(ob(),e)}a(ub,"getSchemaPath");function vV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,PV(process.argv));let n=r[ei.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!MV.isObject(n))throw o;i=n}for(let o of i){let c=o[c_];if(!c)continue;let u=cr.get(ei.DATABASES);u=u??{};let _=c?.tables?.[t]?.[mc.PATH];if(_)return ib.set(u,[c_,mc.TABLES,t,mc.PATH],_),cr.setProperty(ei.DATABASES,u),_;let l=c?.[mc.PATH];if(l)return ib.set(u,[c_,mc.PATH],l),cr.setProperty(ei.DATABASES,u),l}}let s=r[ei.STORAGE_PATH.toUpperCase()];if(s){if(!sb.pathExistsSync(s))throw new Error(s+" does not exist");let i=Rc.join(s,e);return sb.mkdirsSync(i),cr.setProperty(ei.STORAGE_PATH,s),i}return ab()}a(vV,"initSystemSchemaPaths");function BV(){pc=void 0,Sc=void 0,Tc=void 0}a(BV,"resetPaths");lb.exports={getBaseSchemaPath:ob,getSystemSchemaPath:ab,getTransactionAuditStorePath:UV,getTransactionAuditStoreBasePath:cb,getSchemaPath:ub,initSystemSchemaPaths:vV,resetPaths:BV}});var vr=g((pce,hb)=>{"use strict";var HV=Ur().LMDB_ERRORS_ENUM,hce=require("lmdb"),xV=_t(),mce=require("buffer").Buffer,{OVERFLOW_MARKER:_b,MAX_SEARCH_KEY_LENGTH:u_}=xV,db=["number","string","symbol","boolean","bigint"];function GV(e){if(e=e?.primaryStore||e,!e)throw new Error(HV.ENV_REQUIRED)}a(GV,"validateEnv");function qV(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(qV,"stringifyData");function FV(e){return e instanceof Date?e.valueOf():e}a(FV,"convertKeyValueToWrite");function kV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(db.includes(typeof e))return e.length>u_?[e.slice(0,u_)+_b]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(db.includes(typeof i))i.length>u_?r.push(i.slice(0,u_)+_b):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(kV,"getIndexedValues");var l_=0,fb=0;function Eb(){fb=Date.now()-performance.now()}a(Eb,"adjustStartTime");Eb();var VV=6e4;setInterval(Eb,VV).unref();function $V(){let e=performance.now()+fb;return e>l_?(l_=e,e):(l_+=488e-6,l_)}a($V,"getNextMonotonicTime");hb.exports={validateEnv:GV,stringifyData:qV,convertKeyValueToWrite:FV,getNextMonotonicTime:$V,getIndexedValues:kV}});var mb,yn,Yh,Ac=Ae(()=>{mb=require("events"),yn=class extends mb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Yh;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)}},Yh=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 Hi={};qe(Hi,{server:()=>st});var pb,st,ur=Ae(()=>{pb=require("../index"),st={};(0,pb._assignPackageExport)("server",st)});var Qh={};qe(Qh,{loadGQLSchema:()=>WV,start:()=>Wh,startOnMainThread:()=>KV});function Wh({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)),E=new Map,f=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let x=function(v){if(v.kind==="NonNullType"){let Q=x(v.type);return Q.nullable=!1,Q}if(v.kind==="ListType")return{type:"array",elements:x(v.type)};let M={type:v.name?.value};return Object.defineProperty(M,"location",{value:v.loc.startToken}),M};a(x,"getProperty");let T=S.name.value,A=[],R={table:null,database:null,properties:A};E.set(T,R);for(let v of S.directives){if(v.name.value==="table"){for(let k of v.arguments)R[k.name.value]=k.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=T),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,f.push(R)}if(v.name.value==="sealed"&&(R.sealed=!0),v.name.value==="export"){R.export=!0;for(let k of v.arguments)k.name.value==="name"&&(R.export={name:k.value.value})}}let C=!1;for(let v of S.fields){let k=x(v.type);k.name=v.name.value,A.push(k);for(let M of v.directives)if(M.name.value==="primaryKey")C?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,C=!0);else if(M.name.value==="indexed")k.indexed=!0;else if(M.name.value==="relationship"){let Q={};for(let j of M.arguments)Q[j.name.value]=j.value.value;k.relationship=Q}else if(M.name.value==="createdTime")k.assignCreatedTime=!0;else if(M.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")k.expiresAt=!0;else if(M.name.value==="allow"){let Q=k.authorizedRoles=[];for(let j of M.arguments)j.name.value==="role"&&Q.push(j.value.value)}}R.type=T,T==="Query"&&(h=R)}function p(S){let T=E.get(S.type);T?(Object.defineProperty(S,"properties",{value:T.properties}),Object.defineProperty(S,"definition",{value:T})):S.type==="array"?p(S.elements):YV.includes(S.type)||(0,Sb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of E.values())for(let T of S.properties)p(T);for(let S of f)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Kh.dirname)(n),S.tableClass):i.set((0,Kh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var Kh,Sb,YV,KV,WV,Tb=Ae(()=>{Kh=require("path");Oe();Sb=B(Je()),YV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Wh,"start");KV=Wh,WV=Wh({ensureTable:dt}).handleFile});async function __(e){let t=(0,Ab.pathToFileURL)(e).toString();return QV?(Oc||(Oc=zV(jV)),(await(await Oc).import(t)).namespace):import(t)}async function zV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Oc=new Compartment({console,Math,Date,fetch:JV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Rb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:Vt,tables:Br,databases:it})}};let n=await(0,gb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Oc}function JV(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 jV(){return{Resource:Vt,tables:Br}}var gb,Rb,Ab,QV,Oc,zh=Ae(()=>{Nn();Oe();gb=require("fs/promises"),Rb=require("path"),Ab=require("url"),QV=!1;a(__,"secureImport");a(zV,"getCompartment");a(JV,"secureOnlyFetch");a(jV,"getGlobalVars")});var jh={};qe(jh,{handleFile:()=>XV});async function XV(e,t,r,n){let s=new Map,i=await __(r);c(i.default)&&n.set((0,Jh.dirname)(t),i.default),o(i,(0,Jh.dirname)(t));function o(u,_){for(let l in u){let d=u[l];c(d)?n.set(_+"/"+l,d):typeof d=="object"&&o(d,_+"/"+l)}}a(o,"recurseForResources");function c(u){return typeof u=="function"&&(u.get||u.put||u.post||u.delete)}return a(c,"isResource"),s}var Jh,Ob=Ae(()=>{zh();Jh=require("path");a(XV,"handleFile")});var Zh={};qe(Zh,{start:()=>ZV});function ZV({resources:e}){e.set("login",Xh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Xh,bb=Ae(()=>{Nn();a(ZV,"start");Xh=class extends Vt{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 Lb={};qe(Lb,{parse:()=>tm,streamAsJSON:()=>bc,stringify:()=>xi});function bc(e){return new em({value:e})}function yb(e){return console.error(e),JSON.stringify(e.toString())}function Nb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function xi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===Cb)return Db(e);if(t.resolution)return t.resolution.then(()=>xi(e));throw t}}function Db(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+=Db(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+xi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function tm(e){return r$.test(e)?e$.parse(e):JSON.parse(e)}var Ib,wb,e$,t$,Cb,em,r$,rm=Ae(()=>{Ib=require("stream"),wb=B(require("json-bigint-fixes")),e$=(0,wb.default)({useNativeBigInt:!0}),t$=1e4,Cb={};BigInt.prototype.toJSON=function(){throw Cb};a(bc,"streamAsJSON");em=class extends Ib.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),yb)}catch(s){yield yb(s)}else yield xi(t)}else yield xi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Nb(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>t$?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 Nb(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(yb,"handleError");a(Nb,"when");a(xi,"stringify");a(Db,"jsStringify");r$=/[[,:]\s*-?\d{16,}/;a(tm,"parse")});var $b=g((Pce,Vb)=>{"use strict";var nm=require("recursive-iterator"),n$=require("alasql"),sm=require("clone"),Mb=J(),{handleHDBError:Pb,hdb_errors:s$}=ne(),{HDB_ERROR_MSGS:Ub,HTTP_STATUS_CODES:vb}=s$,{getDatabases:i$}=(Oe(),ie(Fe)),o$=["DISTINCT_ARRAY"],Bb=Symbol("validateTables"),im=Symbol("validateTable"),Mce=Symbol("getAllColumns"),Hb=Symbol("validateAllColumns"),d_=Symbol("findColumn"),xb=Symbol("validateOrderBy"),yc=Symbol("validateSegment"),om=Symbol("validateColumn"),Gb=Symbol("setColumnsForTable"),qb=Symbol("checkColumnsForAsterisk"),Fb=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=i$();if(!r[t.databaseid])throw Pb(new Error,Ub.SCHEMA_NOT_FOUND(t.databaseid),vb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Pb(new Error,Ub.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)})}[d_](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[Gb](r.tableid)}[Gb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new n$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Hb](){this[yc](this.statement.columns,!1),this[yc](this.statement.joins,!1),this[yc](this.statement.where,!1),this[Fb](this.statement.group,!1),this[yc](this.statement.order,!0)}[yc](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}[Fb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&o$.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[d_](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[d_](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[d_](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=g((vce,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=g((Hce,Wb)=>{"use strict";var um=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Wb.exports=um});var Xb={};qe(Xb,{HAS_EXPIRATION:()=>mm,LAST_TIMESTAMP_PLACEHOLDER:()=>wc,LOCAL_TIMESTAMP:()=>a$,METADATA:()=>Nc,NO_TIMESTAMP:()=>_m,PENDING_LOCAL_TIME:()=>pm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>hm,RecordEncoder:()=>Em,TIMESTAMP_ASSIGN_LAST:()=>u$,TIMESTAMP_ASSIGN_NEW:()=>Jb,TIMESTAMP_ASSIGN_PREVIOUS:()=>jb,TIMESTAMP_PLACEHOLDER:()=>f_,TIMESTAMP_RECORD_PREVIOUS:()=>dm,getUpdateRecord:()=>Sm,handleLocalTimeForGets:()=>p_});function _$(){return Ic[0]=Ic[0]^64,c$.getFloat64(0)}function p_(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?.[Nc];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?.[Nc]>=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[Nc];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(){this.timerTracked||(this.timerTracked=!0,Gi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Gi.length;u++){let _=Gi[u].deref();(!_||_.isDone||_.isCommitted)&&Gi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Sm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",E,f){if(E||u==null?$o=i?.localTime?dm|jb:_m:$o=u?i?.localTime?dm|16384:Jb|16384:_m,l>0&&(c|=mm),h_=c,fm=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:$o>0},p;try{E&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(f&&(E_=e.encoder.encode(f)),E&&i?.localTime){let A=i?.localTime,R=r.get(A);if(R){let C=Ut(R).previousLocalTime;return r.put(A,m_(o,t,n,C,T,d,E_),{ifVersion:p}),S}}r.put(wc,m_(o,t,n,i?.localTime?1:0,T,d,E_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var zb,lm,f_,wc,hm,a$,Nc,Ic,c$,_m,Jb,u$,jb,dm,mm,pm,l$,E_,$o,h_,fm,Em,Gi,Cc=Ae(()=>{zb=require("msgpackr");ti();lm=B($()),f_=new Uint8Array([1,1,1,1,4,64,0,0]),wc=new Uint8Array([1,1,1,1,1,0,0,0]),hm=new Uint8Array([1,1,1,1,3,64,0,0]),a$=Symbol("local-timestamp"),Nc=Symbol("metadata"),Ic=new Uint8Array(8),c$=new DataView(Ic.buffer,0,8),_m=0,Jb=0,u$=1,jb=3,dm=4,mm=16,pm=1,$o=0,h_=-1,fm=0,Em=class extends zb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if($o||h_>=0){let i=0,o=$o;o&&(i+=8,$o=0);let c=h_,u=fm;c>=0&&(i+=2,h_=-1,u&&(i+=8,fm=0));let _=l$=r.call(this,n,s|2048|i);E_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(f_[4]=o,f_[5]=o>>8,_.set(f_,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(Ic,0,c),c+=8;else for(let d=0;d<8;d++)Ic[d]=t[c++];u=_$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&mm&&(_=(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,[Nc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(_$,"getTimestamp");a(p_,"handleLocalTimeForGets");Gi=[];setInterval(()=>{for(let e=0;e<Gi.length;e++){let t=Gi[e].deref();!t||t.isDone||t.isCommitted?Gi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(lm.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):lm.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(Sm,"getUpdateRecord")});var Dc=g((kce,ey)=>{"use strict";var Zb=Z(),d$=P(),{RecordEncoder:f$}=(Cc(),ie(Xb)),Fce=require("fs");Zb.initSync();var E$=Zb.get(d$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,Tm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=E$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:f$})}};ey.exports=Tm});var Lc=g(($ce,ty)=>{"use strict";var Hr=Z(),cn=P();Hr.initSync();var 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.eventTurnBatching=!1,this.noSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Hr.get(cn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ty.exports=S_;S_.MAX_DBS=1e4});var Ke=g((Kce,_y)=>{"use strict";var Rm=require("lmdb"),In=require("fs-extra"),xr=require("path"),T_=vr(),sy=$(),lr=Ur().LMDB_ERRORS_ENUM,g_=Qb(),Am=Dc(),iy=Lc(),ri=_t(),ry=P(),{table:h$,resetDatabases:m$}=(Oe(),ie(Fe)),ny=Z(),wn=ri.INTERNAL_DBIS_NAME,oy=ri.DBI_DEFINITION_NAME,p$="data.mdb",S$="lock.mdb",Mc=".mdb",T$="-lock",gm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=un(t,r),this.key_type=this.dbi[ri.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ri.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Rm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function R_(e,t){if(e===void 0)throw new Error(lr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(lr.ENV_NAME_REQUIRED)}a(R_,"pathEnvNameValidation");async function Om(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(lr.INVALID_BASE_PATH):n}try{let n=xr.join(e,t+Mc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(xr.join(e,t,p$),In.constants.R_OK|In.constants.F_OK),xr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(lr.INVALID_ENVIRONMENT)}else throw new Error(lr.INVALID_ENVIRONMENT);throw n}}a(Om,"validateEnvironmentPath");function A_(e,t){if(T_.validateEnv(e),t===void 0)throw new Error(lr.DBI_NAME_REQUIRED)}a(A_,"validateEnvDBIName");async function g$(e,t,r=!1,n=!1){R_(e,t);let s=xr.basename(e);t=t.toString();let i=ny.get(ry.CONFIG_PARAMS.DATABASES);i||ny.setProperty(ry.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Om(e,t,n),ay(e,t,r)}catch(o){if(o.message===lr.INVALID_ENVIRONMENT){let c=xr.join(e,t);await In.mkdirp(n?c:e);let u=new iy(n?c:c+Mc,!1),_=Rm.open(u);_.dbis=Object.create(null);let l=new Am(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=bm(e,t,r);return _[ri.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(g$,"createEnvironment");async function R$(e,t,r,n=!0){R_(e,t),t=t.toString();let s=xr.join(e,t);return h$({table:t,database:xr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(R$,"copyEnvironment");async function ay(e,t,r=!1){R_(e,t),t=t.toString();let n=bm(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 Om(e,t),i=xr.join(e,t+Mc),o=s!=i,c=new iy(s,o),u=Rm.open(c);u.dbis=Object.create(null);let _=uy(u);for(let l=0;l<_.length;l++)un(u,_[l]);return u[ri.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(ay,"openEnvironment");async function A$(e,t,r=!1){R_(e,t),t=t.toString();let n=xr.join(e,t+Mc),s=await Om(e,t);if(global.lmdb_map!==void 0){let i=bm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await cy(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+T$:xr.join(xr.dirname(s),S$))}a(A$,"deleteEnvironment");async function cy(e){T_.validateEnv(e);let t=e[ri.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(cy,"closeEnvironment");function bm(e,t,r=!1){let s=`${xr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(bm,"getCachedEnvironmentName");function O$(e){T_.validateEnv(e);let t=Object.create(null),r=un(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new g_,s)}catch{sy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(O$,"listDBIDefinitions");function uy(e){T_.validateEnv(e);let t=[],r=un(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(uy,"listDBIs");function b$(e,t){let n=un(e,wn).getEntry(t),s=new g_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{sy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(b$,"getDBIDefinition");function ly(e,t,r,n=!r){if(A_(e,t),t=t.toString(),t===wn)throw new Error(lr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return un(e,t)}catch(s){if(s.message===lr.DBI_DOES_NOT_EXIST){let i=new Am(r,n===!0),o=e.openDB(t,i),c=new g_(r===!0,n);return o[oy]=c,un(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(ly,"createDBI");function un(e,t){if(A_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=b$(e,t):r=new g_,r===void 0)throw new Error(lr.DBI_DOES_NOT_EXIST);let n;try{let s=new Am(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(lr.DBI_DOES_NOT_EXIST):s}return n[oy]=r,e.dbis[t]=n,n}a(un,"openDBI");function y$(e,t){A_(e,t),t=t.toString();let r=un(e,t),n=r.getStats();return r[ri.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(y$,"statDBI");async function N$(e,t){try{let r=xr.join(e,t+Mc);return(await In.stat(r)).size}catch{throw new Error(lr.INVALID_ENVIRONMENT)}}a(N$,"environmentDataSize");function I$(e,t){if(A_(e,t),t=t.toString(),t===wn)throw new Error(lr.CANNOT_DROP_INTERNAL_DBIS_NAME);un(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],un(e,wn).removeSync(t)}a(I$,"dropDBI");function w$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{un(e,i)}catch(o){if(o.message===lr.DBI_DOES_NOT_EXIST)ly(e,i,i!==t,i===t),n=!0;else throw o}}n&&m$()}a(w$,"initializeDBIs");_y.exports={openDBI:un,openEnvironment:ay,createEnvironment:g$,listDBIs:uy,listDBIDefinitions:O$,createDBI:ly,dropDBI:I$,statDBI:y$,deleteEnvironment:A$,initializeDBIs:w$,TransactionCursor:gm,environmentDataSize:N$,copyEnvironment:R$,closeEnvironment:cy}});var fy=g((Qce,dy)=>{"use strict";var ym=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};dy.exports=ym});var hy=g((Jce,Ey)=>{"use strict";var Nm=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}};Ey.exports=Nm});var py=g((Xce,my)=>{"use strict";var Im=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};my.exports=Im});var Yo=g((nue,gy)=>{"use strict";var C$=Ke(),D$=fy(),L$=hy(),M$=py(),Wn=vr(),Pc=Ur().LMDB_ERRORS_ENUM,P$=_t(),Ts=P(),U$=J(),v$=require("uuid"),eue=require("lmdb"),{handleHDBError:B$,hdb_errors:H$}=ne(),{OVERFLOW_MARKER:tue,MAX_SEARCH_KEY_LENGTH:rue}=P$,Sy=Z();Sy.initSync();var O_=Sy.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),wm=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function x$(e,t,r,n,s=Wn.getNextMonotonicTime()){Mm(e,t,r,n),Cm(e,t,r);let i=new D$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Ty(_,!0,s);let l=G$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Dm(o,c,n,i,s)}a(x$,"insertRecords");function G$(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][Ts.FUNC_VAL],n[o]=c)}let u=Wn.getIndexedValues(c),_=e.dbis[o];if(u){O_&&_.prefetch(u.map(l=>({key:l,value:s})),b_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}O_&&e.dbis[t].prefetch([s],b_),e.dbis[t].put(s,n,n[qi])})}a(G$,"insertRecord");function q$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(q$,"removeSkippedRecords");function Ty(e,t,r){let n=r>0;(n||!Number.isInteger(e[qi]))&&(e[qi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[wm]))&&(e[wm]=r||Wn.getNextMonotonicTime()):delete e[wm]}a(Ty,"setTimestamps");function Cm(e,t,r){r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),C$.initializeDBIs(e,t,r)}a(Cm,"initializeTransaction");async function F$(e,t,r,n,s=Wn.getNextMonotonicTime()){Mm(e,t,r,n),Cm(e,t,r);let i=new L$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],E;try{E=Lm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),u.push(d)}return Dm(c,u,n,i,s,o)}a(F$,"updateRecords");async function k$(e,t,r,n,s=Wn.getNextMonotonicTime()){try{Mm(e,t,r,n)}catch(u){throw B$(u,u.message,H$.HTTP_STATUS_CODES.BAD_REQUEST)}Cm(e,t,r);let i=new M$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;U$.isEmpty(_[t])?(l=v$.v4(),_[t]=l):l=_[t];let d=Lm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Dm(o,c,n,i,s)}a(k$,"upsertRecords");async function Dm(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||Wn.getNextMonotonicTime(),q$(r,i),n}a(Dm,"finalizeWrite");function Lm(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(Ty(r,!l,o),Number.isInteger(r[qi])&&_[qi]>r[qi])return!1;l&&s.original_records.push(_);let d,E=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 T=_[h];if(typeof p=="function"){let R=p([[_]]);Array.isArray(R)&&(p=R[0][Ts.FUNC_VAL],r[h]=p)}if(p===T)continue;let A=Wn.getIndexedValues(T);if(A){O_&&S.prefetch(A.map(R=>({key:R,value:n})),b_);for(let R=0,C=A.length;R<C;R++)S.remove(A[R],n)}if(A=Wn.getIndexedValues(p),A){O_&&S.prefetch(A.map(R=>({key:R,value:n})),b_);for(let R=0,C=A.length;R<C;R++)S.put(A[R],n)}}let f=Object.assign({},_,r);c.put(n,f,f[qi])},"do_put");return u?d=c.ifVersion(n,u.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:Lm(e,t,r,n,s,i,o))}a(Lm,"updateUpsertRecord");function V$(e,t,r){if(Wn.validateEnv(e),t===void 0)throw new Error(Pc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Pc.WRITE_ATTRIBUTES_REQUIRED):new Error(Pc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(V$,"validateBasic");function Mm(e,t,r,n){if(V$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Pc.RECORDS_REQUIRED):new Error(Pc.RECORDS_MUST_BE_ARRAY)}a(Mm,"validateWrite");function b_(){}a(b_,"noop");gy.exports={insertRecords:x$,updateRecords:F$,upsertRecords:k$}});var Fi=g((iue,$$)=>{$$.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"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},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"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var zn=g((oue,Oy)=>{"use strict";var Ay=J(),Ry=P(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Qn=require("joi"),ni={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},Y$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number(),Qn.array()).required(),K$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number()),W$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number()).required();function Q$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ni.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(Q$,"checkValidTable");function z$(e,t){return Ay.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(z$,"validateSchemaExists");function J$(e,t){let r=t.state.ancestors[0].schema;return Ay.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(J$,"validateTableExists");function j$(e,t){return e.toLowerCase()===Ry.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Ry.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(j$,"validateSchemaName");Oy.exports={common_validators:ni,schema_regex:Ko,hdb_schema_table:Y$,validateSchemaExists:z$,validateTableExists:J$,validateSchemaName:j$,checkValidTable:Q$,hdb_database:K$,hdb_table:W$}});var je=g((cue,by)=>{"use strict";var _r=require("validate.js");_r.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||_r.validators.type.checks[t](e)?null:` must be a '${t}' value`};_r.validators.type.checks={Object:function(e){return _r.isObject(e)&&!_r.isArray(e)},Array:_r.isArray,Integer:_r.isInteger,Number:_r.isNumber,String:_r.isString,Date:_r.isDate,Boolean:function(e){return typeof e=="boolean"}};_r.validators.hasValidFileExt=function(e,t){return _r.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};by.exports={validateObject:X$,validateObjectAsync:Z$,validateBySchema:e1};function X$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=_r(e,t,{format:"flat"});return r?new Error(r):null}a(X$,"validateObject");async function Z$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await _r.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(Z$,"validateObjectAsync");function e1(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(e1,"validateBySchema")});var y_=g((lue,yy)=>{var{common_validators:Jn}=zn(),vc=je(),Uc="is required",St={database:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},schema:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},table:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},hash_attribute:{presence:!0,format:Jn.schema_format,length:Jn.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 t1(e){return e=Bc(e),St.table.presence=!1,St.attribute.presence=!1,St.hash_attribute.presence=!1,vc.validateObject(e,St)}a(t1,"schema_object");function r1(e){return e=Bc(e),St.table.presence={message:Uc},St.attribute.presence=!1,St.hash_attribute.presence=!1,vc.validateObject(e,St)}a(r1,"table_object");function n1(e){return e=Bc(e),St.table.presence={message:Uc},St.attribute.presence=!1,vc.validateObject(e,St)}a(n1,"create_table_object");function s1(e){return e=Bc(e),St.table.presence={message:Uc},St.attribute.presence={message:Uc},St.hash_attribute.presence=!1,vc.validateObject(e,St)}a(s1,"attribute_object");function i1(e){return e=Bc(e),St.table.presence={message:Uc},St.attribute.presence=!1,St.hash_attribute.presence=!1,vc.validateObject(e,St)}a(i1,"describe_table");function o1(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(o1,"validateTableResidence");yy.exports={schema_object:t1,create_table_object:n1,table_object:r1,attribute_object:s1,describe_table:i1,validateTableResidence:o1}});var Iy=g((due,Ny)=>{"use strict";var a1=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||a1.v4(),this.schema_table=`${this.schema}.${this.table}`}};Ny.exports=Pm});var N_=g((Eue,wy)=>{"use strict";var c1=Iy(),Um=class extends c1{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}};wy.exports=Um});var Dy=g((mue,Cy)=>{"use strict";Cy.exports=l1;var u1="inserted";function l1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===u1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(l1,"returnObject")});var I_=g((Sue,vy)=>{"use strict";var _1=P(),vm=Ke(),d1=Yo(),{getSystemSchemaPath:f1,getSchemaPath:E1}=ze(),h1=Fi(),m1=y_(),p1=N_(),S1=Dy(),{handleHDBError:Ly,hdb_errors:Py}=ne(),My=J(),{HTTP_STATUS_CODES:T1}=Py,Bm=h1.hdb_attribute,Uy=[];for(let e=0;e<Bm.attributes.length;e++)Uy.push(Bm.attributes[e].attribute);var g1="inserted";vy.exports=R1;async function R1(e){let t=m1.attribute_object(e);if(t)throw Ly(new Error,t.message,Py.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&My.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Ly(new Error,r,T1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=My.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 p1(e.schema,e.table,e.attribute,e.id);try{let i=await vm.openEnvironment(E1(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}`);vm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await vm.openEnvironment(f1(),_1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await d1.insertRecords(o,Bm.hash_attribute,Uy,[s]);return S1(g1,c,{records:[s]},u)}catch(i){throw i}}a(R1,"lmdbCreateAttribute")});var xm=g((gue,Hy)=>{var{hdb_table:A1,hdb_database:By}=zn(),O1=je(),Hm=require("joi"),b1={undefined:"undefined",null:"null"},y1=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||b1[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"),N1=Hm.object({database:By,schema:By,table:A1,records:Hm.array().items(Hm.object().custom(y1)).required()});Hy.exports=function(e){return O1.validateBySchema(e,N1)}});var Hc=g((Oue,Gy)=>{"use strict";var gs=J(),xy=$(),Aue=xm(),{getDatabases:I1}=(Oe(),ie(Fe)),{ClientError:ki}=ne();Gy.exports=w1;function w1(e){if(gs.isEmpty(e))throw new ki("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new ki("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new ki("invalid table specified.");if(!Array.isArray(e.records))throw new ki("records must be an array");let t=I1()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new ki(`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&&gs.isEmptyOrZeroLength(o[r]))throw xy.error("a valid hash attribute must be provided with update record:",o),new ki("a valid hash attribute must be provided with update record, check log for more info");if(!gs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw xy.error(`a valid hash value must be provided with ${e.operation} record:`,o),new ki(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gs.isEmpty(o[r])&&o[r]!==""&&n.has(gs.autoCast(o[r]))&&(o.skip=!0),n.add(gs.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(w1,"insertUpdateValidate")});var xc=g((yue,qy)=>{"use strict";var C1=P().OPERATIONS_ENUM,Gm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=C1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};qy.exports=Gm});var Gc=g((wue,ky)=>{"use strict";var Iue=xc(),w_=P(),qm=J(),Fy=$(),D1=require("uuid"),{handleHDBError:C_,hdb_errors:L1}=ne(),{HDB_ERROR_MSGS:D_,HTTP_STATUS_CODES:L_}=L1;ky.exports=M1;function M1(e,t,r){for(let s=0;s<t.length;s++)P1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];U1(i,r,e.operation)}}a(M1,"processRows");function P1(e){if(Buffer.byteLength(String(e))>w_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw C_(new Error,D_.ATTR_NAME_LENGTH_ERR(e),L_.BAD_REQUEST,void 0,void 0,!0);if(qm.isEmptyOrZeroLength(e)||qm.isEmpty(e.trim()))throw C_(new Error,D_.ATTR_NAME_NULLISH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}a(P1,"validateAttribute");function U1(e,t,r){if(!e.hasOwnProperty(t)||qm.isEmptyOrZeroLength(e[t])){if(r===w_.OPERATIONS_ENUM.INSERT||r===w_.OPERATIONS_ENUM.UPSERT){e[t]=D1.v4();return}throw Fy.error("Update transaction aborted due to record with no hash value:",e),C_(new Error,D_.RECORD_MISSING_HASH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>w_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Fy.error(e),C_(new Error,D_.HASH_VAL_LENGTH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}a(U1,"validateHash")});var $y=g((Due,Vy)=>{"use strict";var Fm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Vy.exports=Fm});var Wy=g((Mue,Ky)=>{"use strict";var km=Ke(),v1=$(),Yy=Ur().LMDB_ERRORS_ENUM;Ky.exports=B1;async function B1(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 km.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Yy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await km.closeEnvironment(global.lmdb_map[n]),await km.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Yy.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){v1.error(t)}}a(B1,"cleanLMDBMap")});var Rs=g((Uue,jy)=>{"use strict";var qc=require("crypto"),H1=Z(),{CONFIG_PARAMS:x1}=P(),zy="aes-256-cbc",G1=32,q1=16,Vm=64,Jy=32,F1=Vm+Jy,Qy=new Map;jy.exports={encrypt:k1,decrypt:V1,createNatsTableStreamName:$1};function k1(e){let t=qc.randomBytes(G1),r=qc.randomBytes(q1),n=qc.createCipheriv(zy,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(k1,"encrypt");function V1(e){let t=e.substr(0,Vm),r=e.substr(Vm,Jy),n=e.substr(F1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=qc.createDecipheriv(zy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(V1,"decrypt");function $1(e,t){let r=H1.get(x1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Qy.get(r);return n||(n=qc.createHash("md5").update(r).digest("hex"),Qy.set(r,n)),n}a($1,"createNatsTableStreamName")});var As=g((Hue,Zy)=>{"use strict";var Bue=Gr(),M_=$(),Xy=y_(),Y1=Rs(),P_=J(),{handleHDBError:U_,hdb_errors:K1}=ne(),{HDB_ERROR_MSGS:v_,HTTP_STATUS_CODES:$m}=K1,W1=Z();W1.initSync();var{getDatabases:Ym}=(Oe(),ie(Fe));Zy.exports={describeAll:Q1,describeTable:B_,describeSchema:z1};async function Q1(e){try{let t=P_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Ym(),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 E in d)try{let f;if(t||n)f=await B_({schema:l,table:E,exact_count:u});else if(r&&r[l].describe&&r[l].tables[E].describe){let h=r[l].tables[E].attribute_permissions;f=await B_({schema:l,table:E,exact_count:u},h)}f&&c.push(f)}catch(f){M_.error(f)}}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 M_.error("Got an error in describeAll"),M_.error(t),U_(new Error,v_.DESCRIBE_ALL_ERR)}}a(Q1,"describeAll");async function B_(e,t){P_.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=Xy.describe_table(e);if(i)throw i;let c=Ym()[r];if(!c)throw U_(new Error,v_.SCHEMA_NOT_FOUND(e.schema),$m.NOT_FOUND);let u=c[n];if(!u)throw U_(new Error,v_.TABLE_NOT_FOUND(e.schema,e.table),$m.NOT_FOUND);function _(E){l.push(Object.assign({},{attribute:E.attribute,type:E.type,elements:E.elements?.type,indexed:E.indexed,is_primary_key:E.isPrimaryKey,assigned_created_time:E.assignCreatedTime,assigned_updated_time:E.assignUpdatedTime,nullable:E.nullable,properties:E.properties?E.properties.map(f=>({type:f.type,name:f.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let E={};s.forEach(f=>{f.describe&&(E[f.attribute_name]=!0)}),u.attributes.forEach(f=>{E[f.name]&&_(f)})}else u.attributes?.forEach(E=>_(E));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(E=>E.isPrimaryKey||E.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=Y1.createNatsTableStreamName(d.schema,d.name);try{let E=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=E.recordCount,d.estimated_record_range=E.estimatedRange;let f=u.auditStore;if(f)for(let h of f.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(E){M_.warn(`unable to stat table dbi due to ${E}`)}return d}a(B_,"descTable");async function z1(e){P_.transformReq(e);let t=Xy.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=Ym()[n];if(!i)throw U_(new Error,v_.SCHEMA_NOT_FOUND(e.schema),$m.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),P_.isEmpty(u)||u.describe){let _=await B_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(z1,"describeSchema")});var Os=g((Fue,sN)=>{var J1=Fi(),{callbackify:tN,promisify:j1}=require("util"),{getDatabases:rN}=(Oe(),ie(Fe));sN.exports={setSchemaDataToGlobal:eN,getTableSchema:X1,getSystemSchema:Z1,setSchemaDataToGlobalAsync:j1(eN)};var nN=As(),Gue=tN(nN.describeAll),que=tN(nN.describeTable);function eN(e){global.hdb_schema=rN(),e&&e()}a(eN,"setSchemaDataToGlobal");function X1(e,t,r){let n=rN()[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(X1,"getTableSchema");function Z1(){return J1}a(Z1,"getSystemSchema")});var qr=g((Vue,cN)=>{"use strict";var x_=xm(),$t=J(),eY=require("util"),G_=Cn(),tY=Os(),iN=$(),{handleHDBError:Vi,hdb_errors:rY}=ne(),{HTTP_STATUS_CODES:$i}=rY,nY=eY.promisify(tY.getTableSchema),sY="updated",oN="inserted",aN="upserted";cN.exports={insert:oY,update:aY,upsert:cY,validation:iY,flush:uY};async function iY(e){if($t.isEmpty(e))throw new Error("invalid update parameters defined.");if($t.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if($t.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await nY(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&&$t.isEmptyOrZeroLength(c[n]))throw iN.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(!$t.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw iN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!$t.isEmpty(c[n])&&c[n]!==""&&s.has($t.autoCast(c[n]))&&(c.skip=!0),s.add($t.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(iY,"validation");async function oY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.createRecords(e);return H_(oN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(oY,"insertData");async function aY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.updateRecords(e);return $t.isEmpty(n.existing_rows)?H_(sY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):H_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(aY,"updateData");async function cY(e){if(e.operation!=="upsert")throw Vi(new Error,"invalid operation, must be upsert",$i.INTERNAL_SERVER_ERROR);let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.upsertRecords(e);return H_(aN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(cY,"upsertData");function H_(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===oN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===aN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(H_,"returnObject");function uY(e){return $t.transformReq(e),G_.flush(e.schema,e.table)}a(uY,"flush")});var Wm=g((Yue,_N)=>{var lY=je(),Km=require("joi"),{hdb_table:_Y,hdb_database:uN}=zn(),lN={schema:uN,database:uN,table:_Y},dY={date:Km.date().iso().required()},fY={timestamp:Km.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};_N.exports=function(e,t){let r=t==="timestamp"?{...lN,...fY}:{...lN,...dY},n=Km.object(r);return lY.validateBySchema(e,n)}});var EN=g((Kue,fN)=>{var EY=je(),Qm=require("joi"),{hdb_table:hY,hdb_database:dN}=zn(),mY=Qm.object({schema:dN,database:dN,table:hY,hash_values:Qm.array().required(),ids:Qm.array()});fN.exports=function(e){return EY.validateBySchema(e,mY)}});var mN=g((Wue,hN)=>{"use strict";var zm=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}},Jm=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}},jm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};hN.exports={InsertObject:zm,NoSQLSeachObject:Jm,DeleteResponseObject:jm}});var oi=g((zue,RN)=>{"use strict";var SN=Wm(),pY=EN(),Yi=J(),pN=require("moment"),TN=$(),{promisify:SY,callbackify:TY}=require("util"),Ki=P(),gY=Os(),Xm=SY(gY.getTableSchema),Zm=Cn(),{DeleteResponseObject:RY}=mN(),{handleHDBError:si,hdb_errors:AY}=ne(),{HDB_ERROR_MSGS:q_,HTTP_STATUS_CODES:ii}=AY,OY="records successfully deleted",bY=TY(gN);RN.exports={delete:bY,deleteRecord:gN,deleteFilesBefore:yY,deleteAuditLogsBefore:NY};async function yY(e){let t=SN(e,"date");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!pN(e.date,pN.ISO_8601).isValid())throw si(new Error,q_.INVALID_DATE,ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,q_.INVALID_DATE,!0);let n=Yi.checkSchemaTableExist(e.schema,e.table);if(n)throw si(new Error,n,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,n,!0);let s=await Zm.deleteRecordsBefore(e);if(await Xm(e.schema,e.table),TN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(yY,"deleteFilesBefore");async function NY(e){let t=SN(e,"timestamp");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),isNaN(e.timestamp))throw si(new Error,q_.INVALID_VALUE("Timestamp"),ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,q_.INVALID_VALUE("Timestamp"),!0);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);let n=await Zm.deleteAuditLogsBefore(e);return await Xm(e.schema,e.table),TN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(NY,"deleteAuditLogsBefore");async function gN(e){e.ids&&(e.hash_values=e.ids);let t=pY(e);if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);Yi.transformReq(e);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);try{await Xm(e.schema,e.table);let n=await Zm.deleteRecords(e);return Yi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${OY}`),n}catch(n){if(n.message===Ki.SEARCH_NOT_FOUND_MESSAGE){let s=new RY;return s.message=Ki.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(gN,"deleteRecord")});var F_=g((jue,bN)=>{var IY=require("crypto"),AN=9;function wY(e){let t=DY(AN),r=ON(e+t);return t+r}a(wY,"createHash");function CY(e,t){let r=e?.substr(0,AN),n=r+ON(t+r);return e===n}a(CY,"validateHash");function DY(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(DY,"generateSalt");function ON(e){return IY.createHash("md5").update(e).digest("hex")}a(ON,"md5");bN.exports={hash:wY,validate:CY}});var NN=g((Zue,yN)=>{var ep=je(),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 LY(e){return jt.password.presence=!0,jt.username.presence=!0,jt.role.presence=!0,jt.active.presence=!0,ep.validateObject(e,jt)}a(LY,"addUserValidation");function MY(e){return jt.password.presence=!1,jt.username.presence=!0,jt.role.presence=!1,jt.active.presence=!1,ep.validateObject(e,jt)}a(MY,"alterUserValidation");function PY(e){return jt.password.presence=!1,jt.username.presence=!0,jt.role.presence=!1,jt.active.presence=!1,ep.validateObject(e,jt)}a(PY,"dropUserValidation");yN.exports={addUserValidation:LY,alterUserValidation:MY,dropUserValidation:PY}});var ke=g((rle,wN)=>{"use strict";var{platform:tle}=require("os"),UY="nats-server.zip",tp="nats-server",vY=process.platform==="win32"?`${tp}.exe`:tp,BY=/^[^\s.,*>]+$/,IN="__request__",HY=a(e=>`${e}.${IN}`,"REQUEST_SUBJECT"),xY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},GY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},qY={HUB:"hub.pid",LEAF:"leaf.pid"},FY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},kY={SUCCESS:"success",ERROR:"error"},VY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},$Y={TXN:"txn",MSGID:"msgid"},Wo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},YY={[Wo.ERR]:1,[Wo.WRN]:2,[Wo.INF]:3,[Wo.DBG]:4,[Wo.TRC]:5},KY={debug:"-D",trace:"-DVV"};wN.exports={NATS_SERVER_ZIP:UY,NATS_SERVER_NAME:tp,NATS_BINARY_NAME:vY,PID_FILES:qY,NATS_CONFIG_FILES:GY,SERVER_SUFFIX:FY,NATS_TERM_CONSTRAINTS_RX:BY,REQUEST_SUFFIX:IN,UPDATE_REMOTE_RESPONSE_STATUSES:kY,CLUSTER_STATUS_STATUSES:VY,REQUEST_SUBJECT:HY,SUBJECT_PREFIXES:$Y,MSG_HEADERS:xY,LOG_LEVELS:Wo,LOG_LEVEL_FLAGS:KY,LOG_LEVEL_HIERARCHY:YY}});var DN=g((sle,CN)=>{"use strict";var WY={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
- `)},QY="certificate.pem",zY="privateKey.pem",JY="ca.pem";wy.exports={CERTIFICATE_VALUES:WY,CERTIFICATE_PEM_NAME:QY,PRIVATEKEY_PEM_NAME:zY,CA_PEM_NAME:JY}});var tp=R((ale,vy)=>{"use strict";var Uy=require("fs-extra"),oe=require("joi"),jY=require("os"),{boolean:be,string:lr,number:Ze,array:ep}=oe.types(),{totalmem:Dy}=require("os"),Wi=require("path"),XY=$(),q_=Q(),ole=Cy(),Ly=M(),ZY=je(),My="log",eK="components",tK="Invalid logging.rotation.maxSize unit. Available units are G, M or K",rK="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",nK="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",sK="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",iK="rootPath config parameter is undefined",oK="clustering.enabled config parameter is undefined",Qi=Ze.min(0).required(),F_=ep.items({host:lr.required(),port:Qi}).empty(null),jn,Py=!1;vy.exports={configValidator:aK,routesValidator:fK,route_constraints:F_};function aK(e,t=!1){if(Py=t,jn=e.rootPath,q_.isEmpty(jn))throw iK;let r=be.required(),n=Ze.min(0).max(1e3).empty(null).default(dK),s=lr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(qc),i=lr.optional().empty(null),o=lr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(qc),u=oe.custom(uK).empty(null).default(qc),_=e.clustering?.enabled;if(q_.isEmpty(_))throw oK;let l=oe.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return _===!0?d=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:Qi,routes:F_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:Qi}).required()}).required(),network:oe.object({port:Qi}).required()}).required(),leafServer:oe.object({network:oe.object({port:Qi,routes:F_}).required(),streams:oe.object({maxAge:Ze.min(120).allow(null).optional(),maxBytes:Ze.min(1).allow(null).optional(),maxMsgs:Ze.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required(),verify:be.optional()}),user:lr.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:Ze.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:Ze}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:be,logSuccessful:be}),file:be.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:be.optional(),compress:be.optional(),interval:lr.custom(_K).optional().empty(null),maxSize:lr.custom(lK).optional().empty(null),path:lr.optional().empty(null).default(qc)}).required(),root:s,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:ep.optional(),headersTimeout:Ze.min(1).optional(),keepAliveTimeout:Ze.min(1).optional(),port:Ze.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(qc),securePort:Ze.optional().empty(null),timeout:Ze.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(l),l])}).required(),rootPath:lr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:Qi,securePort:Qi,mtls:oe.alternatives([be.optional(),oe.object({user:lr.optional(),certificateAuthority:i,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:Ze.optional(),cors:be.optional(),corsAccessList:ep.optional(),headersTimeout:Ze.min(1).optional(),port:Ze.min(0).optional().empty(null),securePort:Ze.min(0).optional().empty(null),maxHeaderSize:Ze.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:lr.optional(),certificateAuthority:i,required:be.optional()})])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:Ze.min(1).optional(),host:lr.optional(),waitForDebugger:be.optional()})),maxHeapMemory:Ze.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:lr.optional(),threshold:Ze.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:u,prefetchWrites:be.optional(),maxFreeSpaceToLoad:Ze.optional(),maxFreeSpaceToRetain:Ze.optional()}).required(),ignoreScripts:be.optional(),tls:oe.alternatives([oe.array().items(l),l])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(aK,"configValidator");function cK(e){return Py||Uy.existsSync(e)?null:`Specified path ${e} does not exist.`}a(cK,"doesPathExist");function uK(e,t){oe.assert(e,lr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=cK(e);if(r)return t.message(r)}a(uK,"validatePath");function lK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(tK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(nK):e}a(lK,"validateRotationMaxSize");function _K(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(rK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(sK):e}a(_K,"validateRotationInterval");function dK(e,t){let r=t.state.path.join("."),n=jY.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||Dy();return i=Math.round(Math.min(i,Dy())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),XY.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(dK,"setDefaultThreads");function qc(e,t){let r=t.state.path.join(".");if(!q_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(q_.isEmpty(jn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(jn,eK);case"logging.root":return Wi.join(jn,My);case"clustering.leafServer.streams.path":return Wi.join(jn,"clustering","leaf");case"storage.path":let n=Wi.join(jn,Ly.LEGACY_DATABASES_DIR_NAME);return Uy.existsSync(n)?n:Wi.join(jn,Ly.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(jn,My);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(jn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(qc,"setDefaultRoot");function fK(e){let t=oe.object({routes:F_});return ZY.validateBySchema({routes:e},t)}a(fK,"routesValidator")});var dr=R((lle,$y)=>{"use strict";var Gr=M(),Pt=Q(),Nt=$(),{configValidator:EK,routesValidator:By}=tp(),_r=require("fs-extra"),hK=require("yaml"),Cn=require("path"),mK=require("is-number"),xy=require("properties-reader"),pK=require("lodash"),{handleHDBError:SK}=ne(),{HTTP_STATUS_CODES:TK,HDB_ERROR_MSGS:k_}=Lr(),ule=require("minimist"),{server:gK}=(ar(),ie(Hi)),{DATABASES_PARAM_CONFIG:Fc,CONFIG_PARAMS:xr,CONFIG_PARAM_MAP:Dn}=Gr,RK="Unable to get config value because config is uninitialized",AK="Config successfully initialized",OK="Error backing up config file",bK="Empty parameter sent to getConfigValue",Gy=Cn.join(Gr.PACKAGE_ROOT,"config","yaml",Gr.HDB_DEFAULT_CONFIG_FILE),NK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Hy={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"},V_,yt,$_;$y.exports={createConfigFile:yK,getDefaultConfig:IK,getConfigValue:Fy,initConfig:np,flattenConfig:Wo,updateConfigValue:ky,updateConfigObject:CK,getConfiguration:MK,setConfiguration:UK,readConfigFile:ip,getClusteringRoutes:PK,initOldConfig:Vy,getConfigFromFile:vK,getConfigFilePath:zi,addConfig:BK,deleteConfigFromFile:HK,getConfigObj:xK};function yK(e,t=!1){let r=ai(Gy);V_=Wo(r.toJSON());let n;for(let c in e){let u=Dn[c.toLowerCase()];if(u===xr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=rp(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){Nt.error(d)}}}n&&qy(r,n),sp(r,t);let s=r.toJSON();yt=Wo(s);let i=r.getIn(["rootPath"]),o=Cn.join(i,Gr.HDB_CONFIG_FILE);_r.createFileSync(o),_r.writeFileSync(o,String(r)),Nt.trace(`Config file written to ${o}`)}a(yK,"createConfigFile");function qy(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Pt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Fc.TABLES))for(let i in n[s][Fc.TABLES])for(let o in n[s][Fc.TABLES][i]){let c=n[s][Fc.TABLES][i][o],u=[xr.DATABASES,s,Fc.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=[xr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){Nt.error("Error parsing schemas CLI/env config arguments",n)}}a(qy,"setSchemasConfig");function IK(e){if(V_===void 0){let r=ai(Gy);V_=Wo(r.toJSON())}let t=Dn[e.toLowerCase()];if(t!==void 0)return V_[t.toLowerCase()]}a(IK,"getDefaultConfig");function Fy(e){if(e==null){Nt.error(bK);return}if(yt===void 0){Nt.trace(RK);return}let t=Dn[e.toLowerCase()];if(t!==void 0)return yt[t.toLowerCase()]}a(Fy,"getConfigValue");function zi(e=Pt.getPropsFilePath()){let t=Pt.getEnvCliRootPath();return t?Cn.join(t,Gr.HDB_CONFIG_FILE):xy(e).get(Gr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function np(e=!1){if(yt===void 0||e){let t;if(!Pt.noBootFile()){t=Pt.getPropsFilePath();try{_r.accessSync(t,_r.constants.F_OK|_r.constants.R_OK)}catch(i){throw Nt.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{Vy(r);return}catch(i){if(i.code!==Gr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ai(r)}catch(i){if(i.code===Gr.NODE_ERROR_CODES.ENOENT){Nt.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 Nt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}wK(n,r),sp(n);let s=n.toJSON();if(gK.config=s,yt=Wo(s),yt.logging_rotation_rotate)for(let i in Hy)yt[i]&&Nt.error(`Config ${Hy[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Nt.trace(AK)}}a(np,"initConfig");function wK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Cn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Cn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Cn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(Nt.trace("Updating config file with missing config params"),_r.writeFileSync(t,String(e)))}a(wK,"checkForUpdatedConfig");function sp(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=EK(r,t);if(n.error)throw k_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(sp,"validateConfig");function CK(e,t){yt===void 0&&(yt={});let r=Dn[e.toLowerCase()];if(r===void 0){Nt.trace(`Unable to update config object because config param '${e}' does not exist`);return}yt[r.toLowerCase()]=t}a(CK,"updateConfigObject");function ky(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&np();let o=Fy(Dn.hdb_root),c=Cn.join(o,Gr.HDB_CONFIG_FILE),u=ai(c),_;if(r===void 0&&e.toLowerCase()===xr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Dn[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=Dn[f.toLowerCase()];if(E===xr.HTTP_SECUREPORT&&r[f]===yt[xr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===xr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===yt[xr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===xr.DATABASES){_=r[f];continue}if(E?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!E&&(f.endsWith("_package")||f.endsWith("_port"))&&(E=f),E!==void 0){let h=E.split("_"),p=Gr.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(T){Nt.error(T)}}}_&&qy(u,_),sp(u);let l=u.getIn(["rootPath"]),d=Cn.join(l,Gr.HDB_CONFIG_FILE);n===!0&&DK(c,l),_r.writeFileSync(d,String(u)),s&&(yt=Wo(u.toJSON())),Nt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(ky,"updateConfigValue");function DK(e,t){try{let r=Cn.join(t,"backup",`${Gr.HDB_CONFIG_FILE}.bak`);_r.copySync(e,r),Nt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Nt.error(OK),Nt.error(r)}}a(DK,"backupConfigFile");var LK=["databases"];function Wo(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)),$_=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])&&!LK.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;!xr[u.toUpperCase()]&&Dn[u]&&(s[Dn[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Wo,"flattenConfig");function rp(e,t){if(e===xr.CLUSTERING_NODENAME||e===xr.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(mK(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 MK(){let e=Pt.getPropsFilePath(),t=zi(e);return ai(t).toJSON()}a(MK,"getConfiguration");async function UK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return ky(void 0,void 0,s,!0),NK}catch(i){throw typeof i=="string"||i instanceof String?SK(i,i,TK.BAD_REQUEST,void 0,void 0,!0):i}}a(UK,"setConfiguration");function ip(){let e=Pt.getPropsFilePath();try{_r.accessSync(e,_r.constants.F_OK|_r.constants.R_OK)}catch(n){if(!Pt.noBootFile())throw Nt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return ai(t).toJSON()}a(ip,"readConfigFile");function ai(e){return hK.parseDocument(_r.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ai,"parseYamlDoc");function PK(){let e=ip(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Pt.isEmptyOrZeroLength(t)?[]:t;let r=By(t);if(r)throw k_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Pt.isEmptyOrZeroLength(n)?[]:n;let s=By(n);if(s)throw k_.CONFIG_VALIDATION(s.message);if(!Pt.isEmptyOrZeroLength(n)&&!Pt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.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 k_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(PK,"getClusteringRoutes");function Vy(e){let t=xy(e);yt={};for(let r in Dn){let n=t.get(r.toUpperCase());if(Pt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Dn[r].toLowerCase();s===xr.LOGGING_ROOT?yt[s]=Cn.dirname(n):yt[s]=n}return yt}a(Vy,"initOldConfig");function vK(e){let t=ip();return pK.get(t,e.replaceAll("_","."))}a(vK,"getConfigFromFile");async function BK(e,t){let r=ai(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await _r.writeFile(zi(),String(r))}a(BK,"addConfig");function HK(e){let t=zi(Pt.getPropsFilePath()),r=ai(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Cn.join(n,Gr.HDB_CONFIG_FILE);_r.writeFileSync(s,String(r))}a(HK,"deleteConfigFromFile");function xK(){return $_||(np(),$_)}a(xK,"getConfigObj")});var Ky=R((dle,Yy)=>{"use strict";var Y_=M(),K_=class{static{a(this,"BaseLicense")}constructor(t=0,r=Y_.RAM_ALLOCATION_ENUM.DEFAULT,n=Y_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},op=class extends K_{static{a(this,"ExtendedLicense")}constructor(t=0,r=Y_.RAM_ALLOCATION_ENUM.DEFAULT,n=Y_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};Yy.exports={BaseLicense:K_,ExtendedLicense:op}});var Ji=R((Ele,Xy)=>{"use strict";var zo=require("fs-extra"),Qy=G_(),zy=require("crypto"),GK=require("moment"),qK=require("uuid").v4,jt=$(),cp=require("path"),FK=Q(),ci=M(),{totalmem:Wy}=require("os"),kK=Ky().ExtendedLicense,Qo="invalid license key format",VK="061183",$K="mofi25",YK="aes-256-cbc",KK=16,WK=32,Jy=Z();Jy.initSync();var ap;Xy.exports={validateLicense:jy,generateFingerPrint:zK,licenseSearch:_p,getLicense:XK,checkMemoryLimit:ZK};function up(){return cp.join(Jy.getHdbBasePath(),ci.LICENSE_KEY_DIR_NAME,ci.LICENSE_FILE_NAME)}a(up,"getLicenseDirPath");function QK(){let e=up();return cp.join(e,ci.LICENSE_FILE_NAME)}a(QK,"getLicenseFilePath");function lp(){let e=up();return cp.join(e,ci.REG_KEY_FILE_NAME)}a(lp,"getFingerPrintFilePath");async function zK(){let e=lp();try{return await zo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await JK();throw jt.error(`Error writing fingerprint file to ${e}`),jt.error(t),new Error("There was an error generating the fingerprint")}}a(zK,"generateFingerPrint");async function JK(){let e=qK(),t=Qy.hash(e),r=lp();try{await zo.mkdirp(up()),await zo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw jt.error(`Error writing fingerprint file to ${r}`),jt.error(n),new Error("There was an error generating the fingerprint")}return t}a(JK,"writeFingerprint");function jy(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 jt.error("empty license key passed to validate."),r;let n=lp(),s=!1;try{s=zo.statSync(n)}catch(i){jt.error(i)}if(s){let i;try{i=zo.readFileSync(n,"utf8")}catch{jt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split($K),c=o[1];c=Buffer.concat([Buffer.from(c)],KK);let u=Buffer.concat([Buffer.from(i)],WK),_=zy.createDecipheriv(YK,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=jK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Qo),jt.error(Qo),new Error(Qo)}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(Qo),jt.error(Qo),new Error(Qo)}else r.exp_date=l;r.exp_date<GK().valueOf()&&(r.valid_date=!1),Qy.validate(o[1],`${VK}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||jt.error("Invalid licence"),r}a(jy,"validateLicense");function jK(e,t){try{let r=zy.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{jt.warn("Check old license failed")}}a(jK,"checkOldLicense");function _p(){let e=new kK,t=[];try{t=zo.readFileSync(QK(),"utf-8").split(ci.NEW_LINE)}catch(r){r.code==="ENOENT"?jt.info("no license file found"):jt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(FK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=jy(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){jt.error("There was an error parsing the license string."),jt.error(s),e.ram_allocation=ci.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return ap=e,e}a(_p,"licenseSearch");async function XK(){return ap||await _p(),ap}a(XK,"getLicense");function ZK(){let e=_p().ram_allocation,t=process.constrainedMemory?.()||Wy();if(t=Math.round(Math.min(t,Wy())/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(ZK,"checkMemoryLimit")});var un=R((Tle,EI)=>{"use strict";var rI="username is required",nI="nothing to update, must supply active, role or password to update",sI="password cannot be an empty string",iI="If role is specified, it cannot be empty.",oI="active must be true or false";EI.exports={addUser:cW,alterUser:uW,dropUser:_W,getSuperUser:hW,userInfo:dW,listUsers:Q_,listUsersExternal:fW,setUsersToGlobal:jo,findAndValidateUser:dI,getClusterUser:mW,USERNAME_REQUIRED:rI,ALTERUSER_NOTHING_TO_UPDATE:nI,EMPTY_PASSWORD:sI,EMPTY_ROLE:iI,ACTIVE_BOOLEAN:oI};var aI=Hr(),eW=oi(),Ep=G_(),cI=Ny(),uI=Br(),hp=bs(),qr=Q(),lI=require("validate.js"),Oe=$(),{promisify:tW}=require("util"),mp=Rs(),Zy=M(),eI=ke(),rW=dr(),mle=Z(),ple=Ji(),nW=Fi(),{table:Sle}=(Ae(),ie(Fe)),{handleHDBError:Xn,hdb_errors:sW}=ne(),{HTTP_STATUS_CODES:Zn,AUTHENTICATION_ERROR_MSGS:dp,HDB_ERROR_MSGS:Jo}=sW,{UserEventMsg:pp}=Ln(),fp=require("lodash"),{server:Sp}=(ar(),ie(Hi)),iW=$();Sp.getUser=(e,t)=>dI(e,t,t!=null);var _I={username:!0,active:!0,role:!0,password:!0},tI=new Map,W_=uI.searchByValue,oW=uI.searchByHash,aW=tW(eW.delete);async function cW(e){let t=lI.cleanAttributes(e,_I),r=cI.addUserValidation(t);if(r)throw Xn(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 W_(n),s=s&&Array.from(s)}catch(u){throw Oe.error("There was an error searching for a role in add user"),Oe.error(u),u}if(!s||s.length<1)throw Xn(new Error,Jo.ROLE_NAME_NOT_FOUND(t.role),Zn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Xn(new Error,Jo.DUP_ROLES_FOUND(t.role),Zn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=mp.encrypt(t.password)),t.password=Ep.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await aI.insert(i)}catch(u){throw Oe.error("There was an error searching for a user."),Oe.error(u),u}Oe.debug(o);try{await jo()}catch(u){throw Oe.error("Got an error setting users to global"),Oe.error(u),u}if(o.skipped_hashes.length===1)throw Xn(new Error,Jo.USER_ALREADY_EXISTS(t.username),Zn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],hp.signalUserChange(new pp(process.pid)),`${c.username} successfully added`}a(cW,"addUser");async function uW(e){let t=lI.cleanAttributes(e,_I);if(qr.isEmptyOrZeroLength(t.username))throw new Error(rI);if(qr.isEmptyOrZeroLength(t.password)&&qr.isEmptyOrZeroLength(t.role)&&qr.isEmptyOrZeroLength(t.active))throw new Error(nI);if(!qr.isEmpty(t.password)&&qr.isEmptyOrZeroLength(t.password.trim()))throw new Error(sI);if(!qr.isEmpty(t.active)&&!qr.isBoolean(t.active))throw new Error(oI);let r=lW(t.username);if(!qr.isEmpty(t.password)&&!qr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=mp.encrypt(t.password)),t.password=Ep.hash(t.password)),t.role==="")throw new Error(iI);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 W_(i)||[])}catch(c){throw Oe.error("Got an error searching for a role."),Oe.error(c),c}if(!o||o.length===0){let c=Jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Oe.error(c),Xn(new Error,c,Zn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Jo.ALTER_USER_DUP_ROLES(t.role);throw Oe.error(c),Xn(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 aI.update(n)}catch(i){throw Oe.error("Error during update."),Oe.error(i),i}try{await jo()}catch(i){throw Oe.error("Got an error setting users to global"),Oe.error(i),i}return hp.signalUserChange(new pp(process.pid)),s}a(uW,"alterUser");function lW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(lW,"isClusterUser");async function _W(e){try{let t=cI.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(qr.isEmpty(global.hdb_users.get(e.username)))throw Xn(new Error,Jo.USER_NOT_EXIST(e.username),Zn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await aW(r)}catch(s){throw Oe.error("Got an error deleting a user."),Oe.error(s),s}Oe.debug(n);try{await jo()}catch(s){throw Oe.error("Got an error setting users to global."),Oe.error(s),s}return hp.signalUserChange(new pp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(_W,"dropUser");async function dW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=fp.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await oW(r)}catch(s){throw Oe.error("Got an error searching for a role."),Oe.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Oe.error(r),r}return t}a(dW,"userInfo");async function fW(){let e;try{e=await Q_()}catch(t){throw Oe.error("Got an error listing users."),Oe.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(fW,"listUsersExternal");async function Q_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await W_(e)}catch(o){throw Oe.error("Got an error searching for roles."),Oe.error(o),o}let r={};for(let o of t)r[o.id]=fp.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 W_(n)}catch(o){throw Oe.error("Got an error searching for users."),Oe.error(o),o}let i=new Map;for(let o of s)o=fp.cloneDeep(o),o.role=r[o.role],EW(o.role),i.set(o.username,o);return i}catch(e){throw Oe.error("got an error listing users"),Oe.error(e),qr.errorizeMessage(e)}return null}a(Q_,"listUsers");function EW(e){try{if(!e){Oe.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(nW)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Oe.error("Got an error trying to set system permissions."),Oe.error(t)}}a(EW,"appendSystemTablesToRole");async function jo(){try{let e=await Q_();global.hdb_users=e}catch(e){throw Oe.error(e),e}}a(jo,"setUsersToGlobal");async function dI(e,t,r=!0){global.hdb_users||await jo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Xn(new Error,dp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Xn(new Error,dp.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(tI.get(t)===n.password)return s;if(Ep.validate(n.password,t))tI.set(t,n.password);else throw Xn(new Error,dp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(dI,"findAndValidateUser");async function hW(){global.hdb_users||await jo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(hW,"getSuperUser");async function mW(){let e=await Q_(),t=rW.getConfigFromFile(Zy.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!qr.isEmpty(r)&&r?.role?.role===Zy.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=mp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+eI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+eI.SERVER_SUFFIX.ADMIN,r}a(mW,"getClusterUser");var fI=[];Sp.invalidateUser=function(e){for(let t of fI)try{t(e)}catch(r){iW.error("Error invalidating user",r)}};Sp.onInvalidatedUser=function(e){fI.push(e)}});var Vc=R((Ole,SI)=>{"use strict";var ji=$(),Fr=M(),pW=KN(),Rle=Os(),Ale=As(),SW=un(),{validateEvent:hI}=Ln(),kc=wn(),TW=require("process"),{resetDatabases:gW}=(Ae(),ie(Fe)),RW={[Fr.ITC_EVENT_TYPES.SCHEMA]:AW,[Fr.ITC_EVENT_TYPES.USER]:pI};async function AW(e){let t=hI(e);if(t){ji.error(t);return}ji.trace("ITC schemaHandler received schema event:",e),await pW(e.message),await OW(e.message)}a(AW,"schemaHandler");async function OW(e){try{kc.resetReadTxn(Fr.SYSTEM_SCHEMA_NAME,Fr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),kc.resetReadTxn(Fr.SYSTEM_SCHEMA_NAME,Fr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),kc.resetReadTxn(Fr.SYSTEM_SCHEMA_NAME,Fr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=gW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ji.error(t)}}a(OW,"syncSchemaMetadata");var mI=[];async function pI(e){try{try{kc.resetReadTxn(Fr.SYSTEM_SCHEMA_NAME,Fr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),kc.resetReadTxn(Fr.SYSTEM_SCHEMA_NAME,Fr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ji.warn(r)}let t=hI(e);if(t){ji.error(t);return}ji.trace(`ITC userHandler ${Fr.HDB_ITC_CLIENT_PREFIX}${TW.pid} received user event:`,e),await SW.setUsersToGlobal();for(let r of mI)r()}catch(t){ji.error(t)}}a(pI,"userHandler");pI.addListener=function(e){mI.push(e)};SI.exports=RW});var Ln=R((Cle,gI)=>{"use strict";var Nle=$(),Tp=Q(),bW=M(),{ITC_ERRORS:$c}=Lr(),{parentPort:yle,threadId:NW,isMainThread:yW,workerData:Ile}=require("worker_threads"),{onMessageFromWorkers:IW,broadcast:wle,broadcastWithAcknowledgement:wW}=Je();gI.exports={sendItcEvent:CW,validateEvent:TI,SchemaEventMsg:DW,UserEventMsg:LW};var z_;IW(async(e,t)=>{z_=z_||Vc(),TI(e),z_[e.type]&&await z_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function CW(e){return!yW&&e.message&&(e.message.originator=NW),wW(e)}a(CW,"sendItcEvent");function TI(e){if(typeof e!="object")return $c.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Tp.isEmpty(e.type))return $c.MISSING_TYPE;if(!e.hasOwnProperty("message")||Tp.isEmpty(e.message))return $c.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Tp.isEmpty(e.message.originator))return $c.MISSING_ORIGIN;if(bW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return $c.INVALID_EVENT(e.type)}a(TI,"validateEvent");function DW(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(DW,"SchemaEventMsg");function LW(e){this.originator=e}a(LW,"UserEventMsg")});var bs=R((Mle,bI)=>{"use strict";var RI=M(),Lle=Q(),J_=$(),AI=VN(),Xo,{sendItcEvent:OI}=Ln();function MW(e){try{J_.trace("signalSchemaChange called with message:",e),Xo=Xo||Vc();let t=new AI(RI.ITC_EVENT_TYPES.SCHEMA,e);return Xo.schema(t),OI(t)}catch(t){J_.error(t)}}a(MW,"signalSchemaChange");function UW(e){try{J_.trace("signalUserChange called with message:",e),Xo=Xo||Vc();let t=new AI(RI.ITC_EVENT_TYPES.USER,e);return Xo.user(t),OI(t)}catch(t){J_.error(t)}}a(UW,"signalUserChange");bI.exports={signalSchemaChange:MW,signalUserChange:UW}});var j_=R((Ple,yI)=>{"use strict";var NI=Q(),PW=M(),vW=$(),BW=N_(),HW=b_(),xW=bs(),{SchemaEventMsg:GW}=Ln(),qW="already exists in";yI.exports=FW;async function FW(e,t,r){if(NI.isEmptyOrZeroLength(r))return r;let n=[];NI.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 kW(e,t.schema,t.name,i)})),s}a(FW,"lmdbCheckForNewAttributes");async function kW(e,t,r,n){let s=new HW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await VW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(qW))vW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(kW,"createNewAttribute");async function VW(e){let t;return t=await BW(e),xW.signalSchemaChange(new GW(process.pid,PW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(VW,"createAttribute")});var Zo=R((Ble,II)=>{"use strict";var gp=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}};II.exports=gp});var CI=R((xle,wI)=>{"use strict";var $W=Zo(),YW=M().OPERATIONS_ENUM,Rp=class extends $W{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(YW.INSERT,r,n,s,i),this.records=t}};wI.exports=Rp});var LI=R((qle,DI)=>{"use strict";var KW=Zo(),WW=M().OPERATIONS_ENUM,Ap=class extends KW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(WW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};DI.exports=Ap});var UI=R((kle,MI)=>{"use strict";var QW=Zo(),zW=M().OPERATIONS_ENUM,Op=class extends QW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(zW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};MI.exports=Op});var vI=R(($le,PI)=>{"use strict";var JW=Zo(),jW=M().OPERATIONS_ENUM,bp=class extends JW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(jW.DELETE,n,s,t,i),this.original_records=r}};PI.exports=bp});var Yc=R((Wle,GI)=>{"use strict";var Kle=require("path"),BI=Ke(),XW=CI(),ZW=LI(),eQ=UI(),tQ=vI(),ea=ut(),HI=Q(),{CONFIG_PARAMS:rQ}=M(),xI=Z();xI.initSync();var X_=M().OPERATIONS_ENUM,{getTransactionAuditStorePath:nQ}=ze();GI.exports=sQ;async function sQ(e,t){if(xI.get(rQ.LOGGING_AUDITLOG)===!1)return;let r=nQ(e.schema,e.table),n=await BI.openEnvironment(r,e.table,!0),s=iQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){BI.initializeDBIs(n,ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ea.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),HI.isEmpty(s.user_name)||n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(sQ,"writeTransaction");function iQ(e,t){let r=HI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===X_.INSERT)return new XW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===X_.UPDATE)return new ZW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===X_.UPSERT)return new eQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===X_.DELETE)return new tQ(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(iQ,"createTransactionObject")});var Np=R((Jle,qI)=>{"use strict";var oQ=Bc(),zle=Hc(),Kc=M(),aQ=xc(),cQ=$o().insertRecords,uQ=Ke(),lQ=$(),_Q=j_(),{getSchemaPath:dQ}=ze(),fQ=Yc();qI.exports=EQ;async function EQ(e){try{let{schema_table:t,attributes:r}=oQ(e);aQ(e,r,t.hash_attribute),e.schema!==Kc.SYSTEM_SCHEMA_NAME&&(r.includes(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await _Q(e.hdb_auth_header,t,r),s=dQ(e.schema,e.table),i=await uQ.openEnvironment(s,e.table),o=await cQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await fQ(e,o)}catch(c){lQ.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(EQ,"lmdbCreateRecords")});var VI=R((Xle,kI)=>{"use strict";var FI=M(),hQ=Np(),mQ=Hc(),pQ=require("fs-extra"),{getSchemaPath:SQ}=ze();kI.exports=TQ;async function TQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new mQ(FI.SYSTEM_SCHEMA_NAME,FI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await hQ(r),await pQ.mkdirp(SQ(e.schema))}a(TQ,"lmdbCreateSchema")});var YI=R((e_e,$I)=>{"use strict";var yp=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}};$I.exports=yp});var zI=R((i_e,QI)=>{"use strict";var KI=Ke(),Ip=Mr(),wp=Lr().LMDB_ERRORS_ENUM,gQ=ut(),WI=$(),r_e=Q(),RQ=require("lmdb"),AQ=YI(),OQ=M(),{OVERFLOW_MARKER:n_e,MAX_SEARCH_KEY_LENGTH:s_e}=gQ,bQ=OQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function NQ(e,t,r,n){if(Ip.validateEnv(e),t===void 0)throw new Error(wp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(wp.IDS_REQUIRED):new Error(wp.IDS_MUST_BE_ITERABLE);try{let s=KI.listDBIs(e);KI.initializeDBIs(e,t,s);let i=new AQ,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[bQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,RQ.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let A=e.dbis[T],g=h[T];if(g!=null)try{let L=Ip.getIndexedValues(g);if(L)for(let v=0,P=L.length;v<P;v++)A.remove(L[v],o)}catch{WI.warn(`cannot delete from attribute: ${T}, ${g}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){WI.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=Ip.getNextMonotonicTime(),i}catch(s){throw s}}a(NQ,"deleteRecords");QI.exports={deleteRecords:NQ}});var Wc=R((a_e,jI)=>{"use strict";var ta=Q(),yQ=zI(),IQ=Ke(),{getSchemaPath:wQ}=ze(),CQ=Yc(),DQ=$();jI.exports=LQ;async function LQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ta.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ta.isEmptyOrZeroLength(e.hash_values)&&!ta.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ta.isEmpty(u)||e.hash_values.push(u)}}if(ta.isEmptyOrZeroLength(e.hash_values))return JI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ta.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=wQ(e.schema,e.table),i=await IQ.openEnvironment(s,e.table),o=await yQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await CQ(e,o)}catch(c){DQ.error(`unable to write transaction due to ${c.message}`)}return JI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(LQ,"lmdbDeleteRecords");function JI(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(JI,"createDeleteResponse")});var Dp=R((l_e,XI)=>{"use strict";var MQ=M(),u_e=Mr();function Cp(e,t){let r=Object.create(null);if(t.length===1&&MQ.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(Cp,"parseRow");function UQ(e,t,r,n){let s=Cp(r,e);n.push(s)}a(UQ,"searchAll");function PQ(e,t,r,n){let s=Cp(r,e);n[t]=s}a(PQ,"searchAllToMap");function vQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(vQ,"iterateDBI");function Xi(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(Xi,"pushResults");function BQ(e,t,r,n,s,i){t.toString().endsWith(e)&&Xi(t,r,n,s,i)}a(BQ,"endsWith");function HQ(e,t,r,n,s,i){t.toString().includes(e)&&Xi(t,r,n,s,i)}a(HQ,"contains");function xQ(e,t,r,n,s,i){t>e&&Xi(t,r,n,s,i)}a(xQ,"greaterThanCompare");function GQ(e,t,r,n,s,i){t>=e&&Xi(t,r,n,s,i)}a(GQ,"greaterThanEqualCompare");function qQ(e,t,r,n,s,i){t<e&&Xi(t,r,n,s,i)}a(qQ,"lessThanCompare");function FQ(e,t,r,n,s,i){t<=e&&Xi(t,r,n,s,i)}a(FQ,"lessThanEqualCompare");XI.exports={parseRow:Cp,searchAll:UQ,searchAllToMap:PQ,iterateDBI:vQ,endsWith:BQ,contains:HQ,greaterThanCompare:xQ,greaterThanEqualCompare:GQ,lessThanCompare:qQ,lessThanEqualCompare:FQ,pushResults:Xi}});var ra=R((h_e,iw)=>{"use strict";var ui=Ke(),d_e=$(),kr=Mr(),Z_=ut(),_t=Lr().LMDB_ERRORS_ENUM,f_e=Q(),kQ=M(),ed=Dp(),{parseRow:VQ}=ed,E_e=require("lmdb"),{OVERFLOW_MARKER:ZI,MAX_SEARCH_KEY_LENGTH:$Q}=Z_;function ew(e,t,r,n=!1,s=void 0,i=void 0){return Zi(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(ew,"iterateFullIndex");function Qc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Zi(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(g=>({value:g}))):d.getRange(A)})}a(Qc,"iterateRangeBetween");function Zi(e,t,r,n){let s=e.database||e,i=ui.openDBI(s,r);i[Z_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ui.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(Zi,"setupTransaction");function tw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(ZI)){if(!s)if(r)s=ui.openDBI(e,r);else{let u=ui.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ui.openDBI(e,u[_]),!s[Z_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(tw,"getOverflowCheck");function YQ(e,t,r,n=!1,s=void 0,i=void 0){if(kr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return Zi(e,t,t,(o,c,u)=>(td(r),r=zc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>VQ(_.value,r))))}a(YQ,"searchAll");function KQ(e,t,r,n=!1,s=void 0,i=void 0){if(kr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);td(r),r=zc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of ew(e,t,t,n,s,i))o.set(c,ed.parseRow(u,r));return o}a(KQ,"searchAllToMap");function WQ(e,t,r=!1,n=void 0,s=void 0){if(kr.validateEnv(e),t===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=ew(e,void 0,t,r,n,s),c=o.transaction,u=tw(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(WQ,"iterateDBI");function QQ(e,t){if(kr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return ui.statDBI(e,t).entryCount}a(QQ,"countAll");function zQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,t,r,(c,u,_,l)=>(n=kr.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(zQ,"equals");function JQ(e,t,r){return li(e,t,r),ui.openDBI(e,t).getValuesCount(r)}a(JQ,"count");function jQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,null,r,(c,u)=>{n=kr.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(jQ,"startsWith");function XQ(e,t,r,n,s=!1,i=void 0,o=void 0){return rw(e,t,r,n,s,i,o,!0)}a(XQ,"endsWith");function rw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return li(e,r,n),Zi(e,null,r,(u,_,l,d)=>{let f=tw(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(ZI)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[Z_.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(rw,"contains");function ZQ(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Qc(e,t,r,n,u,s,i,o,!0,!1)}a(ZQ,"greaterThan");function ez(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Qc(e,t,r,n,u,s,i,o,!1,!1)}a(ez,"greaterThanEqual");function tz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Qc(e,t,r,u,n,s,i,o,!1,!0)}a(tz,"lessThan");function rz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Qc(e,t,r,u,n,s,i,o,!1,!1)}a(rz,"lessThanEqual");function nz(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(kr.validateEnv(e),r===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(_t.START_VALUE_REQUIRED);if(s===void 0)throw new Error(_t.END_VALUE_REQUIRED);if(n=kr.convertKeyValueToWrite(n),s=kr.convertKeyValueToWrite(s),n>s)throw new Error(_t.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Qc(e,t,r,n,s,i,o,c)}a(nz,"between");function sz(e,t,r,n){kr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(td(r),r=zc(s,r),n===void 0)throw new Error(_t.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=ed.parseRow(c,r)),o}a(sz,"searchByHash");function iz(e,t,r){kr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_t.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(iz,"checkHashExists");function oz(e,t,r,n,s=[]){return sw(e,t,r,n,s),nw(e,t,r,n,s).map(i=>i[1])}a(oz,"batchSearchByHash");function az(e,t,r,n,s=[]){sw(e,t,r,n,s);let i=new Map;for(let[o,c]of nw(e,t,r,n,s))i.set(o,c);return i}a(az,"batchSearchByHashToMap");function nw(e,t,r,n,s=[]){return Zi(e,t,t,(i,o,c)=>{r=zc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,ed.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(nw,"batchHashSearch");function sw(e,t,r,n,s){if(kr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(td(r),n==null)throw new Error(_t.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(_t.IDS_MUST_BE_ITERABLE)}a(sw,"initializeBatchSearchByHash");function td(e){if(!Array.isArray(e))throw e===void 0?new Error(_t.FETCH_ATTRIBUTES_REQUIRED):new Error(_t.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(td,"validateFetchAttributes");function li(e,t,r){if(kr.validateEnv(e),t===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_t.SEARCH_VALUE_REQUIRED);if(r?.length>$Q)throw new Error(_t.SEARCH_VALUE_TOO_LARGE)}a(li,"validateComparisonFunctions");function zc(e,t){return t.length===1&&kQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ui.listDBIs(e)),t}a(zc,"setGetWholeRowAttributes");iw.exports={searchAll:YQ,searchAllToMap:KQ,count:JQ,countAll:QQ,equals:zQ,startsWith:jQ,endsWith:XQ,contains:rw,searchByHash:sz,setGetWholeRowAttributes:zc,batchSearchByHash:oz,batchSearchByHashToMap:az,checkHashExists:iz,iterateDBI:WQ,greaterThan:ZQ,greaterThanEqual:ez,lessThan:tz,lessThanEqual:rz,between:nz}});var na=R((p_e,lw)=>{var ow=require("lodash"),aw=je(),fe=require("joi"),cz=Q(),{hdb_schema_table:Jc,checkValidTable:cw,hdb_table:uw,hdb_database:rd}=zn(),{handleHDBError:uz,hdb_errors:lz}=ne(),{getDatabases:_z}=(Ae(),ie(Fe)),{HTTP_STATUS_CODES:dz}=lz,fz=fe.object({database:rd,schema:rd,table:uw,search_attribute:Jc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(Jc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),Ez=fe.object({database:rd,schema:rd,table:uw,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives(Jc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(Jc,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives(Jc,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});lw.exports=function(e,t){let r=null;switch(t){case"value":r=aw.validateBySchema(e,fz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(cw("database",e.schema)),i(cw("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=aw.validateBySchema(e,Ez);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=cz.checkGlobalSchemaTable(e.schema,e.table);if(s)return uz(new Error,s,dz.NOT_FOUND);let o=_z()[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 _=ow.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!ow.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 Lp=R((T_e,_w)=>{"use strict";var hz=Ke(),mz=na(),{getSchemaPath:pz}=ze();_w.exports=Sz;function Sz(e){let t=mz(e,"hashes");if(t)throw t;let r=pz(e.schema,e.table);return hz.openEnvironment(r,e.table)}a(Sz,"initialize")});var Mp=R((R_e,dw)=>{"use strict";var Tz=ra(),gz=Lp();dw.exports=Rz;async function Rz(e){let t=await gz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Tz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(Rz,"lmdbGetDataByHash")});var sa=R((O_e,fw)=>{"use strict";var Up=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};fw.exports=Up});var hw=R((y_e,Ew)=>{"use strict";var N_e=sa(),Az=ra(),Oz=Lp();Ew.exports=bz;async function bz(e){let t=await Oz(e),r=global.hdb_schema[e.schema][e.table];return Az.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(bz,"lmdbSearchByHash")});var es=R((w_e,mw)=>{"use strict";var Pp=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}};mw.exports=Pp});var nd=R((D_e,Aw)=>{"use strict";var Xt=ra(),Nz=Ke(),yz=Q(),Ee=ut(),eo=M(),Iz=Fi(),pw=Lr().LMDB_ERRORS_ENUM,{getSchemaPath:wz}=ze(),Ns=eo.SEARCH_WILDCARDS;async function Cz(e,t,r){let n;e.schema===eo.SYSTEM_SCHEMA_NAME?n=Iz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Rw(e,n.hash_attribute,r,t);return Tw(e,s,n.hash_attribute,r)}a(Cz,"prepSearch");async function Tw(e,t,r,n){let s=wz(e.schema,e.table),i=await Nz.openEnvironment(s,e.table),o=gw(i,e,t,r),c=o.transaction||i;if([Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Ee.SEARCH_TYPES.SEARCH_ALL,Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(Dz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Sw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?Sw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Xt.batchSearchByHashToMap(c,r,e.get_attributes,_):Xt.batchSearchByHash(c,r,e.get_attributes,_)}a(Tw,"executeSearch");function gw(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 Ee.SEARCH_TYPES.EQUALS:s=Xt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=Xt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=Xt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=Xt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Xt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Xt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return Xt.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Xt.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=Xt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=Xt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Xt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=Xt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=Xt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(gw,"searchByType");function Sw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Sw,"createMapFromIterable");function Dz(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(Dz,"checkToFetchMore");function Rw(e,t,r,n){if(yz.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),Ns.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Ns[0])<0&&s.indexOf(Ns[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(Ns.indexOf(i)>=0&&Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(Ns.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(Ns[0])||s.includes(Ns[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(pw.UNKNOWN_SEARCH_TYPE)}else switch(n){case eo.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case eo.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case eo.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case eo.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case eo.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(pw.UNKNOWN_SEARCH_TYPE)}}a(Rw,"createSearchTypeFromSearchObject");Aw.exports={executeSearch:Tw,createSearchTypeFromSearchObject:Rw,prepSearch:Cz,searchByType:gw}});var bw=R((U_e,Ow)=>{"use strict";var M_e=es(),Lz=na(),Mz=Q(),Uz=M(),Pz=nd();Ow.exports=vz;function vz(e,t){if(!Mz.isEmpty(t)&&Uz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Lz(e,"value");if(n)throw n;return Pz.prepSearch(e,t,!0)}a(vz,"lmdbGetDataByValue")});var jc=R((B_e,Nw)=>{"use strict";var v_e=es(),Bz=na(),Hz=Q(),xz=M(),Gz=nd();Nw.exports=qz;async function qz(e,t){if(!Hz.isEmpty(t)&&xz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Bz(e,"value");if(n)throw n;return Gz.prepSearch(e,t,!1)}a(qz,"lmdbSearchByValue")});var Iw=R((G_e,yw)=>{"use strict";var x_e=ut(),vp=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}},Bp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Hp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};yw.exports={SearchByConditionsObject:vp,SearchCondition:Bp,SortAttribute:Hp}});var Mw=R((V_e,Lw)=>{"use strict";var F_e=Iw().SearchByConditionsObject,Fz=es(),kz=na(),xp=ra(),sd=ut(),{Resource:k_e}=(Nn(),ie(Gp)),Dw=nd(),Vz=Dp(),$z=require("lodash"),{getSchemaPath:Yz}=ze(),ww=Ke(),{handleHDBError:Kz,hdb_errors:Wz}=ne(),{HTTP_STATUS_CODES:Qz}=Wz,zz=1e8;Lw.exports=Jz;async function Jz(e){let t=kz(e,"conditions");if(t)throw Kz(t,t.message,Qz.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=Yz(e.schema,e.table),n=await ww.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)ww.openDBI(n,_.search_attribute);let i=$z.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===sd.SEARCH_TYPES.EQUALS?_.estimated_count=xp.count(n,_.search_attribute,_.search_value):l===sd.SEARCH_TYPES.CONTAINS||l===sd.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=zz}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Cw(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(Dw.filterByType),d=l.length,f=xp.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=>Vz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await Cw(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=xp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Jz,"lmdbSearchByConditions");async function Cw(e,t,r,n){let s=new Fz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===sd.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Dw.searchByType(e,s,i,n).map(o=>o.value)}a(Cw,"executeConditionSearch")});var ia=R((Y_e,Uw)=>{"use strict";var jz=M().OPERATIONS_ENUM,qp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=jz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Uw.exports=qp});var Fp=R((W_e,Fw)=>{"use strict";var Hw=es(),xw=ia(),Gw=jc(),qw=Wc(),fr=M(),Pw=Q(),vw=Ke(),{getTransactionAuditStorePath:Xz,getSchemaPath:Zz}=ze(),Bw=$();Fw.exports=e2;async function e2(e){try{if(Pw.isEmpty(global.hdb_schema[e.schema])||Pw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await t2(e),await r2(e);let t=Zz(e.schema,e.table);try{await vw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Bw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Xz(e.schema,e.table);await vw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Bw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(e2,"lmdbDropTable");async function t2(e){let t=new Hw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Gw(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 xw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await qw(s)}a(t2,"deleteAttributesFromSystem");async function r2(e){let t=new Hw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,fr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Gw(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 xw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await qw(s)}catch(i){throw i}}a(r2,"dropTableFromSystem")});var Vw=R((z_e,kw)=>{"use strict";var n2=require("fs-extra"),s2=es(),i2=sa(),o2=ia(),a2=Fp(),c2=Wc(),u2=Mp(),l2=jc(),ys=M(),{getSchemaPath:_2}=ze(),{handleHDBError:d2,hdb_errors:f2}=ne(),{HDB_ERROR_MSGS:E2,HTTP_STATUS_CODES:h2}=f2;kw.exports=m2;async function m2(e){let t;try{t=await p2(e.schema);let r=new s2(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await l2(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await a2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new o2(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await c2(s);let i=_2(t);await n2.remove(i)}catch(r){throw r}}a(m2,"lmdbDropSchema");async function p2(e){let t=new i2(ys.SYSTEM_SCHEMA_NAME,ys.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[ys.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await u2(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw d2(new Error,E2.SCHEMA_NOT_FOUND(e),h2.NOT_FOUND,void 0,void 0,!0);return n}a(p2,"validateDropSchema")});var id=R((j_e,$w)=>{"use strict";var kp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};$w.exports=kp});var Kw=R((ede,Yw)=>{"use strict";var S2=require("fs-extra"),od=Ke(),{getTransactionAuditStorePath:T2}=ze(),Vp=ut(),Z_e=id();Yw.exports=g2;async function g2(e){let t;try{let r=T2(e.schema,e.table);await S2.mkdirp(r),t=await od.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{od.createDBI(t,Vp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),od.createDBI(t,Vp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),od.createDBI(t,Vp.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(g2,"createTransactionsAuditEnvironment")});var Jw=R((rde,zw)=>{"use strict";var $p=M(),Ww=Ke(),R2=$o(),{getSystemSchemaPath:A2,getSchemaPath:O2}=ze(),b2=Fi(),N2=N_(),Yp=b_(),y2=$(),I2=Kw(),Wp=b2.hdb_table,Qw=[];for(let e=0;e<Wp.attributes.length;e++)Qw.push(Wp.attributes[e].attribute);zw.exports=w2;async function w2(e,t){let r=O2(t.schema,t.table),n=new Yp(t.schema,t.table,$p.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Yp(t.schema,t.table,$p.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Yp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Ww.createEnvironment(r,t.table),e!==void 0){let o=await Ww.openEnvironment(A2(),$p.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await R2.insertRecords(o,Wp.hash_attribute,Qw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Kp(n),await Kp(s),await Kp(i)}await I2(t)}catch(o){throw o}}a(w2,"lmdbCreateTable");async function Kp(e){try{await N2(e)}catch(t){y2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Kp,"createAttribute")});var Xw=R((sde,jw)=>{"use strict";var C2=Bc(),D2=xc(),L2=j_(),Xc=M(),M2=$o().updateRecords,U2=Ke(),{getSchemaPath:P2}=ze(),v2=Yc(),B2=$();jw.exports=H2;async function H2(e){try{let{schema_table:t,attributes:r}=C2(e);D2(e,r,t.hash_attribute),e.schema!==Xc.SYSTEM_SCHEMA_NAME&&(r.includes(Xc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Xc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Xc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Xc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await L2(e.hdb_auth_header,t,r),s=P2(e.schema,e.table),i=await U2.openEnvironment(s,e.table),o=await M2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await v2(e,o)}catch(c){B2.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(H2,"lmdbUpdateRecords")});var eC=R((ode,Zw)=>{"use strict";var x2=M().OPERATIONS_ENUM,Qp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=x2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Zw.exports=Qp});var rC=R((ude,tC)=>{"use strict";var cde=eC(),G2=Bc(),q2=xc(),F2=j_(),Zc=M(),k2=$o().upsertRecords,V2=Ke(),{getSchemaPath:$2}=ze(),Y2=Yc(),K2=$(),{handleHDBError:W2,hdb_errors:Q2}=ne();tC.exports=z2;async function z2(e){let t;try{t=G2(e)}catch(u){throw W2(u,u.message,Q2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;q2(e,n,r.hash_attribute),e.schema!==Zc.SYSTEM_SCHEMA_NAME&&(n.includes(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await F2(e.hdb_auth_header,r,n),i=$2(e.schema,e.table),o=await V2.openEnvironment(i,e.table),c=await k2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await Y2(e,c)}catch(u){K2.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(z2,"lmdbUpsertRecords")});var sC=R((_de,nC)=>{"use strict";var zp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};nC.exports=zp});var oC=R((fde,iC)=>{"use strict";var Jp=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}};iC.exports=Jp});var uC=R((mde,cC)=>{"use strict";var jp=Ke(),{getTransactionAuditStorePath:J2}=ze(),hde=sC(),eu=ut(),j2=Q(),aC=oC(),X2=require("util").promisify,Z2=X2(setTimeout),eJ=1e4,tJ=100;cC.exports=rJ;async function rJ(e){let t=J2(e.schema,e.table),r=await jp.openEnvironment(t,e.table,!0),n=jp.listDBIs(r);jp.initializeDBIs(r,eu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new aC;do s=await nJ(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 Z2(tJ);while(s.transactions_deleted>0);return i}a(rJ,"deleteAuditLogsBefore");async function nJ(e,t){let r=new aC;try{let n=e.dbis[eu.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[eu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];j2.isEmpty(c)||(s=e.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>eJ)break}return await s,r}catch(n){throw n}}a(nJ,"deleteTransactions")});var _C=R((Sde,lC)=>{"use strict";var Xp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};lC.exports=Xp});var fC=R((Rde,dC)=>{"use strict";var sJ=es(),iJ=ia(),gde=_C(),ts=M(),oJ=Q(),Zp=Ke(),aJ=Fi(),cJ=jc(),uJ=Wc(),{getSchemaPath:lJ}=ze();dC.exports=_J;async function _J(e,t=!0){let r;e.schema===ts.SYSTEM_SCHEMA_NAME?r=aJ[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await fJ(e),s=lJ(e.schema,e.table),i=await Zp.openEnvironment(s,e.table);return t===!0&&await dJ(e,i,r.hash_attribute),Zp.dropDBI(i,e.attribute),n}a(_J,"lmdbDropAttribute");async function dJ(e,t,r){let n=Zp.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(dJ,"removeAttributeFromAllObjects");async function fJ(e){let t=new sJ(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await cJ(t)).filter(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(oJ.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new iJ(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return uJ(i)}a(fJ,"dropAttributeFromSystem")});var TC=R((bde,SC)=>{"use strict";var eS=Ke(),oa=ut(),Ode=Mr(),tS=M(),EC=Q(),{getTransactionAuditStorePath:EJ}=ze(),hJ=ra(),ad=Zo(),mJ=$();SC.exports=pJ;async function pJ(e){let t=EJ(e.schema,e.table),r=await eS.openEnvironment(t,e.table,!0),n=eS.listDBIs(r);eS.initializeDBIs(r,oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return hC(r,e.search_values);case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,TJ(r,e.search_values,s);case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return SJ(r,e.search_values);default:return hC(r)}}a(pJ,"readAuditLog");function hC(e,t=[0,Date.now()]){EC.isEmpty(t[0])&&(t[0]=0),EC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[oa.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 ad,s))}a(hC,"searchTransactionsByTimestamp");function SJ(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[oa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,pC(e,i))}return Object.fromEntries(r)}a(SJ,"searchTransactionsByUsername");function TJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=hJ.equals(e,oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,oa.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=pC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);mC(u,"records",r,l,o),mC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(TJ,"searchTransactionsByHashValues");function mC(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 ad(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new ad(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(mC,"loopRecords");function pC(e,t){let r=[];try{let n=e.dbis[oa.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 ad,i);r.push(o)}}catch(i){mJ.warn(i)}return r}catch(n){throw n}}a(pC,"batchSearchTransactions")});var RC=R((wde,gC)=>{"use strict";var{getSchemaPath:yde}=ze(),Ide=Ke(),{database:gJ}=(Ae(),ie(Fe));gC.exports={writeTransaction:RJ};async function RJ(e,t,r){return gJ({database:e,table:t}).transaction(r)}a(RJ,"writeTransaction")});var NC=R((Dde,bC)=>{"use strict";var{getSchemaPath:AC}=ze(),OC=Ke();bC.exports={flush:AJ,resetReadTxn:OJ};async function AJ(e,t){return(await OC.openEnvironment(AC(e,t),t.toString())).flushed}a(AJ,"flush");async function OJ(e,t){try{(await OC.openEnvironment(AC(e,t),t.toString())).resetReadTxn()}catch{}}a(OJ,"resetReadTxn")});var CC=R((Mde,wC)=>{"use strict";var{Readable:bJ}=require("stream"),{getDatabases:NJ}=(Ae(),ie(Fe)),{readSync:yJ,openSync:IJ,createReadStream:yC}=require("fs"),{open:wJ}=require("lmdb"),IC=Cc(),CJ=Dc(),{AUDIT_STORE_OPTIONS:DJ}=(ti(),ie(DC)),{INTERNAL_DBIS_NAME:LJ,AUDIT_STORE_NAME:MJ}=ut();wC.exports=PJ;var rS=32768,UJ=100;async function PJ(e){let t=e.database||e.schema||"data",r=NJ()[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=wJ({noSync:!0,maxDbs:CJ.MAX_DBS}),f,E=d.openDB(LJ,new IC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(A,g){g.encoding="binary",g.encoder=void 0;let L=d.openDB(A,g),v=l.openDB(A,g);for(let{key:P,version:k,value:H}of v.getRange({start:null,transaction:h,versions:v.useVersions}))f=L.put(P,H,k),p++%UJ===0&&(await new Promise(j=>setTimeout(j,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:g}of l.getRange({transaction:h,start:!1}))if(s.some(L=>A.startsWith?.(L+"/"))){E.put(A,g);let[,L]=A.split("/"),v=!L,P=new IC(!v,v);await S(A,P)}e.include_audit&&await S(MJ,Object.assign({},DJ)),await f;let T=yC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=IJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(rS);yJ(c,_,0,rS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=yC(null,{fd:c,start:rS}),f=new bJ.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(PJ,"getBackup")});var UC=R((Pde,MC)=>{"use strict";var vJ=$(),{handleHDBError:BJ}=ne(),HJ=Yb(),xJ=N_(),GJ=Np(),qJ=VI(),FJ=Wc(),kJ=Mp(),VJ=hw(),$J=bw(),YJ=jc(),KJ=Mw(),WJ=Vw(),QJ=Jw(),zJ=Xw(),JJ=rC(),jJ=uC(),XJ=Fp(),ZJ=fC(),e4=TC(),t4=RC(),LC=NC(),r4=CC(),nS=class extends HJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return KJ(t)}async getDataByHash(t){return await kJ(t)}async searchByHash(t){return await VJ(t)}async getDataByValue(t,r){return await $J(t,r)}async searchByValue(t){return await YJ(t)}async createSchema(t){return await qJ(t)}async dropSchema(t){return await WJ(t)}async createTable(t,r){return await QJ(t,r)}async dropTable(t){return await XJ(t)}async createAttribute(t){return await xJ(t)}async createRecords(t){return await GJ(t)}async updateRecords(t){return await zJ(t)}async upsertRecords(t){try{return await JJ(t)}catch(r){throw BJ(r,null,null,vJ.ERR,r)}}async deleteRecords(t){return await FJ(t)}async dropAttribute(t){return await ZJ(t)}async deleteAuditLogsBefore(t){return await jJ(t)}async readAuditLog(t){return await e4(t)}writeTransaction(t,r,n){return t4.writeTransaction(t,r,n)}flush(t,r){return LC.flush(t,r)}resetReadTxn(t,r){return LC.resetReadTxn(t,r)}getBackup(t){return r4(t)}};MC.exports=nS});function o4(){i4=setInterval(function(){for(let e of sS)if(e.stale){let t=e[Ne]?.url;HC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},s4).unref()}var iS,BC,HC,xC,GC,qC,PC,sS,n4,tu,vC,to,cd,s4,i4,oS=Re(()=>{iS=B(Mr()),BC=B(ne()),HC=B($());Nn();xC=B(Z()),GC=B(M()),qC=B(Q()),PC=100,sS=new Set,n4=(0,qC.convertToMS)(xC.get(GC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,to=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;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===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),sS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(sS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(tu&&!this.overloadChecked&&performance.now()-vC>n4)throw new BC.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}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,iS.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let E=d;E<this.validated;E++)this.writes[E]?.validate?.(this.timestamp);let f;for(let E=d;E<this.validated;E++){let h=this.writes[E];h&&(h.before||h.beforeIntermediate)&&(f=!0)}if(f)return(async()=>{try{for(let E=0;E<2;E++){let h;for(let p=d;p<this.validated;p++){let S=this.writes[p];if(!S)continue;let T=S[E===0?"before":"beforeIntermediate"];if(T){let A=T();h?h.push?h.push(A):h=[h,A]:h=A}}h&&await(h.push?Promise.all(h):h)}}catch(E){throw this.abort(),E}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),u=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let f=d.store.ifVersion(d.key,d.entry?.version??null,u);s=s||f}else u();else for(let f of this.writes)c(f)},"nextCondition"),_=this.lmdbDb;if(this.writes.length>0&&(_?.retryRisk&&(_.retryRisk*=.99),this.writes.length+(_?.retryRisk||0)<PC>>n?u():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return tu||(tu=s,vC=performance.now(),tu.then(()=>{tu=null})),s.then(d=>d?(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}))):(_&&(_.retryRisk=(_.retryRisk||0)+PC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let l={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(f=>({txnTime:r,next:f}));l.next=d}return l}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},cd=class extends to{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,iS.getNextMonotonicTime)())}getReadTxn(){}},s4=3e4;a(o4,"startMonitoringTxns");o4()});function Xe(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&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 to;e.timestamp&&(n.timestamp=e.timestamp),n[Ne]=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({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var FC,ro=Re(()=>{FC=require("../index");Nn();oS();a(Xe,"transaction");(0,FC._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var JC={};qe(JC,{ResourceBridge:()=>uS});function lS({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 VC(e,t){let r=rs(e),n=lS(e,r);if(!r)throw new Mn.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&&ld(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 rs(e){let t=e.database||e.schema||c4,r=Er()[t];if(!r)throw(0,Mn.handleHDBError)(new Error,a4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function $C(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*YC(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 KC,ud,Mn,WC,QC,Un,aS,cS,zC,a4,c4,u4,l4,kC,uS,jC=Re(()=>{"use strict";KC=B(UC()),ud=B(na()),Mn=B(ne());Ae();WC=B(Bc()),QC=B(xc()),Un=B(M()),aS=B(bs()),cS=B(Ln()),zC=B(Q());ro();_d();({HDB_ERROR_MSGS:a4}=Mn.hdb_errors),c4="data",u4=1e4,l4=10,uS=class extends KC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),kC=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,ud.default)(t,"conditions");if(r)throw(0,Mn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=rs(t);if(!n)throw new Mn.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:lS(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 Mn.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}]}lt({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await rs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=rs(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){rs(t).dropTable()}createSchema(t){return ru({database:t.schema,table:null}),aS.signalSchemaChange(new cS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await _S(t.schema),aS.signalSchemaChange(new cS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,kC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,WC.default)(t);(0,QC.default)(t,n,r.primaryKey);let s,i=Er()[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=ld(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=Er()[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 $C(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=Er()[t.schema][t.table];if(!r.createdTimeProperty)throw new Mn.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:Un.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,zC.async_set_timeout)(l4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%u4===0&&await _();return u.length>0&&await _(),s?$C(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,ud.default)(t,"hashes");if(r)throw r;return VC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of VC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.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,ud.default)(t,"value");if(n)throw n;let s=rs(t);if(!s)throw new Mn.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===Un.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:lS(t,s)})}async getDataByValue(t,r){let n=new Map,s=rs(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){rs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return rs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=rs(t),n={};switch(t.search_type){case Un.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 Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of YC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return YC(r,t.search_values?.[0],t.search_values?.[1])}}};a(lS,"getSelect");a(VC,"getRecords");a(rs,"getTable");a($C,"createDeleteResponse");a(YC,"groupRecordsInHistory")});var wn=R((zde,XC)=>{"use strict";var{ResourceBridge:_4}=(jC(),ie(JC)),d4=Z();d4.initSync();var dd;function f4(){return dd||(dd=new _4,dd)}a(f4,"getBridge");XC.exports=f4()});var rD=R((jde,tD)=>{"use strict";var ZC=require("lodash"),nu=require("mathjs"),E4=require("jsonata"),eD=Q();tD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?ZC.uniqWith(e,ZC.isEqual):e,searchJSON:h4,mad:su.bind(null,nu.mad),mean:su.bind(null,nu.mean),mode:su.bind(null,nu.mode),prod:su.bind(null,nu.prod),median:su.bind(null,nu.median)};function su(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(su,"aggregateFunction");function h4(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(eD.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),eD.isEmpty(this.__ala__.res[r])){let n=E4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(h4,"searchJSON")});var sD=R((Zde,nD)=>{"use strict";var St=require("moment"),dS="YYYY-MM-DDTHH:mm:ss.SSSZZ";St.suppressDeprecationWarnings=!0;nD.exports={current_date:()=>St().utc().format("YYYY-MM-DD"),current_time:()=>St().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return St(e).utc().format("YYYY");case"month":return St(e).utc().format("MM");case"day":return St(e).utc().format("DD");case"hour":return St(e).utc().format("HH");case"minute":return St(e).utc().format("mm");case"second":return St(e).utc().format("ss");case"millisecond":return St(e).utc().format("SSS");default:break}},date:e=>St(e).utc().format(dS),date_format:(e,t)=>St(e).utc().format(t),date_add:(e,t,r)=>St(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>St(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=St(e).utc(),s=St(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>St().utc().valueOf(),get_server_time:()=>St().format(dS),offset_utc:(e,t)=>St(e).utc().utcOffset(t).format(dS)}});var cD=R((efe,aD)=>{"use strict";var m4=require("@turf/area"),p4=require("@turf/length"),S4=require("@turf/circle"),T4=require("@turf/difference"),g4=require("@turf/distance"),R4=require("@turf/boolean-contains"),A4=require("@turf/boolean-equal"),O4=require("@turf/boolean-disjoint"),b4=require("@turf/helpers"),iD=M(),Te=Q(),Is=$();aD.exports={geoArea:N4,geoLength:y4,geoCircle:I4,geoDifference:w4,geoDistance:oD,geoNear:C4,geoContains:D4,geoEqual:L4,geoCrosses:M4,geoConvert:U4};function N4(e){if(Te.isEmpty(e))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return m4.default(e)}catch(t){return Is.trace(t,e),NaN}}a(N4,"geoArea");function y4(e,t){if(Te.isEmpty(e))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return p4.default(e,{units:t||"kilometers"})}catch(r){return Is.trace(r,e),NaN}}a(y4,"geoLength");function I4(e,t,r){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return S4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(I4,"geoCircle");function w4(e,t){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return T4(e,t)}catch(r){return Is.trace(r,e,t),NaN}}a(w4,"geoDifference");function oD(e,t,r){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return g4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(oD,"geoDistance");function C4(e,t,r,n){if(Te.isEmpty(e)||Te.isEmpty(t))return!1;if(Te.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return oD(e,t,n)<=r}catch(s){return Is.trace(s,e,t),!1}}a(C4,"geoNear");function D4(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return R4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(D4,"geoContains");function L4(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return A4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(L4,"geoEqual");function M4(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return!O4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(M4,"geoCrosses");function U4(e,t,r){if(Te.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Te.isEmpty(t))throw new Error("geo_type is required");if(Te.isEmpty(iD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(iD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Te.autoCastJSON(e)),b4[t](e,r)}a(U4,"geoConvert")});var fd=R((rfe,uD)=>{var no=rD(),Vr=sD(),ns=cD();uD.exports=e=>{e.aggr.mad=e.aggr.MAD=no.mad,e.aggr.mean=e.aggr.MEAN=no.mean,e.aggr.mode=e.aggr.MODE=no.mode,e.aggr.prod=e.aggr.PROD=no.prod,e.aggr.median=e.aggr.MEDIAN=no.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=no.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=no.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=ns.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ns.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ns.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ns.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ns.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ns.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ns.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ns.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ns.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ns.geoNear}});var fD=R((nfe,dD)=>{"use strict";var iu=require("lodash"),hr=require("alasql");hr.options.cache=!1;var P4=fd(),lD=require("clone"),Ed=require("recursive-iterator"),le=$(),Ce=Q(),aa=wn(),v4=M(),{hdb_errors:B4}=ne(),{getDatabases:_D}=(Ae(),ie(Fe)),H4="IS NULL",Pn="There was a problem performing this search. Please check the logs and try again.";P4(hr);var fS=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw le.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(),Ce.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(n))return le.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw le.error("Error thrown from checkEmptySQL in SQLSearch class method search."),le.error(n),new Error(Pn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw le.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),le.error(n),new Error(Pn)}if(Object.keys(this.data).length===0)return le.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw le.error("Error thrown from processJoins in SQLSearch class method search."),le.error(n),new Error(Pn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw le.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),le.error(n),new Error(Pn)}try{return t=await this._finalSQL(),t}catch(n){throw le.error("Error thrown from finalSQL in SQLSearch class method search."),le.error(n),new Error(Pn)}}_getColumns(){let t=new Ed(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(lD(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=iu.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=_D()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ce.isEmpty(this.statement.where)){le.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Ed(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ce.isEmpty(r)&&r.right)if(Ce.isNotEmptyAndHasValue(r.right.value)){let n=Ce.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new hr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Ce.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new hr.yy.LogicValue({value:i}):n instanceof hr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new hr.yy.NumValue({value:i}))});if(t){le.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Ed(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(!Ce.isEmpty(v4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ce.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ce.isEmptyOrZeroLength(r.left.columnid)||Ce.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(Ce.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"=":!Ce.isEmpty(r.right.value)||!Ce.isEmpty(r.left.value)?n.add(Ce.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(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.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&&iu.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(Ce.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Ce.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(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&!Ce.isEmptyOrZeroLength(this.columns.columns))return t;if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await hr.promise(r)}catch(r){throw le.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),le.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(lD(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(Ce.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(H4)>-1&&this.tables.forEach(s=>{let i={columnid:_D()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=iu.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),!Ce.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await aa.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 le.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Pn)}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 aa.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 le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Pn)}else if(!Ce.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ce.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 aa.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),le.error(l),new Error(Pn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await aa.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 le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),le.error(l),new Error(Pn)}}}_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 hr.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 hr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new hr.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 hr.yy.FuncValue:new hr.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,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,s);f=await hr.promise(h,t),t=null}catch(E){throw le.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),le.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=iu.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let A=p[S];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 Ed(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=iu.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 le.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),le.error(i),new Error(Pn)}}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 aa.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 p=s.columns[h],S=E[p]===void 0?null:E[p];this.data[n].__merged_data[f].push(S)}}}}catch(r){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getData."),le.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();le.trace(`Final SQL: ${s}`),n=await hr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),le.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw le.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),le.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 le.error(B4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),le.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 aa.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 le.error("There was an error when processing this SQL operation. Check your logs"),le.error(o),new Error(Pn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};dD.exports=fS});var Br=R((ife,ED)=>{"use strict";var x4=Vb();ED.exports={searchByConditions:q4,searchByHash:F4,searchByValue:k4,search:V4};var ES=wn(),{transformReq:hS}=Q(),G4=fD();async function q4(e){return hS(e),ES.searchByConditions(e)}a(q4,"searchByConditions");async function F4(e){hS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of ES.searchByHash(e))r&&t.push(r);return t}a(F4,"searchByHash");async function k4(e){hS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of ES.searchByValue(e))t.push(r);return t}a(k4,"searchByValue");function V4(e,t){try{let r=new x4(e);r.validate(),new G4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(V4,"search")});var hd=R((afe,hD)=>{"use strict";var $4=wn();hD.exports={writeTransaction:Y4};function Y4(e,t,r){return $4.writeTransaction(e,t,r)}a(Y4,"writeTransaction")});var TD=R((lfe,SD)=>{"use strict";var K4=Br(),W4=Os(),mD=$(),Q4=Hr(),ufe=hd(),z4=require("clone"),pS=require("alasql"),J4=fd(),pD=require("util"),j4=pD.promisify(W4.getTableSchema),X4=pD.promisify(K4.search),Z4=M(),mS=Q();J4(pS);SD.exports={update:t3};var e3="There was a problem performing this update. Please check the logs and try again.";async function t3({statement:e,hdb_user:t}){let r=await j4(e.table.databaseid,e.table.tableid),n=r3(e.columns);mS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=z4(s),c=mS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=pS.parse(u).statements[0],l=await X4(_),d=n3(n,l);return s3(o,d,t)}a(t3,"update");function r3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=pS.compile(`SELECT ${r.expression.toString()} AS [${Z4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw mD.error(t),new Error(e3)}}a(r3,"createUpdateRecord");function n3(e,t){return mS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(n3,"buildUpdateRecords");async function s3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await Q4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){mD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(s3,"updateRecords")});var RD=R((Efe,gD)=>{var i3=require("alasql"),o3=Br(),a3=$(),c3=wn(),TS=require("util"),SS=Q(),u3=M(),l3=Os(),dfe=hd(),ffe=Hr(),_3="record",d3="successfully deleted",f3=TS.callbackify(p3),E3=TS.promisify(o3.search),h3=TS.promisify(l3.getTableSchema);gD.exports={convertDelete:f3};function m3(e){return`${e.deleted_hashes.length} ${_3}${e.deleted_hashes.length===1?"":"s"} ${d3}`}a(m3,"generateReturnMessage");async function p3({statement:e,hdb_user:t}){let r=await h3(e.table.databaseid,e.table.tableid);SS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=SS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=i3.parse(o).statements[0],u={operation:u3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await E3(c);let _=await c3.deleteRecords(u);return SS.isEmptyOrZeroLength(_.message)&&(_.message=m3(_)),delete _.txn_time,_}catch(_){throw a3.error(_),_.hdb_code?_.message:_}}a(p3,"convertDelete")});var yD=R((mfe,ND)=>{"use strict";var S3=As(),{hdb_errors:AD}=ne(),{getDatabases:OD}=(Ae(),ie(Fe));ND.exports={checkSchemaExists:bD,checkSchemaTableExists:T3,schema_describe:S3};async function bD(e){if(!OD()[e])return AD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(bD,"checkSchemaExists");async function T3(e,t){let r=await bD(e);if(r)return r;if(!OD()[e][t])return AD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(T3,"checkSchemaTableExists")});var ou=R((Sfe,g3)=>{g3.exports={name:"harperdb",version:"4.3.16",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},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/client-s3":"3.535.0","@aws-sdk/lib-storage":"3.535.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","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.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.11",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","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.1",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.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.16.0",yaml:"2.4.1"},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.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",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.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",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.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var _u={};qe(_u,{addAnalyticsListener:()=>lu,recordAction:()=>$r,recordActionBinary:()=>Yr,setAnalyticsEnabled:()=>R3});function R3(e){vD=e}function $r(e,t,r,n,s){if(!vD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Sd.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},Sd.set(i,o)}md||A3()}function Yr(e,t,r,n,s){$r(!!e,t,r,n,s)}function lu(e){xD.push(e)}function A3(){md=performance.now(),setTimeout(async()=>{let e=performance.now()-md;md=0;let t=[],r={time:Date.now(),period:e,threadId:so.threadId,metrics:t};for(let[s,i]of Sd){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 GD){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 qD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:so.threadId,byThread:!0,...n});for(let s of xD)s(t);Sd=new Map,so.parentPort?so.parentPort.postMessage({type:HD,report:r}):VD({report:r})},BD).unref()}async function O3(e,t=6e4){let r=AS(),n=FD(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,au.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let T=performance.now();T-S>5e3&&(0,au.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:A}=S;for(let g of T||[]){let{path:L,method:v,type:P,metric:k,count:H,total:j,distribution:z,threads:J,...me}=g;H||(H=1);let ce=k+(L?"-"+L:"");v!==void 0&&(ce+="-"+v),P!==void 0&&(ce+="-"+P);let de=c.get(ce);if(de){if(de.threads){let ve=de.threads[A];if(ve)de=ve;else{de.threads[A]=Object.assign({},me);continue}}de.count||(de.count=1);let De=de.count;for(let ve in me){let Mt=me[ve];typeof Mt=="number"&&(de[ve]=(de[ve]*De+Mt*H)/(De+H))}de.count+=H,j>=0&&(de.total+=j,de.ratio=de.total/de.count)}else de=Object.assign({period:t},g),delete de.distribution,c.set(ce,de),de.byThread&&(de.threads=[],de.threads[A]=Object.assign({},me),_.push(de));if(z){z=z.map(ve=>typeof ve=="number"?{value:ve,count:1}:ve);let De=u.get(ce);De?De.push(...z):u.set(ce,z)}}await qD()}for(let p of _){let{path:S,method:T,type:A,metric:g,count:L,total:v,distribution:P,threads:k,...H}=p;k=k.filter(j=>j);for(let j in H){if(typeof p[j]!="number")continue;let z=0;for(let J of k){let me=J[j];typeof me=="number"&&(z+=me)}p[j]=z}p.count=k.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((ve,Mt)=>ve.value>Mt.value?1:-1);let A=T.count-1,g=[],L=0,v=0,P;for(let ve of GD){let Mt=A*ve;for(;L<Mt;)P=S[v++],L+=P.count,v===1&&L--;let Wl=S[v>1?v-2:0];P||(P=S[0]),g.push(P.value-(P.value-Wl.value)*(L-Mt)/P.count)}let[k,H,j,z,J,me,ce,de,De]=g;Object.assign(T,{p1:k,p10:H,p25:j,median:z,p75:J,p90:me,p95:ce,p99:de,p999:De})}let d;for(let[p,S]of c)S.id=(0,pd.getNextMonotonicTime)(),S.time=l,n.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||n.primaryStore.put(S.id,S)}),d=!0;let f=Date.now(),{idle:E,active:h}=performance.eventLoopUtilization();if(d||h*10>E){let p=(0,pd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:E-ID,active:h-wD,taskQueueLatency:await s,time:f,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}ID=E,wD=h}async function CD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function AS(){return DD||(DD=lt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function FD(){return LD||(LD=lt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function y3(){kD=!0;let e=(0,uu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await O3(BD,e),await CD(AS(),b3),await CD(FD(),N3)},Math.min(e/2,2147483647)).unref()}function VD(e,t){let r=e.report;r.threadId=t?.threadId||so.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(MD+=n.mean*n.count);r.totalBytesProcessed=MD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(UD.get(t))}),UD.set(t,t.performance.eventLoopUtilization())),r.id=(0,pd.getNextMonotonicTime)(),AS().primaryStore.put(r.id,r),kD||y3(),I3&&($D=C3(r))}async function C3(e){if(await $D,!_i){let r=(0,cu.dirname)((0,au.getLogFilePath)());try{_i=await(0,gS.open)((0,cu.join)(r,"analytics.log"),"r+")}catch{_i=await(0,gS.open)((0,cu.join)(r,"analytics.log"),"w+")}}let t=(await _i.stat()).size;if(t>w3){let r=Buffer.alloc(t);await _i.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await _i.write(r,{position:0}),await _i.truncate(r.length),t=r.length}await _i.write(JSON.stringify(e)+`
8
- `,t)}var so,PD,au,cu,gS,pd,uu,RS,Sd,vD,md,BD,HD,xD,GD,ID,wD,qD,b3,N3,DD,LD,kD,MD,UD,I3,$D,_i,w3,ws=Re(()=>{so=require("worker_threads"),PD=B(Je());Ae();au=B($()),cu=require("path"),gS=require("fs/promises"),pd=B(Mr()),uu=B(Z()),RS=B(M());ar();(0,uu.initSync)();Sd=new Map,vD=(0,uu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(R3,"setAnalyticsEnabled");a($r,"recordAction");nt.recordAnalytics=$r;a(Yr,"recordActionBinary");md=0,BD=1e3,HD="analytics-report",xD=[];a(lu,"addAnalyticsListener");GD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(A3,"sendAnalytics");a(O3,"aggregation");ID=0,wD=0,qD=a(()=>new Promise(setImmediate),"rest");a(CD,"cleanup");b3=36e5,N3=31536e6;a(AS,"getRawAnalyticsTable");a(FD,"getAnalyticsTable");(0,PD.setChildListenerByType)(HD,VD);a(y3,"startScheduledTasks");MD=0,UD=new Map,I3=!1;a(VD,"recordAnalytics");w3=1e6;a(C3,"logAnalytics")});var IS=R((Lfe,tL)=>{"use strict";var{decode:D3}=require("msgpackr"),{isMainThread:wfe,parentPort:Cfe,threadId:Dfe}=require("worker_threads"),Rd=it(),ca=ke(),NS=M(),Zt=$(),bS=Z(),L3=M(),{onMessageByType:M3}=Je(),WD=Rs(),{recordAction:U3,recordActionBinary:P3}=(ws(),ie(_u)),{publishToStream:v3}=Rd,{ConsumerEvents:YD}=require("nats"),B3=Br(),{promisify:H3}=require("util"),QD=H3(setTimeout),Ad=1e4,Od,gd,x3,G3,zD,du=new Map,ua=new Map;tL.exports={initialize:JD,ingestConsumer:yS,setSubscription:q3,setIgnoreOrigin:V3,getDatabaseSubscriptions:k3,updateConsumer:jD};async function JD(){M3(NS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await jD(n)}),zD=!0,Zt.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await Rd.getNATSReferences();Od=e,gd=e.info.server_name,x3=t,G3=r}a(JD,"initialize");async function jD(e){if(e.status==="start"){let{js:t,jsm:r}=await XD(e.node_domain_name);yS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=du.get(e.stream_name+e.node_domain_name);t&&(Zt.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),du.set(e.stream_name+e.node_domain_name,"close")),ua.get(e.node_domain_name)==="failed"&&ua.set(e.node_domain_name,"close")}}a(jD,"updateConsumer");var bd=new Map;function q3(e,t,r){let n=bd.get(e);n||bd.set(e,n=new Map),n.set(t,r),zD||JD().then(F3)}a(q3,"setSubscription");async function F3(){let e=await B3.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+ca.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await XD(r),!n))break;let{schema:o,table:c}=i,u=WD.createNatsTableStreamName(o,c);yS(u,n,s,r)}}}a(F3,"accessConsumers");async function XD(e){let t,r,n=1;for(;!r;)try{t=await Od.jetstream({domain:e}),r=await Od.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(ua.get(e)==="close")break;ua.set(e,"failed"),n%10===1&&Zt.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<Ad?n++*100:Ad;await QD(i)}return{js:t,jsm:r}}a(XD,"connectToRemoteJS");function k3(){return bd}a(k3,"getDatabaseSubscriptions");var ZD;function V3(e){ZD=e}a(V3,"setIgnoreOrigin");var eL=100,KD=new Array(eL),Td=0;async function yS(e,t,r,n){let{connection:s}=await Rd.getNATSReferences();Od=s,gd=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,gd),Zt.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(ua.get(n)==="close")break;o%10===1&&Zt.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(Zt.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await Rd.createConsumer(r,e,gd,new Date(Date.now()).toISOString()));let l=o++*100<Ad?o++*100:Ad;await QD(l)}let c=!1,u;for(;!c;){if(du.get(e+n)==="close"||ua.get(n)==="close"){du.delete(e+n),c=!0;continue}u=await i.consume({max_messages:bS.get(NS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),du.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===YD.ConsumerDeleted&&(await u.close(),c=!0),l.type===YD.HeartbeatsMissed){let d=l.data;Zt.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===100&&(Zt.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await KD[Td],KD[Td]=$3(l).catch(d=>{Zt.error(d)}),++Td>=eL&&(Td=0)}catch(l){l.message==="consumer deleted"?(Zt.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):Zt.error("Error consuming clustering ingest, restarting consumer",l)}}}a(yS,"ingestConsumer");async function $3(e){let t=D3(e.data);U3(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),Zt.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=bS.get(NS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(ca.MSG_HEADERS.TRANSACTED_NODES)&&r.values(ca.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(ca.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!ZD),P3(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(ca.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Zt.trace("processing message:",o,c,_,(l?"records: "+l.map(L=>L?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Zt.trace(`messageProcessor nats msg id: ${e.headers.get(ca.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let p=new Promise(L=>h=L),{timestamp:S,user:T,node_name:A}=f||{},g=bd.get(c)?.get(_);if(!g)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,g.send(t);else if(l.length===1&&!u)g.send({type:OS(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:S,table:_,onCommit:h,user:T,nodeName:A});else{let L=l.map((v,P)=>({type:OS(o),value:v,expiresAt:E,id:d?.[P],table:_}));for(;u;)L.push({type:OS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;g.send({type:"transaction",writes:L,table:_,timestamp:S,onCommit:h,user:T,nodeName:A})}bS.get(L3.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&v3(e.subject.split(".").slice(0,-1).join("."),WD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){Zt.error(o)}e.ack()}a($3,"messageProcessor");function OS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(OS,"convertOperation")});var it=R((xfe,SL)=>{"use strict";var vt=Z();vt.initSync();var Y3=require("fs-extra"),K3=require("semver"),hu=require("path"),{monotonicFactory:W3}=require("ulidx"),nL=W3(),Q3=require("util"),sL=require("child_process"),z3=Q3.promisify(sL.exec),J3=sL.spawn,$t=ke(),ye=M(),Nd=Q(),vn=$(),yd=Rs(),j3=hd(),fu=dr(),{broadcast:X3,onMessageByType:Z3,getWorkerIndex:ej}=Je(),{isMainThread:iL}=require("worker_threads"),{Encoder:tj,decode:LS}=require("msgpackr"),oL=new tj,{isEmpty:co}=Nd,aL=un(),Ufe=48*36e11;iL&&Z3(ye.ITC_EVENT_TYPES.RESTART,()=>{mr=void 0,ao=void 0});var{connect:rj,StorageType:nj,RetentionPolicy:sj,AckPolicy:MS,DeliverPolicy:US,DiscardPolicy:ij,NatsConnection:Pfe,JetStreamManager:vfe,JetStreamClient:Bfe,StringCodec:Hfe,JSONCodec:oj,createInbox:PS,headers:aj,ErrorCode:rL}=require("nats"),{PACKAGE_ROOT:cj}=M(),uj=ou(),{recordAction:lj}=(ws(),ie(_u)),cL=oj(),_j="clustering",dj=uj.engines[$t.NATS_SERVER_NAME],fj=hu.join(cj,"dependencies"),DS=hu.join(fj,`${process.platform}-${process.arch}`,$t.NATS_BINARY_NAME),wS,CS,Eu,io,oo;SL.exports={runCommand:uL,checkNATSServerInstalled:Ej,createConnection:vS,getConnection:mu,getJetStreamManager:pu,getJetStream:_L,getNATSReferences:ss,getServerList:mj,createLocalStream:BS,listStreams:dL,deleteLocalStream:pj,getServerConfig:la,listRemoteStreams:Sj,viewStream:Tj,viewStreamIterator:gj,publishToStream:Rj,request:bj,reloadNATS:HS,reloadNATSHub:Nj,reloadNATSLeaf:yj,extractServerName:Oj,requestErrorHandler:Ij,createLocalTableStream:mL,createTableStreams:Dj,purgeTableStream:pL,purgeSchemaTableStreams:Lj,getStreamInfo:Mj,updateLocalStreams:Pj,closeConnection:hj,getJsmServerName:Id,addNatsMsgHeader:fL,clearClientCache:lL,updateRemoteConsumer:wj,createConsumer:EL,updateConsumerIterator:Cj};async function uL(e,t=void 0){let{stdout:r,stderr:n}=await z3(e,{cwd:t});if(n)throw new Error(n.replace(`
6
+ `)},QY="certificate.pem",zY="privateKey.pem",JY="ca.pem";CN.exports={CERTIFICATE_VALUES:WY,CERTIFICATE_PEM_NAME:QY,PRIVATEKEY_PEM_NAME:zY,CA_PEM_NAME:JY}});var rp=g((ole,BN)=>{"use strict";var UN=require("fs-extra"),oe=require("joi"),jY=require("os"),{boolean:ye,string:Xt,number:Ze,array:k_}=oe.types(),{totalmem:LN}=require("os"),Wi=require("path"),XY=$(),V_=J(),ile=DN(),MN=P(),ZY=je(),PN="log",eK="components",tK="Invalid logging.rotation.maxSize unit. Available units are G, M or K",rK="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",nK="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",sK="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",iK="rootPath config parameter is undefined",oK="clustering.enabled config parameter is undefined",Qi=Ze.min(0).required(),$_=k_.items({host:Xt.required(),port:Qi}).empty(null),jn,vN=!1;BN.exports={configValidator:aK,routesValidator:fK,route_constraints:$_};function aK(e,t=!1){if(vN=t,jn=e.rootPath,V_.isEmpty(jn))throw iK;let r=ye.required(),n=Ze.min(0).max(1e3).empty(null).default(dK),s=Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Fc),i=Xt.optional().empty(null),o=Xt.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(Fc),u=oe.custom(uK).empty(null).default(Fc),_=e.clustering?.enabled;if(V_.isEmpty(_))throw oK;let l=oe.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return _===!0?d=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:Qi,routes:$_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:Qi}).required()}).required(),network:oe.object({port:Qi}).required()}).required(),leafServer:oe.object({network:oe.object({port:Qi,routes:$_}).required(),streams:oe.object({maxAge:Ze.min(120).allow(null).optional(),maxBytes:Ze.min(1).allow(null).optional(),maxMsgs:Ze.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:ye.optional(),databaseLevel:ye.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required(),verify:ye.optional()}),user:Xt.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:ye,cacheTTL:Ze.required(),enableSessions:ye}),analytics:oe.object({aggregatePeriod:Ze}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:ye,logSuccessful:ye}),file:ye.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:ye.optional(),compress:ye.optional(),interval:Xt.custom(_K).optional().empty(null),maxSize:Xt.custom(lK).optional().empty(null),path:Xt.optional().empty(null).default(Fc)}).required(),root:s,stdStreams:ye.required(),auditLog:ye.required()}).required(),operationsApi:oe.object({network:oe.object({cors:ye.optional(),corsAccessList:k_.optional(),headersTimeout:Ze.min(1).optional(),keepAliveTimeout:Ze.min(1).optional(),port:Ze.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(Fc),securePort:Ze.optional().empty(null),timeout:Ze.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(l),l])}).required(),rootPath:Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:Qi,securePort:Qi,mtls:oe.alternatives([ye.optional(),oe.object({user:Xt.optional(),certificateAuthority:i,required:ye.optional()})])}).required(),webSocket:ye.optional(),requireAuthentication:ye.optional()}),http:oe.object({compressionThreshold:Ze.optional(),cors:ye.optional(),corsAccessList:k_.optional(),headersTimeout:Ze.min(1).optional(),port:Ze.min(0).optional().empty(null),securePort:Ze.min(0).optional().empty(null),maxHeaderSize:Ze.optional(),mtls:oe.alternatives([ye.optional(),oe.object({user:Xt.optional(),certificateAuthority:i,required:ye.optional()})]),threadRange:oe.alternatives([k_.optional(),Xt.optional()])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(ye.optional(),oe.object({startingPort:Ze.min(1).optional(),host:Xt.optional(),waitForDebugger:ye.optional()})),maxHeapMemory:Ze.min(0).optional()})),storage:oe.object({writeAsync:ye.required(),overlappingSync:ye.optional(),caching:ye.optional(),compression:oe.alternatives([ye.optional(),oe.object({dictionary:Xt.optional(),threshold:Ze.optional()})]),compactOnStart:ye.optional(),compactOnStartKeepBackup:ye.optional(),noReadAhead:ye.optional(),path:u,prefetchWrites:ye.optional(),maxFreeSpaceToLoad:Ze.optional(),maxFreeSpaceToRetain:Ze.optional()}).required(),ignoreScripts:ye.optional(),tls:oe.alternatives([oe.array().items(l),l])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(aK,"configValidator");function cK(e){return vN||UN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(cK,"doesPathExist");function uK(e,t){oe.assert(e,Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=cK(e);if(r)return t.message(r)}a(uK,"validatePath");function lK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(tK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(nK):e}a(lK,"validateRotationMaxSize");function _K(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(rK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(sK):e}a(_K,"validateRotationInterval");function dK(e,t){let r=t.state.path.join("."),n=jY.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||LN();return i=Math.round(Math.min(i,LN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),XY.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(dK,"setDefaultThreads");function Fc(e,t){let r=t.state.path.join(".");if(!V_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(V_.isEmpty(jn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(jn,eK);case"logging.root":return Wi.join(jn,PN);case"clustering.leafServer.streams.path":return Wi.join(jn,"clustering","leaf");case"storage.path":let n=Wi.join(jn,MN.LEGACY_DATABASES_DIR_NAME);return UN.existsSync(n)?n:Wi.join(jn,MN.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(jn,PN);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(jn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Fc,"setDefaultRoot");function fK(e){let t=oe.object({routes:$_});return ZY.validateBySchema({routes:e},t)}a(fK,"routesValidator")});var fr=g((ule,YN)=>{"use strict";var kr=P(),vt=J(),Nt=$(),{configValidator:EK,routesValidator:HN}=rp(),dr=require("fs-extra"),hK=require("yaml"),Dn=require("path"),mK=require("is-number"),GN=require("properties-reader"),pK=require("lodash"),{handleHDBError:SK}=ne(),{HTTP_STATUS_CODES:TK,HDB_ERROR_MSGS:Y_}=Ur(),cle=require("minimist"),{server:gK}=(ur(),ie(Hi)),{DATABASES_PARAM_CONFIG:kc,CONFIG_PARAMS:Fr,CONFIG_PARAM_MAP:Ln}=kr,RK="Unable to get config value because config is uninitialized",AK="Config successfully initialized",OK="Error backing up config file",bK="Empty parameter sent to getConfigValue",qN=Dn.join(kr.PACKAGE_ROOT,"config","yaml",kr.HDB_DEFAULT_CONFIG_FILE),yK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",xN={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"},K_,It,W_;YN.exports={createConfigFile:NK,getDefaultConfig:IK,getConfigValue:kN,initConfig:sp,flattenConfig:Qo,updateConfigValue:VN,updateConfigObject:CK,getConfiguration:MK,setConfiguration:PK,readConfigFile:op,getClusteringRoutes:UK,initOldConfig:$N,getConfigFromFile:vK,getConfigFilePath:zi,addConfig:BK,deleteConfigFromFile:HK,getConfigObj:xK};function NK(e,t=!1){let r=ai(qN);K_=Qo(r.toJSON());let n;for(let c in e){let u=Ln[c.toLowerCase()];if(u===Fr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=np(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){Nt.error(d)}}}n&&FN(r,n),ip(r,t);let s=r.toJSON();It=Qo(s);let i=r.getIn(["rootPath"]),o=Dn.join(i,kr.HDB_CONFIG_FILE);dr.createFileSync(o),dr.writeFileSync(o,String(r)),Nt.trace(`Config file written to ${o}`)}a(NK,"createConfigFile");function FN(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(kc.TABLES))for(let i in n[s][kc.TABLES])for(let o in n[s][kc.TABLES][i]){let c=n[s][kc.TABLES][i][o],u=[Fr.DATABASES,s,kc.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=[Fr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){Nt.error("Error parsing schemas CLI/env config arguments",n)}}a(FN,"setSchemasConfig");function IK(e){if(K_===void 0){let r=ai(qN);K_=Qo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return K_[t.toLowerCase()]}a(IK,"getDefaultConfig");function kN(e){if(e==null){Nt.error(bK);return}if(It===void 0){Nt.trace(RK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return It[t.toLowerCase()]}a(kN,"getConfigValue");function zi(e=vt.getPropsFilePath()){let t=vt.getEnvCliRootPath();return t?Dn.join(t,kr.HDB_CONFIG_FILE):GN(e).get(kr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function sp(e=!1){if(It===void 0||e){let t;if(!vt.noBootFile()){t=vt.getPropsFilePath();try{dr.accessSync(t,dr.constants.F_OK|dr.constants.R_OK)}catch(i){throw Nt.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{$N(r);return}catch(i){if(i.code!==kr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ai(r)}catch(i){if(i.code===kr.NODE_ERROR_CODES.ENOENT){Nt.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 Nt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}wK(n,r),ip(n);let s=n.toJSON();if(gK.config=s,It=Qo(s),It.logging_rotation_rotate)for(let i in xN)It[i]&&Nt.error(`Config ${xN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Nt.trace(AK)}}a(sp,"initConfig");function wK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(Nt.trace("Updating config file with missing config params"),dr.writeFileSync(t,String(e)))}a(wK,"checkForUpdatedConfig");function ip(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=EK(r,t);if(n.error)throw Y_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(ip,"validateConfig");function CK(e,t){It===void 0&&(It={});let r=Ln[e.toLowerCase()];if(r===void 0){Nt.trace(`Unable to update config object because config param '${e}' does not exist`);return}It[r.toLowerCase()]=t}a(CK,"updateConfigObject");function VN(e,t,r=void 0,n=!1,s=!1,i=!1){It===void 0&&sp();let o=kN(Ln.hdb_root),c=Dn.join(o,kr.HDB_CONFIG_FILE),u=ai(c),_;if(r===void 0&&e.toLowerCase()===Fr.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=Ln[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=np(E,t);u.setIn([...f],h)}else for(let E in r){let f=Ln[E.toLowerCase()];if(f===Fr.HTTP_SECUREPORT&&r[E]===It[Fr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),f===Fr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===It[Fr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),f===Fr.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),p=kr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(f=p,h=p.split("_"));let S=np(f,r[E]);f==="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(T){Nt.error(T)}}}_&&FN(u,_),ip(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,kr.HDB_CONFIG_FILE);n===!0&&DK(c,l),dr.writeFileSync(d,String(u)),s&&(It=Qo(u.toJSON())),Nt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(VN,"updateConfigValue");function DK(e,t){try{let r=Dn.join(t,"backup",`${kr.HDB_CONFIG_FILE}.bak`);dr.copySync(e,r),Nt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Nt.error(OK),Nt.error(r)}}a(DK,"backupConfigFile");var LK=["databases"];function Qo(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)),W_=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])&&!LK.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;!Fr[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Qo,"flattenConfig");function np(e,t){if(e===Fr.CLUSTERING_NODENAME||e===Fr.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(mK(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(np,"castConfigValue");function MK(){let e=vt.getPropsFilePath(),t=zi(e);return ai(t).toJSON()}a(MK,"getConfiguration");async function PK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return VN(void 0,void 0,s,!0),yK}catch(i){throw typeof i=="string"||i instanceof String?SK(i,i,TK.BAD_REQUEST,void 0,void 0,!0):i}}a(PK,"setConfiguration");function op(){let e=vt.getPropsFilePath();try{dr.accessSync(e,dr.constants.F_OK|dr.constants.R_OK)}catch(n){if(!vt.noBootFile())throw Nt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return ai(t).toJSON()}a(op,"readConfigFile");function ai(e){return hK.parseDocument(dr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ai,"parseYamlDoc");function UK(){let e=op(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=vt.isEmptyOrZeroLength(t)?[]:t;let r=HN(t);if(r)throw Y_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=vt.isEmptyOrZeroLength(n)?[]:n;let s=HN(n);if(s)throw Y_.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 Y_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(UK,"getClusteringRoutes");function $N(e){let t=GN(e);It={};for(let r in Ln){let n=t.get(r.toUpperCase());if(vt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Fr.LOGGING_ROOT?It[s]=Dn.dirname(n):It[s]=n}return It}a($N,"initOldConfig");function vK(e){let t=op();return pK.get(t,e.replaceAll("_","."))}a(vK,"getConfigFromFile");async function BK(e,t){let r=ai(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await dr.writeFile(zi(),String(r))}a(BK,"addConfig");function HK(e){let t=zi(vt.getPropsFilePath()),r=ai(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,kr.HDB_CONFIG_FILE);dr.writeFileSync(s,String(r))}a(HK,"deleteConfigFromFile");function xK(){return W_||(sp(),W_)}a(xK,"getConfigObj")});var WN=g((_le,KN)=>{"use strict";var Q_=P(),z_=class{static{a(this,"BaseLicense")}constructor(t=0,r=Q_.RAM_ALLOCATION_ENUM.DEFAULT,n=Q_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},ap=class extends z_{static{a(this,"ExtendedLicense")}constructor(t=0,r=Q_.RAM_ALLOCATION_ENUM.DEFAULT,n=Q_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};KN.exports={BaseLicense:z_,ExtendedLicense:ap}});var Ji=g((fle,ZN)=>{"use strict";var Jo=require("fs-extra"),zN=F_(),JN=require("crypto"),GK=require("moment"),qK=require("uuid").v4,Zt=$(),up=require("path"),FK=J(),ci=P(),{totalmem:QN}=require("os"),kK=WN().ExtendedLicense,zo="invalid license key format",VK="061183",$K="mofi25",YK="aes-256-cbc",KK=16,WK=32,jN=Z();jN.initSync();var cp;ZN.exports={validateLicense:XN,generateFingerPrint:zK,licenseSearch:dp,getLicense:XK,checkMemoryLimit:ZK};function lp(){return up.join(jN.getHdbBasePath(),ci.LICENSE_KEY_DIR_NAME,ci.LICENSE_FILE_NAME)}a(lp,"getLicenseDirPath");function QK(){let e=lp();return up.join(e,ci.LICENSE_FILE_NAME)}a(QK,"getLicenseFilePath");function _p(){let e=lp();return up.join(e,ci.REG_KEY_FILE_NAME)}a(_p,"getFingerPrintFilePath");async function zK(){let e=_p();try{return await Jo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await JK();throw Zt.error(`Error writing fingerprint file to ${e}`),Zt.error(t),new Error("There was an error generating the fingerprint")}}a(zK,"generateFingerPrint");async function JK(){let e=qK(),t=zN.hash(e),r=_p();try{await Jo.mkdirp(lp()),await Jo.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(JK,"writeFingerprint");function XN(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 Zt.error("empty license key passed to validate."),r;let n=_p(),s=!1;try{s=Jo.statSync(n)}catch(i){Zt.error(i)}if(s){let i;try{i=Jo.readFileSync(n,"utf8")}catch{Zt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split($K),c=o[1];c=Buffer.concat([Buffer.from(c)],KK);let u=Buffer.concat([Buffer.from(i)],WK),_=JN.createDecipheriv(YK,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 f=jK(o[0],i);if(f)l=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(zo),Zt.error(zo),new Error(zo)}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(zo),Zt.error(zo),new Error(zo)}else r.exp_date=l;r.exp_date<GK().valueOf()&&(r.valid_date=!1),zN.validate(o[1],`${VK}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||Zt.error("Invalid licence"),r}a(XN,"validateLicense");function jK(e,t){try{let r=JN.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(jK,"checkOldLicense");function dp(){let e=new kK,t=[];try{t=Jo.readFileSync(QK(),"utf-8").split(ci.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(FK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=XN(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=ci.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return cp=e,e}a(dp,"licenseSearch");async function XK(){return cp||await dp(),cp}a(XK,"getLicense");function ZK(){let e=dp().ram_allocation,t=process.constrainedMemory?.()||QN();if(t=Math.round(Math.min(t,QN())/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(ZK,"checkMemoryLimit")});var ln=g((Sle,hI)=>{"use strict";var nI="username is required",sI="nothing to update, must supply active, role or password to update",iI="password cannot be an empty string",oI="If role is specified, it cannot be empty.",aI="active must be true or false";hI.exports={addUser:cW,alterUser:uW,dropUser:_W,getSuperUser:hW,userInfo:dW,listUsers:j_,listUsersExternal:fW,setUsersToGlobal:Xo,findAndValidateUser:fI,getClusterUser:mW,USERNAME_REQUIRED:nI,ALTERUSER_NOTHING_TO_UPDATE:sI,EMPTY_PASSWORD:iI,EMPTY_ROLE:oI,ACTIVE_BOOLEAN:aI};var cI=qr(),eW=oi(),hp=F_(),uI=NN(),lI=Gr(),mp=bs(),Vr=J(),_I=require("validate.js"),be=$(),{promisify:tW}=require("util"),pp=Rs(),eI=P(),tI=ke(),rW=fr(),hle=Z(),mle=Ji(),nW=Fi(),{table:ple}=(Oe(),ie(Fe)),{handleHDBError:Xn,hdb_errors:sW}=ne(),{HTTP_STATUS_CODES:Zn,AUTHENTICATION_ERROR_MSGS:fp,HDB_ERROR_MSGS:jo}=sW,{UserEventMsg:Sp}=Mn(),Ep=require("lodash"),{server:Tp}=(ur(),ie(Hi)),iW=$();Tp.getUser=(e,t)=>fI(e,t,t!=null);var dI={username:!0,active:!0,role:!0,password:!0},rI=new Map,J_=lI.searchByValue,oW=lI.searchByHash,aW=tW(eW.delete);async function cW(e){let t=_I.cleanAttributes(e,dI),r=uI.addUserValidation(t);if(r)throw Xn(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 J_(n),s=s&&Array.from(s)}catch(u){throw be.error("There was an error searching for a role in add user"),be.error(u),u}if(!s||s.length<1)throw Xn(new Error,jo.ROLE_NAME_NOT_FOUND(t.role),Zn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Xn(new Error,jo.DUP_ROLES_FOUND(t.role),Zn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=pp.encrypt(t.password)),t.password=hp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await cI.insert(i)}catch(u){throw be.error("There was an error searching for a user."),be.error(u),u}be.debug(o);try{await Xo()}catch(u){throw be.error("Got an error setting users to global"),be.error(u),u}if(o.skipped_hashes.length===1)throw Xn(new Error,jo.USER_ALREADY_EXISTS(t.username),Zn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],mp.signalUserChange(new Sp(process.pid)),`${c.username} successfully added`}a(cW,"addUser");async function uW(e){let t=_I.cleanAttributes(e,dI);if(Vr.isEmptyOrZeroLength(t.username))throw new Error(nI);if(Vr.isEmptyOrZeroLength(t.password)&&Vr.isEmptyOrZeroLength(t.role)&&Vr.isEmptyOrZeroLength(t.active))throw new Error(sI);if(!Vr.isEmpty(t.password)&&Vr.isEmptyOrZeroLength(t.password.trim()))throw new Error(iI);if(!Vr.isEmpty(t.active)&&!Vr.isBoolean(t.active))throw new Error(aI);let r=lW(t.username);if(!Vr.isEmpty(t.password)&&!Vr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=pp.encrypt(t.password)),t.password=hp.hash(t.password)),t.role==="")throw new Error(oI);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 J_(i)||[])}catch(c){throw be.error("Got an error searching for a role."),be.error(c),c}if(!o||o.length===0){let c=jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw be.error(c),Xn(new Error,c,Zn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=jo.ALTER_USER_DUP_ROLES(t.role);throw be.error(c),Xn(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 cI.update(n)}catch(i){throw be.error("Error during update."),be.error(i),i}try{await Xo()}catch(i){throw be.error("Got an error setting users to global"),be.error(i),i}return mp.signalUserChange(new Sp(process.pid)),s}a(uW,"alterUser");function lW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(lW,"isClusterUser");async function _W(e){try{let t=uI.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Vr.isEmpty(global.hdb_users.get(e.username)))throw Xn(new Error,jo.USER_NOT_EXIST(e.username),Zn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await aW(r)}catch(s){throw be.error("Got an error deleting a user."),be.error(s),s}be.debug(n);try{await Xo()}catch(s){throw be.error("Got an error setting users to global."),be.error(s),s}return mp.signalUserChange(new Sp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(_W,"dropUser");async function dW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Ep.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await oW(r)}catch(s){throw be.error("Got an error searching for a role."),be.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw be.error(r),r}return t}a(dW,"userInfo");async function fW(){let e;try{e=await j_()}catch(t){throw be.error("Got an error listing users."),be.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(fW,"listUsersExternal");async function j_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await J_(e)}catch(o){throw be.error("Got an error searching for roles."),be.error(o),o}let r={};for(let o of t)r[o.id]=Ep.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 J_(n)}catch(o){throw be.error("Got an error searching for users."),be.error(o),o}let i=new Map;for(let o of s)o=Ep.cloneDeep(o),o.role=r[o.role],EW(o.role),i.set(o.username,o);return i}catch(e){throw be.error("got an error listing users"),be.error(e),Vr.errorizeMessage(e)}return null}a(j_,"listUsers");function EW(e){try{if(!e){be.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(nW)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){be.error("Got an error trying to set system permissions."),be.error(t)}}a(EW,"appendSystemTablesToRole");async function Xo(){try{let e=await j_();global.hdb_users=e}catch(e){throw be.error(e),e}}a(Xo,"setUsersToGlobal");async function fI(e,t,r=!0){global.hdb_users||await Xo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Xn(new Error,fp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Xn(new Error,fp.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(rI.get(t)===n.password)return s;if(hp.validate(n.password,t))rI.set(t,n.password);else throw Xn(new Error,fp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(fI,"findAndValidateUser");async function hW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(hW,"getSuperUser");async function mW(){let e=await j_(),t=rW.getConfigFromFile(eI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Vr.isEmpty(r)&&r?.role?.role===eI.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=pp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+tI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+tI.SERVER_SUFFIX.ADMIN,r}a(mW,"getClusterUser");var EI=[];Tp.invalidateUser=function(e){for(let t of EI)try{t(e)}catch(r){iW.error("Error invalidating user",r)}};Tp.onInvalidatedUser=function(e){EI.push(e)}});var $c=g((Ale,TI)=>{"use strict";var ji=$(),$r=P(),pW=Wy(),gle=Os(),Rle=As(),SW=ln(),{validateEvent:mI}=Mn(),Vc=Cn(),TW=require("process"),{resetDatabases:gW}=(Oe(),ie(Fe)),RW={[$r.ITC_EVENT_TYPES.SCHEMA]:AW,[$r.ITC_EVENT_TYPES.USER]:SI};async function AW(e){let t=mI(e);if(t){ji.error(t);return}ji.trace("ITC schemaHandler received schema event:",e),await pW(e.message),await OW(e.message)}a(AW,"schemaHandler");async function OW(e){try{Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=gW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ji.error(t)}}a(OW,"syncSchemaMetadata");var pI=[];async function SI(e){try{try{Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ji.warn(r)}let t=mI(e);if(t){ji.error(t);return}ji.trace(`ITC userHandler ${$r.HDB_ITC_CLIENT_PREFIX}${TW.pid} received user event:`,e),await SW.setUsersToGlobal();for(let r of pI)r()}catch(t){ji.error(t)}}a(SI,"userHandler");SI.addListener=function(e){pI.push(e)};TI.exports=RW});var Mn=g((wle,RI)=>{"use strict";var ble=$(),gp=J(),bW=P(),{ITC_ERRORS:Yc}=Ur(),{parentPort:yle,threadId:yW,isMainThread:NW,workerData:Nle}=require("worker_threads"),{onMessageFromWorkers:IW,broadcast:Ile,broadcastWithAcknowledgement:wW}=Je();RI.exports={sendItcEvent:CW,validateEvent:gI,SchemaEventMsg:DW,UserEventMsg:LW};var X_;IW(async(e,t)=>{X_=X_||$c(),gI(e),X_[e.type]&&await X_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function CW(e){return!NW&&e.message&&(e.message.originator=yW),wW(e)}a(CW,"sendItcEvent");function gI(e){if(typeof e!="object")return Yc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||gp.isEmpty(e.type))return Yc.MISSING_TYPE;if(!e.hasOwnProperty("message")||gp.isEmpty(e.message))return Yc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||gp.isEmpty(e.message.originator))return Yc.MISSING_ORIGIN;if(bW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Yc.INVALID_EVENT(e.type)}a(gI,"validateEvent");function DW(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(DW,"SchemaEventMsg");function LW(e){this.originator=e}a(LW,"UserEventMsg")});var bs=g((Lle,yI)=>{"use strict";var AI=P(),Dle=J(),Z_=$(),OI=$y(),Zo,{sendItcEvent:bI}=Mn();function MW(e){try{Z_.trace("signalSchemaChange called with message:",e),Zo=Zo||$c();let t=new OI(AI.ITC_EVENT_TYPES.SCHEMA,e);return Zo.schema(t),bI(t)}catch(t){Z_.error(t)}}a(MW,"signalSchemaChange");function PW(e){try{Z_.trace("signalUserChange called with message:",e),Zo=Zo||$c();let t=new OI(AI.ITC_EVENT_TYPES.USER,e);return Zo.user(t),bI(t)}catch(t){Z_.error(t)}}a(PW,"signalUserChange");yI.exports={signalSchemaChange:MW,signalUserChange:PW}});var ed=g((Ple,II)=>{"use strict";var NI=J(),UW=P(),vW=$(),BW=I_(),HW=N_(),xW=bs(),{SchemaEventMsg:GW}=Mn(),qW="already exists in";II.exports=FW;async function FW(e,t,r){if(NI.isEmptyOrZeroLength(r))return r;let n=[];NI.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 kW(e,t.schema,t.name,i)})),s}a(FW,"lmdbCheckForNewAttributes");async function kW(e,t,r,n){let s=new HW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await VW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(qW))vW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(kW,"createNewAttribute");async function VW(e){let t;return t=await BW(e),xW.signalSchemaChange(new GW(process.pid,UW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(VW,"createAttribute")});var ea=g((vle,wI)=>{"use strict";var Rp=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}};wI.exports=Rp});var DI=g((Hle,CI)=>{"use strict";var $W=ea(),YW=P().OPERATIONS_ENUM,Ap=class extends $W{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(YW.INSERT,r,n,s,i),this.records=t}};CI.exports=Ap});var MI=g((Gle,LI)=>{"use strict";var KW=ea(),WW=P().OPERATIONS_ENUM,Op=class extends KW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(WW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};LI.exports=Op});var UI=g((Fle,PI)=>{"use strict";var QW=ea(),zW=P().OPERATIONS_ENUM,bp=class extends QW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(zW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};PI.exports=bp});var BI=g((Vle,vI)=>{"use strict";var JW=ea(),jW=P().OPERATIONS_ENUM,yp=class extends JW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(jW.DELETE,n,s,t,i),this.original_records=r}};vI.exports=yp});var Kc=g((Kle,qI)=>{"use strict";var Yle=require("path"),HI=Ke(),XW=DI(),ZW=MI(),eQ=UI(),tQ=BI(),ta=_t(),xI=J(),{CONFIG_PARAMS:rQ}=P(),GI=Z();GI.initSync();var td=P().OPERATIONS_ENUM,{getTransactionAuditStorePath:nQ}=ze();qI.exports=sQ;async function sQ(e,t){if(GI.get(rQ.LOGGING_AUDITLOG)===!1)return;let r=nQ(e.schema,e.table),n=await HI.openEnvironment(r,e.table,!0),s=iQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){HI.initializeDBIs(n,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ta.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),xI.isEmpty(s.user_name)||n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(sQ,"writeTransaction");function iQ(e,t){let r=xI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===td.INSERT)return new XW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.UPDATE)return new ZW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.UPSERT)return new eQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.DELETE)return new tQ(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(iQ,"createTransactionObject")});var Np=g((zle,FI)=>{"use strict";var oQ=Hc(),Qle=xc(),Wc=P(),aQ=Gc(),cQ=Yo().insertRecords,uQ=Ke(),lQ=$(),_Q=ed(),{getSchemaPath:dQ}=ze(),fQ=Kc();FI.exports=EQ;async function EQ(e){try{let{schema_table:t,attributes:r}=oQ(e);aQ(e,r,t.hash_attribute),e.schema!==Wc.SYSTEM_SCHEMA_NAME&&(r.includes(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await _Q(e.hdb_auth_header,t,r),s=dQ(e.schema,e.table),i=await uQ.openEnvironment(s,e.table),o=await cQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await fQ(e,o)}catch(c){lQ.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(EQ,"lmdbCreateRecords")});var $I=g((jle,VI)=>{"use strict";var kI=P(),hQ=Np(),mQ=xc(),pQ=require("fs-extra"),{getSchemaPath:SQ}=ze();VI.exports=TQ;async function TQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new mQ(kI.SYSTEM_SCHEMA_NAME,kI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await hQ(r),await pQ.mkdirp(SQ(e.schema))}a(TQ,"lmdbCreateSchema")});var KI=g((Zle,YI)=>{"use strict";var Ip=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}};YI.exports=Ip});var JI=g((s_e,zI)=>{"use strict";var WI=Ke(),wp=vr(),Cp=Ur().LMDB_ERRORS_ENUM,gQ=_t(),QI=$(),t_e=J(),RQ=require("lmdb"),AQ=KI(),OQ=P(),{OVERFLOW_MARKER:r_e,MAX_SEARCH_KEY_LENGTH:n_e}=gQ,bQ=OQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function yQ(e,t,r,n){if(wp.validateEnv(e),t===void 0)throw new Error(Cp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Cp.IDS_REQUIRED):new Error(Cp.IDS_MUST_BE_ITERABLE);try{let s=WI.listDBIs(e);WI.initializeDBIs(e,t,s);let i=new AQ,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[bQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,RQ.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let A=e.dbis[T],R=h[T];if(R!=null)try{let C=wp.getIndexedValues(R);if(C)for(let x=0,v=C.length;x<v;x++)A.remove(C[x],o)}catch{QI.warn(`cannot delete from attribute: ${T}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){QI.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let E=0,f=l.length;E<f;E++)l[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),_.push(E));let d=0;for(let E=0;E<_.length;E++){let f=_[E];i.original_records.splice(f-d,1),d++}return i.txn_time=wp.getNextMonotonicTime(),i}catch(s){throw s}}a(yQ,"deleteRecords");zI.exports={deleteRecords:yQ}});var Qc=g((o_e,XI)=>{"use strict";var ra=J(),NQ=JI(),IQ=Ke(),{getSchemaPath:wQ}=ze(),CQ=Kc(),DQ=$();XI.exports=LQ;async function LQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ra.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ra.isEmptyOrZeroLength(e.hash_values)&&!ra.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ra.isEmpty(u)||e.hash_values.push(u)}}if(ra.isEmptyOrZeroLength(e.hash_values))return jI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ra.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=wQ(e.schema,e.table),i=await IQ.openEnvironment(s,e.table),o=await NQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await CQ(e,o)}catch(c){DQ.error(`unable to write transaction due to ${c.message}`)}return jI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(LQ,"lmdbDeleteRecords");function jI(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(jI,"createDeleteResponse")});var Lp=g((u_e,ZI)=>{"use strict";var MQ=P(),c_e=vr();function Dp(e,t){let r=Object.create(null);if(t.length===1&&MQ.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(Dp,"parseRow");function PQ(e,t,r,n){let s=Dp(r,e);n.push(s)}a(PQ,"searchAll");function UQ(e,t,r,n){let s=Dp(r,e);n[t]=s}a(UQ,"searchAllToMap");function vQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(vQ,"iterateDBI");function Xi(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(Xi,"pushResults");function BQ(e,t,r,n,s,i){t.toString().endsWith(e)&&Xi(t,r,n,s,i)}a(BQ,"endsWith");function HQ(e,t,r,n,s,i){t.toString().includes(e)&&Xi(t,r,n,s,i)}a(HQ,"contains");function xQ(e,t,r,n,s,i){t>e&&Xi(t,r,n,s,i)}a(xQ,"greaterThanCompare");function GQ(e,t,r,n,s,i){t>=e&&Xi(t,r,n,s,i)}a(GQ,"greaterThanEqualCompare");function qQ(e,t,r,n,s,i){t<e&&Xi(t,r,n,s,i)}a(qQ,"lessThanCompare");function FQ(e,t,r,n,s,i){t<=e&&Xi(t,r,n,s,i)}a(FQ,"lessThanEqualCompare");ZI.exports={parseRow:Dp,searchAll:PQ,searchAllToMap:UQ,iterateDBI:vQ,endsWith:BQ,contains:HQ,greaterThanCompare:xQ,greaterThanEqualCompare:GQ,lessThanCompare:qQ,lessThanEqualCompare:FQ,pushResults:Xi}});var na=g((E_e,ow)=>{"use strict";var ui=Ke(),__e=$(),Yr=vr(),rd=_t(),ft=Ur().LMDB_ERRORS_ENUM,d_e=J(),kQ=P(),nd=Lp(),{parseRow:VQ}=nd,f_e=require("lmdb"),{OVERFLOW_MARKER:ew,MAX_SEARCH_KEY_LENGTH:$Q}=rd;function tw(e,t,r,n=!1,s=void 0,i=void 0){return Zi(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(tw,"iterateFullIndex");function zc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Zi(e,t,r,(l,d,E,f)=>{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 f===r?(A.values=!1,d.getRange(A).map(R=>({value:R}))):d.getRange(A)})}a(zc,"iterateRangeBetween");function Zi(e,t,r,n){let s=e.database||e,i=ui.openDBI(s,r);i[rd.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ui.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(Zi,"setupTransaction");function rw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(ew)){if(!s)if(r)s=ui.openDBI(e,r);else{let u=ui.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ui.openDBI(e,u[_]),!s[rd.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(rw,"getOverflowCheck");function YQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);return Zi(e,t,t,(o,c,u)=>(sd(r),r=Jc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>VQ(_.value,r))))}a(YQ,"searchAll");function KQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);sd(r),r=Jc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of tw(e,t,t,n,s,i))o.set(c,nd.parseRow(u,r));return o}a(KQ,"searchAllToMap");function WQ(e,t,r=!1,n=void 0,s=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=tw(e,void 0,t,r,n,s),c=o.transaction,u=rw(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(WQ,"iterateDBI");function QQ(e,t){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);return ui.statDBI(e,t).entryCount}a(QQ,"countAll");function zQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,t,r,(c,u,_,l)=>(n=Yr.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(zQ,"equals");function JQ(e,t,r){return li(e,t,r),ui.openDBI(e,t).getValuesCount(r)}a(JQ,"count");function jQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,null,r,(c,u)=>{n=Yr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let E of u.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;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(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(n))return E;if(_===!0)return l.DONE}}),l.filter(E=>E)}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(jQ,"startsWith");function XQ(e,t,r,n,s=!1,i=void 0,o=void 0){return nw(e,t,r,n,s,i,o,!0)}a(XQ,"endsWith");function nw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return li(e,r,n),Zi(e,null,r,(u,_,l,d)=>{let E=rw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(ew)?_.getValues(f,{transaction:u}).map(p=>{let S=E(f,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[rd.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:u}).map(p=>({key:f,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(nw,"contains");function ZQ(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),zc(e,t,r,n,u,s,i,o,!0,!1)}a(ZQ,"greaterThan");function ez(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),zc(e,t,r,n,u,s,i,o,!1,!1)}a(ez,"greaterThanEqual");function tz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),zc(e,t,r,u,n,s,i,o,!1,!0)}a(tz,"lessThan");function rz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),zc(e,t,r,u,n,s,i,o,!1,!1)}a(rz,"lessThanEqual");function nz(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Yr.validateEnv(e),r===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(ft.START_VALUE_REQUIRED);if(s===void 0)throw new Error(ft.END_VALUE_REQUIRED);if(n=Yr.convertKeyValueToWrite(n),s=Yr.convertKeyValueToWrite(s),n>s)throw new Error(ft.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return zc(e,t,r,n,s,i,o,c)}a(nz,"between");function sz(e,t,r,n){Yr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(sd(r),r=Jc(s,r),n===void 0)throw new Error(ft.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=nd.parseRow(c,r)),o}a(sz,"searchByHash");function iz(e,t,r){Yr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ft.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(iz,"checkHashExists");function oz(e,t,r,n,s=[]){return iw(e,t,r,n,s),sw(e,t,r,n,s).map(i=>i[1])}a(oz,"batchSearchByHash");function az(e,t,r,n,s=[]){iw(e,t,r,n,s);let i=new Map;for(let[o,c]of sw(e,t,r,n,s))i.set(o,c);return i}a(az,"batchSearchByHashToMap");function sw(e,t,r,n,s=[]){return Zi(e,t,t,(i,o,c)=>{r=Jc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,nd.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(sw,"batchHashSearch");function iw(e,t,r,n,s){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(sd(r),n==null)throw new Error(ft.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(ft.IDS_MUST_BE_ITERABLE)}a(iw,"initializeBatchSearchByHash");function sd(e){if(!Array.isArray(e))throw e===void 0?new Error(ft.FETCH_ATTRIBUTES_REQUIRED):new Error(ft.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(sd,"validateFetchAttributes");function li(e,t,r){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ft.SEARCH_VALUE_REQUIRED);if(r?.length>$Q)throw new Error(ft.SEARCH_VALUE_TOO_LARGE)}a(li,"validateComparisonFunctions");function Jc(e,t){return t.length===1&&kQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ui.listDBIs(e)),t}a(Jc,"setGetWholeRowAttributes");ow.exports={searchAll:YQ,searchAllToMap:KQ,count:JQ,countAll:QQ,equals:zQ,startsWith:jQ,endsWith:XQ,contains:nw,searchByHash:sz,setGetWholeRowAttributes:Jc,batchSearchByHash:oz,batchSearchByHashToMap:az,checkHashExists:iz,iterateDBI:WQ,greaterThan:ZQ,greaterThanEqual:ez,lessThan:tz,lessThanEqual:rz,between:nz}});var sa=g((m_e,_w)=>{var aw=require("lodash"),cw=je(),he=require("joi"),cz=J(),{hdb_schema_table:jc,checkValidTable:uw,hdb_table:lw,hdb_database:id}=zn(),{handleHDBError:uz,hdb_errors:lz}=ne(),{getDatabases:_z}=(Oe(),ie(Fe)),{HTTP_STATUS_CODES:dz}=lz,fz=he.object({database:id,schema:id,table:lw,search_attribute:jc,search_value:he.any().required(),get_attributes:he.array().min(1).items(he.alternatives(jc,he.object())).optional(),desc:he.bool(),limit:he.number().integer().min(1),offset:he.number().integer().min(0)}),Ez=he.object({database:id,schema:id,table:lw,operator:he.string().valid("and","or").default("and").lowercase(),offset:he.number().integer().min(0),limit:he.number().integer().min(1),get_attributes:he.array().min(1).items(he.alternatives(jc,he.object())).optional(),sort:he.object({attribute:he.alternatives(jc,he.array().min(1)),descending:he.bool().optional()}).optional(),conditions:he.array().min(1).items(he.alternatives(he.object({operator:he.string().valid("and","or").default("and").lowercase(),conditions:he.array()}),he.object({search_attribute:he.alternatives(jc,he.array().min(1)),search_type:he.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:he.when("search_type",{switch:[{is:"equals",then:he.any()},{is:"between",then:he.array().items(he.alternatives([he.string(),he.number()])).length(2)}],otherwise:he.alternatives(he.string(),he.number())}).required()}))).required()});_w.exports=function(e,t){let r=null;switch(t){case"value":r=cw.validateBySchema(e,fz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(uw("database",e.schema)),i(uw("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=cw.validateBySchema(e,Ez);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=cz.checkGlobalSchemaTable(e.schema,e.table);if(s)return uz(new Error,s,dz.NOT_FOUND);let o=_z()[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,E=l.conditions.length;d<E;d++){let f=l.conditions[d];f.conditions?u(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=aw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!aw.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 Mp=g((S_e,dw)=>{"use strict";var hz=Ke(),mz=sa(),{getSchemaPath:pz}=ze();dw.exports=Sz;function Sz(e){let t=mz(e,"hashes");if(t)throw t;let r=pz(e.schema,e.table);return hz.openEnvironment(r,e.table)}a(Sz,"initialize")});var Pp=g((g_e,fw)=>{"use strict";var Tz=na(),gz=Mp();fw.exports=Rz;async function Rz(e){let t=await gz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Tz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(Rz,"lmdbGetDataByHash")});var ia=g((A_e,Ew)=>{"use strict";var Up=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};Ew.exports=Up});var mw=g((y_e,hw)=>{"use strict";var b_e=ia(),Az=na(),Oz=Mp();hw.exports=bz;async function bz(e){let t=await Oz(e),r=global.hdb_schema[e.schema][e.table];return Az.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(bz,"lmdbSearchByHash")});var es=g((I_e,pw)=>{"use strict";var vp=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}};pw.exports=vp});var od=g((C_e,Ow)=>{"use strict";var er=na(),yz=Ke(),Nz=J(),me=_t(),eo=P(),Iz=Fi(),Sw=Ur().LMDB_ERRORS_ENUM,{getSchemaPath:wz}=ze(),ys=eo.SEARCH_WILDCARDS;async function Cz(e,t,r){let n;e.schema===eo.SYSTEM_SCHEMA_NAME?n=Iz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Aw(e,n.hash_attribute,r,t);return gw(e,s,n.hash_attribute,r)}a(Cz,"prepSearch");async function gw(e,t,r,n){let s=wz(e.schema,e.table),i=await yz.openEnvironment(s,e.table),o=Rw(i,e,t,r),c=o.transaction||i;if([me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,me.SEARCH_TYPES.SEARCH_ALL,me.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(Dz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Tw(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[l]:E.key}),"toObject");return n?Tw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?er.batchSearchByHashToMap(c,r,e.get_attributes,_):er.batchSearchByHash(c,r,e.get_attributes,_)}a(gw,"executeSearch");function Rw(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 me.SEARCH_TYPES.EQUALS:s=er.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.CONTAINS:s=er.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.ENDS_WITH:case me.SEARCH_TYPES._ENDS_WITH:s=er.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.STARTS_WITH:case me.SEARCH_TYPES._STARTS_WITH:s=er.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return er.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return er.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case me.SEARCH_TYPES.SEARCH_ALL:return er.searchAll(e,n,t.get_attributes,o,c,u);case me.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return er.searchAllToMap(e,n,t.get_attributes,o,c,u);case me.SEARCH_TYPES.BETWEEN:s=er.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case me.SEARCH_TYPES.GREATER_THAN:case me.SEARCH_TYPES._GREATER_THAN:s=er.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.GREATER_THAN_EQUAL:case me.SEARCH_TYPES._GREATER_THAN_EQUAL:s=er.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.LESS_THAN:case me.SEARCH_TYPES._LESS_THAN:s=er.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.LESS_THAN_EQUAL:case me.SEARCH_TYPES._LESS_THAN_EQUAL:s=er.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Rw,"searchByType");function Tw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Tw,"createMapFromIterable");function Dz(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(Dz,"checkToFetchMore");function Aw(e,t,r,n){if(Nz.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),ys.indexOf(s)>-1)return r===!0?me.SEARCH_TYPES.SEARCH_ALL_TO_MAP:me.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(ys[0])<0&&s.indexOf(ys[1])<0)return c===!0?r===!0?me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:me.SEARCH_TYPES.EQUALS;if(ys.indexOf(i)>=0&&ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),me.SEARCH_TYPES.CONTAINS;if(ys.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),me.SEARCH_TYPES.ENDS_WITH;if(ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),me.SEARCH_TYPES.STARTS_WITH;if(s.includes(ys[0])||s.includes(ys[1]))return me.SEARCH_TYPES.EQUALS;throw new Error(Sw.UNKNOWN_SEARCH_TYPE)}else switch(n){case eo.VALUE_SEARCH_COMPARATORS.BETWEEN:return me.SEARCH_TYPES.BETWEEN;case eo.VALUE_SEARCH_COMPARATORS.GREATER:return me.SEARCH_TYPES.GREATER_THAN;case eo.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return me.SEARCH_TYPES.GREATER_THAN_EQUAL;case eo.VALUE_SEARCH_COMPARATORS.LESS:return me.SEARCH_TYPES.LESS_THAN;case eo.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return me.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Sw.UNKNOWN_SEARCH_TYPE)}}a(Aw,"createSearchTypeFromSearchObject");Ow.exports={executeSearch:gw,createSearchTypeFromSearchObject:Aw,prepSearch:Cz,searchByType:Rw}});var yw=g((M_e,bw)=>{"use strict";var L_e=es(),Lz=sa(),Mz=J(),Pz=P(),Uz=od();bw.exports=vz;function vz(e,t){if(!Mz.isEmpty(t)&&Pz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Lz(e,"value");if(n)throw n;return Uz.prepSearch(e,t,!0)}a(vz,"lmdbGetDataByValue")});var Xc=g((v_e,Nw)=>{"use strict";var U_e=es(),Bz=sa(),Hz=J(),xz=P(),Gz=od();Nw.exports=qz;async function qz(e,t){if(!Hz.isEmpty(t)&&xz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Bz(e,"value");if(n)throw n;return Gz.prepSearch(e,t,!1)}a(qz,"lmdbSearchByValue")});var ww=g((x_e,Iw)=>{"use strict";var H_e=_t(),Bp=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}},Hp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},xp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Iw.exports={SearchByConditionsObject:Bp,SearchCondition:Hp,SortAttribute:xp}});var Pw=g((k_e,Mw)=>{"use strict";var q_e=ww().SearchByConditionsObject,Fz=es(),kz=sa(),Gp=na(),ad=_t(),{Resource:F_e}=(Nn(),ie(qp)),Lw=od(),Vz=Lp(),$z=require("lodash"),{getSchemaPath:Yz}=ze(),Cw=Ke(),{handleHDBError:Kz,hdb_errors:Wz}=ne(),{HTTP_STATUS_CODES:Qz}=Wz,zz=1e8;Mw.exports=Jz;async function Jz(e){let t=kz(e,"conditions");if(t)throw Kz(t,t.message,Qz.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=Yz(e.schema,e.table),n=await Cw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Cw.openDBI(n,_.search_attribute);let i=$z.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===ad.SEARCH_TYPES.EQUALS?_.estimated_count=Gp.count(n,_.search_attribute,_.search_value):l===ad.SEARCH_TYPES.CONTAINS||l===ad.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=zz}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Dw(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(Lw.filterByType),d=l.length,E=Gp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!l[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>Vz.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await Dw(o,e,E,s.hash_attribute);c=c.concat(f)}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=Gp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Jz,"lmdbSearchByConditions");async function Dw(e,t,r,n){let s=new Fz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===ad.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Lw.searchByType(e,s,i,n).map(o=>o.value)}a(Dw,"executeConditionSearch")});var oa=g(($_e,Uw)=>{"use strict";var jz=P().OPERATIONS_ENUM,Fp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=jz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Uw.exports=Fp});var kp=g((K_e,kw)=>{"use strict";var xw=es(),Gw=oa(),qw=Xc(),Fw=Qc(),Er=P(),vw=J(),Bw=Ke(),{getTransactionAuditStorePath:Xz,getSchemaPath:Zz}=ze(),Hw=$();kw.exports=e2;async function e2(e){try{if(vw.isEmpty(global.hdb_schema[e.schema])||vw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await t2(e),await r2(e);let t=Zz(e.schema,e.table);try{await Bw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Hw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Xz(e.schema,e.table);await Bw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Hw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(e2,"lmdbDropTable");async function t2(e){let t=new xw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await qw(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 Gw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Fw(s)}a(t2,"deleteAttributesFromSystem");async function r2(e){let t=new xw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await qw(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 Gw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Fw(s)}catch(i){throw i}}a(r2,"dropTableFromSystem")});var $w=g((Q_e,Vw)=>{"use strict";var n2=require("fs-extra"),s2=es(),i2=ia(),o2=oa(),a2=kp(),c2=Qc(),u2=Pp(),l2=Xc(),Ns=P(),{getSchemaPath:_2}=ze(),{handleHDBError:d2,hdb_errors:f2}=ne(),{HDB_ERROR_MSGS:E2,HTTP_STATUS_CODES:h2}=f2;Vw.exports=m2;async function m2(e){let t;try{t=await p2(e.schema);let r=new s2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await l2(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await a2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new o2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await c2(s);let i=_2(t);await n2.remove(i)}catch(r){throw r}}a(m2,"lmdbDropSchema");async function p2(e){let t=new i2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await u2(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw d2(new Error,E2.SCHEMA_NOT_FOUND(e),h2.NOT_FOUND,void 0,void 0,!0);return n}a(p2,"validateDropSchema")});var cd=g((J_e,Yw)=>{"use strict";var Vp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Yw.exports=Vp});var Ww=g((Z_e,Kw)=>{"use strict";var S2=require("fs-extra"),ud=Ke(),{getTransactionAuditStorePath:T2}=ze(),$p=_t(),X_e=cd();Kw.exports=g2;async function g2(e){let t;try{let r=T2(e.schema,e.table);await S2.mkdirp(r),t=await ud.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{ud.createDBI(t,$p.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),ud.createDBI(t,$p.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),ud.createDBI(t,$p.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(g2,"createTransactionsAuditEnvironment")});var jw=g((tde,Jw)=>{"use strict";var Yp=P(),Qw=Ke(),R2=Yo(),{getSystemSchemaPath:A2,getSchemaPath:O2}=ze(),b2=Fi(),y2=I_(),Kp=N_(),N2=$(),I2=Ww(),Qp=b2.hdb_table,zw=[];for(let e=0;e<Qp.attributes.length;e++)zw.push(Qp.attributes[e].attribute);Jw.exports=w2;async function w2(e,t){let r=O2(t.schema,t.table),n=new Kp(t.schema,t.table,Yp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Kp(t.schema,t.table,Yp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Kp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Qw.createEnvironment(r,t.table),e!==void 0){let o=await Qw.openEnvironment(A2(),Yp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await R2.insertRecords(o,Qp.hash_attribute,zw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Wp(n),await Wp(s),await Wp(i)}await I2(t)}catch(o){throw o}}a(w2,"lmdbCreateTable");async function Wp(e){try{await y2(e)}catch(t){N2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Wp,"createAttribute")});var Zw=g((nde,Xw)=>{"use strict";var C2=Hc(),D2=Gc(),L2=ed(),Zc=P(),M2=Yo().updateRecords,P2=Ke(),{getSchemaPath:U2}=ze(),v2=Kc(),B2=$();Xw.exports=H2;async function H2(e){try{let{schema_table:t,attributes:r}=C2(e);D2(e,r,t.hash_attribute),e.schema!==Zc.SYSTEM_SCHEMA_NAME&&(r.includes(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await L2(e.hdb_auth_header,t,r),s=U2(e.schema,e.table),i=await P2.openEnvironment(s,e.table),o=await M2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await v2(e,o)}catch(c){B2.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(H2,"lmdbUpdateRecords")});var tC=g((ide,eC)=>{"use strict";var x2=P().OPERATIONS_ENUM,zp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=x2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};eC.exports=zp});var nC=g((cde,rC)=>{"use strict";var ade=tC(),G2=Hc(),q2=Gc(),F2=ed(),eu=P(),k2=Yo().upsertRecords,V2=Ke(),{getSchemaPath:$2}=ze(),Y2=Kc(),K2=$(),{handleHDBError:W2,hdb_errors:Q2}=ne();rC.exports=z2;async function z2(e){let t;try{t=G2(e)}catch(u){throw W2(u,u.message,Q2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;q2(e,n,r.hash_attribute),e.schema!==eu.SYSTEM_SCHEMA_NAME&&(n.includes(eu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(eu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(eu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(eu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await F2(e.hdb_auth_header,r,n),i=$2(e.schema,e.table),o=await V2.openEnvironment(i,e.table),c=await k2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await Y2(e,c)}catch(u){K2.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(z2,"lmdbUpsertRecords")});var iC=g((lde,sC)=>{"use strict";var Jp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};sC.exports=Jp});var aC=g((dde,oC)=>{"use strict";var jp=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}};oC.exports=jp});var lC=g((hde,uC)=>{"use strict";var Xp=Ke(),{getTransactionAuditStorePath:J2}=ze(),Ede=iC(),tu=_t(),j2=J(),cC=aC(),X2=require("util").promisify,Z2=X2(setTimeout),eJ=1e4,tJ=100;uC.exports=rJ;async function rJ(e){let t=J2(e.schema,e.table),r=await Xp.openEnvironment(t,e.table,!0),n=Xp.listDBIs(r);Xp.initializeDBIs(r,tu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new cC;do s=await nJ(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 Z2(tJ);while(s.transactions_deleted>0);return i}a(rJ,"deleteAuditLogsBefore");async function nJ(e,t){let r=new cC;try{let n=e.dbis[tu.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[tu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];j2.isEmpty(c)||(s=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>eJ)break}return await s,r}catch(n){throw n}}a(nJ,"deleteTransactions")});var dC=g((pde,_C)=>{"use strict";var Zp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};_C.exports=Zp});var EC=g((gde,fC)=>{"use strict";var sJ=es(),iJ=oa(),Tde=dC(),ts=P(),oJ=J(),eS=Ke(),aJ=Fi(),cJ=Xc(),uJ=Qc(),{getSchemaPath:lJ}=ze();fC.exports=_J;async function _J(e,t=!0){let r;e.schema===ts.SYSTEM_SCHEMA_NAME?r=aJ[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await fJ(e),s=lJ(e.schema,e.table),i=await eS.openEnvironment(s,e.table);return t===!0&&await dJ(e,i,r.hash_attribute),eS.dropDBI(i,e.attribute),n}a(_J,"lmdbDropAttribute");async function dJ(e,t,r){let n=eS.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(dJ,"removeAttributeFromAllObjects");async function fJ(e){let t=new sJ(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await cJ(t)).filter(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(oJ.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new iJ(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return uJ(i)}a(fJ,"dropAttributeFromSystem")});var gC=g((Ode,TC)=>{"use strict";var tS=Ke(),aa=_t(),Ade=vr(),rS=P(),hC=J(),{getTransactionAuditStorePath:EJ}=ze(),hJ=na(),ld=ea(),mJ=$();TC.exports=pJ;async function pJ(e){let t=EJ(e.schema,e.table),r=await tS.openEnvironment(t,e.table,!0),n=tS.listDBIs(r);tS.initializeDBIs(r,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return mC(r,e.search_values);case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,TJ(r,e.search_values,s);case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return SJ(r,e.search_values);default:return mC(r)}}a(pJ,"readAuditLog");function mC(e,t=[0,Date.now()]){hC.isEmpty(t[0])&&(t[0]=0),hC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[aa.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 ld,s))}a(mC,"searchTransactionsByTimestamp");function SJ(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[aa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,SC(e,i))}return Object.fromEntries(r)}a(SJ,"searchTransactionsByUsername");function TJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=hJ.equals(e,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,aa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=SC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);pC(u,"records",r,l,o),pC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(TJ,"searchTransactionsByHashValues");function pC(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 ld(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new ld(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(pC,"loopRecords");function SC(e,t){let r=[];try{let n=e.dbis[aa.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 ld,i);r.push(o)}}catch(i){mJ.warn(i)}return r}catch(n){throw n}}a(SC,"batchSearchTransactions")});var AC=g((Ide,RC)=>{"use strict";var{getSchemaPath:yde}=ze(),Nde=Ke(),{database:gJ}=(Oe(),ie(Fe));RC.exports={writeTransaction:RJ};async function RJ(e,t,r){return gJ({database:e,table:t}).transaction(r)}a(RJ,"writeTransaction")});var NC=g((Cde,yC)=>{"use strict";var{getSchemaPath:OC}=ze(),bC=Ke();yC.exports={flush:AJ,resetReadTxn:OJ};async function AJ(e,t){return(await bC.openEnvironment(OC(e,t),t.toString())).flushed}a(AJ,"flush");async function OJ(e,t){try{(await bC.openEnvironment(OC(e,t),t.toString())).resetReadTxn()}catch{}}a(OJ,"resetReadTxn")});var DC=g((Lde,CC)=>{"use strict";var{Readable:bJ}=require("stream"),{getDatabases:yJ}=(Oe(),ie(Fe)),{readSync:NJ,openSync:IJ,createReadStream:IC}=require("fs"),{open:wJ}=require("lmdb"),wC=Dc(),CJ=Lc(),{AUDIT_STORE_OPTIONS:DJ}=(ti(),ie(LC)),{INTERNAL_DBIS_NAME:LJ,AUDIT_STORE_NAME:MJ}=_t();CC.exports=UJ;var nS=32768,PJ=100;async function UJ(e){let t=e.database||e.schema||"data",r=yJ()[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=wJ({noSync:!0,maxDbs:CJ.MAX_DBS}),E,f=d.openDB(LJ,new wC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(A,R){R.encoding="binary",R.encoder=void 0;let C=d.openDB(A,R),x=l.openDB(A,R);for(let{key:v,version:k,value:M}of x.getRange({start:null,transaction:h,versions:x.useVersions}))E=C.put(v,M,k),p++%PJ===0&&(await new Promise(Q=>setTimeout(Q,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:R}of l.getRange({transaction:h,start:!1}))if(s.some(C=>A.startsWith?.(C+"/"))){f.put(A,R);let[,C]=A.split("/"),x=!C,v=new wC(!x,x);await S(A,v)}e.include_audit&&await S(MJ,Object.assign({},DJ)),await E;let T=IC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=IJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(nS);NJ(c,_,0,nS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=IC(null,{fd:c,start:nS}),E=new bJ.from(async function*(){yield _;for await(let f of d)l.openTimer&&(l.openTimer=0),yield f;l.done()}());return E.headers=u(),E});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(UJ,"getBackup")});var UC=g((Pde,PC)=>{"use strict";var vJ=$(),{handleHDBError:BJ}=ne(),HJ=Kb(),xJ=I_(),GJ=Np(),qJ=$I(),FJ=Qc(),kJ=Pp(),VJ=mw(),$J=yw(),YJ=Xc(),KJ=Pw(),WJ=$w(),QJ=jw(),zJ=Zw(),JJ=nC(),jJ=lC(),XJ=kp(),ZJ=EC(),e4=gC(),t4=AC(),MC=NC(),r4=DC(),sS=class extends HJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return KJ(t)}async getDataByHash(t){return await kJ(t)}async searchByHash(t){return await VJ(t)}async getDataByValue(t,r){return await $J(t,r)}async searchByValue(t){return await YJ(t)}async createSchema(t){return await qJ(t)}async dropSchema(t){return await WJ(t)}async createTable(t,r){return await QJ(t,r)}async dropTable(t){return await XJ(t)}async createAttribute(t){return await xJ(t)}async createRecords(t){return await GJ(t)}async updateRecords(t){return await zJ(t)}async upsertRecords(t){try{return await JJ(t)}catch(r){throw BJ(r,null,null,vJ.ERR,r)}}async deleteRecords(t){return await FJ(t)}async dropAttribute(t){return await ZJ(t)}async deleteAuditLogsBefore(t){return await jJ(t)}async readAuditLog(t){return await e4(t)}writeTransaction(t,r,n){return t4.writeTransaction(t,r,n)}flush(t,r){return MC.flush(t,r)}resetReadTxn(t,r){return MC.resetReadTxn(t,r)}getBackup(t){return r4(t)}};PC.exports=sS});function o4(){i4=setInterval(function(){for(let e of iS)if(e.stale){let t=e[Ne]?.url;xC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},s4).unref()}var oS,HC,xC,GC,qC,FC,vC,iS,n4,ru,BC,to,_d,s4,i4,aS=Ae(()=>{oS=B(vr()),HC=B(ne()),xC=B($());Nn();GC=B(Z()),qC=B(P()),FC=B(J()),vC=100,iS=new Set,n4=(0,FC.convertToMS)(GC.get(qC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,to=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;overloadChecked;open=1;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===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),iS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(iS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(ru&&!this.overloadChecked&&performance.now()-BC>n4)throw new HC.ServerError("Outstanding write transactions have too long of queue, please try again later",503);this.overloadChecked=!0}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}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,oS.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let f=d;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let E;for(let f=d;f<this.validated;f++){let h=this.writes[f];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let f=0;f<2;f++){let h;for(let p=d;p<this.validated;p++){let S=this.writes[p];if(!S)continue;let T=S[f===0?"before":"beforeIntermediate"];if(T){let A=T();h?h.push?h.push(A):h=[h,A]:h=A}}h&&await(h.push?Promise.all(h):h)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(d=>d);let c=a(d=>{d.commit(r,d.entry,n)},"doWrite"),u=a(()=>{let d=this.writes[o++];if(d)if(d.key){n>0&&(d.entry=d.store.getEntry(d.key));let E=d.store.ifVersion(d.key,d.entry?.version??null,u);s=s||E}else u();else for(let E of this.writes)c(E)},"nextCondition"),_=this.lmdbDb;if(this.writes.length>0&&(_?.retryRisk&&(_.retryRisk*=.99),this.writes.length+(_?.retryRisk||0)<vC>>n?u():s=this.writes[0].store.transaction(()=>{for(let d of this.writes)d.entry=d.store.getEntry(d.key),c(d);return!0})),s)return ru||(ru=s,BC=performance.now(),ru.then(()=>{ru=null})),s.then(d=>d?(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}))):(_&&(_.retryRisk=(_.retryRisk||0)+vC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let l={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));l.next=d}return l}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},_d=class extends to{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,oS.getNextMonotonicTime)())}getReadTxn(){}},s4=3e4;a(o4,"startMonitoringTxns");o4()});function Xe(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&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 to;e.timestamp&&(n.timestamp=e.timestamp),n[Ne]=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({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var kC,ro=Ae(()=>{kC=require("../index");Nn();aS();a(Xe,"transaction");(0,kC._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var jC={};qe(jC,{ResourceBridge:()=>lS});function _S({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function $C(e,t){let r=rs(e),n=_S(e,r);if(!r)throw new Pn.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&&fd(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 rs(e){let t=e.database||e.schema||c4,r=hr()[t];if(!r)throw(0,Pn.handleHDBError)(new Error,a4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function YC(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*KC(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 WC,dd,Pn,QC,zC,Un,cS,uS,JC,a4,c4,u4,l4,VC,lS,XC=Ae(()=>{"use strict";WC=B(UC()),dd=B(sa()),Pn=B(ne());Oe();QC=B(Hc()),zC=B(Gc()),Un=B(P()),cS=B(bs()),uS=B(Mn()),JC=B(J());ro();Ed();({HDB_ERROR_MSGS:a4}=Pn.hdb_errors),c4="data",u4=1e4,l4=10,lS=class extends WC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),VC=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,dd.default)(t,"conditions");if(r)throw(0,Pn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=rs(t);if(!n)throw new Pn.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:_S(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 Pn.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}]}dt({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await rs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=rs(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){rs(t).dropTable()}createSchema(t){return nu({database:t.schema,table:null}),cS.signalSchemaChange(new uS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await dS(t.schema),cS.signalSchemaChange(new uS.SchemaEventMsg(process.pid,Un.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,VC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,QC.default)(t);(0,zC.default)(t,n,r.primaryKey);let s,i=hr()[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(E=>E.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=fd(d));for(let E in l)if(Object.prototype.hasOwnProperty.call(l,E)){let f=l[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,l[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(l),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(l,E)||(l[E]=d[E]);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=hr()[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 YC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=hr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Pn.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:Un.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,JC.async_set_timeout)(l4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%u4===0&&await _();return u.length>0&&await _(),s?YC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,dd.default)(t,"hashes");if(r)throw r;return $C(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of $C(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.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,dd.default)(t,"value");if(n)throw n;let s=rs(t);if(!s)throw new Pn.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===Un.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:_S(t,s)})}async getDataByValue(t,r){let n=new Map,s=rs(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){rs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return rs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=rs(t),n={};switch(t.search_type){case Un.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 Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of KC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return KC(r,t.search_values?.[0],t.search_values?.[1])}}};a(_S,"getSelect");a($C,"getRecords");a(rs,"getTable");a(YC,"createDeleteResponse");a(KC,"groupRecordsInHistory")});var Cn=g((Qde,ZC)=>{"use strict";var{ResourceBridge:_4}=(XC(),ie(jC)),d4=Z();d4.initSync();var hd;function f4(){return hd||(hd=new _4,hd)}a(f4,"getBridge");ZC.exports=f4()});var nD=g((Jde,rD)=>{"use strict";var eD=require("lodash"),su=require("mathjs"),E4=require("jsonata"),tD=J();rD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?eD.uniqWith(e,eD.isEqual):e,searchJSON:h4,mad:iu.bind(null,su.mad),mean:iu.bind(null,su.mean),mode:iu.bind(null,su.mode),prod:iu.bind(null,su.prod),median:iu.bind(null,su.median)};function iu(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(iu,"aggregateFunction");function h4(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(tD.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),tD.isEmpty(this.__ala__.res[r])){let n=E4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(h4,"searchJSON")});var iD=g((Xde,sD)=>{"use strict";var Tt=require("moment"),fS="YYYY-MM-DDTHH:mm:ss.SSSZZ";Tt.suppressDeprecationWarnings=!0;sD.exports={current_date:()=>Tt().utc().format("YYYY-MM-DD"),current_time:()=>Tt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Tt(e).utc().format("YYYY");case"month":return Tt(e).utc().format("MM");case"day":return Tt(e).utc().format("DD");case"hour":return Tt(e).utc().format("HH");case"minute":return Tt(e).utc().format("mm");case"second":return Tt(e).utc().format("ss");case"millisecond":return Tt(e).utc().format("SSS");default:break}},date:e=>Tt(e).utc().format(fS),date_format:(e,t)=>Tt(e).utc().format(t),date_add:(e,t,r)=>Tt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Tt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=Tt(e).utc(),s=Tt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>Tt().utc().valueOf(),get_server_time:()=>Tt().format(fS),offset_utc:(e,t)=>Tt(e).utc().utcOffset(t).format(fS)}});var uD=g((Zde,cD)=>{"use strict";var m4=require("@turf/area"),p4=require("@turf/length"),S4=require("@turf/circle"),T4=require("@turf/difference"),g4=require("@turf/distance"),R4=require("@turf/boolean-contains"),A4=require("@turf/boolean-equal"),O4=require("@turf/boolean-disjoint"),b4=require("@turf/helpers"),oD=P(),ge=J(),Is=$();cD.exports={geoArea:y4,geoLength:N4,geoCircle:I4,geoDifference:w4,geoDistance:aD,geoNear:C4,geoContains:D4,geoEqual:L4,geoCrosses:M4,geoConvert:P4};function y4(e){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return m4.default(e)}catch(t){return Is.trace(t,e),NaN}}a(y4,"geoArea");function N4(e,t){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return p4.default(e,{units:t||"kilometers"})}catch(r){return Is.trace(r,e),NaN}}a(N4,"geoLength");function I4(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return S4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(I4,"geoCircle");function w4(e,t){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return T4(e,t)}catch(r){return Is.trace(r,e,t),NaN}}a(w4,"geoDifference");function aD(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return g4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(aD,"geoDistance");function C4(e,t,r,n){if(ge.isEmpty(e)||ge.isEmpty(t))return!1;if(ge.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return aD(e,t,n)<=r}catch(s){return Is.trace(s,e,t),!1}}a(C4,"geoNear");function D4(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return R4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(D4,"geoContains");function L4(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return A4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(L4,"geoEqual");function M4(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return!O4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(M4,"geoCrosses");function P4(e,t,r){if(ge.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(ge.isEmpty(t))throw new Error("geo_type is required");if(ge.isEmpty(oD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(oD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=ge.autoCastJSON(e)),b4[t](e,r)}a(P4,"geoConvert")});var md=g((tfe,lD)=>{var no=nD(),Kr=iD(),ns=uD();lD.exports=e=>{e.aggr.mad=e.aggr.MAD=no.mad,e.aggr.mean=e.aggr.MEAN=no.mean,e.aggr.mode=e.aggr.MODE=no.mode,e.aggr.prod=e.aggr.PROD=no.prod,e.aggr.median=e.aggr.MEDIAN=no.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=no.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=no.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Kr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Kr.current_time,e.fn.extract=e.fn.EXTRACT=Kr.extract,e.fn.date=e.fn.DATE=Kr.date,e.fn.date_format=e.fn.DATE_FORMAT=Kr.date_format,e.fn.date_add=e.fn.DATE_ADD=Kr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Kr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Kr.date_diff,e.fn.now=e.fn.NOW=Kr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Kr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Kr.get_server_time,e.fn.getdate=e.fn.GETDATE=Kr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Kr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=ns.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ns.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ns.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ns.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ns.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ns.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ns.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ns.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ns.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ns.geoNear}});var ED=g((rfe,fD)=>{"use strict";var ou=require("lodash"),mr=require("alasql");mr.options.cache=!1;var U4=md(),_D=require("clone"),pd=require("recursive-iterator"),_e=$(),De=J(),ca=Cn(),v4=P(),{hdb_errors:B4}=ne(),{getDatabases:dD}=(Oe(),ie(Fe)),H4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";U4(mr);var ES=class{static{a(this,"SQLSearch")}constructor(t,r){if(De.isEmpty(t))throw _e.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(),De.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!De.isEmptyOrZeroLength(n))return _e.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw _e.error("Error thrown from checkEmptySQL in SQLSearch class method search."),_e.error(n),new Error(vn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw _e.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),_e.error(n),new Error(vn)}if(Object.keys(this.data).length===0)return _e.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw _e.error("Error thrown from processJoins in SQLSearch class method search."),_e.error(n),new Error(vn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw _e.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),_e.error(n),new Error(vn)}try{return t=await this._finalSQL(),t}catch(n){throw _e.error("Error thrown from finalSQL in SQLSearch class method search."),_e.error(n),new Error(vn)}}_getColumns(){let t=new pd(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(_D(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=ou.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=dD()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(De.isEmpty(this.statement.where)){_e.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new pd(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!De.isEmpty(r)&&r.right)if(De.isNotEmptyAndHasValue(r.right.value)){let n=De.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new mr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=De.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new mr.yy.LogicValue({value:i}):n instanceof mr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new mr.yy.NumValue({value:i}))});if(t){_e.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new pd(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(!De.isEmpty(v4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(De.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(De.isEmptyOrZeroLength(r.left.columnid)||De.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(De.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"=":!De.isEmpty(r.right.value)||!De.isEmpty(r.left.value)?n.add(De.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(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from)&&De.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&&ou.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(De.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);De.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(De.isEmptyOrZeroLength(this.all_table_attributes)&&!De.isEmptyOrZeroLength(this.columns.columns))return t;if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await mr.promise(r)}catch(r){throw _e.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),_e.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(_D(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(De.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(H4)>-1&&this.tables.forEach(s=>{let i={columnid:dD()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=ou.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),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ca.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 _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}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 E=await ca.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,f))}))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,E=l.length;d<E;d++){let f=l[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ca.getDataByValue(c,f.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ca.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,E]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(l),new Error(vn)}}}_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 mr.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 mr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new mr.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 mr.yy.FuncValue:new mr.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(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,p=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${p}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${p}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";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(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let 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 E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(f,s);E=await mr.promise(h,t),t=null}catch(f){throw _e.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),_e.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let p=E[f];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),p=ou.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let A=p[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[A]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new pd(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=ou.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 _e.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),_e.error(i),new Error(vn)}}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 ca.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let E=o[l],f=u.get(E);for(let h=0;h<_;h++){let p=s.columns[h],S=f[p]===void 0?null:f[p];this.data[n].__merged_data[E].push(S)}}}}catch(r){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getData."),_e.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();_e.trace(`Final SQL: ${s}`),n=await mr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),_e.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw _e.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),_e.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 _e.error(B4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),_e.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 ca.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 _e.error("There was an error when processing this SQL operation. Check your logs"),_e.error(o),new Error(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};fD.exports=ES});var Gr=g((sfe,hD)=>{"use strict";var x4=$b();hD.exports={searchByConditions:q4,searchByHash:F4,searchByValue:k4,search:V4};var hS=Cn(),{transformReq:mS}=J(),G4=ED();async function q4(e){return mS(e),hS.searchByConditions(e)}a(q4,"searchByConditions");async function F4(e){mS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of hS.searchByHash(e))r&&t.push(r);return t}a(F4,"searchByHash");async function k4(e){mS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of hS.searchByValue(e))t.push(r);return t}a(k4,"searchByValue");function V4(e,t){try{let r=new x4(e);r.validate(),new G4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(V4,"search")});var Sd=g((ofe,mD)=>{"use strict";var $4=Cn();mD.exports={writeTransaction:Y4};function Y4(e,t,r){return $4.writeTransaction(e,t,r)}a(Y4,"writeTransaction")});var gD=g((ufe,TD)=>{"use strict";var K4=Gr(),W4=Os(),pD=$(),Q4=qr(),cfe=Sd(),z4=require("clone"),SS=require("alasql"),J4=md(),SD=require("util"),j4=SD.promisify(W4.getTableSchema),X4=SD.promisify(K4.search),Z4=P(),pS=J();J4(SS);TD.exports={update:t3};var e3="There was a problem performing this update. Please check the logs and try again.";async function t3({statement:e,hdb_user:t}){let r=await j4(e.table.databaseid,e.table.tableid),n=r3(e.columns);pS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=z4(s),c=pS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=SS.parse(u).statements[0],l=await X4(_),d=n3(n,l);return s3(o,d,t)}a(t3,"update");function r3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=SS.compile(`SELECT ${r.expression.toString()} AS [${Z4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw pD.error(t),new Error(e3)}}a(r3,"createUpdateRecord");function n3(e,t){return pS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(n3,"buildUpdateRecords");async function s3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await Q4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){pD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(s3,"updateRecords")});var AD=g((ffe,RD)=>{var i3=require("alasql"),o3=Gr(),a3=$(),c3=Cn(),gS=require("util"),TS=J(),u3=P(),l3=Os(),_fe=Sd(),dfe=qr(),_3="record",d3="successfully deleted",f3=gS.callbackify(p3),E3=gS.promisify(o3.search),h3=gS.promisify(l3.getTableSchema);RD.exports={convertDelete:f3};function m3(e){return`${e.deleted_hashes.length} ${_3}${e.deleted_hashes.length===1?"":"s"} ${d3}`}a(m3,"generateReturnMessage");async function p3({statement:e,hdb_user:t}){let r=await h3(e.table.databaseid,e.table.tableid);TS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=TS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=i3.parse(o).statements[0],u={operation:u3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await E3(c);let _=await c3.deleteRecords(u);return TS.isEmptyOrZeroLength(_.message)&&(_.message=m3(_)),delete _.txn_time,_}catch(_){throw a3.error(_),_.hdb_code?_.message:_}}a(p3,"convertDelete")});var ID=g((hfe,ND)=>{"use strict";var S3=As(),{hdb_errors:OD}=ne(),{getDatabases:bD}=(Oe(),ie(Fe));ND.exports={checkSchemaExists:yD,checkSchemaTableExists:T3,schema_describe:S3};async function yD(e){if(!bD()[e])return OD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(yD,"checkSchemaExists");async function T3(e,t){let r=await yD(e);if(r)return r;if(!bD()[e][t])return OD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(T3,"checkSchemaTableExists")});var au=g((pfe,g3)=>{g3.exports={name:"harperdb",version:"4.3.18",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},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/client-s3":"3.535.0","@aws-sdk/lib-storage":"3.535.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","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.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.12",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","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.1",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.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.16.0",yaml:"2.4.1"},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.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",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.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",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.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var du={};qe(du,{addAnalyticsListener:()=>_u,recordAction:()=>pr,recordActionBinary:()=>Wr,setAnalyticsEnabled:()=>R3});function R3(e){BD=e}function pr(e,t,r,n,s){if(!BD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Rd.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},Rd.set(i,o)}Td||A3()}function Wr(e,t,r,n,s){pr(!!e,t,r,n,s)}function _u(e){GD.push(e)}function A3(){Td=performance.now(),setTimeout(async()=>{let e=performance.now()-Td;Td=0;let t=[],r={time:Date.now(),period:e,threadId:so.threadId,metrics:t};for(let[s,i]of Rd){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 qD){let E=Math.floor(c*d),f=o[E-1];if(E>u){let h=E-u;if(f===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:f,count:h}:f),l=f;u=E}}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 FD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:so.threadId,byThread:!0,...n});for(let s of GD)s(t);Rd=new Map,so.parentPort?so.parentPort.postMessage({type:xD,report:r}):$D({report:r})},HD).unref()}async function O3(e,t=6e4){let r=OS(),n=kD(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,cu.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let T=performance.now();T-S>5e3&&(0,cu.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:A}=S;for(let R of T||[]){let{path:C,method:x,type:v,metric:k,count:M,total:Q,distribution:j,threads:z,...ae}=R;M||(M=1);let ue=k+(C?"-"+C:"");x!==void 0&&(ue+="-"+x),v!==void 0&&(ue+="-"+v);let de=c.get(ue);if(de){if(de.threads){let Ee=de.threads[A];if(Ee)de=Ee;else{de.threads[A]=Object.assign({},ae);continue}}de.count||(de.count=1);let xe=de.count;for(let Ee in ae){let Pt=ae[Ee];typeof Pt=="number"&&(de[Ee]=(de[Ee]*xe+Pt*M)/(xe+M))}de.count+=M,Q>=0&&(de.total+=Q,de.ratio=de.total/de.count)}else de=Object.assign({period:t},R),delete de.distribution,c.set(ue,de),de.byThread&&(de.threads=[],de.threads[A]=Object.assign({},ae),_.push(de));if(j){j=j.map(Ee=>typeof Ee=="number"?{value:Ee,count:1}:Ee);let xe=u.get(ue);xe?xe.push(...j):u.set(ue,j)}}await FD()}for(let p of _){let{path:S,method:T,type:A,metric:R,count:C,total:x,distribution:v,threads:k,...M}=p;k=k.filter(Q=>Q);for(let Q in M){if(typeof p[Q]!="number")continue;let j=0;for(let z of k){let ae=z[Q];typeof ae=="number"&&(j+=ae)}p[Q]=j}p.count=k.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Ee,Pt)=>Ee.value>Pt.value?1:-1);let A=T.count-1,R=[],C=0,x=0,v;for(let Ee of qD){let Pt=A*Ee;for(;C<Pt;)v=S[x++],C+=v.count,x===1&&C--;let zl=S[x>1?x-2:0];v||(v=S[0]),R.push(v.value-(v.value-zl.value)*(C-Pt)/v.count)}let[k,M,Q,j,z,ae,ue,de,xe]=R;Object.assign(T,{p1:k,p10:M,p25:Q,median:j,p75:z,p90:ae,p95:ue,p99:de,p999:xe})}let d;for(let[p,S]of c)S.id=(0,gd.getNextMonotonicTime)(),S.time=l,n.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||n.primaryStore.put(S.id,S)}),d=!0;let E=Date.now(),{idle:f,active:h}=performance.eventLoopUtilization();if(d||h*10>f){let p=(0,gd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:f-wD,active:h-CD,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}wD=f,CD=h}async function DD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function OS(){return LD||(LD=dt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function kD(){return MD||(MD=dt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function N3(){VD=!0;let e=(0,lu.get)(AS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await O3(HD,e),await DD(OS(),b3),await DD(kD(),y3)},Math.min(e/2,2147483647)).unref()}function $D(e,t){let r=e.report;r.threadId=t?.threadId||so.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(PD+=n.mean*n.count);r.totalBytesProcessed=PD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(UD.get(t))}),UD.set(t,t.performance.eventLoopUtilization())),r.id=(0,gd.getNextMonotonicTime)(),OS().primaryStore.put(r.id,r),VD||N3(),I3&&(YD=C3(r))}async function C3(e){if(await YD,!_i){let r=(0,uu.dirname)((0,cu.getLogFilePath)());try{_i=await(0,RS.open)((0,uu.join)(r,"analytics.log"),"r+")}catch{_i=await(0,RS.open)((0,uu.join)(r,"analytics.log"),"w+")}}let t=(await _i.stat()).size;if(t>w3){let r=Buffer.alloc(t);await _i.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await _i.write(r,{position:0}),await _i.truncate(r.length),t=r.length}await _i.write(JSON.stringify(e)+`
8
+ `,t)}var so,vD,cu,uu,RS,gd,lu,AS,Rd,BD,Td,HD,xD,GD,qD,wD,CD,FD,b3,y3,LD,MD,VD,PD,UD,I3,YD,_i,w3,ws=Ae(()=>{so=require("worker_threads"),vD=B(Je());Oe();cu=B($()),uu=require("path"),RS=require("fs/promises"),gd=B(vr()),lu=B(Z()),AS=B(P());ur();(0,lu.initSync)();Rd=new Map,BD=(0,lu.get)(AS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(R3,"setAnalyticsEnabled");a(pr,"recordAction");st.recordAnalytics=pr;a(Wr,"recordActionBinary");Td=0,HD=1e3,xD="analytics-report",GD=[];a(_u,"addAnalyticsListener");qD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(A3,"sendAnalytics");a(O3,"aggregation");wD=0,CD=0,FD=a(()=>new Promise(setImmediate),"rest");a(DD,"cleanup");b3=36e5,y3=31536e6;a(OS,"getRawAnalyticsTable");a(kD,"getAnalyticsTable");(0,vD.setChildListenerByType)(xD,$D);a(N3,"startScheduledTasks");PD=0,UD=new Map,I3=!1;a($D,"recordAnalytics");w3=1e6;a(C3,"logAnalytics")});var wS=g((Dfe,rL)=>{"use strict";var{decode:D3}=require("msgpackr"),{isMainThread:Ife,parentPort:wfe,threadId:Cfe}=require("worker_threads"),bd=ot(),ua=ke(),NS=P(),tr=$(),yS=Z(),L3=P(),{onMessageByType:M3}=Je(),QD=Rs(),{recordAction:P3,recordActionBinary:U3}=(ws(),ie(du)),{publishToStream:v3}=bd,{ConsumerEvents:KD}=require("nats"),B3=Gr(),{promisify:H3}=require("util"),zD=H3(setTimeout),yd=1e4,Nd,Od,x3,G3,JD,fu=new Map,la=new Map;rL.exports={initialize:jD,ingestConsumer:IS,setSubscription:q3,setIgnoreOrigin:V3,getDatabaseSubscriptions:k3,updateConsumer:XD};async function jD(){M3(NS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await XD(n)}),JD=!0,tr.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await bd.getNATSReferences();Nd=e,Od=e.info.server_name,x3=t,G3=r}a(jD,"initialize");async function XD(e){if(e.status==="start"){let{js:t,jsm:r}=await ZD(e.node_domain_name);IS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=fu.get(e.stream_name+e.node_domain_name);t&&(tr.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),fu.set(e.stream_name+e.node_domain_name,"close")),la.get(e.node_domain_name)==="failed"&&la.set(e.node_domain_name,"close")}}a(XD,"updateConsumer");var Id=new Map;function q3(e,t,r){let n=Id.get(e);n||Id.set(e,n=new Map),n.set(t,r),JD||jD().then(F3)}a(q3,"setSubscription");async function F3(){let e=await B3.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+ua.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await ZD(r),!n))break;let{schema:o,table:c}=i,u=QD.createNatsTableStreamName(o,c);IS(u,n,s,r)}}}a(F3,"accessConsumers");async function ZD(e){let t,r,n=1;for(;!r;)try{t=await Nd.jetstream({domain:e}),r=await Nd.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(la.get(e)==="close")break;la.set(e,"failed"),n%10===1&&tr.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<yd?n++*100:yd;await zD(i)}return{js:t,jsm:r}}a(ZD,"connectToRemoteJS");function k3(){return Id}a(k3,"getDatabaseSubscriptions");var eL;function V3(e){eL=e}a(V3,"setIgnoreOrigin");var tL=100,WD=new Array(tL),Ad=0;async function IS(e,t,r,n){let{connection:s}=await bd.getNATSReferences();Nd=s,Od=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,Od),tr.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(la.get(n)==="close")break;o%10===1&&tr.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(tr.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await bd.createConsumer(r,e,Od,new Date(Date.now()).toISOString()));let l=o++*100<yd?o++*100:yd;await zD(l)}let c=!1,u;for(;!c;){if(fu.get(e+n)==="close"||la.get(n)==="close"){fu.delete(e+n),c=!0;continue}u=await i.consume({max_messages:yS.get(NS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),fu.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===KD.ConsumerDeleted&&(await u.close(),c=!0),l.type===KD.HeartbeatsMissed){let d=l.data;tr.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===100&&(tr.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await WD[Ad],WD[Ad]=$3(l).catch(d=>{tr.error(d)}),++Ad>=tL&&(Ad=0)}catch(l){l.message==="consumer deleted"?(tr.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):tr.error("Error consuming clustering ingest, restarting consumer",l)}}}a(IS,"ingestConsumer");async function $3(e){let t=D3(e.data);P3(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),tr.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=yS.get(NS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(ua.MSG_HEADERS.TRANSACTED_NODES)&&r.values(ua.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(ua.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!eL),U3(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(ua.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:E,expiresAt:f}=t;tr.trace("processing message:",o,c,_,(l?"records: "+l.map(C=>C?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),tr.trace(`messageProcessor nats msg id: ${e.headers.get(ua.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let p=new Promise(C=>h=C),{timestamp:S,user:T,node_name:A}=E||{},R=Id.get(c)?.get(_);if(!R)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,R.send(t);else if(l.length===1&&!u)R.send({type:bS(o),value:l[0],id:d?.[0],expiresAt:f,timestamp:S,table:_,onCommit:h,user:T,nodeName:A});else{let C=l.map((x,v)=>({type:bS(o),value:x,expiresAt:f,id:d?.[v],table:_}));for(;u;)C.push({type:bS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;R.send({type:"transaction",writes:C,table:_,timestamp:S,onCommit:h,user:T,nodeName:A})}yS.get(L3.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&v3(e.subject.split(".").slice(0,-1).join("."),QD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){tr.error(o)}e.ack()}a($3,"messageProcessor");function bS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(bS,"convertOperation")});var ot=g((Hfe,TL)=>{"use strict";var Bt=Z();Bt.initSync();var Y3=require("fs-extra"),K3=require("semver"),mu=require("path"),{monotonicFactory:W3}=require("ulidx"),sL=W3(),Q3=require("util"),iL=require("child_process"),z3=Q3.promisify(iL.exec),J3=iL.spawn,Yt=ke(),Ie=P(),wd=J(),Bn=$(),Cd=Rs(),j3=Sd(),Eu=fr(),{broadcast:X3,onMessageByType:Z3,getWorkerIndex:ej}=Je(),{isMainThread:oL}=require("worker_threads"),{Encoder:tj,decode:MS}=require("msgpackr"),aL=new tj,{isEmpty:co}=wd,cL=ln(),Mfe=48*36e11;oL&&Z3(Ie.ITC_EVENT_TYPES.RESTART,()=>{Sr=void 0,ao=void 0});var{connect:rj,StorageType:nj,RetentionPolicy:sj,AckPolicy:PS,DeliverPolicy:US,DiscardPolicy:ij,NatsConnection:Pfe,JetStreamManager:Ufe,JetStreamClient:vfe,StringCodec:Bfe,JSONCodec:oj,createInbox:vS,headers:aj,ErrorCode:nL}=require("nats"),{PACKAGE_ROOT:cj}=P(),uj=au(),{recordAction:lj}=(ws(),ie(du)),uL=oj(),_j="clustering",dj=uj.engines[Yt.NATS_SERVER_NAME],fj=mu.join(cj,"dependencies"),LS=mu.join(fj,`${process.platform}-${process.arch}`,Yt.NATS_BINARY_NAME),CS,DS,hu,io,oo;TL.exports={runCommand:lL,checkNATSServerInstalled:Ej,createConnection:BS,getConnection:pu,getJetStreamManager:Su,getJetStream:dL,getNATSReferences:ss,getServerList:mj,createLocalStream:HS,listStreams:fL,deleteLocalStream:pj,getServerConfig:_a,listRemoteStreams:Sj,viewStream:Tj,viewStreamIterator:gj,publishToStream:Rj,request:bj,reloadNATS:xS,reloadNATSHub:yj,reloadNATSLeaf:Nj,extractServerName:Oj,requestErrorHandler:Ij,createLocalTableStream:pL,createTableStreams:Dj,purgeTableStream:SL,purgeSchemaTableStreams:Lj,getStreamInfo:Mj,updateLocalStreams:Uj,closeConnection:hj,getJsmServerName:Dd,addNatsMsgHeader:EL,clearClientCache:_L,updateRemoteConsumer:wj,createConsumer:hL,updateConsumerIterator:Cj};async function lL(e,t=void 0){let{stdout:r,stderr:n}=await z3(e,{cwd:t});if(n)throw new Error(n.replace(`
9
9
  `,""));return r.replace(`
10
- `,"")}a(uL,"runCommand");async function Ej(){try{await Y3.access(DS)}catch{return!1}let e=await uL(`${DS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return K3.eq(t,dj)}a(Ej,"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}vn.trace("create nats connection called");let i=await rj({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:vt.get(ye.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:vt.get(ye.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:vt.get(ye.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),vn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&vn.error("Error with Nats client connection, connection closed",o),lL()}),i}a(vS,"createConnection");function lL(){mr=void 0,io=void 0,oo=void 0,ao=void 0}a(lL,"clearClientCache");async function hj(){mr&&(await mr.drain(),mr=void 0,io=void 0,oo=void 0,ao=void 0)}a(hj,"closeConnection");var mr,ao;async function mu(){return ao||(ao=vS(vt.get(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),mr=await ao),mr||ao}a(mu,"getConnection");async function pu(){if(io)return io;co(mr)&&await mu();let{domain:e}=la(ye.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await mr.jetstreamManager({domain:e,timeout:6e4}),io}a(pu,"getJetStreamManager");async function _L(){if(oo)return oo;co(mr)&&await mu();let{domain:e}=la(ye.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=mr.jetstream({domain:e,timeout:6e4}),oo}a(_L,"getJetStream");async function ss(){let e=mr||await mu(),t=io||await pu(),r=oo||await _L();return{connection:e,jsm:t,js:r}}a(ss,"getNATSReferences");async function mj(e){let t=vt.get(ye.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=cL.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 Nd.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(mj,"getServerList");async function BS(e,t){let{jsm:r}=await ss(),n=vt.get(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=vt.get(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=vt.get(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:nj.File,retention:sj.Limits,subjects:t,discard:ij.Old,max_msgs:s,max_bytes:i,max_age:n})}a(BS,"createLocalStream");async function dL(){let{jsm:e}=await ss(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(dL,"listStreams");async function pj(e){let{jsm:t}=await ss();await t.streams.delete(e)}a(pj,"deleteLocalStream");async function Sj(e){let{connection:t}=await ss(),r=[],n=PS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(cL.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(Sj,"listRemoteStreams");async function Tj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=nL(),o={durable_name:i,ack_policy:MS.Explicit};t&&(o.deliver_policy=US.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=LS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get($t.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Tj,"viewStream");async function*gj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=nL(),o={durable_name:i,ack_policy:MS.Explicit};t&&(o.deliver_policy=US.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=LS(_.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($t.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(gj,"viewStreamIterator");async function Rj(e,t,r,n){vn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=fL(n,r);let{js:s}=await ss(),i=await Id(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:oL.encode(n);try{vn.trace(`publishToStream publishing to subject: ${o}`),lj(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 hL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){vn.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(Rj,"publishToStream");function fL(e,t){t===void 0&&(t=aj());let r=vt.get(ye.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has($t.MSG_HEADERS.ORIGIN)&&r&&t.append($t.MSG_HEADERS.ORIGIN,r),t}a(fL,"addNatsMsgHeader");function la(e){e=e.toLowerCase();let t=hu.join(vt.get(ye.CONFIG_PARAMS.ROOTPATH),_j);if(e===ye.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(CS)&&(CS={port:fu.getConfigFromFile(ye.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:fu.getConfigFromFile(ye.CONFIG_PARAMS.CLUSTERING_NODENAME)+$t.SERVER_SUFFIX.HUB,config_file:$t.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:hu.join(t,$t.PID_FILES.HUB),hdb_nats_path:t}),CS;if(e===ye.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(wS)&&(wS={port:fu.getConfigFromFile(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:fu.getConfigFromFile(ye.CONFIG_PARAMS.CLUSTERING_NODENAME)+$t.SERVER_SUFFIX.LEAF,config_file:$t.NATS_CONFIG_FILES.LEAF_SERVER,domain:fu.getConfigFromFile(ye.CONFIG_PARAMS.CLUSTERING_NODENAME)+$t.SERVER_SUFFIX.LEAF,pid_file_path:hu.join(t,$t.PID_FILES.LEAF),hdb_nats_path:t}),wS;vn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(la,"getServerConfig");async function EL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:MS.Explicit,durable_name:r,deliver_policy:US.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(EL,"createConsumer");async function Aj(e,t,r){await e.consumers.delete(t,r)}a(Aj,"removeConsumer");function Oj(e){return e.split(".")[1]}a(Oj,"extractServerName");async function bj(e,t,r=6e4,n=PS()){if(!Nd.isObject(t))throw new Error("data param must be an object");let s=oL.encode(t),{connection:i}=await ss(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return LS(c.data)}a(bj,"request");function HS(e){return new Promise(async(t,r)=>{let n=J3(DS,["--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 Nj(){let{pid_file_path:e}=la(ye.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await HS(e)}a(Nj,"reloadNATSHub");async function yj(){let{pid_file_path:e}=la(ye.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await HS(e)}a(yj,"reloadNATSLeaf");function Ij(e,t,r){let n;switch(e.code){case rL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case rL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Ij,"requestErrorHandler");async function wj(e,t){let r=t+$t.SERVER_SUFFIX.LEAF,{connection:n}=await ss(),{jsm:s}=await Bj(r),{schema:i,table:o}=e,c=yd.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await hL(async()=>{if(e.subscribe===!0)await EL(s,c,n.info.server_name,u);else try{await Aj(s,c,n.info.server_name)}catch(_){vn.trace(_)}})}a(wj,"updateRemoteConsumer");async function Cj(e,t,r,n){let s=yd.createNatsTableStreamName(e,t),i=r+$t.SERVER_SUFFIX.LEAF,o={type:ye.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!iL&&ej()<vt.get(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=IS();await c(o)}await X3(o),n==="stop"&&await Nd.async_set_timeout(1e3)}a(Cj,"updateConsumerIterator");function hL(e){return j3.writeTransaction(ye.SYSTEM_SCHEMA_NAME,ye.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(hL,"exclusiveLock");async function mL(e,t){let r=yd.createNatsTableStreamName(e,t),n=await Id(),s=Uj(e,t,n);await BS(r,[s])}a(mL,"createLocalTableStream");async function Dj(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await mL(n,s)}}a(Dj,"createTableStreams");async function pL(e,t,r=void 0){if(vt.get(ye.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=yd.createNatsTableStreamName(e,t),{domain:s}=la(ye.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await mu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")vn.warn(n);else throw n}}a(pL,"purgeTableStream");async function Lj(e,t){if(vt.get(ye.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await pL(e,t[r])}a(Lj,"purgeSchemaTableStreams");async function Mj(e){return(await pu()).streams.info(e)}a(Mj,"getStreamInfo");function Uj(e,t,r){return`${$t.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Uj,"createSubjectName");async function Id(){if(Eu)return Eu;if(Eu=(await pu())?.nc?.info?.server_name,Eu===void 0)throw new Error("Unable to get jetstream manager server name");return Eu}a(Id,"getJsmServerName");async function Pj(){let e=await pu(),t=await Id(),r=await dL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=vj(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");vn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(Pj,"updateLocalStreams");function vj(e){let{config:t}=e,r=!1,n=vt.get(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=vt.get(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=vt.get(ye.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(vj,"updateStreamLimits");async function Bj(e){let t,r;try{t=await mr.jetstream({domain:e}),r=await mr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw vn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(Bj,"connectToRemoteJS")});var Su=R((Ffe,AL)=>{"use strict";var _a=O_(),da=yD(),Hj=$(),xj=require("uuid").v4,qfe=require("clone"),Cd=bs(),fa=M(),Gj=require("util"),di=wn(),{handleHDBError:pr,hdb_errors:qj}=ne(),{HDB_ERROR_MSGS:wd,HTTP_STATUS_CODES:Sr}=qj,{SchemaEventMsg:Dd}=Ln(),TL=it(),{getDatabases:Fj}=(Ae(),ie(Fe)),{transformReq:Ea}=Q();AL.exports={createSchema:kj,createSchemaStructure:gL,createTable:Vj,createTableStructure:RL,createAttribute:Qj,dropSchema:$j,dropTable:Yj,dropAttribute:Kj,getBackup:zj};async function kj(e){let t=await gL(e);return Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),t}a(kj,"createSchema");async function gL(e){let t=_a.schema_object(e);if(t)throw pr(t,t.message,Sr.BAD_REQUEST,void 0,void 0,!0);if(Ea(e),!await da.checkSchemaExists(e.schema))throw pr(new Error,wd.SCHEMA_EXISTS_ERR(e.schema),Sr.BAD_REQUEST,fa.LOG_LEVELS.ERROR,wd.SCHEMA_EXISTS_ERR(e.schema),!0);return await di.createSchema(e),`database '${e.schema}' successfully created`}a(gL,"createSchemaStructure");async function Vj(e){return Ea(e),e.hash_attribute=e.primary_key??e.hash_attribute,await RL(e)}a(Vj,"createTable");async function RL(e){let t=_a.create_table_object(e);if(t)throw pr(t,t.message,Sr.BAD_REQUEST,void 0,void 0,!0);if(_a.validateTableResidence(e.residence),!await da.checkSchemaTableExists(e.schema,e.table))throw pr(new Error,wd.TABLE_EXISTS_ERR(e.schema,e.table),Sr.BAD_REQUEST,fa.LOG_LEVELS.ERROR,wd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:xj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await di.createTable(n,e);else throw pr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Sr.BAD_REQUEST);else await di.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(RL,"createTableStructure");async function $j(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=_a.schema_object(e),n=t??r;if(n)throw pr(n,n.message,Sr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let s=await da.checkSchemaExists(e.schema);if(s)throw pr(new Error,s,Sr.NOT_FOUND,fa.LOG_LEVELS.ERROR,s,!0);let i=await da.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await di.dropSchema(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),await TL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a($j,"dropSchema");async function Yj(e){let t=_a.table_object(e);if(t)throw pr(t,t.message,Sr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let r=await da.checkSchemaTableExists(e.schema,e.table);if(r)throw pr(new Error,r,Sr.NOT_FOUND,fa.LOG_LEVELS.ERROR,r,!0);return await di.dropTable(e),await TL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Yj,"dropTable");async function Kj(e){let t=_a.attribute_object(e);if(t)throw pr(t,t.message,Sr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let r=await da.checkSchemaTableExists(e.schema,e.table);if(r)throw pr(new Error,r,Sr.NOT_FOUND,fa.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw pr(new Error,"You cannot drop a hash attribute",Sr.BAD_REQUEST,void 0,void 0,!0);if(fa.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw pr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Sr.BAD_REQUEST,void 0,void 0,!0);try{return await di.dropAttribute(e),Wj(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Hj.error(`Got an error deleting attribute ${Gj.inspect(e)}.`),n}}a(Kj,"dropAttribute");function Wj(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(Wj,"dropAttributeFromGlobal");async function Qj(e){Ea(e);let t=Fj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw pr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Sr.BAD_REQUEST,void 0,void 0,!0);return await di.createAttribute(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Qj,"createAttribute");function zj(e){return di.getBackup(e)}a(zj,"getBackup")});var bL=R((Vfe,OL)=>{"use strict";var{OPERATIONS_ENUM:Jj}=M(),xS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Jj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};OL.exports=xS});var GS=R((Kfe,CL)=>{"use strict";var jj=wn(),Yfe=bL(),Ld=Q(),Md=M(),Xj=Z(),{handleHDBError:NL,hdb_errors:Zj}=ne(),{HDB_ERROR_MSGS:yL,HTTP_STATUS_CODES:IL}=Zj,eX=Object.values(Md.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),wL="To use this operation audit log must be enabled in harperdb-config.yaml";CL.exports=tX;async function tX(e){if(Ld.isEmpty(e.schema))throw new Error(yL.SCHEMA_REQUIRED_ERR);if(Ld.isEmpty(e.table))throw new Error(yL.TABLE_REQUIRED_ERR);if(!Xj.get(Md.CONFIG_PARAMS.LOGGING_AUDITLOG))throw NL(new Error,wL,IL.BAD_REQUEST,Md.LOG_LEVELS.ERROR,wL,!0);let t=Ld.checkSchemaTableExist(e.schema,e.table);if(t)throw NL(new Error,t,IL.NOT_FOUND,Md.LOG_LEVELS.ERROR,t,!0);if(!Ld.isEmpty(e.search_type)&&eX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await jj.readAuditLog(e)}a(tX,"readAuditLog")});var LL=R((Qfe,DL)=>{"use strict";var{OPERATIONS_ENUM:rX}=M(),qS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=rX.GET_BACKUP,this.schema=t,this.table=r}};DL.exports=qS});var PL=R((Xfe,UL)=>{"use strict";var nX=wn(),Jfe=LL(),FS=Q(),sX=M(),jfe=Z(),{handleHDBError:iX,hdb_errors:oX}=ne(),{HDB_ERROR_MSGS:ML,HTTP_STATUS_CODES:aX}=oX;UL.exports=cX;async function cX(e){if(FS.isEmpty(e.schema))throw new Error(ML.SCHEMA_REQUIRED_ERR);if(FS.isEmpty(e.table))throw new Error(ML.TABLE_REQUIRED_ERR);let t=FS.checkSchemaTableExist(e.schema,e.table);if(t)throw iX(new Error,t,aX.NOT_FOUND,sX.LOG_LEVELS.ERROR,t,!0);return await nX.getBackup(read_audit_log_object)}a(cX,"getBackup")});var qL=R((eEe,GL)=>{var fi=require("validate.js"),BL=je(),ha=M(),{handleHDBError:uX,hdb_errors:lX}=ne(),{HDB_ERROR_MSGS:dt,HTTP_STATUS_CODES:_X}=lX,kS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),dX={STRUCTURE_USER:"structure_user"},vL=Object.values(ha.ROLE_TYPES_ENUM),fX="attribute_permissions",EX="attribute_name",{PERMS_CRUD_ENUM:ma}=ha,hX=[fX,...Object.values(ma)],HL=[ma.READ,ma.INSERT,ma.UPDATE],mX=[EX,...HL];function pX(e){let t=kS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,xL(e,t)}a(pX,"addRoleValidation");function SX(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,xL(e,t)}a(SX,"alterRoleValidation");function TX(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,BL.validateObject(e,t)}a(TX,"dropRoleValidation");var gX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function xL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)gX.includes(n[o])||s.push(n[o]);s.length>0&&Tt(dt.INVALID_ROLE_JSON_KEYS(s),r);let i=BL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Tt(o,r)}),e.permission){let o=RX(e);o&&Tt(o,r),vL.forEach(c=>{e.permission[c]&&!fi.isBoolean(e.permission[c])&&Tt(dt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(vL.indexOf(o)<0){if(o===dX.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]||Tt(dt.SCHEMA_NOT_FOUND(d),r)}continue}Tt(dt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Tt(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]){Tt(dt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{hX.includes(l)||Tt(dt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ma).forEach(l=>{fi.isDefined(_[l])?fi.isBoolean(_[l])||Tt(dt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):Tt(dt.TABLE_PERM_MISSING(l),r,o,u)}),fi.isDefined(_.attribute_permissions)){if(!fi.isArray(_.attribute_permissions)){Tt(dt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Tt(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(p=>{!mX.includes(p)&&p!==ma.DELETE&&Tt(dt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!fi.isDefined(E.attribute_name)){Tt(dt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){Tt(dt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}HL.forEach(p=>{fi.isDefined(E[p])?fi.isBoolean(E[p])||Tt(dt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):Tt(dt.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}`;Tt(dt.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return AX(r)}a(xL,"customValidate");GL.exports={addRoleValidation:pX,alterRoleValidation:SX,dropRoleValidation:TX};function RX(e){let{operation:t,permission:r}=e;if(t===ha.OPERATIONS_ENUM.ADD_ROLE||t===ha.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?ha.ROLE_TYPES_ENUM.SUPER_USER:ha.ROLE_TYPES_ENUM.CLUSTER_USER;return dt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(RX,"validateNoSUPerms");function AX(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 uX(new Error,n,_X.BAD_REQUEST)}else return null}a(AX,"generateRolePermResponse");function Tt(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(Tt,"addPermError")});var QS=R((rEe,$L)=>{"use strict";var FL=Hr(),kL=Br(),OX=oi(),$S=qL(),YS=bs(),bX=require("uuid").v4,NX=require("util"),Ud=M(),yX=Q(),KS=kL.searchByValue,IX=kL.searchByHash,wX=NX.promisify(OX.delete),CX=es(),DX=sa(),{hdb_errors:LX,handleHDBError:uo}=ne(),{HDB_ERROR_MSGS:VL,HTTP_STATUS_CODES:Tu}=LX,{UserEventMsg:WS}=Ln();$L.exports={addRole:MX,alterRole:UX,dropRole:PX,listRoles:vX};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 MX(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,VL.ROLE_ALREADY_EXISTS(e.role),Tu.CONFLICT,void 0,void 0,!0);e.id||(e.id=bX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await FL.insert(s),YS.signalUserChange(new WS(process.pid)),e=VS(e),e}a(MX,"addRole");async function UX(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 FL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",Tu.BAD_REQUEST,void 0,void 0,!0);return await YS.signalUserChange(new WS(process.pid)),e}a(UX,"alterRole");async function PX(e){let t=$S.dropRoleValidation(e);if(t)throw uo(new Error,t,Tu.BAD_REQUEST,void 0,void 0,!0);let r=new DX(Ud.SYSTEM_SCHEMA_NAME,Ud.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await IX(r));if(n.length===0)throw uo(new Error,VL.ROLE_NOT_FOUND,Tu.NOT_FOUND,void 0,void 0,!0);let s=new CX(Ud.SYSTEM_SCHEMA_NAME,Ud.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await KS(s)),o=!1;if(yX.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`,Tu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await wX(c),YS.signalUserChange(new WS(process.pid)),`${n[0].role} successfully deleted`}a(PX,"dropRole");async function vX(){return KS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(vX,"listRoles")});var QL=R((sEe,WL)=>{"use strict";var BX=Z(),Ei=require("joi"),HX=je(),YL=require("moment"),xX=require("fs-extra"),zS=require("path"),GX=require("lodash"),gu=M(),{LOG_LEVELS:lo}=M(),qX="YYYY-MM-DD hh:mm:ss",FX=zS.resolve(__dirname,"../logs");WL.exports=function(e){return HX.validateBySchema(e,kX)};var kX=Ei.object({from:Ei.custom(KL),until:Ei.custom(KL),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(VX)});function KL(e,t){if(YL(e,YL.ISO_8601).format(qX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(KL,"validateDatetime");function VX(e,t){if(GX.invert(gu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=BX.get(gu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?gu.LOG_NAMES.HDB:e,i=s===gu.LOG_NAMES.INSTALL?zS.join(FX,gu.LOG_NAMES.INSTALL):zS.join(n,s);return xX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(VX,"validateReadLogPath")});var jS=R((oEe,JL)=>{"use strict";var Pd=M(),$X=$(),YX=Z(),KX=QL(),JS=require("path"),zL=require("fs-extra"),{once:WX}=require("events"),{handleHDBError:QX,hdb_errors:zX}=ne(),{PACKAGE_ROOT:JX}=M(),jX=JS.join(JX,"logs"),XX=1e3,ZX=200;JL.exports=eZ;async function eZ(e){let t=KX(e);if(t)throw QX(t,t.message,zX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=YX.get(Pd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Pd.LOG_NAMES.HDB:e.log_name,s=n===Pd.LOG_NAMES.INSTALL?JS.join(jX,Pd.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?XX: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(zL.statSync(s).size-(h+5)*ZX,0));let S=zL.createReadStream(s,{start:p});S.on("error",P=>{$X.error(P)});let T=0,A=[],g="",L;S.on("data",P=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;P=g+P;let H=0,j;for(;(j=k.exec(P))&&!S.destroyed;){L&&(L.message=P.slice(H,j.index),v(L));let[z,J,me]=j,ce=me.split("] ["),de=ce[0],De=ce[1];ce.splice(0,2),L={timestamp:J,thread:de,level:De,tags:ce,message:""},H=j.index+z.length}g=P.slice(H)}),S.on("end",P=>{S.destroyed||L&&(L.message=g.trim(),v(L))}),S.resume();function v(P){let k,H,j;switch(!0){case(i&&c&&_):k=new Date(P.timestamp),H=new Date(u),j=new Date(l),P.level===o&&k>=H&&k<=j&&T<E?T++:P.level===o&&k>=H&&k<=j&&(hi(P,f,A),T++,T===h&&S.destroy());break;case(i&&c):k=new Date(P.timestamp),H=new Date(u),P.level===o&&k>=H&&T<E?T++:P.level===o&&k>=H&&(hi(P,f,A),T++,T===h&&S.destroy());break;case(i&&_):k=new Date(P.timestamp),j=new Date(l),P.level===o&&k<=j&&T<E?T++:P.level===o&&k<=j&&(hi(P,f,A),T++,T===h&&S.destroy());break;case(c&&_):k=new Date(P.timestamp),H=new Date(u),j=new Date(l),k>=H&&k<=j&&T<E?T++:k>=H&&k<=j&&(hi(P,f,A),T++,T===h&&S.destroy());break;case i:P.level===o&&T<E?T++:P.level===o&&(hi(P,f,A),T++,T===h&&S.destroy());break;case c:k=new Date(P.timestamp),H=new Date(u),k>=H&&T<E?T++:k>=H&&T>=E&&(hi(P,f,A),T++,T===h&&S.destroy());break;case _:k=new Date(P.timestamp),j=new Date(l),k<=j&&T<E?T++:k<=j&&T>=E&&(hi(P,f,A),T++,T===h&&S.destroy());break;default:T<E?T++:(hi(P,f,A),T++,T===h&&S.destroy())}}return a(v,"onLogMessage"),await WX(S,"close"),A}a(eZ,"readLog");function hi(e,t,r){t==="desc"?tZ(e,r):t==="asc"?rZ(e,r):r.push(e)}a(hi,"pushLineToResult");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,"insertDescending");function rZ(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(rZ,"insertAscending")});var vd=R((_Ee,eM)=>{"use strict";var XS=require("joi"),{string:Ru,boolean:jL,date:nZ}=XS.types(),sZ=je(),{validateSchemaExists:cEe,validateTableExists:uEe,validateSchemaName:lEe}=zn(),iZ=M(),oZ=ke(),XL=Z();XL.initSync();var aZ=Ru.invalid(XL.get(iZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(oZ.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(),ZL={operation:Ru.valid("add_node","update_node","set_node_replication"),node_name:aZ,subscriptions:XS.array().items({table:Ru.optional(),schema:Ru.optional(),database:Ru.optional(),subscribe:jL.required(),publish:jL.required().custom(uZ),start_time:nZ.iso()}).min(1).required()};function cZ(e){return sZ.validateBySchema(e,XS.object(ZL))}a(cZ,"addUpdateNodeValidator");function uZ(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(uZ,"checkForFalsy");eM.exports={addUpdateNodeValidator:cZ,validation_schema:ZL}});var rM=R((fEe,tM)=>{var lZ=je(),_Z={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};tM.exports=function(e){return lZ.validateObject(e,_Z)}});var Bd=R((EEe,nM)=>{"use strict";var dZ=M().OPERATIONS_ENUM,ZS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=dZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};nM.exports=ZS});var iM=R((mEe,sM)=>{"use strict";var fZ={OPERATION:"operation",REFRESH:"refresh"},eT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},tT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};sM.exports={JWTTokens:eT,TOKEN_TYPE_ENUM:fZ,JWTRSAKeys:tT}});var bu=R((SEe,uM)=>{"use strict";var Ou=require("jsonwebtoken"),rT=require("fs-extra"),nT=Q(),ln=M(),{handleHDBError:Tr,hdb_errors:EZ}=ne(),{HTTP_STATUS_CODES:gr,AUTHENTICATION_ERROR_MSGS:Rr}=EZ,Au=$(),oM=G_(),oT=un(),hZ=Hr().update,mZ=Bd(),pZ=bs(),{UserEventMsg:SZ}=Ln(),mi=Z();mi.initSync();var sT=require("path"),{JWTTokens:TZ,JWTRSAKeys:gZ,TOKEN_TYPE_ENUM:Hd}=iM(),RZ=mi.get(ln.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?mi.get(ln.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",AZ=mi.get(ln.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?mi.get(ln.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",xd="RS256",iT;uM.exports={createTokens:OZ,validateOperationToken:NZ,refreshOperationToken:bZ,validateRefreshToken:cM};async function OZ(e){if(nT.isEmpty(e)||typeof e!="object")throw Tr(new Error,Rr.INVALID_AUTH_OBJECT,gr.BAD_REQUEST,void 0,void 0,!0);if(nT.isEmpty(e.username))throw Tr(new Error,Rr.USERNAME_REQUIRED,gr.BAD_REQUEST,void 0,void 0,!0);if(nT.isEmpty(e.password))throw Tr(new Error,Rr.PASSWORD_REQUIRED,gr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await oT.findAndValidateUser(e.username,e.password),!t)throw Tr(new Error,Rr.INVALID_CREDENTIALS,gr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Au.error(f),Tr(new Error,Rr.INVALID_CREDENTIALS,gr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Gd(),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 aM(i,r.private_key,r.passphrase),c=await Ou.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:AZ,algorithm:xd,subject:Hd.REFRESH}),u=oM.hash(c),_=new mZ(ln.SYSTEM_SCHEMA_NAME,ln.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await hZ(_)}catch(f){Au.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw Tr(new Error,Rr.REFRESH_TOKEN_SAVE_FAILED,gr.INTERNAL_SERVER_ERROR);return pZ.signalUserChange(new SZ(process.pid)),new TZ(o,c)}a(OZ,"createTokens");async function aM(e,t,r){return await Ou.sign(e,{key:t,passphrase:r},{expiresIn:RZ,algorithm:xd,subject:Hd.OPERATION})}a(aM,"signOperationToken");async function Gd(){if(iT===void 0)try{let e=sT.join(mi.getHdbBasePath(),ln.LICENSE_KEY_DIR_NAME,ln.JWT_ENUM.JWT_PASSPHRASE_NAME),t=sT.join(mi.getHdbBasePath(),ln.LICENSE_KEY_DIR_NAME,ln.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=sT.join(mi.getHdbBasePath(),ln.LICENSE_KEY_DIR_NAME,ln.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await rT.readFile(e)).toString(),s=(await rT.readFile(t)).toString(),i=(await rT.readFile(r)).toString();iT=new gZ(i,s,n)}catch(e){throw Au.error(e),Tr(new Error,Rr.NO_ENCRYPTION_KEYS,gr.INTERNAL_SERVER_ERROR)}return iT}a(Gd,"getJWTRSAKeys");async function bZ(e){if(!e)throw Tr(new Error,Rr.INVALID_BODY,gr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Tr(new Error,Rr.REFRESH_TOKEN_REQUIRED,gr.BAD_REQUEST,void 0,void 0,!0);await cM(e.refresh_token);let t=await Gd(),r=await Ou.decode(e.refresh_token);return{operation_token:await aM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(bZ,"refreshOperationToken");async function NZ(e){try{let t=await Gd(),r=await Ou.verify(e,t.public_key,{algorithms:xd,subject:Hd.OPERATION});return await oT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Au.warn(t),t.name&&t.name==="TokenExpiredError"?Tr(new Error,Rr.TOKEN_EXPIRED,gr.FORBIDDEN):Tr(new Error,Rr.INVALID_TOKEN,gr.UNAUTHORIZED)}}a(NZ,"validateOperationToken");async function cM(e){let t;try{let r=await Gd(),n=await Ou.verify(e,r.public_key,{algorithms:xd,subject:Hd.REFRESH});t=await oT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Au.warn(r),r.name&&r.name==="TokenExpiredError"?Tr(new Error,Rr.TOKEN_EXPIRED,gr.FORBIDDEN):Tr(new Error,Rr.INVALID_TOKEN,gr.UNAUTHORIZED)}if(!oM.validate(t.refresh_token,e))throw Tr(new Error,Rr.INVALID_TOKEN,gr.UNAUTHORIZED);return t}a(cM,"validateRefreshToken")});var aT=R((REe,dM)=>{"use strict";var yZ=rM(),pa=require("passport"),IZ=require("passport-local").Strategy,wZ=require("passport-http").BasicStrategy,CZ=require("util"),DZ=un(),_M=CZ.callbackify(DZ.findAndValidateUser),gEe=Lr(),LZ=M(),lM=bu();pa.use(new IZ(function(e,t,r){_M(e,t,r)}));pa.use(new wZ(function(e,t,r){_M(e,t,r)}));pa.serializeUser(function(e,t){t(null,e)});pa.deserializeUser(function(e,t){t(null,e)});function MZ(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":pa.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===LZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?lM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):lM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:pa.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(MZ,"authorize");function UZ(e,t){let r=yZ(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(UZ,"checkPermissions");dM.exports={authorize:MZ,checkPermissions:UZ}});var pi=R((OEe,fM)=>{"use strict";var cT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},uT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};fM.exports={Node:cT,NodeSubscription:uT}});var hM=R((NEe,EM)=>{"use strict";var PZ=M().OPERATIONS_ENUM,lT=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=PZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};EM.exports=lT});var Nu=R((IEe,mM)=>{"use strict";var _T=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},dT=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)}};mM.exports={RemotePayloadObject:_T,RemotePayloadSubscription:dT}});var SM=R((CEe,pM)=>{"use strict";var fT=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}};pM.exports=fT});var RM=R((PEe,gM)=>{"use strict";var vZ=SM(),LEe=ut(),TM=Ke(),BZ=$(),{getSchemaPath:MEe,getTransactionAuditStorePath:UEe}=ze(),{getDatabases:HZ}=(Ae(),ie(Fe));gM.exports=xZ;async function xZ(e){let t=new vZ;try{let r=HZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await TM.environmentDataSize(schema_path,e.name),o=await TM.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){BZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(xZ,"lmdbGetTableSize")});var OM=R((BEe,AM)=>{"use strict";var ET=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}};AM.exports=ET});var Sa=R((FEe,wM)=>{"use strict";var GZ=require("fs-extra"),qZ=require("path"),er=require("systeminformation"),Si=$(),bM=it(),xEe=ke(),Fd=M(),FZ=RM(),kZ=As(),{getThreadInfo:NM}=Je(),bT=Z();bT.initSync();var VZ=OM(),{openEnvironment:GEe}=Ke(),{getSchemaPath:qEe}=ze(),{database:$Z,databases:yM}=(Ae(),ie(Fe)),qd;wM.exports={getHDBProcessInfo:ST,getNetworkInfo:gT,getDiskInfo:TT,getMemoryInfo:pT,getCPUInfo:mT,getTimeInfo:hT,getSystemInformation:RT,systemInformation:YZ,getTableSize:AT,getMetrics:OT};function hT(){return er.time()}a(hT,"getTimeInfo");async function mT(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await er.cpu();l.cpu_speed=await er.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:T,...A}=await er.currentLoad();return A.cpus=[],T.forEach(g=>{let{raw_load:L,raw_load_idle:v,raw_load_irq:P,raw_load_nice:k,raw_load_system:H,raw_load_user:j,...z}=g;A.cpus.push(z)}),l.current_load=A,l}catch(e){return Si.error(`error in getCPUInfo: ${e}`),{}}}a(mT,"getCPUInfo");async function pT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await er.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Si.error(`error in getMemoryInfo: ${e}`),{}}}a(pT,"getMemoryInfo");async function ST(){let e={core:[],clustering:[]};try{let t=await er.processes(),r;try{r=Number.parseInt(await GZ.readFile(qZ.join(bT.get(Fd.CONFIG_PARAMS.ROOTPATH),Fd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Fd.NODE_ERROR_CODES.ENOENT)Si.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Si.error(`error in getHDBProcessInfo: ${t}`),e}}a(ST,"getHDBProcessInfo");async function TT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await er.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await er.fsStats();return e.read_write=_,e.size=await er.fsSize(),e}catch(t){return Si.error(`error in getDiskInfo: ${t}`),e}}a(TT,"getDiskInfo");async function gT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await er.networkInterfaceDefault(),e.latency=await er.inetChecksite("google.com"),(await er.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 er.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Si.error(`error in getNetworkInfo: ${t}`),e}}a(gT,"getNetworkInfo");async function RT(){if(qd!==void 0)return qd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await er.osInfo();e=c;let u=await er.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,qd=e,qd}catch(t){return Si.error(`error in getSystemInformation: ${t}`),e}}a(RT,"getSystemInformation");async function AT(){let e=[],t=await kZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await FZ(n));return e}a(AT,"getTableSize");async function OT(){let e={};for(let t in yM){let r=e[t]={};for(let n in yM[t])try{let s=$Z({database:t,table:n}),i=s.getStats();i.readers=s.readerList().split(/\n\s+/).slice(1).map(o=>{let[c,u,_]=o.trim().split(" ");return{pid:c,thread:u,txnid:_}}),r[n]=i}catch(s){Si.notify(`Error getting stats for table ${n}: ${s}`)}}return e}a(OT,"getMetrics");async function IM(){if(bT.get(Fd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await bM.getNATSReferences(),t=await bM.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(IM,"getNatsStreamInfo");async function YZ(e){let t=new VZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await RT(),t.time=hT(),t.cpu=await mT(),t.memory=await pT(),t.disk=await TT(),t.network=await gT(),t.harperdb_processes=await ST(),t.table_size=await AT(),t.metrics=await OT(),t.threads=await NM(),t.replication=await IM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await RT();break;case"time":t.time=hT();break;case"cpu":t.cpu=await mT();break;case"memory":t.memory=await pT();break;case"disk":t.disk=await TT();break;case"network":t.network=await gT();break;case"harperdb_processes":t.harperdb_processes=await ST();break;case"table_size":t.table_size=await AT();break;case"database_metrics":case"metrics":t.metrics=await OT();break;case"threads":t.threads=await NM();break;case"replication":t.replication=await IM();break;default:break}return t}a(YZ,"systemInformation")});var Vd=R((VEe,CM)=>{"use strict";CM.exports={version:KZ,printVersion:WZ};var kd=ou();function KZ(){if(kd)return kd.version}a(KZ,"version");function WZ(){kd&&console.log(`HarperDB Version ${kd.version}`)}a(WZ,"printVersion")});var _n=R((WEe,UM)=>{"use strict";var QZ=Hr(),NT=Q(),zZ=require("util"),_o=M(),DM=Z();DM.initSync();var JZ=aT(),LM=Br(),{Node:YEe,NodeSubscription:KEe}=pi(),jZ=sa(),XZ=hM(),{RemotePayloadObject:ZZ,RemotePayloadSubscription:e5}=Nu(),{handleHDBError:t5,hdb_errors:r5}=ne(),{HTTP_STATUS_CODES:n5,HDB_ERROR_MSGS:s5}=r5,i5=es(),o5=Sa(),a5=Vd(),{getDatabases:c5}=(Ae(),ie(Fe)),u5=zZ.promisify(JZ.authorize),l5=LM.searchByHash,_5=LM.searchByValue;UM.exports={authHeaderToUser:d5,isEmpty:f5,getNodeRecord:E5,upsertNodeRecord:h5,buildNodePayloads:m5,checkClusteringEnabled:p5,getAllNodeRecords:S5,getSystemInfo:T5,reverseSubscription:MM};async function d5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await u5(t,null),e}a(d5,"authHeaderToUser");function f5(e){return e==null}a(f5,"isEmpty");async function E5(e){let t=new jZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return l5(t)}a(E5,"getNodeRecord");async function h5(e){let t=new XZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return QZ.upsert(t)}a(h5,"upsertNodeRecord");function MM(e){if(NT.isEmpty(e.subscribe)||NT.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(MM,"reverseSubscription");function m5(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=NT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=MM(c),E=c5()[u]?.[_],h=new e5(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new ZZ(r,t,s,n)}a(m5,"buildNodePayloads");function p5(){if(!DM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw t5(new Error,s5.CLUSTERING_NOT_ENABLED,n5.BAD_REQUEST,void 0,void 0,!0)}a(p5,"checkClusteringEnabled");async function S5(){let e=new i5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await _5(e))}a(S5,"getAllNodeRecords");async function T5(){let e=await o5.getSystemInformation();return{hdb_version:a5.version(),node_version:e.node_version,platform:e.platform}}a(T5,"getSystemInfo")});var yT=R((zEe,FM)=>{"use strict";var $d=it(),PM=Q(),vM=ke(),BM=M(),Yd=$(),HM=Su(),g5=id(),{RemotePayloadObject:R5}=Nu(),{handleHDBError:xM,hdb_errors:A5}=ne(),{HTTP_STATUS_CODES:GM}=A5,{NodeSubscription:qM}=pi();FM.exports=O5;async function O5(e,t){let r;try{r=await $d.request(`${t}.${vM.REQUEST_SUFFIX}`,new R5(BM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Yd.trace("Response from remote describe all request:",r)}catch(o){Yd.error(`addNode received error from describe all request to remote node: ${o}`);let c=$d.requestErrorHandler(o,"add_node",t);throw xM(new Error,c,GM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===vM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw xM(new Error,o,GM.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===BM.SYSTEM_SCHEMA_NAME){await $d.createLocalTableStream(u,c);let h=new qM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=PM.doesSchemaExist(u),l=n[u]!==void 0,d=c?PM.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(Yd.trace(`addNode creating schema: ${u}`),await HM.createSchema({operation:"create_schema",schema:u})),!d&&f){Yd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new g5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await HM.createTable(h)}await $d.createLocalTableStream(u,c);let E=new qM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(O5,"reviewSubscriptions")});var zd=R((jEe,$M)=>{"use strict";var{handleHDBError:Kd,hdb_errors:b5}=ne(),{HTTP_STATUS_CODES:Wd}=b5,{addUpdateNodeValidator:N5}=vd(),Qd=$(),VM=M(),kM=ke(),y5=Q(),yu=it(),Iu=_n(),I5=Z(),w5=yT(),{Node:C5,NodeSubscription:D5}=pi(),{broadcast:L5}=Je(),M5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",U5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",P5=I5.get(VM.CONFIG_PARAMS.CLUSTERING_NODENAME);$M.exports=v5;async function v5(e,t=!1){Qd.trace("addNode called with:",e),Iu.checkClusteringEnabled();let r=N5(e);if(r)throw Kd(r,r.message,Wd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Iu.getNodeRecord(n);if(!y5.isEmptyOrZeroLength(d))throw Kd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Wd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await w5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=M5,o;let c=Iu.buildNodePayloads(s,P5,VM.OPERATIONS_ENUM.ADD_NODE,await Iu.getSystemInfo()),u=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new D5(E.schema,E.table,E.publish,E.subscribe))}Qd.trace("addNode sending remote payload:",c);let _;try{_=await yu.request(`${n}.${kM.REQUEST_SUFFIX}`,c)}catch(d){Qd.error(`addNode received error from request: ${d}`);for(let E=0,h=s.length;E<h;E++){let p=s[E];p.publish=!1,p.subscribe=!1,await yu.updateRemoteConsumer(p,n)}let f=yu.requestErrorHandler(d,"add_node",n);throw Kd(new Error,f,Wd.INTERNAL_SERVER_ERROR,"error",f)}if(_.status===kM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw Kd(new Error,d,Wd.INTERNAL_SERVER_ERROR,"error",d)}Qd.trace(_);for(let d=0,f=s.length;d<f;d++){let E=s[d];await yu.updateRemoteConsumer(E,n),E.subscribe===!0&&await yu.updateConsumerIterator(E.schema,E.table,n,"start")}let l=new C5(n,u,_.system_info);return await Iu.upsertNodeRecord(l),L5({type:"nats_update"}),i.length>0?o.message=U5:o.message=`Successfully added '${n}' to manifest`,o}a(v5,"addNode")});var CT=R((ehe,WM)=>{"use strict";var{handleHDBError:IT,hdb_errors:B5}=ne(),{HTTP_STATUS_CODES:wT}=B5,{addUpdateNodeValidator:H5}=vd(),wu=$(),KM=M(),YM=ke(),ZEe=Q(),Cu=it(),Du=_n(),x5=Z(),{cloneDeep:G5}=require("lodash"),q5=yT(),{Node:F5,NodeSubscription:k5}=pi(),{broadcast:V5}=Je(),$5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Y5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",K5=x5.get(KM.CONFIG_PARAMS.CLUSTERING_NODENAME);WM.exports=W5;async function W5(e){wu.trace("updateNode called with:",e),Du.checkClusteringEnabled();let t=H5(e);if(t)throw IT(t,t.message,wT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Du.getNodeRecord(r);s.length>0&&(n=G5(s));let{added:i,skipped:o}=await q5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=$5,c;let u=Du.buildNodePayloads(i,K5,KM.OPERATIONS_ENUM.UPDATE_NODE,await Du.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let f=i[l];wu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),i[l].start_time===void 0&&delete i[l].start_time}wu.trace("updateNode sending remote payload:",u);let _;try{_=await Cu.request(`${r}.${YM.REQUEST_SUFFIX}`,u)}catch(l){wu.error(`updateNode received error from request: ${l}`);let d=Cu.requestErrorHandler(l,"update_node",r);throw IT(new Error,d,wT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===YM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw IT(new Error,l,wT.INTERNAL_SERVER_ERROR,"error",l)}wu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];await Cu.updateRemoteConsumer(f,r),f.subscribe===!0?await Cu.updateConsumerIterator(f.schema,f.table,r,"start"):await Cu.updateConsumerIterator(f.schema,f.table,r,"stop")}return n||(n=[new F5(r,[],_.system_info)]),await Q5(n[0],i,_.system_info),o.length>0?c.message=Y5:c.message=`Successfully updated '${r}'`,c}a(W5,"updateNode");async function Q5(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 k5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Du.upsertNodeRecord(n),V5({type:"nats_update"})}a(Q5,"updateNodeTable")});var XM=R((rhe,jM)=>{"use strict";var JM=require("joi"),{string:QM}=JM.types(),z5=je(),zM=M(),J5=Z(),j5=ke();jM.exports=X5;function X5(e){let t=QM.invalid(J5.get(zM.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=JM.object({operation:QM.valid(zM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return z5.validateBySchema(e,r)}a(X5,"removeNodeValidator")});var jd=R((she,nU)=>{"use strict";var{handleHDBError:ZM,hdb_errors:Z5}=ne(),{HTTP_STATUS_CODES:eU}=Z5,e8=XM(),Lu=$(),tU=_n(),t8=Q(),Jd=M(),rU=ke(),DT=it(),r8=Z(),{RemotePayloadObject:n8}=Nu(),{NodeSubscription:s8}=pi(),i8=ia(),o8=oi(),{broadcast:a8}=Je(),c8=r8.get(Jd.CONFIG_PARAMS.CLUSTERING_NODENAME);nU.exports=u8;async function u8(e){Lu.trace("removeNode called with:",e),tU.checkClusteringEnabled();let t=e8(e);if(t)throw ZM(t,t.message,eU.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await tU.getNodeRecord(r);if(t8.isEmptyOrZeroLength(n))throw ZM(new Error,`Node '${r}' was not found.`,eU.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new n8(Jd.OPERATIONS_ENUM.REMOVE_NODE,c8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await DT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await DT.updateRemoteConsumer(new s8(l.schema,l.table,!1,!1),r)}catch(d){Lu.error(d)}}try{i=await DT.request(`${r}.${rU.REQUEST_SUFFIX}`,s),Lu.trace("Remove node reply from remote node:",r,i)}catch(u){Lu.error("removeNode received error from request:",u),o=!0}let c=new i8(Jd.SYSTEM_SCHEMA_NAME,Jd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await o8.deleteRecord(c),a8({type:"nats_update"}),i?.status===rU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Lu.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(u8,"removeNode")});var oU=R((ohe,iU)=>{"use strict";var sU=require("joi"),{string:l8,array:_8}=sU.types(),d8=je(),f8=vd();iU.exports=E8;function E8(e){let t=sU.object({operation:l8.valid("configure_cluster").required(),connections:_8.items(f8.validation_schema).required()});return d8.validateBySchema(e,t)}a(E8,"configureClusterValidator")});var LT=R((che,_U)=>{"use strict";var h8=M(),Xd=$(),m8=Q(),p8=jd(),S8=zd(),aU=_n(),T8=oU(),{handleHDBError:cU,hdb_errors:g8}=ne(),{HTTP_STATUS_CODES:uU}=g8,R8="Configure cluster complete.",A8="Failed to configure the cluster. Check the logs for more details.",O8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";_U.exports=b8;async function b8(e){Xd.trace("configure cluster called with:",e),aU.checkClusteringEnabled();let t=T8(e);if(t)throw cU(t,t.message,uU.BAD_REQUEST,void 0,void 0,!0);let r=await aU.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let f=await lU(p8,{operation:h8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(f)}Xd.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],f=await lU(S8,d,d.node_name);s.push(f)}Xd.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let f=_[l];f.status==="rejected"&&(Xd.error(f),o.includes(f.node_name)||o.push(f.node_name)),(f?.result?.message?.includes?.("Successfully")||f?.result?.includes?.("Successfully"))&&(u=!0),!(typeof f.result=="string"&&f.result.includes("Successfully removed")||f.status==="rejected")&&c.push({node_name:f?.node_name,subscriptions:f?.result})}if(m8.isEmptyOrZeroLength(o))return{message:R8,connections:c};if(u)return{message:O8,failed_nodes:o,connections:c};throw cU(new Error,A8,uU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(b8,"configureCluster");async function lU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(lU,"functionWrapper")});var hU=R((lhe,EU)=>{"use strict";var Mu=require("joi"),N8=je(),{validateSchemaExists:dU,validateTableExists:y8,validateSchemaName:fU}=zn(),I8=Mu.object({operation:Mu.string().valid("purge_stream"),schema:Mu.string().custom(dU).custom(fU).optional(),database:Mu.string().custom(dU).custom(fU).optional(),table:Mu.string().custom(y8).required()});function w8(e){return N8.validateBySchema(e,I8)}a(w8,"purgeStreamValidator");EU.exports=w8});var MT=R((dhe,mU)=>{"use strict";var{handleHDBError:C8,hdb_errors:D8}=ne(),{HTTP_STATUS_CODES:L8}=D8,M8=hU(),U8=it(),P8=_n();mU.exports=v8;async function v8(e){e.schema=e.schema??e.database;let t=M8(e);if(t)throw C8(t,t.message,L8.BAD_REQUEST,void 0,void 0,!0);P8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await U8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(v8,"purgeStream")});var vT=R((Ehe,AU)=>{"use strict";var PT=_n(),B8=it(),TU=Z(),Zd=M(),fo=ke(),H8=Q(),UT=$(),{RemotePayloadObject:x8}=Nu(),{ErrorCode:pU}=require("nats"),SU=TU.get(Zd.CONFIG_PARAMS.CLUSTERING_ENABLED),gU=TU.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);AU.exports={clusterStatus:G8,buildNodeStatus:RU};async function G8(){let e={node_name:gU,is_enabled:SU,connections:[]};if(!SU)return e;let t=await PT.getAllNodeRecords();if(H8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(RU(t[n],e.connections));return await Promise.allSettled(r),e}a(G8,"clusterStatus");async function RU(e,t){let r=e.name,n=new x8(Zd.OPERATIONS_ENUM.CLUSTER_STATUS,gU,void 0,await PT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await B8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,UT.error(`Error getting node status from ${r} `,s))}catch(u){UT.warn(`Error getting node status from ${r}`,u),u.code===pU.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===pU.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new q8(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!==Zd.PRE_4_0_0_VERSION&&await PT.upsertNodeRecord(u)}catch(u){UT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(RU,"buildNodeStatus");function q8(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(q8,"NodeStatusObject")});var HT=R((mhe,OU)=>{"use strict";var{handleHDBError:F8,hdb_errors:k8}=ne(),{HTTP_STATUS_CODES:V8}=k8,$8=it(),Y8=_n(),BT=Q(),ef=require("joi"),K8=je(),W8=2e3,Q8=ef.object({timeout:ef.number().min(1),connected_nodes:ef.boolean(),routes:ef.boolean()});OU.exports=z8;async function z8(e){Y8.checkClusteringEnabled();let t=K8.validateBySchema(e,Q8);if(t)throw F8(t,t.message,V8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||BT.autoCastBoolean(n),o=s===void 0||BT.autoCastBoolean(s),c={nodes:[]},u=await $8.getServerList(r??W8),_={};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:BT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(z8,"clusterNetwork")});var IU=R((She,yU)=>{"use strict";var xT=require("joi"),bU=je(),{route_constraints:NU}=tp();yU.exports={setRoutesValidator:J8,deleteRoutesValidator:j8};function J8(e){let t=xT.object({server:xT.valid("hub","leaf").required(),routes:NU.required()});return bU.validateBySchema(e,t)}a(J8,"setRoutesValidator");function j8(e){let t=xT.object({routes:NU.required()});return bU.validateBySchema(e,t)}a(j8,"deleteRoutesValidator")});var qT=R((ghe,LU)=>{"use strict";var Eo=dr(),GT=Q(),tf=M(),wU=IU(),{handleHDBError:CU,hdb_errors:X8}=ne(),{HTTP_STATUS_CODES:DU}=X8,Z8="cluster routes successfully set",e6="cluster routes successfully deleted";LU.exports={setRoutes:t6,getRoutes:r6,deleteRoutes:n6};function t6(e){let t=wU.setRoutesValidator(e);if(t)throw CU(t,t.message,DU.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=GT.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(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:Z8,set:o,skipped:i}}a(t6,"setRoutes");function r6(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(r6,"getRoutes");function n6(e){let t=wU.deleteRoutesValidator(e);if(t)throw CU(t,t.message,DU.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 p=n[E];if(d.host===p.host&&d.port===p.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=GT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=GT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:e6,deleted:i,skipped:o}}a(n6,"deleteRoutes")});var UU=R((Ahe,MU)=>{"use strict";var Uu=require("alasql"),ho=require("recursive-iterator"),Bn=$(),s6=Q(),Pu=M(),FT=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,o6(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=>Pu.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=>!Pu.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][Pu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=i6(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(_=>!Pu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Uu.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 i6(e){return e.filter(t=>t[Pu.PERMS_CRUD_ENUM.READ])}a(i6,"filterReadRestrictedAttrs");function o6(e,t,r,n,s){a6(e,t,r,n,s)}a(o6,"interpretAST");function vu(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(vu,"addSchemaTableToMap");function a6(e,t,r,n,s){if(!e){Bn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Uu.yy.Insert?_6(e,t,r):e instanceof Uu.yy.Select?c6(e,t,r,n,s):e instanceof Uu.yy.Update?u6(e,t,r):e instanceof Uu.yy.Delete?l6(e,t,r):Bn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(a6,"getRecordAttributesAST");function c6(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(s6.isEmptyOrZeroLength(i)){Bn.error("No schema specified");return}e.from.forEach(c=>{vu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),vu(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(c6,"getSelectAttributes");function u6(e,t,r){if(!e){Bn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;vu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&kT(e.table.tableid,s,i.columnid,t,r)}a(u6,"getUpdateAttributes");function l6(e,t,r){if(!e){Bn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;vu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&kT(e.table.tableid,s,i.columnid,t,r)}a(l6,"getDeleteAttributes");function _6(e,t,r){if(!e){Bn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;vu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&kT(e.into.tableid,s,i.columnid,t,r)}a(_6,"getInsertAttributes");function kT(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(kT,"pushAttribute");MU.exports=FT});var YT=R((bhe,HU)=>{var rf=Ji(),PU=require("chalk"),Kr=$(),vU=require("prompt"),{promisify:d6}=require("util"),VT=M(),f6=require("fs-extra"),E6=require("path"),h6=Q(),m6=Vd(),BU=Z();BU.initSync();var p6=require("moment"),S6=d6(vU.get),T6=E6.join(BU.getHdbBasePath(),VT.LICENSE_KEY_DIR_NAME,VT.LICENSE_FILE_NAME,VT.LICENSE_FILE_NAME);HU.exports={getFingerprint:R6,setLicense:g6,parseLicense:$T,register:A6,getRegistrationInfo:b6};async function g6(e){if(e&&e.key&&e.company){try{Kr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await $T(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Kr.error(r),Kr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(g6,"setLicense");async function R6(){let e={};try{e=await rf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Kr.error(r),Kr.error(t),new Error(r)}return e}a(R6,"getFingerprint");async function $T(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Kr.info("Validating license input...");let r=rf.validateLicense(e,t);if(Kr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Kr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Kr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Kr.info("writing license to disk"),await f6.writeFile(T6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Kr.error("Failed to write License"),n}return"Registration successful."}a($T,"parseLicense");async function A6(){let e=await O6();return $T(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(A6,"register");async function O6(){let e=await rf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:PU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:PU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{vU.start()}catch(n){Kr.error(n)}let r;try{r=await S6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(O6,"promptForRegistration");async function b6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await rf.getLicense()}catch(r){throw Kr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(h6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=m6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=p6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(b6,"getRegistrationInfo")});var GU=R((yhe,xU)=>{"use strict";var N6=ke(),KT=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+N6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file: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"}};xU.exports=KT});var kU=R((whe,FU)=>{"use strict";var qU=ke(),WT=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+qU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+qU.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"}};FU.exports=WT});var $U=R((Dhe,VU)=>{"use strict";var QT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};VU.exports=QT});var KU=R((Mhe,YU)=>{"use strict";var y6=ke(),zT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+y6.SERVER_SUFFIX.ADMIN,this.password=r}};YU.exports=zT});var XT=R((Phe,zU)=>{"use strict";var Ta=require("path"),of=require("fs-extra"),I6=GU(),w6=kU(),C6=$U(),D6=KU(),JT=un(),Ra=Q(),Ar=dr(),sf=M(),Bu=ke(),{CONFIG_PARAMS:ft}=sf,Aa=$(),Hu=Z(),WU=Rs(),jT=it(),ga="clustering",L6=1e4,QU=50;zU.exports={generateNatsConfig:U6,removeNatsConfig:P6,getHubConfigPath:M6};function M6(){let e=Hu.get(ft.ROOTPATH);return Ta.join(e,ga,Bu.NATS_CONFIG_FILES.HUB_SERVER)}a(M6,"getHubConfigPath");async function U6(e=!1,t=void 0){Hu.initSync();let r=Hu.get(ft.ROOTPATH),n=Ta.join(r,ga,Bu.PID_FILES.HUB),s=Ta.join(r,ga,Bu.PID_FILES.LEAF),i=Ar.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ta.join(r,ga,Bu.NATS_CONFIG_FILES.HUB_SERVER),c=Ta.join(r,ga,Bu.NATS_CONFIG_FILES.LEAF_SERVER),u=Ar.getConfigFromFile(ft.CLUSTERING_TLS_CERTIFICATE),_=Ar.getConfigFromFile(ft.CLUSTERING_TLS_PRIVATEKEY),l=Ar.getConfigFromFile(ft.CLUSTERING_TLS_CERT_AUTH),d=Ar.getConfigFromFile(ft.CLUSTERING_TLS_INSECURE),f=Ar.getConfigFromFile(ft.CLUSTERING_TLS_VERIFY),E=Ar.getConfigFromFile(ft.CLUSTERING_NODENAME),h=Ar.getConfigFromFile(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await jT.checkNATSServerInstalled()||af("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await JT.listUsers(),S=Ar.getConfigFromFile(ft.CLUSTERING_USER),T=await JT.getClusterUser();(Ra.isEmpty(T)||T.active!==!0)&&af(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await nf(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await nf(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await nf(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),await nf(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],g=[];for(let[z,J]of p.entries())J.role.role===sf.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(A.push(new D6(J.username,WU.decrypt(J.hash))),g.push(new C6(J.username,WU.decrypt(J.hash))));let L=[],{hub_routes:v}=Ar.getClusteringRoutes();if(!Ra.isEmptyOrZeroLength(v))for(let z of v)L.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${z.host}:${z.port}`);let P=new I6(Ar.getConfigFromFile(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,Ar.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NAME),Ar.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),L,A,g);l==null&&(delete P.tls.ca_file,delete P.leafnodes.tls.ca_file),t=Ra.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===sf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await of.writeJson(o,P),Aa.trace(`Hub server config written to ${o}`));let k=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,H=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,j=new w6(Ar.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[k],[H],A,g,u,_,l,d);l==null&&delete j.tls.ca_file,(t===void 0||t===sf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await of.writeJson(c,j),Aa.trace(`Leaf server config written to ${c}`))}a(U6,"generateNatsConfig");async function nf(e){let t=Hu.get(e);return Ra.isEmpty(t)&&af(`port undefined for '${e}'`),await Ra.isPortTaken(t)&&af(`'${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(nf,"isPortAvailable");function af(e){let t=`Error generating clustering config: ${e}`;Aa.error(t),console.error(t),process.exit(1)}a(af,"generateNatsConfigError");async function P6(e){let{port:t,config_file:r}=jT.getServerConfig(e),{username:n,decrypt_hash:s}=await JT.getClusterUser(),i=0,o=2e3;for(;i<QU;){try{let l=await jT.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){Aa.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=QU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&Aa.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Ra.async_set_timeout(_)}let c="0".repeat(L6),u=Ta.join(Hu.get(ft.ROOTPATH),ga,r);await of.writeFile(u,c),await of.remove(u),Aa.notify(e,"started.")}a(P6,"removeNatsConfig")});var tP=R((Bhe,eP)=>{"use strict";var Wr=Z(),v6=Ji(),he=M(),xu=ke(),Cs=require("path"),{PACKAGE_ROOT:uf}=M(),JU=Z(),cf=Q(),Oa="/dev/null",B6=Cs.join(uf,"launchServiceScripts"),jU=Cs.join(uf,"utility/scripts"),H6=Cs.join(jU,he.HDB_RESTART_SCRIPT),XU=Cs.resolve(uf,"dependencies",`${process.platform}-${process.arch}`,xu.NATS_BINARY_NAME);function ZU(){let t=v6.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,n={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return cf.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=cf.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:uf}}a(ZU,"generateMainServerConfig");var x6=9930;function G6(){Wr.initSync(!0);let e=Wr.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",xu.NATS_CONFIG_FILES.HUB_SERVER),r=Cs.join(Wr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=JU.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=xu.LOG_LEVEL_FLAGS[Wr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==x6?"-"+n:""),script:XU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Wr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Oa,i.error_file=Oa),i}a(G6,"generateNatsHubServerConfig");var q6=9940;function F6(){Wr.initSync(!0);let e=Wr.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",xu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cs.join(Wr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=JU.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=xu.LOG_LEVEL_FLAGS[Wr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==q6?"-"+n:""),script:XU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Wr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Oa,i.error_file=Oa),i}a(F6,"generateNatsLeafServerConfig");function k6(){Wr.initSync();let e=Cs.join(Wr.get(he.CONFIG_PARAMS.LOGGING_ROOT),he.LOG_NAMES.HDB),t={name:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:he.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:B6,autorestart:!1};return Wr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Oa,t.error_file=Oa),t}a(k6,"generateClusteringUpgradeV4ServiceConfig");function V6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return cf.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=cf.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:jU},script:H6}}a(V6,"generateRestart");function $6(){return{apps:[ZU()]}}a($6,"generateAllServiceConfigs");eP.exports={generateAllServiceConfigs:$6,generateMainServerConfig:ZU,generateRestart:V6,generateNatsHubServerConfig:G6,generateNatsLeafServerConfig:F6,generateClusteringUpgradeV4ServiceConfig:k6}});var hP=R((Ghe,EP)=>{"use strict";var Pe=M(),Y6=Q(),Ls=XT(),lf=it(),Ds=ke(),Ti=tP(),_f=Z(),gi=$(),K6=_n(),{startWorker:rP,onMessageFromWorkers:W6}=Je(),Q6=Sa(),xhe=require("util"),z6=require("child_process"),J6=require("fs"),{execFile:j6}=z6,Ie;EP.exports={enterPM2Mode:X6,start:Ri,stop:ZT,reload:sP,restart:iP,list:eg,describe:aP,connect:Ms,kill:n9,startAllServices:s9,startService:tg,getUniqueServicesList:cP,restartAllServices:i9,isServiceRegistered:uP,reloadStopStart:lP,restartHdb:oP,deleteProcess:t9,startClusteringProcesses:dP,startClusteringThreads:fP,isHdbRestartRunning:r9,isClusteringRunning:a9,stopClustering:o9,reloadClustering:c9};var Gu=!1;W6(e=>{e.type==="restart"&&_f.initSync(!0)});function X6(){Gu=!0}a(X6,"enterPM2Mode");function Ms(){return Ie||(Ie=require("pm2")),new Promise((e,t)=>{Ie.connect((r,n)=>{gi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ms,"connect");var Or,Z6=10,nP;function Ri(e,t=!1){if(Gu)return e9(e);let r=j6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Or.indexOf(r);o>-1&&Or.splice(o,1),!nP&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<Z6&&(J6.existsSync(Ls.getHubConfigPath())?Ri(e):(await Ls.generateNatsConfig(!0),Ri(e),await new Promise(c=>setTimeout(c,3e3)),await Ls.removeNatsConfig(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ls.removeNatsConfig(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=_f.get(Pe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Ds.LOG_LEVELS[f]}if(Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Or=[],!Or&&!t){let i=a(()=>{nP=!0,Or&&(Or.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)}Or.push(r)}a(Ri,"start");function e9(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.start(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(e9,"startWithPM2");function ZT(e){if(!Gu){for(let t of Or||[])t.name===e&&(Or.splice(Or.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.stop(e,async(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.delete(e,(i,o)=>{i&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(o)})})})}a(ZT,"stop");function sP(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.reload(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(sP,"reload");function iP(e){if(!Gu)for(let t of Or||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.restart(e,(n,s)=>{Ie.disconnect(),t(s)})})}a(iP,"restart");function t9(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.delete(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(t9,"deleteProcess");async function oP(){await Ri(Ti.generateRestart())}a(oP,"restartHdb");async function r9(){let e=await eg();for(let t in e)if(e[t].name===Pe.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(r9,"isHdbRestartRunning");function eg(){return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}Ie.list((r,n)=>{r&&(Ie.disconnect(),t(r)),Ie.disconnect(),e(n)})})}a(eg,"list");function aP(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ie.describe(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(aP,"describe");function n9(){if(!Gu){for(let e of Or||[])e.kill();Or=[];return}return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}Ie.killDaemon((r,n)=>{r&&(Ie.disconnect(),t(r)),Ie.disconnect(),e(n)})})}a(n9,"kill");async function s9(){try{await dP(),await fP(),await Ri(Ti.generateAllServiceConfigs())}catch(e){throw Ie?.disconnect(),e}}a(s9,"startAllServices");async function tg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Pe.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ti.generateMainServerConfig();break;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ti.generateNatsIngestServiceConfig();break;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ti.generateNatsReplyServiceConfig();break;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ti.generateNatsHubServerConfig(),await Ri(r,t),await Ls.removeNatsConfig(e);return;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ti.generateNatsLeafServerConfig(),await Ri(r,t),await Ls.removeNatsConfig(e);return;case Pe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ti.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ri(r)}catch(r){throw Ie?.disconnect(),r}}a(tg,"startService");async function cP(){try{let e=await eg(),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 Ie?.disconnect(),e}}a(cP,"getUniqueServicesList");async function i9(e=[]){try{let t=!1,r=await cP();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Pe.PROCESS_DESCRIPTORS.HDB?t=!0:await iP(o))}t&&await lP(Pe.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ie?.disconnect(),t}}a(i9,"restartAllServices");async function uP(e){if(Or?.find(r=>r.name===e))return!0;let t=await Q6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(uP,"isServiceRegistered");async function lP(e){let t=_f.get(Pe.CONFIG_PARAMS.THREADS_COUNT)??_f.get(Pe.CONFIG_PARAMS.THREADS),r=await aP(e),n=Y6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await ZT(e),await tg(e)):e===Pe.PROCESS_DESCRIPTORS.HDB?await oP():await sP(e)}a(lP,"reloadStopStart");var _P;async function dP(e=!1){for(let t in Pe.CLUSTERING_PROCESSES){let r=Pe.CLUSTERING_PROCESSES[t];await tg(r,e)}}a(dP,"startClusteringProcesses");async function fP(){_P=rP(Pe.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Pe.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await lf.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await lf.updateLocalStreams();let e=await K6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Pe.PRE_4_0_0_VERSION){gi.info("Starting clustering upgrade 4.0.0 process"),rP(Pe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(fP,"startClusteringThreads");async function o9(){for(let e in Pe.CLUSTERING_PROCESSES)if(e!==Pe.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Pe.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await _P.terminate();else{let t=Pe.CLUSTERING_PROCESSES[e];await ZT(t)}}a(o9,"stopClustering");async function a9(){for(let e in Pe.CLUSTERING_PROCESSES){let t=Pe.CLUSTERING_PROCESSES[e];if(await uP(t)===!1)return!1}return!0}a(a9,"isClusteringRunning");async function c9(){await Ls.generateNatsConfig(!0),await lf.reloadNATSHub(),await lf.reloadNATSLeaf(),await Ls.removeNatsConfig(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ls.removeNatsConfig(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(c9,"reloadClustering")});var AP={};qe(AP,{compactOnStart:()=>u9,copyDb:()=>RP});async function u9(){Fu.notify("Running compact on start"),console.log("Running compact on start");let e=(0,rg.get)(Ai.CONFIG_PARAMS.ROOTPATH),t=new Map,r=Er();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,df.join)(e,"backup",n+".mdb"),o=(0,df.join)(e,Ai.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await mP(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await RP(n,o),console.log("Backing up",n,"to",i),await(0,mo.move)(s,i,{overwrite:!0})}qu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,mo.move)(i,s,{overwrite:!0}),await(0,mo.remove)((0,df.join)(e,Ai.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));qu()}catch(n){Fu.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,ng.updateConfigValue)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,mo.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw qu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await mP(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
10
+ `,"")}a(lL,"runCommand");async function Ej(){try{await Y3.access(LS)}catch{return!1}let e=await lL(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return K3.eq(t,dj)}a(Ej,"checkNATSServerInstalled");async function BS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await cL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bn.trace("create nats connection called");let i=await rj({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),_L()}),i}a(BS,"createConnection");function _L(){Sr=void 0,io=void 0,oo=void 0,ao=void 0}a(_L,"clearClientCache");async function hj(){Sr&&(await Sr.drain(),Sr=void 0,io=void 0,oo=void 0,ao=void 0)}a(hj,"closeConnection");var Sr,ao;async function pu(){return ao||(ao=BS(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Sr=await ao),Sr||ao}a(pu,"getConnection");async function Su(){if(io)return io;co(Sr)&&await pu();let{domain:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await Sr.jetstreamManager({domain:e,timeout:6e4}),io}a(Su,"getJetStreamManager");async function dL(){if(oo)return oo;co(Sr)&&await pu();let{domain:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=Sr.jetstream({domain:e,timeout:6e4}),oo}a(dL,"getJetStream");async function ss(){let e=Sr||await pu(),t=io||await Su(),r=oo||await dL();return{connection:e,jsm:t,js:r}}a(ss,"getNATSReferences");async function mj(e){let t=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await cL.getClusterUser(),s=await BS(t,r,n),i=vS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=uL.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 wd.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(mj,"getServerList");async function HS(e,t){let{jsm:r}=await ss(),n=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:nj.File,retention:sj.Limits,subjects:t,discard:ij.Old,max_msgs:s,max_bytes:i,max_age:n})}a(HS,"createLocalStream");async function fL(){let{jsm:e}=await ss(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(fL,"listStreams");async function pj(e){let{jsm:t}=await ss();await t.streams.delete(e)}a(pj,"deleteLocalStream");async function Sj(e){let{connection:t}=await ss(),r=[],n=vS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(uL.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(Sj,"listRemoteStreams");async function Tj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=sL(),o={durable_name:i,ack_policy:PS.Explicit};t&&(o.deliver_policy=US.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=MS(l.data),E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(E.origin=l.headers.get(Yt.MSG_HEADERS.ORIGIN)),_.push(E),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Tj,"viewStream");async function*gj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=sL(),o={durable_name:i,ack_policy:PS.Explicit};t&&(o.deliver_policy=US.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=MS(_.data);l[0]||(l=[l]);for(let d of l){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(Yt.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(gj,"viewStreamIterator");async function Rj(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=EL(n,r);let{js:s}=await ss(),i=await Dd(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:aL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),lj(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 mL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await HS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(Rj,"publishToStream");function EL(e,t){t===void 0&&(t=aj());let r=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Yt.MSG_HEADERS.ORIGIN)&&r&&t.append(Yt.MSG_HEADERS.ORIGIN,r),t}a(EL,"addNatsMsgHeader");function _a(e){e=e.toLowerCase();let t=mu.join(Bt.get(Ie.CONFIG_PARAMS.ROOTPATH),_j);if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(DS)&&(DS={port:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.HUB,config_file:Yt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:mu.join(t,Yt.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(CS)&&(CS={port:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.LEAF,config_file:Yt.NATS_CONFIG_FILES.LEAF_SERVER,domain:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.LEAF,pid_file_path:mu.join(t,Yt.PID_FILES.LEAF),hdb_nats_path:t}),CS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(_a,"getServerConfig");async function hL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:PS.Explicit,durable_name:r,deliver_policy:US.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(hL,"createConsumer");async function Aj(e,t,r){await e.consumers.delete(t,r)}a(Aj,"removeConsumer");function Oj(e){return e.split(".")[1]}a(Oj,"extractServerName");async function bj(e,t,r=6e4,n=vS()){if(!wd.isObject(t))throw new Error("data param must be an object");let s=aL.encode(t),{connection:i}=await ss(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return MS(c.data)}a(bj,"request");function xS(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(xS,"reloadNATS");async function yj(){let{pid_file_path:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await xS(e)}a(yj,"reloadNATSHub");async function Nj(){let{pid_file_path:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await xS(e)}a(Nj,"reloadNATSLeaf");function Ij(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(Ij,"requestErrorHandler");async function wj(e,t){let r=t+Yt.SERVER_SUFFIX.LEAF,{connection:n}=await ss(),{jsm:s}=await Bj(r),{schema:i,table:o}=e,c=Cd.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await mL(async()=>{if(e.subscribe===!0)await hL(s,c,n.info.server_name,u);else try{await Aj(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(wj,"updateRemoteConsumer");async function Cj(e,t,r,n){let s=Cd.createNatsTableStreamName(e,t),i=r+Yt.SERVER_SUFFIX.LEAF,o={type:Ie.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!oL&&ej()<Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=wS();await c(o)}await X3(o),n==="stop"&&await wd.async_set_timeout(1e3)}a(Cj,"updateConsumerIterator");function mL(e){return j3.writeTransaction(Ie.SYSTEM_SCHEMA_NAME,Ie.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(mL,"exclusiveLock");async function pL(e,t){let r=Cd.createNatsTableStreamName(e,t),n=await Dd(),s=Pj(e,t,n);await HS(r,[s])}a(pL,"createLocalTableStream");async function Dj(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await pL(n,s)}}a(Dj,"createTableStreams");async function SL(e,t,r=void 0){if(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Cd.createNatsTableStreamName(e,t),{domain:s}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await pu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(SL,"purgeTableStream");async function Lj(e,t){if(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await SL(e,t[r])}a(Lj,"purgeSchemaTableStreams");async function Mj(e){return(await Su()).streams.info(e)}a(Mj,"getStreamInfo");function Pj(e,t,r){return`${Yt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Pj,"createSubjectName");async function Dd(){if(hu)return hu;if(hu=(await Su())?.nc?.info?.server_name,hu===void 0)throw new Error("Unable to get jetstream manager server name");return hu}a(Dd,"getJsmServerName");async function Uj(){let e=await Su(),t=await Dd(),r=await fL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=vj(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(Uj,"updateLocalStreams");function vj(e){let{config:t}=e,r=!1,n=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Bt.get(Ie.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(vj,"updateStreamLimits");async function Bj(e){let t,r;try{t=await Sr.jetstream({domain:e}),r=await Sr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(Bj,"connectToRemoteJS")});var Tu=g((qfe,OL)=>{"use strict";var da=y_(),fa=ID(),Hj=$(),xj=require("uuid").v4,Gfe=require("clone"),Md=bs(),Ea=P(),Gj=require("util"),di=Cn(),{handleHDBError:Tr,hdb_errors:qj}=ne(),{HDB_ERROR_MSGS:Ld,HTTP_STATUS_CODES:gr}=qj,{SchemaEventMsg:Pd}=Mn(),gL=ot(),{getDatabases:Fj}=(Oe(),ie(Fe)),{transformReq:ha}=J();OL.exports={createSchema:kj,createSchemaStructure:RL,createTable:Vj,createTableStructure:AL,createAttribute:Qj,dropSchema:$j,dropTable:Yj,dropAttribute:Kj,getBackup:zj};async function kj(e){let t=await RL(e);return Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema)),t}a(kj,"createSchema");async function RL(e){let t=da.schema_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);if(ha(e),!await fa.checkSchemaExists(e.schema))throw Tr(new Error,Ld.SCHEMA_EXISTS_ERR(e.schema),gr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,Ld.SCHEMA_EXISTS_ERR(e.schema),!0);return await di.createSchema(e),`database '${e.schema}' successfully created`}a(RL,"createSchemaStructure");async function Vj(e){return ha(e),e.hash_attribute=e.primary_key??e.hash_attribute,await AL(e)}a(Vj,"createTable");async function AL(e){let t=da.create_table_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);if(da.validateTableResidence(e.residence),!await fa.checkSchemaTableExists(e.schema,e.table))throw Tr(new Error,Ld.TABLE_EXISTS_ERR(e.schema,e.table),gr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,Ld.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:xj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await di.createTable(n,e);else throw Tr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",gr.BAD_REQUEST);else await di.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(AL,"createTableStructure");async function $j(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 Tr(n,n.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let s=await fa.checkSchemaExists(e.schema);if(s)throw Tr(new Error,s,gr.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 di.dropSchema(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema)),await gL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a($j,"dropSchema");async function Yj(e){let t=da.table_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw Tr(new Error,r,gr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);return await di.dropTable(e),await gL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Yj,"dropTable");async function Kj(e){let t=da.attribute_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw Tr(new Error,r,gr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Tr(new Error,"You cannot drop a hash attribute",gr.BAD_REQUEST,void 0,void 0,!0);if(Ea.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Tr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,gr.BAD_REQUEST,void 0,void 0,!0);try{return await di.dropAttribute(e),Wj(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Hj.error(`Got an error deleting attribute ${Gj.inspect(e)}.`),n}}a(Kj,"dropAttribute");function Wj(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(Wj,"dropAttributeFromGlobal");async function Qj(e){ha(e);let t=Fj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw Tr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,gr.BAD_REQUEST,void 0,void 0,!0);return await di.createAttribute(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Qj,"createAttribute");function zj(e){return di.getBackup(e)}a(zj,"getBackup")});var yL=g((kfe,bL)=>{"use strict";var{OPERATIONS_ENUM:Jj}=P(),GS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Jj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};bL.exports=GS});var qS=g((Yfe,DL)=>{"use strict";var jj=Cn(),$fe=yL(),Ud=J(),vd=P(),Xj=Z(),{handleHDBError:NL,hdb_errors:Zj}=ne(),{HDB_ERROR_MSGS:IL,HTTP_STATUS_CODES:wL}=Zj,eX=Object.values(vd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),CL="To use this operation audit log must be enabled in harperdb-config.yaml";DL.exports=tX;async function tX(e){if(Ud.isEmpty(e.schema))throw new Error(IL.SCHEMA_REQUIRED_ERR);if(Ud.isEmpty(e.table))throw new Error(IL.TABLE_REQUIRED_ERR);if(!Xj.get(vd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw NL(new Error,CL,wL.BAD_REQUEST,vd.LOG_LEVELS.ERROR,CL,!0);let t=Ud.checkSchemaTableExist(e.schema,e.table);if(t)throw NL(new Error,t,wL.NOT_FOUND,vd.LOG_LEVELS.ERROR,t,!0);if(!Ud.isEmpty(e.search_type)&&eX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await jj.readAuditLog(e)}a(tX,"readAuditLog")});var ML=g((Wfe,LL)=>{"use strict";var{OPERATIONS_ENUM:rX}=P(),FS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=rX.GET_BACKUP,this.schema=t,this.table=r}};LL.exports=FS});var vL=g((jfe,UL)=>{"use strict";var nX=Cn(),zfe=ML(),kS=J(),sX=P(),Jfe=Z(),{handleHDBError:iX,hdb_errors:oX}=ne(),{HDB_ERROR_MSGS:PL,HTTP_STATUS_CODES:aX}=oX;UL.exports=cX;async function cX(e){if(kS.isEmpty(e.schema))throw new Error(PL.SCHEMA_REQUIRED_ERR);if(kS.isEmpty(e.table))throw new Error(PL.TABLE_REQUIRED_ERR);let t=kS.checkSchemaTableExist(e.schema,e.table);if(t)throw iX(new Error,t,aX.NOT_FOUND,sX.LOG_LEVELS.ERROR,t,!0);return await nX.getBackup(read_audit_log_object)}a(cX,"getBackup")});var FL=g((Zfe,qL)=>{var fi=require("validate.js"),HL=je(),ma=P(),{handleHDBError:uX,hdb_errors:lX}=ne(),{HDB_ERROR_MSGS:Et,HTTP_STATUS_CODES:_X}=lX,VS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),dX={STRUCTURE_USER:"structure_user"},BL=Object.values(ma.ROLE_TYPES_ENUM),fX="attribute_permissions",EX="attribute_name",{PERMS_CRUD_ENUM:pa}=ma,hX=[fX,...Object.values(pa)],xL=[pa.READ,pa.INSERT,pa.UPDATE],mX=[EX,...xL];function pX(e){let t=VS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,GL(e,t)}a(pX,"addRoleValidation");function SX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,GL(e,t)}a(SX,"alterRoleValidation");function TX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,HL.validateObject(e,t)}a(TX,"dropRoleValidation");var gX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function GL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)gX.includes(n[o])||s.push(n[o]);s.length>0&&gt(Et.INVALID_ROLE_JSON_KEYS(s),r);let i=HL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{gt(o,r)}),e.permission){let o=RX(e);o&&gt(o,r),BL.forEach(c=>{e.permission[c]&&!fi.isBoolean(e.permission[c])&&gt(Et.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(BL.indexOf(o)<0){if(o===dX.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]||gt(Et.SCHEMA_NOT_FOUND(d),r)}continue}gt(Et.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){gt(Et.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]){gt(Et.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{hX.includes(l)||gt(Et.INVALID_PERM_KEY(l),r,o,u)}),Object.values(pa).forEach(l=>{fi.isDefined(_[l])?fi.isBoolean(_[l])||gt(Et.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):gt(Et.TABLE_PERM_MISSING(l),r,o,u)}),fi.isDefined(_.attribute_permissions)){if(!fi.isArray(_.attribute_permissions)){gt(Et.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{gt(Et.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in _.attribute_permissions){let f=_.attribute_permissions[E];if(Object.keys(f).forEach(p=>{!mX.includes(p)&&p!==pa.DELETE&&gt(Et.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!fi.isDefined(f.attribute_name)){gt(Et.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!l.includes(h)){gt(Et.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}xL.forEach(p=>{fi.isDefined(f[p])?fi.isBoolean(f[p])||gt(Et.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):gt(Et.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let E=`${o}.${u}`;gt(Et.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return AX(r)}a(GL,"customValidate");qL.exports={addRoleValidation:pX,alterRoleValidation:SX,dropRoleValidation:TX};function RX(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 Et.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ma.ROLE_TYPES_ENUM.SUPER_USER:ma.ROLE_TYPES_ENUM.CLUSTER_USER;return Et.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(RX,"validateNoSUPerms");function AX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:Et.ROLE_PERMS_ERROR,...e};return uX(new Error,n,_X.BAD_REQUEST)}else return null}a(AX,"generateRolePermResponse");function gt(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(gt,"addPermError")});var zS=g((tEe,YL)=>{"use strict";var kL=qr(),VL=Gr(),OX=oi(),YS=FL(),KS=bs(),bX=require("uuid").v4,yX=require("util"),Bd=P(),NX=J(),WS=VL.searchByValue,IX=VL.searchByHash,wX=yX.promisify(OX.delete),CX=es(),DX=ia(),{hdb_errors:LX,handleHDBError:uo}=ne(),{HDB_ERROR_MSGS:$L,HTTP_STATUS_CODES:gu}=LX,{UserEventMsg:QS}=Mn();YL.exports={addRole:MX,alterRole:PX,dropRole:UX,listRoles:vX};function $S(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($S,"scrubRoleDetails");async function MX(e){let t=YS.addRoleValidation(e);if(t)throw t;e=$S(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 WS(r)||[])}catch(i){throw uo(i)}if(n&&n.length>0)throw uo(new Error,$L.ROLE_ALREADY_EXISTS(e.role),gu.CONFLICT,void 0,void 0,!0);e.id||(e.id=bX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await kL.insert(s),KS.signalUserChange(new QS(process.pid)),e=$S(e),e}a(MX,"addRole");async function PX(e){let t=YS.alterRoleValidation(e);if(t)throw t;e=$S(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await kL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",gu.BAD_REQUEST,void 0,void 0,!0);return await KS.signalUserChange(new QS(process.pid)),e}a(PX,"alterRole");async function UX(e){let t=YS.dropRoleValidation(e);if(t)throw uo(new Error,t,gu.BAD_REQUEST,void 0,void 0,!0);let r=new DX(Bd.SYSTEM_SCHEMA_NAME,Bd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await IX(r));if(n.length===0)throw uo(new Error,$L.ROLE_NOT_FOUND,gu.NOT_FOUND,void 0,void 0,!0);let s=new CX(Bd.SYSTEM_SCHEMA_NAME,Bd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await WS(s)),o=!1;if(NX.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`,gu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await wX(c),KS.signalUserChange(new QS(process.pid)),`${n[0].role} successfully deleted`}a(UX,"dropRole");async function vX(){return WS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(vX,"listRoles")});var zL=g((nEe,QL)=>{"use strict";var BX=Z(),Ei=require("joi"),HX=je(),KL=require("moment"),xX=require("fs-extra"),JS=require("path"),GX=require("lodash"),Ru=P(),{LOG_LEVELS:lo}=P(),qX="YYYY-MM-DD hh:mm:ss",FX=JS.resolve(__dirname,"../logs");QL.exports=function(e){return HX.validateBySchema(e,kX)};var kX=Ei.object({from:Ei.custom(WL),until:Ei.custom(WL),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(VX)});function WL(e,t){if(KL(e,KL.ISO_8601).format(qX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(WL,"validateDatetime");function VX(e,t){if(GX.invert(Ru.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=BX.get(Ru.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Ru.LOG_NAMES.HDB:e,i=s===Ru.LOG_NAMES.INSTALL?JS.join(FX,Ru.LOG_NAMES.INSTALL):JS.join(n,s);return xX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(VX,"validateReadLogPath")});var XS=g((iEe,jL)=>{"use strict";var Hd=P(),$X=$(),YX=Z(),KX=zL(),jS=require("path"),JL=require("fs-extra"),{once:WX}=require("events"),{handleHDBError:QX,hdb_errors:zX}=ne(),{PACKAGE_ROOT:JX}=P(),jX=jS.join(JX,"logs"),XX=1e3,ZX=200;jL.exports=eZ;async function eZ(e){let t=KX(e);if(t)throw QX(t,t.message,zX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=YX.get(Hd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Hd.LOG_NAMES.HDB:e.log_name,s=n===Hd.LOG_NAMES.INSTALL?jS.join(jX,Hd.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?XX:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,p=0;E==="desc"&&!u&&!l&&(p=Math.max(JL.statSync(s).size-(h+5)*ZX,0));let S=JL.createReadStream(s,{start:p});S.on("error",v=>{$X.error(v)});let T=0,A=[],R="",C;S.on("data",v=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=R+v;let M=0,Q;for(;(Q=k.exec(v))&&!S.destroyed;){C&&(C.message=v.slice(M,Q.index),x(C));let[j,z,ae]=Q,ue=ae.split("] ["),de=ue[0],xe=ue[1];ue.splice(0,2),C={timestamp:z,thread:de,level:xe,tags:ue,message:""},M=Q.index+j.length}R=v.slice(M)}),S.on("end",v=>{S.destroyed||C&&(C.message=R.trim(),x(C))}),S.resume();function x(v){let k,M,Q;switch(!0){case(i&&c&&_):k=new Date(v.timestamp),M=new Date(u),Q=new Date(l),v.level===o&&k>=M&&k<=Q&&T<f?T++:v.level===o&&k>=M&&k<=Q&&(hi(v,E,A),T++,T===h&&S.destroy());break;case(i&&c):k=new Date(v.timestamp),M=new Date(u),v.level===o&&k>=M&&T<f?T++:v.level===o&&k>=M&&(hi(v,E,A),T++,T===h&&S.destroy());break;case(i&&_):k=new Date(v.timestamp),Q=new Date(l),v.level===o&&k<=Q&&T<f?T++:v.level===o&&k<=Q&&(hi(v,E,A),T++,T===h&&S.destroy());break;case(c&&_):k=new Date(v.timestamp),M=new Date(u),Q=new Date(l),k>=M&&k<=Q&&T<f?T++:k>=M&&k<=Q&&(hi(v,E,A),T++,T===h&&S.destroy());break;case i:v.level===o&&T<f?T++:v.level===o&&(hi(v,E,A),T++,T===h&&S.destroy());break;case c:k=new Date(v.timestamp),M=new Date(u),k>=M&&T<f?T++:k>=M&&T>=f&&(hi(v,E,A),T++,T===h&&S.destroy());break;case _:k=new Date(v.timestamp),Q=new Date(l),k<=Q&&T<f?T++:k<=Q&&T>=f&&(hi(v,E,A),T++,T===h&&S.destroy());break;default:T<f?T++:(hi(v,E,A),T++,T===h&&S.destroy())}}return a(x,"onLogMessage"),await WX(S,"close"),A}a(eZ,"readLog");function hi(e,t,r){t==="desc"?tZ(e,r):t==="asc"?rZ(e,r):r.push(e)}a(hi,"pushLineToResult");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,"insertDescending");function rZ(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(rZ,"insertAscending")});var xd=g((lEe,tM)=>{"use strict";var ZS=require("joi"),{string:Au,boolean:XL,date:nZ}=ZS.types(),sZ=je(),{validateSchemaExists:aEe,validateTableExists:cEe,validateSchemaName:uEe}=zn(),iZ=P(),oZ=ke(),ZL=Z();ZL.initSync();var aZ=Au.invalid(ZL.get(iZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(oZ.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(),eM={operation:Au.valid("add_node","update_node","set_node_replication"),node_name:aZ,subscriptions:ZS.array().items({table:Au.optional(),schema:Au.optional(),database:Au.optional(),subscribe:XL.required(),publish:XL.required().custom(uZ),start_time:nZ.iso()}).min(1).required()};function cZ(e){return sZ.validateBySchema(e,ZS.object(eM))}a(cZ,"addUpdateNodeValidator");function uZ(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(uZ,"checkForFalsy");tM.exports={addUpdateNodeValidator:cZ,validation_schema:eM}});var nM=g((dEe,rM)=>{var lZ=je(),_Z={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};rM.exports=function(e){return lZ.validateObject(e,_Z)}});var Gd=g((fEe,sM)=>{"use strict";var dZ=P().OPERATIONS_ENUM,eT=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=dZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};sM.exports=eT});var oM=g((hEe,iM)=>{"use strict";var fZ={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}};iM.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:fZ,JWTRSAKeys:rT}});var yu=g((pEe,lM)=>{"use strict";var bu=require("jsonwebtoken"),nT=require("fs-extra"),sT=J(),_n=P(),{handleHDBError:Rr,hdb_errors:EZ}=ne(),{HTTP_STATUS_CODES:Ar,AUTHENTICATION_ERROR_MSGS:Or}=EZ,Ou=$(),aM=F_(),aT=ln(),hZ=qr().update,mZ=Gd(),pZ=bs(),{UserEventMsg:SZ}=Mn(),mi=Z();mi.initSync();var iT=require("path"),{JWTTokens:TZ,JWTRSAKeys:gZ,TOKEN_TYPE_ENUM:qd}=oM(),RZ=mi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?mi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",AZ=mi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?mi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Fd="RS256",oT;lM.exports={createTokens:OZ,validateOperationToken:yZ,refreshOperationToken:bZ,validateRefreshToken:uM};async function OZ(e){if(sT.isEmpty(e)||typeof e!="object")throw Rr(new Error,Or.INVALID_AUTH_OBJECT,Ar.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.username))throw Rr(new Error,Or.USERNAME_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.password))throw Rr(new Error,Or.PASSWORD_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw Rr(new Error,Or.INVALID_CREDENTIALS,Ar.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw Ou.error(E),Rr(new Error,Or.INVALID_CREDENTIALS,Ar.UNAUTHORIZED,void 0,void 0,!0)}let r=await kd(),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 cM(i,r.private_key,r.passphrase),c=await bu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:AZ,algorithm:Fd,subject:qd.REFRESH}),u=aM.hash(c),_=new mZ(_n.SYSTEM_SCHEMA_NAME,_n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await hZ(_)}catch(E){Ou.error(E),d=E}if(d!==void 0||l.skipped_hashes.length>0)throw Rr(new Error,Or.REFRESH_TOKEN_SAVE_FAILED,Ar.INTERNAL_SERVER_ERROR);return pZ.signalUserChange(new SZ(process.pid)),new TZ(o,c)}a(OZ,"createTokens");async function cM(e,t,r){return await bu.sign(e,{key:t,passphrase:r},{expiresIn:RZ,algorithm:Fd,subject:qd.OPERATION})}a(cM,"signOperationToken");async function kd(){if(oT===void 0)try{let e=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.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 gZ(i,s,n)}catch(e){throw Ou.error(e),Rr(new Error,Or.NO_ENCRYPTION_KEYS,Ar.INTERNAL_SERVER_ERROR)}return oT}a(kd,"getJWTRSAKeys");async function bZ(e){if(!e)throw Rr(new Error,Or.INVALID_BODY,Ar.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Rr(new Error,Or.REFRESH_TOKEN_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);await uM(e.refresh_token);let t=await kd(),r=await bu.decode(e.refresh_token);return{operation_token:await cM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(bZ,"refreshOperationToken");async function yZ(e){try{let t=await kd(),r=await bu.verify(e,t.public_key,{algorithms:Fd,subject:qd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Ou.warn(t),t.name&&t.name==="TokenExpiredError"?Rr(new Error,Or.TOKEN_EXPIRED,Ar.FORBIDDEN):Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED)}}a(yZ,"validateOperationToken");async function uM(e){let t;try{let r=await kd(),n=await bu.verify(e,r.public_key,{algorithms:Fd,subject:qd.REFRESH});t=await aT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Ou.warn(r),r.name&&r.name==="TokenExpiredError"?Rr(new Error,Or.TOKEN_EXPIRED,Ar.FORBIDDEN):Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED)}if(!aM.validate(t.refresh_token,e))throw Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED);return t}a(uM,"validateRefreshToken")});var cT=g((gEe,fM)=>{"use strict";var NZ=nM(),Sa=require("passport"),IZ=require("passport-local").Strategy,wZ=require("passport-http").BasicStrategy,CZ=require("util"),DZ=ln(),dM=CZ.callbackify(DZ.findAndValidateUser),TEe=Ur(),LZ=P(),_M=yu();Sa.use(new IZ(function(e,t,r){dM(e,t,r)}));Sa.use(new wZ(function(e,t,r){dM(e,t,r)}));Sa.serializeUser(function(e,t){t(null,e)});Sa.deserializeUser(function(e,t){t(null,e)});function MZ(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===LZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?_M.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):_M.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(MZ,"authorize");function PZ(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(PZ,"checkPermissions");fM.exports={authorize:MZ,checkPermissions:PZ}});var pi=g((AEe,EM)=>{"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}};EM.exports={Node:uT,NodeSubscription:lT}});var mM=g((bEe,hM)=>{"use strict";var UZ=P().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}};hM.exports=_T});var Nu=g((NEe,pM)=>{"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)}};pM.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var TM=g((wEe,SM)=>{"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}};SM.exports=ET});var AM=g((PEe,RM)=>{"use strict";var vZ=TM(),DEe=_t(),gM=Ke(),BZ=$(),{getSchemaPath:LEe,getTransactionAuditStorePath:MEe}=ze(),{getDatabases:HZ}=(Oe(),ie(Fe));RM.exports=xZ;async function xZ(e){let t=new vZ;try{let r=HZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await gM.environmentDataSize(schema_path,e.name),o=await gM.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){BZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(xZ,"lmdbGetTableSize")});var bM=g((vEe,OM)=>{"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}};OM.exports=hT});var Ta=g((FEe,wM)=>{"use strict";var GZ=require("fs-extra"),qZ=require("path"),rr=require("systeminformation"),Si=$(),yM=ot(),HEe=ke(),$d=P(),FZ=AM(),kZ=As(),{getThreadInfo:NM}=Je(),NT=Z();NT.initSync();var VZ=bM(),{openEnvironment:xEe}=Ke(),{getSchemaPath:GEe}=ze(),{database:qEe,databases:mT}=(Oe(),ie(Fe)),Vd;wM.exports={getHDBProcessInfo:gT,getNetworkInfo:AT,getDiskInfo:RT,getMemoryInfo:TT,getCPUInfo:ST,getTimeInfo:pT,getSystemInformation:OT,systemInformation:$Z,getTableSize:bT,getMetrics:yT};function pT(){return rr.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 rr.cpu();l.cpu_speed=await rr.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...A}=await rr.currentLoad();return A.cpus=[],T.forEach(R=>{let{raw_load:C,raw_load_idle:x,raw_load_irq:v,raw_load_nice:k,raw_load_system:M,raw_load_user:Q,...j}=R;A.cpus.push(j)}),l.current_load=A,l}catch(e){return Si.error(`error in getCPUInfo: ${e}`),{}}}a(ST,"getCPUInfo");async function TT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await rr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Si.error(`error in getMemoryInfo: ${e}`),{}}}a(TT,"getMemoryInfo");async function gT(){let e={core:[],clustering:[]};try{let t=await rr.processes(),r;try{r=Number.parseInt(await GZ.readFile(qZ.join(NT.get($d.CONFIG_PARAMS.ROOTPATH),$d.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===$d.NODE_ERROR_CODES.ENOENT)Si.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Si.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 rr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await rr.fsStats();return e.read_write=_,e.size=await rr.fsSize(),e}catch(t){return Si.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 rr.networkInterfaceDefault(),e.latency=await rr.inetChecksite("google.com"),(await rr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await rr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Si.error(`error in getNetworkInfo: ${t}`),e}}a(AT,"getNetworkInfo");async function OT(){if(Vd!==void 0)return Vd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await rr.osInfo();e=c;let u=await rr.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Vd=e,Vd}catch(t){return Si.error(`error in getSystemInformation: ${t}`),e}}a(OT,"getSystemInformation");async function bT(){let e=[],t=await kZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await FZ(n));return e}a(bT,"getTableSize");async function yT(){let e={};for(let t in mT){let r=e[t]={},n=r.tables={};for(let s in mT[t])try{let i=mT[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(u=>{let[_,l,d]=u.trim().split(" ");return{pid:_,thread:l,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let u of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[u]=o[u];n[s]=c}catch(i){Si.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(yT,"getMetrics");async function IM(){if(NT.get($d.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await yM.getNATSReferences(),t=await yM.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(IM,"getNatsStreamInfo");async function $Z(e){let t=new VZ;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 yT(),t.threads=await NM(),t.replication=await IM(),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 yT();break;case"threads":t.threads=await NM();break;case"replication":t.replication=await IM();break;default:break}return t}a($Z,"systemInformation")});var Kd=g((VEe,CM)=>{"use strict";CM.exports={version:YZ,printVersion:KZ};var Yd=au();function YZ(){if(Yd)return Yd.version}a(YZ,"version");function KZ(){Yd&&console.log(`HarperDB Version ${Yd.version}`)}a(KZ,"printVersion")});var dn=g((WEe,PM)=>{"use strict";var WZ=qr(),IT=J(),QZ=require("util"),_o=P(),DM=Z();DM.initSync();var zZ=cT(),LM=Gr(),{Node:YEe,NodeSubscription:KEe}=pi(),JZ=ia(),jZ=mM(),{RemotePayloadObject:XZ,RemotePayloadSubscription:ZZ}=Nu(),{handleHDBError:e5,hdb_errors:t5}=ne(),{HTTP_STATUS_CODES:r5,HDB_ERROR_MSGS:n5}=t5,s5=es(),i5=Ta(),o5=Kd(),{getDatabases:a5}=(Oe(),ie(Fe)),c5=QZ.promisify(zZ.authorize),u5=LM.searchByHash,l5=LM.searchByValue;PM.exports={authHeaderToUser:_5,isEmpty:d5,getNodeRecord:f5,upsertNodeRecord:E5,buildNodePayloads:h5,checkClusteringEnabled:m5,getAllNodeRecords:p5,getSystemInfo:S5,reverseSubscription:MM};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 jZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return WZ.upsert(t)}a(E5,"upsertNodeRecord");function MM(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(MM,"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:E}=MM(c),f=a5()[u]?.[_],h=new ZZ(u,_,l,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new XZ(r,t,s,n)}a(h5,"buildNodePayloads");function m5(){if(!DM.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=g((zEe,FM)=>{"use strict";var Wd=ot(),UM=J(),vM=ke(),BM=P(),Qd=$(),HM=Tu(),T5=cd(),{RemotePayloadObject:g5}=Nu(),{handleHDBError:xM,hdb_errors:R5}=ne(),{HTTP_STATUS_CODES:GM}=R5,{NodeSubscription:qM}=pi();FM.exports=A5;async function A5(e,t){let r;try{r=await Wd.request(`${t}.${vM.REQUEST_SUFFIX}`,new g5(BM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Qd.trace("Response from remote describe all request:",r)}catch(o){Qd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Wd.requestErrorHandler(o,"add_node",t);throw xM(new Error,c,GM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===vM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw xM(new Error,o,GM.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===BM.SYSTEM_SCHEMA_NAME){await Wd.createLocalTableStream(u,c);let h=new qM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=UM.doesSchemaExist(u),l=n[u]!==void 0,d=c?UM.doesTableExist(u,c):!0,E=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!E){s.push(o);continue}if(!_&&l&&(Qd.trace(`addNode creating schema: ${u}`),await HM.createSchema({operation:"create_schema",schema:u})),!d&&E){Qd.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 HM.createTable(h)}await Wd.createLocalTableStream(u,c);let f=new qM(u,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(A5,"reviewSubscriptions")});var Xd=g((jEe,$M)=>{"use strict";var{handleHDBError:zd,hdb_errors:O5}=ne(),{HTTP_STATUS_CODES:Jd}=O5,{addUpdateNodeValidator:b5}=xd(),jd=$(),VM=P(),kM=ke(),y5=J(),Iu=ot(),wu=dn(),N5=Z(),I5=wT(),{Node:w5,NodeSubscription:C5}=pi(),{broadcast:D5}=Je(),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",P5=N5.get(VM.CONFIG_PARAMS.CLUSTERING_NODENAME);$M.exports=U5;async function U5(e,t=!1){jd.trace("addNode called with:",e),wu.checkClusteringEnabled();let r=b5(e);if(r)throw zd(r,r.message,Jd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await wu.getNodeRecord(n);if(!y5.isEmptyOrZeroLength(d))throw zd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Jd.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=wu.buildNodePayloads(s,P5,VM.OPERATIONS_ENUM.ADD_NODE,await wu.getSystemInfo()),u=[];for(let d=0,E=s.length;d<E;d++){let f=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new C5(f.schema,f.table,f.publish,f.subscribe))}jd.trace("addNode sending remote payload:",c);let _;try{_=await Iu.request(`${n}.${kM.REQUEST_SUFFIX}`,c)}catch(d){jd.error(`addNode received error from request: ${d}`);for(let f=0,h=s.length;f<h;f++){let p=s[f];p.publish=!1,p.subscribe=!1,await Iu.updateRemoteConsumer(p,n)}let E=Iu.requestErrorHandler(d,"add_node",n);throw zd(new Error,E,Jd.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===kM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw zd(new Error,d,Jd.INTERNAL_SERVER_ERROR,"error",d)}jd.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await Iu.updateRemoteConsumer(f,n),f.subscribe===!0&&await Iu.updateConsumerIterator(f.schema,f.table,n,"start")}let l=new w5(n,u,_.system_info);return await wu.upsertNodeRecord(l),D5({type:"nats_update"}),i.length>0?o.message=M5:o.message=`Successfully added '${n}' to manifest`,o}a(U5,"addNode")});var LT=g((ehe,WM)=>{"use strict";var{handleHDBError:CT,hdb_errors:v5}=ne(),{HTTP_STATUS_CODES:DT}=v5,{addUpdateNodeValidator:B5}=xd(),Cu=$(),KM=P(),YM=ke(),ZEe=J(),Du=ot(),Lu=dn(),H5=Z(),{cloneDeep:x5}=require("lodash"),G5=wT(),{Node:q5,NodeSubscription:F5}=pi(),{broadcast:k5}=Je(),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(KM.CONFIG_PARAMS.CLUSTERING_NODENAME);WM.exports=K5;async function K5(e){Cu.trace("updateNode called with:",e),Lu.checkClusteringEnabled();let t=B5(e);if(t)throw CT(t,t.message,DT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Lu.getNodeRecord(r);s.length>0&&(n=x5(s));let{added:i,skipped:o}=await G5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=V5,c;let u=Lu.buildNodePayloads(i,Y5,KM.OPERATIONS_ENUM.UPDATE_NODE,await Lu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let E=i[l];Cu.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[l].start_time===void 0&&delete i[l].start_time}Cu.trace("updateNode sending remote payload:",u);let _;try{_=await Du.request(`${r}.${YM.REQUEST_SUFFIX}`,u)}catch(l){Cu.error(`updateNode received error from request: ${l}`);let d=Du.requestErrorHandler(l,"update_node",r);throw CT(new Error,d,DT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===YM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw CT(new Error,l,DT.INTERNAL_SERVER_ERROR,"error",l)}Cu.trace(_);for(let l=0,d=i.length;l<d;l++){let E=i[l];await Du.updateRemoteConsumer(E,r),E.subscribe===!0?await Du.updateConsumerIterator(E.schema,E.table,r,"start"):await Du.updateConsumerIterator(E.schema,E.table,r,"stop")}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 F5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Lu.upsertNodeRecord(n),k5({type:"nats_update"})}a(W5,"updateNodeTable")});var XM=g((rhe,jM)=>{"use strict";var JM=require("joi"),{string:QM}=JM.types(),Q5=je(),zM=P(),z5=Z(),J5=ke();jM.exports=j5;function j5(e){let t=QM.invalid(z5.get(zM.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=JM.object({operation:QM.valid(zM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Q5.validateBySchema(e,r)}a(j5,"removeNodeValidator")});var ef=g((she,nP)=>{"use strict";var{handleHDBError:ZM,hdb_errors:X5}=ne(),{HTTP_STATUS_CODES:eP}=X5,Z5=XM(),Mu=$(),tP=dn(),e8=J(),Zd=P(),rP=ke(),MT=ot(),t8=Z(),{RemotePayloadObject:r8}=Nu(),{NodeSubscription:n8}=pi(),s8=oa(),i8=oi(),{broadcast:o8}=Je(),a8=t8.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);nP.exports=c8;async function c8(e){Mu.trace("removeNode called with:",e),tP.checkClusteringEnabled();let t=Z5(e);if(t)throw ZM(t,t.message,eP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await tP.getNodeRecord(r);if(e8.isEmptyOrZeroLength(n))throw ZM(new Error,`Node '${r}' was not found.`,eP.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new r8(Zd.OPERATIONS_ENUM.REMOVE_NODE,a8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await MT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await MT.updateRemoteConsumer(new n8(l.schema,l.table,!1,!1),r)}catch(d){Mu.error(d)}}try{i=await MT.request(`${r}.${rP.REQUEST_SUFFIX}`,s),Mu.trace("Remove node reply from remote node:",r,i)}catch(u){Mu.error("removeNode received error from request:",u),o=!0}let c=new s8(Zd.SYSTEM_SCHEMA_NAME,Zd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await i8.deleteRecord(c),o8({type:"nats_update"}),i?.status===rP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Mu.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 oP=g((ohe,iP)=>{"use strict";var sP=require("joi"),{string:u8,array:l8}=sP.types(),_8=je(),d8=xd();iP.exports=f8;function f8(e){let t=sP.object({operation:u8.valid("configure_cluster").required(),connections:l8.items(d8.validation_schema).required()});return _8.validateBySchema(e,t)}a(f8,"configureClusterValidator")});var PT=g((che,_P)=>{"use strict";var E8=P(),tf=$(),h8=J(),m8=ef(),p8=Xd(),aP=dn(),S8=oP(),{handleHDBError:cP,hdb_errors:T8}=ne(),{HTTP_STATUS_CODES:uP}=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.";_P.exports=O8;async function O8(e){tf.trace("configure cluster called with:",e),aP.checkClusteringEnabled();let t=S8(e);if(t)throw cP(t,t.message,uP.BAD_REQUEST,void 0,void 0,!0);let r=await aP.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let E=await lP(m8,{operation:E8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(E)}tf.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],E=await lP(p8,d,d.node_name);s.push(E)}tf.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let E=_[l];E.status==="rejected"&&(tf.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(u=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(h8.isEmptyOrZeroLength(o))return{message:g8,connections:c};if(u)return{message:A8,failed_nodes:o,connections:c};throw cP(new Error,R8,uP.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(O8,"configureCluster");async function lP(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(lP,"functionWrapper")});var hP=g((lhe,EP)=>{"use strict";var Pu=require("joi"),b8=je(),{validateSchemaExists:dP,validateTableExists:y8,validateSchemaName:fP}=zn(),N8=Pu.object({operation:Pu.string().valid("purge_stream"),schema:Pu.string().custom(dP).custom(fP).optional(),database:Pu.string().custom(dP).custom(fP).optional(),table:Pu.string().custom(y8).required()});function I8(e){return b8.validateBySchema(e,N8)}a(I8,"purgeStreamValidator");EP.exports=I8});var UT=g((dhe,mP)=>{"use strict";var{handleHDBError:w8,hdb_errors:C8}=ne(),{HTTP_STATUS_CODES:D8}=C8,L8=hP(),M8=ot(),P8=dn();mP.exports=U8;async function U8(e){e.schema=e.schema??e.database;let t=L8(e);if(t)throw w8(t,t.message,D8.BAD_REQUEST,void 0,void 0,!0);P8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await M8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(U8,"purgeStream")});var HT=g((Ehe,AP)=>{"use strict";var BT=dn(),v8=ot(),TP=Z(),rf=P(),fo=ke(),B8=J(),vT=$(),{RemotePayloadObject:H8}=Nu(),{ErrorCode:pP}=require("nats"),SP=TP.get(rf.CONFIG_PARAMS.CLUSTERING_ENABLED),gP=TP.get(rf.CONFIG_PARAMS.CLUSTERING_NODENAME);AP.exports={clusterStatus:x8,buildNodeStatus:RP};async function x8(){let e={node_name:gP,is_enabled:SP,connections:[]};if(!SP)return e;let t=await BT.getAllNodeRecords();if(B8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(RP(t[n],e.connections));return await Promise.allSettled(r),e}a(x8,"clusterStatus");async function RP(e,t){let r=e.name,n=new H8(rf.OPERATIONS_ENUM.CLUSTER_STATUS,gP,void 0,await BT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await v8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,vT.error(`Error getting node status from ${r} `,s))}catch(u){vT.warn(`Error getting node status from ${r}`,u),u.code===pP.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===pP.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!==rf.PRE_4_0_0_VERSION&&await BT.upsertNodeRecord(u)}catch(u){vT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(RP,"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 GT=g((mhe,OP)=>{"use strict";var{handleHDBError:q8,hdb_errors:F8}=ne(),{HTTP_STATUS_CODES:k8}=F8,V8=ot(),$8=dn(),xT=J(),nf=require("joi"),Y8=je(),K8=2e3,W8=nf.object({timeout:nf.number().min(1),connected_nodes:nf.boolean(),routes:nf.boolean()});OP.exports=Q8;async function Q8(e){$8.checkClusteringEnabled();let t=Y8.validateBySchema(e,W8);if(t)throw q8(t,t.message,k8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||xT.autoCastBoolean(n),o=s===void 0||xT.autoCastBoolean(s),c={nodes:[]},u=await V8.getServerList(r??K8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let E=u[l].statsz;E&&(_[u[l].server.name]=E.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let E=u[l].server,f=u[l].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[E.name]&&_[E.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(p=>({host:p.split(":")[0],port:xT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(Q8,"clusterNetwork")});var IP=g((She,NP)=>{"use strict";var qT=require("joi"),bP=je(),{route_constraints:yP}=rp();NP.exports={setRoutesValidator:z8,deleteRoutesValidator:J8};function z8(e){let t=qT.object({server:qT.valid("hub","leaf").required(),routes:yP.required()});return bP.validateBySchema(e,t)}a(z8,"setRoutesValidator");function J8(e){let t=qT.object({routes:yP.required()});return bP.validateBySchema(e,t)}a(J8,"deleteRoutesValidator")});var kT=g((ghe,LP)=>{"use strict";var Eo=fr(),FT=J(),sf=P(),wP=IP(),{handleHDBError:CP,hdb_errors:j8}=ne(),{HTTP_STATUS_CODES:DP}=j8,X8="cluster routes successfully set",Z8="cluster routes successfully deleted";LP.exports={setRoutes:e6,getRoutes:t6,deleteRoutes:r6};function e6(e){let t=wP.setRoutesValidator(e);if(t)throw CP(t,t.message,DP.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=FT.autoCast(_.port);let l=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:X8,set:o,skipped:i}}a(e6,"setRoutes");function t6(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(t6,"getRoutes");function r6(e){let t=wP.deleteRoutesValidator(e);if(t)throw CP(t,t.message,DP.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[_],E=!1;for(let f=0,h=n.length;f<h;f++){let p=n[f];if(d.host===p.host&&d.port===p.port){n.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=FT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=FT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:Z8,deleted:i,skipped:o}}a(r6,"deleteRoutes")});var PP=g((Ahe,MP)=>{"use strict";var Uu=require("alasql"),ho=require("recursive-iterator"),Hn=$(),n6=J(),vu=P(),VT=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,i6(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=>vu.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=>!vu.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][vu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=s6(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(_=>!vu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Uu.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 s6(e){return e.filter(t=>t[vu.PERMS_CRUD_ENUM.READ])}a(s6,"filterReadRestrictedAttrs");function i6(e,t,r,n,s){o6(e,t,r,n,s)}a(i6,"interpretAST");function Bu(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(Bu,"addSchemaTableToMap");function o6(e,t,r,n,s){if(!e){Hn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Uu.yy.Insert?l6(e,t,r):e instanceof Uu.yy.Select?a6(e,t,r,n,s):e instanceof Uu.yy.Update?c6(e,t,r):e instanceof Uu.yy.Delete?u6(e,t,r):Hn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(o6,"getRecordAttributesAST");function a6(e,t,r,n,s){if(!e){Hn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(n6.isEmptyOrZeroLength(i)){Hn.error("No schema specified");return}e.from.forEach(c=>{Bu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Bu(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{Hn.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{Hn.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{Hn.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{Hn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(a6,"getSelectAttributes");function c6(e,t,r){if(!e){Hn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.table.tableid,s,i.columnid,t,r)}a(c6,"getUpdateAttributes");function u6(e,t,r){if(!e){Hn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.table.tableid,s,i.columnid,t,r)}a(u6,"getDeleteAttributes");function l6(e,t,r){if(!e){Hn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;Bu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.into.tableid,s,i.columnid,t,r)}a(l6,"getInsertAttributes");function $T(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($T,"pushAttribute");MP.exports=VT});var WT=g((bhe,HP)=>{var of=Ji(),UP=require("chalk"),Qr=$(),vP=require("prompt"),{promisify:_6}=require("util"),YT=P(),d6=require("fs-extra"),f6=require("path"),E6=J(),h6=Kd(),BP=Z();BP.initSync();var m6=require("moment"),p6=_6(vP.get),S6=f6.join(BP.getHdbBasePath(),YT.LICENSE_KEY_DIR_NAME,YT.LICENSE_FILE_NAME,YT.LICENSE_FILE_NAME);HP.exports={getFingerprint:g6,setLicense:T6,parseLicense:KT,register:R6,getRegistrationInfo:O6};async function T6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await KT(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(T6,"setLicense");async function g6(){let e={};try{e=await of.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(g6,"getFingerprint");async function KT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=of.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 d6.writeFile(S6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(KT,"parseLicense");async function R6(){let e=await A6();return KT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(R6,"register");async function A6(){let e=await of.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:UP.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:UP.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{vP.start()}catch(n){Qr.error(n)}let r;try{r=await p6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(A6,"promptForRegistration");async function O6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await of.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(E6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=h6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=m6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(O6,"getRegistrationInfo")});var GP=g((Nhe,xP)=>{"use strict";var b6=ke(),QT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+b6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file: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:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};xP.exports=QT});var kP=g((whe,FP)=>{"use strict";var qP=ke(),zT=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+qP.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+qP.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"}};FP.exports=zT});var $P=g((Dhe,VP)=>{"use strict";var JT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};VP.exports=JT});var KP=g((Mhe,YP)=>{"use strict";var y6=ke(),jT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+y6.SERVER_SUFFIX.ADMIN,this.password=r}};YP.exports=jT});var eg=g((Uhe,zP)=>{"use strict";var ga=require("path"),uf=require("fs-extra"),N6=GP(),I6=kP(),w6=$P(),C6=KP(),XT=ln(),Aa=J(),br=fr(),cf=P(),Hu=ke(),{CONFIG_PARAMS:ht}=cf,Oa=$(),xu=Z(),WP=Rs(),ZT=ot(),Ra="clustering",D6=1e4,QP=50;zP.exports={generateNatsConfig:M6,removeNatsConfig:P6,getHubConfigPath:L6};function L6(){let e=xu.get(ht.ROOTPATH);return ga.join(e,Ra,Hu.NATS_CONFIG_FILES.HUB_SERVER)}a(L6,"getHubConfigPath");async function M6(e=!1,t=void 0){xu.initSync();let r=xu.get(ht.ROOTPATH),n=ga.join(r,Ra,Hu.PID_FILES.HUB),s=ga.join(r,Ra,Hu.PID_FILES.LEAF),i=br.getConfigFromFile(ht.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=ga.join(r,Ra,Hu.NATS_CONFIG_FILES.HUB_SERVER),c=ga.join(r,Ra,Hu.NATS_CONFIG_FILES.LEAF_SERVER),u=br.getConfigFromFile(ht.CLUSTERING_TLS_CERTIFICATE),_=br.getConfigFromFile(ht.CLUSTERING_TLS_PRIVATEKEY),l=br.getConfigFromFile(ht.CLUSTERING_TLS_CERT_AUTH),d=br.getConfigFromFile(ht.CLUSTERING_TLS_INSECURE),E=br.getConfigFromFile(ht.CLUSTERING_TLS_VERIFY),f=br.getConfigFromFile(ht.CLUSTERING_NODENAME),h=br.getConfigFromFile(ht.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await ZT.checkNATSServerInstalled()||lf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await XT.listUsers(),S=br.getConfigFromFile(ht.CLUSTERING_USER),T=await XT.getClusterUser();(Aa.isEmpty(T)||T.active!==!0)&&lf(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await af(ht.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await af(ht.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await af(ht.CLUSTERING_HUBSERVER_NETWORK_PORT),await af(ht.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],R=[];for(let[j,z]of p.entries())z.role.role===cf.ROLE_TYPES_ENUM.CLUSTER_USER&&z.active&&(A.push(new C6(z.username,WP.decrypt(z.hash))),R.push(new w6(z.username,WP.decrypt(z.hash))));let C=[],{hub_routes:x}=br.getClusteringRoutes();if(!Aa.isEmptyOrZeroLength(x))for(let j of x)C.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${j.host}:${j.port}`);let v=new N6(br.getConfigFromFile(ht.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,u,_,l,d,E,h,br.getConfigFromFile(ht.CLUSTERING_HUBSERVER_CLUSTER_NAME),br.getConfigFromFile(ht.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),C,A,R);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=Aa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===cf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await uf.writeJson(o,v),Oa.trace(`Hub server config written to ${o}`));let k=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,M=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,Q=new I6(br.getConfigFromFile(ht.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[k],[M],A,R,u,_,l,d);l==null&&delete Q.tls.ca_file,(t===void 0||t===cf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await uf.writeJson(c,Q),Oa.trace(`Leaf server config written to ${c}`))}a(M6,"generateNatsConfig");async function af(e){let t=xu.get(e);return Aa.isEmpty(t)&&lf(`port undefined for '${e}'`),await Aa.isPortTaken(t)&&lf(`'${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(af,"isPortAvailable");function lf(e){let t=`Error generating clustering config: ${e}`;Oa.error(t),console.error(t),process.exit(1)}a(lf,"generateNatsConfigError");async function P6(e){let{port:t,config_file:r}=ZT.getServerConfig(e),{username:n,decrypt_hash:s}=await XT.getClusterUser(),i=0,o=2e3;for(;i<QP;){try{let l=await ZT.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){Oa.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=QP)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&Oa.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Aa.async_set_timeout(_)}let c="0".repeat(D6),u=ga.join(xu.get(ht.ROOTPATH),Ra,r);await uf.writeFile(u,c),await uf.remove(u),Oa.notify(e,"started.")}a(P6,"removeNatsConfig")});var tU=g((Bhe,eU)=>{"use strict";var zr=Z(),U6=Ji(),pe=P(),Gu=ke(),Cs=require("path"),{PACKAGE_ROOT:df}=P(),JP=Z(),_f=J(),ba="/dev/null",v6=Cs.join(df,"launchServiceScripts"),jP=Cs.join(df,"utility/scripts"),B6=Cs.join(jP,pe.HDB_RESTART_SCRIPT),XP=Cs.resolve(df,"dependencies",`${process.platform}-${process.arch}`,Gu.NATS_BINARY_NAME);function ZP(){let t=U6.licenseSearch().ram_allocation||pe.RAM_ALLOCATION_ENUM.DEFAULT,r=pe.MEM_SETTING_KEY+t,n={[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return _f.noBootFile()&&(n[pe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=_f.getEnvCliRootPath()),{name:pe.PROCESS_DESCRIPTORS.HDB,script:pe.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:df}}a(ZP,"generateMainServerConfig");var H6=9930;function x6(){zr.initSync(!0);let e=zr.get(pe.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.HUB_SERVER),r=Cs.join(zr.get(pe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),pe.LOG_NAMES.HDB),n=JP.get(pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[zr.get(pe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==H6?"-"+n:""),script:XP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(x6,"generateNatsHubServerConfig");var G6=9940;function q6(){zr.initSync(!0);let e=zr.get(pe.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cs.join(zr.get(pe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),pe.LOG_NAMES.HDB),n=JP.get(pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[zr.get(pe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==G6?"-"+n:""),script:XP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(q6,"generateNatsLeafServerConfig");function F6(){zr.initSync();let e=Cs.join(zr.get(pe.CONFIG_PARAMS.LOGGING_ROOT),pe.LOG_NAMES.HDB),t={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:pe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:v6,autorestart:!1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ba,t.error_file=ba),t}a(F6,"generateClusteringUpgradeV4ServiceConfig");function k6(){let e={[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.RESTART_HDB};return _f.noBootFile()&&(e[pe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=_f.getEnvCliRootPath()),{...{name:pe.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:jP},script:B6}}a(k6,"generateRestart");function V6(){return{apps:[ZP()]}}a(V6,"generateAllServiceConfigs");eU.exports={generateAllServiceConfigs:V6,generateMainServerConfig:ZP,generateRestart:k6,generateNatsHubServerConfig:x6,generateNatsLeafServerConfig:q6,generateClusteringUpgradeV4ServiceConfig:F6}});var hU=g((Ghe,EU)=>{"use strict";var Ue=P(),$6=J(),Ls=eg(),ff=ot(),Ds=ke(),Ti=tU(),Ef=Z(),gi=$(),Y6=dn(),{startWorker:rU,onMessageFromWorkers:K6}=Je(),W6=Ta(),xhe=require("util"),Q6=require("child_process"),z6=require("fs"),{execFile:J6}=Q6,we;EU.exports={enterPM2Mode:j6,start:Ri,stop:tg,reload:sU,restart:iU,list:rg,describe:aU,connect:Ms,kill:r9,startAllServices:n9,startService:ng,getUniqueServicesList:cU,restartAllServices:s9,isServiceRegistered:uU,reloadStopStart:lU,restartHdb:oU,deleteProcess:e9,startClusteringProcesses:dU,startClusteringThreads:fU,isHdbRestartRunning:t9,isClusteringRunning:o9,stopClustering:i9,reloadClustering:a9};var qu=!1;K6(e=>{e.type==="restart"&&Ef.initSync(!0)});function j6(){qu=!0}a(j6,"enterPM2Mode");function Ms(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{gi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ms,"connect");var yr,X6=10,nU;function Ri(e,t=!1){if(qu)return Z6(e);let r=J6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=yr.indexOf(r);o>-1&&yr.splice(o,1),!nU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<X6&&(z6.existsSync(Ls.getHubConfigPath())?Ri(e):(await Ls.generateNatsConfig(!0),Ri(e),await new Promise(c=>setTimeout(c,3e3)),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Ef.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let f=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",f,n,i.slice(_,u.index).trim())}let[d,E]=u;_=u.index+d.length,l=Ds.LOG_LEVELS[E]}if(Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),yr=[],!yr&&!t){let i=a(()=>{nU=!0,yr&&(yr.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)}yr.push(r)}a(Ri,"start");function Z6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(Z6,"startWithPM2");function tg(e){if(!qu){for(let t of yr||[])t.name===e&&(yr.splice(yr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(tg,"stop");function sU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(sU,"reload");function iU(e){if(!qu)for(let t of yr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(iU,"restart");function e9(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(e9,"deleteProcess");async function oU(){await Ri(Ti.generateRestart())}a(oU,"restartHdb");async function t9(){let e=await rg();for(let t in e)if(e[t].name===Ue.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(t9,"isHdbRestartRunning");function rg(){return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(rg,"list");function aU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(aU,"describe");function r9(){if(!qu){for(let e of yr||[])e.kill();yr=[];return}return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(r9,"kill");async function n9(){try{await dU(),await fU(),await Ri(Ti.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(n9,"startAllServices");async function ng(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ue.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ti.generateMainServerConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ti.generateNatsIngestServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ti.generateNatsReplyServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ti.generateNatsHubServerConfig(),await Ri(r,t),await Ls.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ti.generateNatsLeafServerConfig(),await Ri(r,t),await Ls.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ti.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ri(r)}catch(r){throw we?.disconnect(),r}}a(ng,"startService");async function cU(){try{let e=await rg(),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 we?.disconnect(),e}}a(cU,"getUniqueServicesList");async function s9(e=[]){try{let t=!1,r=await cU();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Ue.PROCESS_DESCRIPTORS.HDB?t=!0:await iU(o))}t&&await lU(Ue.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(s9,"restartAllServices");async function uU(e){if(yr?.find(r=>r.name===e))return!0;let t=await W6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(uU,"isServiceRegistered");async function lU(e){let t=Ef.get(Ue.CONFIG_PARAMS.THREADS_COUNT)??Ef.get(Ue.CONFIG_PARAMS.THREADS),r=await aU(e),n=$6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await tg(e),await ng(e)):e===Ue.PROCESS_DESCRIPTORS.HDB?await oU():await sU(e)}a(lU,"reloadStopStart");var _U;async function dU(e=!1){for(let t in Ue.CLUSTERING_PROCESSES){let r=Ue.CLUSTERING_PROCESSES[t];await ng(r,e)}}a(dU,"startClusteringProcesses");async function fU(){_U=rU(Ue.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await ff.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await ff.updateLocalStreams();let e=await Y6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ue.PRE_4_0_0_VERSION){gi.info("Starting clustering upgrade 4.0.0 process"),rU(Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(fU,"startClusteringThreads");async function i9(){for(let e in Ue.CLUSTERING_PROCESSES)if(e!==Ue.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ue.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await _U.terminate();else{let t=Ue.CLUSTERING_PROCESSES[e];await tg(t)}}a(i9,"stopClustering");async function o9(){for(let e in Ue.CLUSTERING_PROCESSES){let t=Ue.CLUSTERING_PROCESSES[e];if(await uU(t)===!1)return!1}return!0}a(o9,"isClusteringRunning");async function a9(){await Ls.generateNatsConfig(!0),await ff.reloadNATSHub(),await ff.reloadNATSLeaf(),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(a9,"reloadClustering")});var AU={};qe(AU,{compactOnStart:()=>c9,copyDb:()=>RU});async function c9(){ku.notify("Running compact on start"),console.log("Running compact on start");let e=(0,sg.get)(Ai.CONFIG_PARAMS.ROOTPATH),t=new Map,r=hr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,hf.join)(e,"backup",n+".mdb"),o=(0,hf.join)(e,Ai.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await mU(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await RU(n,o),console.log("Backing up",n,"to",i),await(0,mo.move)(s,i,{overwrite:!0})}Fu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,mo.move)(i,s,{overwrite:!0}),await(0,mo.remove)((0,hf.join)(e,Ai.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Fu()}catch(n){ku.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,ig.updateConfigValue)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,mo.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Fu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await mU(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
11
11
  Total record count before compaction: ${i}, total after: ${c}.
12
- Database backup has not been removed and can be found here: ${s}`;Fu.error(u),console.error(u)}(0,rg.get)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,mo.remove)(s))}(0,ng.updateConfigValue)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function mP(e){let t=await(0,gP.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function RP(e,t){console.log("copyDb start");let r=Er()[e],n;for(let d in r){n=r[d].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,pP.open)(new SP.default(t)),c=o.openDB(ff.INTERNAL_DBIS_NAME),u,_=0,l=s.useReadTransaction();try{for(let{key:E,value:h}of s.getRange({transaction:l})){let p=h.is_hash_attribute||h.isPrimaryKey,S,T;if(p&&(S=h.compression,T=hf(),T?h.compression=T:delete h.compression,S?.dictionary?.toString()===T?.dictionary?.toString()&&(S=null,T=null)),c.put(E,h),!(p||h.indexed))continue;let A=new TP.default(!p,p);A.encoding="binary",A.compression=S;let g=n.openDB(E,A);g.decoder=null,A.compression=T;let L=o.openDB(E,A);L.encoder=null,console.log("copying",E,"from",e,"to",t),await f(g,L,p,l)}let d=n.openDB(ff.AUDIT_STORE_NAME,Ef);console.log("copying audit log"),f(i,d,!1,l);async function f(E,h,p,S){let T=0,A=0;for(let{key:g,value:L,version:v}of E.getRange({start:null,versions:p,transaction:S}))u=h.put(g,L,v),T++,S.openTimer&&(S.openTimer=0),A+=(g?.length||10)+L.length,_++>5e3&&(await u,console.log("copied",T,"entries",A,"bytes"),_=0);console.log("finish copying, copied",T,"entries",A,"bytes")}a(f,"copyDbi"),await u,console.log("copied database "+e+" to "+t)}finally{l.done(),o.close()}}var pP,df,mo,rg,SP,TP,ff,Ai,gP,ng,Fu,OP=Re(()=>{Ae();pP=require("lmdb"),df=require("path"),mo=require("fs-extra"),rg=B(Z()),SP=B(Dc()),TP=B(Cc()),ff=B(ut()),Ai=B(M());ti();gP=B(As()),ng=B(dr()),Fu=B($());a(u9,"compactOnStart");a(mP,"getTotalDBRecordCount");a(RP,"copyDb")});var Tf=R((Yhe,DP)=>{"use strict";var l9=require("minimist"),{isMainThread:ig,parentPort:yP}=require("worker_threads"),et=M(),{PROCESS_DESCRIPTORS_VALIDATE:ku}=et,is=$(),og=Q(),pf=XT(),mf=it(),$he=ke(),IP=dr(),os=hP(),bP=Sa(),{compactOnStart:_9}=(OP(),ie(AP)),d9=Uh(),{restartWorkers:Sf,onMessageByType:f9}=Je(),{handleHDBError:E9,hdb_errors:h9}=ne(),{HTTP_STATUS_CODES:m9}=h9,$u=Z();$u.initSync();var Vu=`Restarting HarperDB. This may take up to ${et.RESTART_TIMEOUT_MS/1e3} seconds.`,p9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",NP="Clustering is not enabled so cannot be restarted",S9="Invalid service",ba,dn;DP.exports={restart:wP,restartService:ag};ig&&f9(et.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?ag({service:e.workerType}):wP({operation:"restart"})});async function wP(e){dn=Object.keys(e).length===0,ba=await os.isServiceRegistered(et.HDB_PROC_DESCRIPTOR);let t=l9(process.argv);if(t.service){await ag(t);return}if(dn&&!ba){console.error(p9);return}if(dn&&console.log(Vu),ba){os.enterPM2Mode(),is.notify(Vu);let r=d9(Object.keys(et.CONFIG_PARAM_MAP),!0);return og.isEmptyOrZeroLength(Object.keys(r))||IP.updateConfigValue(void 0,void 0,r,!0,!0),T9(),Vu}return ig?(is.notify(Vu),$u.get(et.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await _9(),setTimeout(()=>{Sf()},50)):yP.postMessage({type:et.ITC_EVENT_TYPES.RESTART}),Vu}a(wP,"restart");async function ag(e){let{service:t}=e;if(et.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw E9(new Error,S9,m9.BAD_REQUEST,void 0,void 0,!0);if(ba=await os.isServiceRegistered(et.HDB_PROC_DESCRIPTOR),!ig)return yP.postMessage({type:et.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case ku.clustering:if(!$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=NP;break}dn&&console.log("Restarting clustering"),is.notify("Restarting clustering"),await CP();break;case ku.clustering_config:case ku["clustering config"]:if(!$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=NP;break}dn&&console.log("Restarting clustering_config"),is.notify("Restarting clustering_config"),await os.reloadClustering();break;case"custom_functions":case"custom functions":case ku.harperdb:case ku.http_workers:if(dn&&!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}dn&&console.log("Restarting http_workers"),is.notify("Restarting http_workers"),dn?await os.restart(et.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Sf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(is.error(r),dn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(ag,"restartService");async function T9(){await CP(),await os.restart(et.HDB_PROC_DESCRIPTOR),await og.async_set_timeout(2e3),$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await sg(),dn&&(await mf.closeConnection(),process.exit(0))}a(T9,"restartPM2Mode");async function CP(){if(!IP.getConfigFromFile(et.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await bP.getHDBProcessInfo()).clustering.length===0)is.trace("Clustering not running, restart will start clustering services"),await pf.generateNatsConfig(!0),await os.startClusteringProcesses(),await os.startClusteringThreads(),await sg(),dn&&await mf.closeConnection();else{await pf.generateNatsConfig(!0),ba?(is.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await os.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await os.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await bP.getHDBProcessInfo()).clustering.forEach(s=>{is.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await og.async_set_timeout(3e3),await sg(),await mf.updateLocalStreams(),dn&&await mf.closeConnection(),is.trace("Restart clustering restarting ingest and reply service threads");let t=Sf(et.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Sf(et.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(CP,"restartClustering");async function sg(){await pf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await pf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(sg,"removeNatsConfig")});var FP=R((Qhe,qP)=>{"use strict";var Whe=require("lodash"),br=M(),{handleHDBError:LP,hdb_errors:g9}=ne(),{HDB_ERROR_MSGS:R9,HTTP_STATUS_CODES:A9}=g9,cg=$();qP.exports={getRolePermissions:b9};var po=Object.create(null),O9=a(e=>({key:e,perms:{}}),"perms_template_obj"),vP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),BP=a((e=!1,t=!1,r=!1,n=!1)=>({[br.PERMS_CRUD_ENUM.READ]:e,[br.PERMS_CRUD_ENUM.INSERT]:t,[br.PERMS_CRUD_ENUM.UPDATE]:r,[br.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),ug=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...BP(t,r,n,s)}),"table_perms_template"),MP=a((e,t=BP())=>({attribute_name:e,describe:GP(t),[Yu]:t[Yu],[lg]:t[lg],[_g]:t[_g]}),"attr_perms_template"),UP=a((e,t=!1)=>({attribute_name:e,describe:t,[Yu]:t}),"timestamp_attr_perms_template"),{READ:Yu,INSERT:lg,UPDATE:_g}=br.PERMS_CRUD_ENUM,HP=Object.values(br.PERMS_CRUD_ENUM),xP=[Yu,lg,_g];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[br.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(po[t]&&po[t].key===n)return po[t].perms;let s=N9(e,r);return po[t]?po[t].key=n:po[t]=O9(n),po[t].perms=s,s}catch(r){if(!e[br.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[br.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<br.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 cg.error(n),cg.debug(r),LP(new Error,R9.OUTDATED_PERMS_TRANSLATION_ERROR,A9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
13
- ${r.stack}`;throw cg.error(n),LP(new Error)}}}a(b9,"getRolePermissions");function N9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[br.SYSTEM_SCHEMA_NAME]=n[br.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]=vP(),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||HP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=ug()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=ug()})}),r}a(N9,"translateRolePermissions");function y9(e){let t=vP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=ug(!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 br.TIME_STAMP_NAMES.includes(d)&&(f=UP(d,l[Yu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=MP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=GP(l),s.attribute_permissions.push(l),c||w9(l,u)}else if(_!==o){let l;br.TIME_STAMP_NAMES.includes(_)?l=UP(_):l=MP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=PP(s),s}else return e.describe=PP(e),e}a(I9,"getTableAttrPerms");function PP(e){return HP.filter(t=>e[t]).length>0}a(PP,"getSchemaTableDescribePerm");function GP(e){return xP.filter(t=>e[t]).length>0}a(GP,"getAttributeDescribePerm");function w9(e,t){xP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(w9,"checkForHashPerms")});var kP={};qe(kP,{Resources:()=>gf,keyArrayToString:()=>Na,resetResources:()=>C9,resources:()=>Oi});function C9(){return Oi=new gf}function Na(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var gf,Oi,Ku=Re(()=>{ro();gf=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(C9,"resetResources");a(Na,"keyArrayToString")});var VP={};qe(VP,{Headers:()=>bi,appendHeader:()=>dg});function dg(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var bi,Wu=Re(()=>{bi=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];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(dg,"appendHeader")});var Qu={};qe(Qu,{authentication:()=>jP,bypassAuth:()=>B9,login:()=>x9,logout:()=>G9,start:()=>H9});function B9(){JP=!0}async function jP(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?U9?M9:[]:L9?D9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new bi([["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){i||(i=r.host);let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let p of h)if(p.startsWith(E)){let S=p.indexOf(";");u=p.slice(E.length,S===-1?p.length:S),_=await YP.get(u);break}e.session=_||(_={})}let l=a((E,h,p)=>{let S=new ya.AuthAuditLog(E,h,Bt.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===Bt.AUTH_AUDIT_STATUS.SUCCESS?$P.notify(S):$P.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let E=e.mtlsConfig.user;E!==null?((E===void 0||E==="Common Name"||E==="CN")&&(E=e.peerCertificate.subject.CN),e.user=await nt.getUser(E,null,null),l(E,Bt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,ya.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=So.get(n),!d){let E=n.indexOf(" "),h=n.slice(0,E),p=n.slice(E+1),S,T;try{switch(h){case"Basic":let A=atob(p),g=A.indexOf(":");S=A.slice(0,g),T=A.slice(g+1),d=S||T?await nt.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,Af.validateOperationToken)(p)}catch(L){if(L.message==="invalid token")try{return await(0,Af.validateRefreshToken)(p),c({status:-1})}catch{throw L}}break}}catch(A){return v9&&(So.get(p)||(So.set(p,p),l(S,Bt.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:To({error:A.message},e)})}So.set(n,d),P9&&l(d.username,Bt.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await nt.getUser(_.user,null,e):(JP&&(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,QP.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 nt.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")&&Oi.loginPath?(f.status=302,f.headers.set("Location",Oi.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 bi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function H9({server:e,port:t}){e.http(jP,{port:t||"all"}),KP||(KP=!0,setInterval(()=>{So=new Map},fn.get(Bt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),zP.user.addListener(()=>{So=new Map}))}async function x9(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 G9(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,QP,fn,Bt,ya,zP,$P,D9,L9,M9,U9,YP,Rf,JP,P9,v9,So,KP,Of=Re(()=>{WP=B(un());ar();Ku();Af=B(bu());Ae();QP=require("uuid"),fn=B(Z()),Bt=B(M()),ya=B($()),zP=B(Vc());Wu();Ia();$P=(0,ya.loggerWithTag)("auth-event");fn.initSync();D9=fn.get(Bt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),L9=fn.get(Bt.CONFIG_PARAMS.HTTP_CORS),M9=fn.get(Bt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),U9=fn.get(Bt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),YP=lt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Rf=fn.get(Bt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,JP=fn.get(Bt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,P9=fn.get(Bt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,v9=fn.get(Bt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,So=new Map;nt.onInvalidatedUser(()=>{So=new Map});a(B9,"bypassAuth");a(jP,"authentication");a(H9,"start");a(x9,"login");a(G9,"logout")});var sv=R((ime,nv)=>{"use strict";var we=require("joi"),XP=require("fs-extra"),ZP=require("path"),Ps=je(),ev=Z(),tv=M(),rv=$(),{hdb_errors:q9}=ne(),{HDB_ERROR_MSGS:tr}=q9,Us=/^[a-zA-Z0-9-_]+$/;nv.exports={getDropCustomFunctionValidator:k9,setCustomFunctionValidator:V9,addComponentValidator:W9,dropCustomFunctionProjectValidator:Q9,packageComponentValidator:z9,deployComponentValidator:J9,setComponentFileValidator:$9,getComponentFileValidator:K9,dropComponentFileValidator:Y9};function bf(e,t,r){try{let n=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),s=ZP.join(n,t);return XP.existsSync(s)?e?t:r.message(tr.PROJECT_EXISTS):e?r.message(tr.NO_PROJECT):t}catch(n){return rv.error(n),r.message(tr.VALIDATION_ERR)}}a(bf,"checkProjectExists");function zu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(zu,"checkFilePath");function F9(e,t,r,n){try{let s=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),i=ZP.join(s,e,t,r+".js");return XP.existsSync(i)?r:n.message(tr.NO_FILE)}catch(s){return rv.error(s),n.message(tr.VALIDATION_ERR)}}a(F9,"checkFileExists");function k9(e){let t=we.object({project:we.string().pattern(Us).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().pattern(Us).custom(F9.bind(null,e.project,e.type)).custom(zu).required().messages({"string.pattern.base":tr.BAD_FILE_NAME})});return Ps.validateBySchema(e,t)}a(k9,"getDropCustomFunctionValidator");function V9(e){let t=we.object({project:we.string().pattern(Us).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().custom(zu).required(),function_content:we.string().required()});return Ps.validateBySchema(e,t)}a(V9,"setCustomFunctionValidator");function $9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),file:we.string().custom(zu).required(),payload:we.string().allow("").optional(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a($9,"setComponentFileValidator");function Y9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),file:we.string().custom(zu).optional()});return Ps.validateBySchema(e,t)}a(Y9,"dropComponentFileValidator");function K9(e){let t=we.object({project:we.string().required(),file:we.string().custom(zu).required(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a(K9,"getComponentFileValidator");function W9(e){let t=we.object({project:we.string().pattern(Us).custom(bf.bind(null,!1)).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(W9,"addComponentValidator");function Q9(e){let t=we.object({project:we.string().pattern(Us).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(Q9,"dropCustomFunctionProjectValidator");function z9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),skip_node_modules:we.boolean()});return Ps.validateBySchema(e,t)}a(z9,"packageComponentValidator");function J9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":tr.BAD_PROJECT_NAME}),payload:we.string().optional().messages({"string.pattern.base":tr.BAD_PACKAGE}),package:we.string().optional()});return Ps.validateBySchema(e,t)}a(J9,"deployComponentValidator")});var wf=R((ame,_v)=>{"use strict";var Nf=require("joi"),yf=require("path"),iv=require("fs-extra"),{exec:j9}=require("child_process"),X9=require("util"),ov=X9.promisify(j9),Ju=M(),{handleHDBError:wa,hdb_errors:Z9}=ne(),{HTTP_STATUS_CODES:Ca}=Z9,ju=Z(),e7=je(),Da=$();ju.initSync();var fg=ju.get(Ju.CONFIG_PARAMS.COMPONENTSROOT),av="npm install --omit=dev --json",t7=`${av} --dry-run`;_v.exports={installModules:i7,auditModules:o7,installAllRootModules:r7,uninstallRootModule:n7,linkHarperdb:s7};async function r7(e=!1){await If(),await Xu(e?"npm install --ignore-scripts":"npm install",ju.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(r7,"installAllRootModules");async function n7(e){await Xu(`npm uninstall ${e}`,ju.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(n7,"uninstallRootModule");async function s7(){await If(),await Xu(`npm link ${Ju.PACKAGE_ROOT}`,ju.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(s7,"linkHarperdb");async function Xu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await ov(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
14
- `,""))}return n&&!n.includes("Debugger listening")&&Da.error("Error running NPM command:",e,n),Da.trace(r,n),r?.replace(`
15
- `,"")}a(Xu,"runCommand");async function i7(e){Da.info(`starting installModules for request: ${e}`);let t=lv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?t7:av;await If(),await uv(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 _=yf.join(fg,u),l,d=null;try{let{stdout:f,stderr:E}=await ov(s,{cwd:_});l=f?f.replace(`
16
- `,""):null,d=E?E.replace(`
17
- `,""):null}catch(f){f.stderr?i[u].npm_error=cv(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(i7,"installModules");function cv(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
18
- `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(cv,"parseNPMStdErr");async function o7(e){Da.info(`starting auditModules for request: ${e}`);let t=lv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r}=e;await If(),await uv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=yf.join(fg,o);n[o]={npm_output:null,npm_error:null};try{let u=await Xu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=cv(u.stderr)}}return Da.info(`finished auditModules with response ${n}`),n}a(o7,"auditModules");async function If(){try{return await Xu("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(If,"checkNPMInstalled");async function uv(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=yf.join(fg,i.toString());if(!await iv.pathExists(o)){t.push(i);continue}let u=yf.join(o,"package.json");await iv.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(uv,"checkProjectPaths");function lv(e){let t=Nf.object({projects:Nf.array().min(1).items(Nf.string()).required(),dry_run:Nf.boolean().default(!1)});return e7.validateBySchema(e,t)}a(lv,"modulesValidator")});var hg=R((ume,mv)=>{"use strict";var La=require("fs-extra"),Eg=require("path"),Cf=$(),dv=Q(),Df=M(),hv=Z(),a7=dr();mv.exports=c7;async function c7(){let e=u7(),t=hv.get(Df.CONFIG_PARAMS.ROOTPATH),r=Eg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Df.PACKAGE_ROOT}},s=Eg.join(t,"node_modules");await La.ensureDir(s);let i,o=!0,c=!1;try{i=await La.readJson(r)}catch(u){if(dv.isEmptyOrZeroLength(e))return;if(u.code!==Df.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!dv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await fv(_);n.dependencies[u]=l+_}if(!o){Cf.notify("Installing components"),await Ev(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await fv(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Cf.notify("Removing component",u),c=!0);c&&(Cf.notify("Updating components."),await Ev(r,n,i))}a(c7,"installComponents");function u7(){let e=a7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(u7,"getComponentsConfig");async function fv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":Eg.extname(e)||await La.pathExists(e)?"file:":"github:"}a(fv,"getPkgPrefix");async function Ev(e,t,r){Cf.trace("npm installing components package.json",t),await La.writeFile(e,JSON.stringify(t,null," "));try{await wf().installAllRootModules(hv.get(Df.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await La.writeFile(e,JSON.stringify(r,null," ")):await La.unlink(e),n}}a(Ev,"installPackages")});var Sg=R((dme,gv)=>{"use strict";var Ve=require("fs-extra"),mg=require("fast-glob"),ge=require("path"),Sv=require("tar-fs"),_me=require("uuid").v4,pg=require("normalize-path"),as=sv(),It=$(),We=M(),gt=Z(),Zu=dr(),l7=Q(),{PACKAGE_ROOT:_7}=M(),{handleHDBError:Ht,hdb_errors:d7}=ne(),{basename:f7}=require("path"),E7=hg(),Tv=Z(),h7=M(),{Readable:m7}=require("stream"),{isMainThread:p7}=require("worker_threads"),{HDB_ERROR_MSGS:go,HTTP_STATUS_CODES:xt}=d7,S7=ge.join(_7,"application-template"),pv=ge.join(gt.get(We.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function T7(){It.trace("getting custom api status");let e={};try{e={port:gt.get(We.CONFIG_PARAMS.HTTP_PORT),directory:gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Ht(new Error,go.FUNCTION_STATUS,xt.INTERNAL_SERVER_ERROR,It.ERR,t)}return e}a(T7,"customFunctionsStatus");function g7(){It.trace("getting custom api endpoints");let e={},t=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT);try{mg.sync(pg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:mg.sync(pg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:mg.sync(pg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Ht(new Error,go.GET_FUNCTIONS,xt.INTERNAL_SERVER_ERROR,It.ERR,r)}return e}a(g7,"getCustomFunctions");function R7(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);It.trace("getting custom api endpoint file content");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=ge.join(r,n,s,i+".js");try{return Ve.readFileSync(o,{encoding:"utf8"})}catch(c){throw Ht(new Error,go.GET_FUNCTION,xt.INTERNAL_SERVER_ERROR,It.ERR,c)}}a(R7,"getCustomFunction");function A7(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=as.setCustomFunctionValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);It.trace("setting custom function file content");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Ve.outputFileSync(ge.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Ht(new Error,go.SET_FUNCTION,xt.INTERNAL_SERVER_ERROR,It.ERR,c)}}a(A7,"setCustomFunction");function O7(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);It.trace("dropping custom function file");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Ve.unlinkSync(ge.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Ht(new Error,go.DROP_FUNCTION,xt.INTERNAL_SERVER_ERROR,It.ERR,o)}}a(O7,"dropCustomFunction");function b7(e){e.project&&(e.project=ge.parse(e.project).name);let t=as.addComponentValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);It.trace("adding component");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=ge.join(r,n);return Ve.mkdirSync(s,{recursive:!0}),Ve.copySync(S7,s),`Successfully added project: ${n}`}catch(s){throw Ht(new Error,go.ADD_FUNCTION,xt.INTERNAL_SERVER_ERROR,It.ERR,s)}}a(b7,"addComponent");function N7(e){e.project&&(e.project=ge.parse(e.project).name);let t=as.dropCustomFunctionProjectValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);It.trace("dropping custom function project");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=gt.get(We.CONFIG_PARAMS.APPS);if(!l7.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(We.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=ge.join(r,n);return Ve.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Ht(new Error,go.DROP_FUNCTION_PROJECT,xt.INTERNAL_SERVER_ERROR,It.ERR,i)}}a(N7,"dropCustomFunctionProject");async function y7(e){e.project&&(e.project=ge.parse(e.project).name);let t=as.packageComponentValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;It.trace("packaging component",n);let s;try{s=await Ve.realpath(ge.join(r,n))}catch(u){if(u.code!==We.NODE_ERROR_CODES.ENOENT)throw u;try{s=await Ve.realpath(ge.join(gt.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===We.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Ve.ensureDir(pv);let i=ge.join(pv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(ge.join(s,"node_modules"))}),Sv.pack(s,o).pipe(Ve.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Ve.readFileSync(i,{encoding:"base64"});return await Ve.remove(i),{project:n,payload:c}}a(y7,"packageComponent");async function I7(e){e.project&&(e.project=ge.parse(e.project).name);let t=as.deployComponentValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let r=gt.get(We.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=ge.join(r,n),i="file:"+o,await Ve.ensureDir(o);let f=m7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{f.pipe(Sv.extract(o,{finish:h})).on("error",p)});let E=await Ve.readdir(o);E.length===1&&E[0]==="package"&&(await Ve.copy(ge.join(o,"package"),o),await Ve.remove(ge.join(o,"package")))}if(await Zu.addConfig(n,{package:i}),!s){await E7();let f=Tv.get(h7.CONFIG_PARAMS.ROOTPATH);o=ge.join(f,"node_modules",n)}if(p7)return;let c=new Map;c.isWorker=!0;let u=(Mf(),ie(Lf)),_;u.setErrorReporter(f=>_=f);let l=f7(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(I7,"deployComponent");async function w7(){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 Ve.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=ge.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await Ve.stat(d),E={name:ge.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(gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{name:gt.get(We.CONFIG_PARAMS.COMPONENTSROOT).split(ge.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(ge.join(gt.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(Mf(),ie(Lf)).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(w7,"getComponents");async function C7(e){let t=as.getComponentFileValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let n=Zu.getConfigObj()[e.project]||e.project==="harperdb"?ge.join(Tv.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules"):gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ve.stat(ge.join(n,e.project,e.file));return{message:await Ve.readFile(ge.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===We.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${ge.join(e.project,e.file)}'`):i}}a(C7,"getComponentFile");async function D7(e){let t=as.setComponentFileValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=ge.join(gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Ve.ensureFile(n),await Ve.outputFile(n,e.payload,r)):await Ve.ensureDir(n),"Successfully set component: "+e.file}a(D7,"setComponentFile");async function L7(e){let t=as.dropComponentFileValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let r=e.file?ge.join(e.project,e.file):e.project,n=ge.join(gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ve.pathExists(n)&&await Ve.remove(n),Zu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(L7,"dropComponent");gv.exports={customFunctionsStatus:T7,getCustomFunctions:g7,getCustomFunction:R7,setCustomFunction:A7,dropCustomFunction:O7,addComponent:b7,dropCustomFunctionProject:N7,packageComponent:y7,deployComponent:I7,getComponents:w7,getComponentFile:C7,setComponentFile:D7,dropComponent:L7}});var Tg=R((Eme,Av)=>{"use strict";var cs=require("joi"),Rv=je();Av.exports={readTransactionLogValidator:M7,deleteTransactionLogsBeforeValidator:U7};function M7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),from:cs.date().timestamp(),to:cs.date().timestamp(),limit:cs.number().min(1)});return Rv.validateBySchema(e,t)}a(M7,"readTransactionLogValidator");function U7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),timestamp:cs.date().timestamp().required()});return Rv.validateBySchema(e,t)}a(U7,"deleteTransactionLogsBeforeValidator")});var Uf=R((mme,Iv)=>{"use strict";var gg=M(),el=it(),Ov=Q(),bv=Z(),Nv=Rs(),{handleHDBError:Ma,hdb_errors:P7}=ne(),{HTTP_STATUS_CODES:Ua}=P7,{readTransactionLogValidator:v7,deleteTransactionLogsBeforeValidator:B7}=Tg(),yv="This operation relies on clustering and cannot run with it disable.",H7="Logs successfully deleted from transaction log.",x7="All logs successfully deleted from transaction log.";Iv.exports={readTransactionLog:G7,deleteTransactionLogsBefore:q7};async function*G7(e){let t=v7(e);if(t)throw Ma(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(gg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,yv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Ov.checkSchemaTableExist(r,n);if(s)throw Ma(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=Nv.createNatsTableStreamName(r,n),o=await el.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===gg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(G7,"readTransactionLog");async function q7(e){let t=B7(e);if(t)throw Ma(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(gg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,yv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Ov.checkSchemaTableExist(r,n);if(i)throw Ma(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=Nv.createNatsTableStreamName(r,n),{jsm:c}=await el.getNATSReferences(),u=await el.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=H7,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=x7):d=(await el.viewStream(o,parseInt(s),1))[0].nats_sequence,await el.purgeTableStream(r,n,{seq:d}),l}a(q7,"deleteTransactionLogsBefore")});var Cv=R((Sme,wv)=>{"use strict";var Rg=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}};wv.exports=Rg});var Lv=R((gme,Dv)=>{"use strict";var Ag=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Dv.exports=Ag});var bg=R((Ame,Uv)=>{"use strict";var Mv=Cv(),F7=Lv(),{HDB_ERROR_MSGS:k7}=Lr(),Og=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=k7.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 Mv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new F7(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 Mv(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}};Uv.exports=Og});var Hf=R((bme,zv)=>{"use strict";var Ng=Hr(),Pf=Br(),hn=Su(),nl=As(),yg=oi(),V7=GS(),$7=PL(),sl=un(),vf=QS(),wt=$(),Y7=jS(),K7=zd(),W7=CT(),Q7=jd(),z7=LT(),J7=MT(),j7=vT(),X7=HT(),Ig=qT(),vs=Q(),Z7=UU(),wg=YT(),Bv=Tf(),En=M(),Hv=FP(),eee=Sa(),xv=bu(),Gv=(Of(),ie(Qu)),qv=dr(),Qr=Sg(),tee=require("alasql"),Fv=Uf(),kv=wf(),Vv=bg(),{handleHDBError:Nr,hdb_errors:$v}=ne(),{HDB_ERROR_MSGS:Yt,HTTP_STATUS_CODES:tl}=$v,V=new Map,Yv="delete",Ni="insert",Bs="read",Ro="update",rl="describe",Pv=nl.describeSchema.name,vv=nl.describeTable.name,Kv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},ree="catchup",nee="handleGetJob",see="handleGetJobsByStartDate",Bf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},iee=[hn.createTable.name,hn.createAttribute.name,hn.dropTable.name,hn.dropAttribute.name],Wv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(Ng.insert.name,new W(!1,[Ni]));V.set(Ng.update.name,new W(!1,[Ro]));V.set(Ng.upsert.name,new W(!1,[Ni,Ro]));V.set(Pf.searchByConditions.name,new W(!1,[Bs]));V.set(Pf.searchByHash.name,new W(!1,[Bs]));V.set(Pf.searchByValue.name,new W(!1,[Bs]));V.set(Pf.search.name,new W(!1,[Bs]));V.set(hn.createSchema.name,new W(!0,[]));V.set(hn.createTable.name,new W(!0,[]));V.set(hn.createAttribute.name,new W(!1,[Ni]));V.set(hn.dropSchema.name,new W(!0,[]));V.set(hn.dropTable.name,new W(!0,[]));V.set(hn.dropAttribute.name,new W(!0,[]));V.set(nl.describeSchema.name,new W(!1,[Bs]));V.set(nl.describeTable.name,new W(!1,[Bs]));V.set(yg.deleteRecord.name,new W(!1,[Yv]));V.set(sl.addUser.name,new W(!0,[]));V.set(sl.alterUser.name,new W(!0,[]));V.set(sl.dropUser.name,new W(!0,[]));V.set(sl.listUsersExternal.name,new W(!0,[]));V.set(vf.listRoles.name,new W(!0,[]));V.set(vf.addRole.name,new W(!0,[]));V.set(vf.alterRole.name,new W(!0,[]));V.set(vf.dropRole.name,new W(!0,[]));V.set(Y7.name,new W(!0,[]));V.set(K7.name,new W(!0,[]));V.set(W7.name,new W(!0,[]));V.set(Q7.name,new W(!0,[]));V.set(z7.name,new W(!0,[]));V.set(J7.name,new W(!0,[]));V.set(Ig.setRoutes.name,new W(!0,[]));V.set(Ig.getRoutes.name,new W(!0,[]));V.set(Ig.deleteRoutes.name,new W(!0,[]));V.set(qv.setConfiguration.name,new W(!0,[]));V.set(j7.clusterStatus.name,new W(!0,[]));V.set(X7.name,new W(!0,[]));V.set(wg.getFingerprint.name,new W(!0,[]));V.set(wg.setLicense.name,new W(!0,[]));V.set(yg.deleteFilesBefore.name,new W(!0,[]));V.set(yg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Bv.restart.name,new W(!0,[]));V.set(Bv.restartService.name,new W(!0,[]));V.set(V7.name,new W(!0,[]));V.set($7.name,new W(!0,[Bs]));V.set(eee.systemInformation.name,new W(!0,[]));V.set(qv.getConfiguration.name,new W(!0,[]));V.set(Fv.readTransactionLog.name,new W(!0,[]));V.set(Fv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(kv.installModules.name,new W(!0,[]));V.set(kv.auditModules.name,new W(!0,[]));V.set(xv.createTokens.name,new W(!1,[]));V.set(xv.refreshOperationToken.name,new W(!1,[]));V.set(Gv.login.name,new W(!1,[]));V.set(Gv.logout.name,new W(!1,[]));V.set(Qr.customFunctionsStatus.name,new W(!0,[]));V.set(Qr.getCustomFunctions.name,new W(!0,[]));V.set(Qr.getComponents.name,new W(!0,[]));V.set(Qr.getComponentFile.name,new W(!0,[]));V.set(Qr.setComponentFile.name,new W(!0,[]));V.set(Qr.dropComponent.name,new W(!0,[]));V.set(Qr.getCustomFunction.name,new W(!0,[]));V.set(Qr.setCustomFunction.name,new W(!0,[]));V.set(Qr.dropCustomFunction.name,new W(!0,[]));V.set(Qr.addComponent.name,new W(!0,[]));V.set(Qr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Qr.packageComponent.name,new W(!0,[]));V.set(Qr.deployComponent.name,new W(!0,[]));V.set(wg.getRegistrationInfo.name,new W(!1,[]));V.set(sl.userInfo.name,new W(!1,[]));V.set(nl.describeAll.name,new W(!1,[]));V.set(nee,new W(!1,[]));V.set(see,new W(!0,[]));V.set(ree,new W(!0,[]));V.set(Bf.CSV_DATA_LOAD,new W(!1,[Ni,Ro]));V.set(Bf.CSV_URL_LOAD,new W(!1,[Ni,Ro]));V.set(Bf.CSV_FILE_LOAD,new W(!1,[Ni,Ro]));V.set(Bf.IMPORT_FROM_S3,new W(!1,[Ni,Ro]));V.set(Wv.EXPORT_TO_S3,new W(!0,[]));V.set(Wv.EXPORT_LOCAL,new W(!0,[]));V.set(En.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Yv]));V.set(En.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bs]));V.set(En.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[Ni]));V.set(En.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ro]));zv.exports={verifyPerms:aee,verifyPermsAst:oee,verifyBulkLoadAttributePerms:uee};function oee(e,t,r){if(vs.isEmptyOrZeroLength(e))throw wt.info("verify_perms_ast has an empty user parameter"),Nr(new Error);if(vs.isEmptyOrZeroLength(t))throw wt.info("verify_perms_ast has an empty user parameter"),Nr(new Error);if(vs.isEmptyOrZeroLength(r))throw wt.info("verify_perms_ast has a null operation parameter"),Nr(new Error);try{let n=new Vv,s=new Z7(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."),Nr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Kv[r])throw Nr(new Error,Yt.DROP_SYSTEM,tl.FORBIDDEN);if(c&&!u)return null;let _=Hv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof tee.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=Qv(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]),p=Dg(t.role.permission,f,d[E]);Cg(h,p,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw Nr(n)}}a(oee,"verifyPermsAst");function aee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw wt.info("null required parameter in verifyPerms"),Nr(new Error,Yt.DEFAULT_INVALID_REQUEST,tl.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 Vv;if(vs.isEmptyOrZeroLength(e.hdb_user.role)||vs.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(Yt.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(En.SYSTEM_SCHEMA_NAME)||s===En.SYSTEM_SCHEMA_NAME;if(l&&Kv[r])throw Nr(new Error,Yt.DROP_SYSTEM,tl.FORBIDDEN);if(u&&!l||_===!0&&(r===hn.createSchema.name||r===hn.dropSchema.name))return null;if(iee.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=Hv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Pv||r===vv){if(s===En.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Yt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Pv&&(!d[s]||!d[s][rl]))return c.handleInvalidItem(Yt.SCHEMA_NOT_FOUND(s));if(r===vv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][rl]))return c.handleInvalidItem(Yt.TABLE_NOT_FOUND(s,i))}}let f=Qv(e.hdb_user,r,o,c,n);if(f)return f;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&En.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[En.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(A=>A[En.PERMS_CRUD_ENUM.READ]).forEach(A=>{p.push(A.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let E=cee(e),h=Dg(e.hdb_user.role.permission,s,i);return Cg(E,h,r,i,s,c,n),c.getPermsResponse()}a(aee,"verifyPerms");function Qv(e,t,r,n,s){if(vs.arrayHasEmptyValues([e,t,r]))throw wt.info("hasPermissions has an invalid parameter"),Nr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw wt.info(`operation ${t} not found.`),Nr(new Error,Yt.OP_NOT_FOUND(t),tl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return wt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Yt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][rl]===!1){n.addInvalidItem(Yt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Yt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[rl]===!1)n.addInvalidItem(Yt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=V.get(t).perms;!vs.isEmpty(s)&&E.includes(s)&&(E=[s]);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} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=Yt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw wt.error(E),wt.error(f),Nr($v.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Qv,"hasPermissions");function Cg(e,t,r,n,s,i,o){if(!e||!t)throw wt.info("no attributes specified in checkAttributePerms."),Nr(new Error);let c=V.get(r).perms;if(!c||c==="")throw wt.info(`no permissions found for ${r} in checkAttributePerms().`),Nr(new Error);if(vs.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[rl]===!1){i.addInvalidItem(Yt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(En.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Bs)throw Nr(new Error,Yt.SYSTEM_TIMESTAMP_PERMS_ERR,tl.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(Yt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Cg,"checkAttributePerms");function cee(e){let t=new Set;try{if(e.action)return t;if(e.operation===En.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(cee,"getRecordAttributes");function Dg(e,t,r){let n=new Map;if(vs.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(Dg,"getAttributePermissions");function uee(e,t,r,n,s,i,o){let c=new Set(i),u=Dg(e,n,s);Cg(c,u,t,s,n,o,r)}a(uee,"verifyBulkLoadAttributePerms")});var Gf=R((yme,e0)=>{"use strict";e0.exports={evaluateSQL:Aee,processAST:Zv,convertSQLToAST:Xv,checkASTPermissions:jv};var lee=Hr(),Jv=require("util"),_ee=Jv.callbackify(lee.insert),dee=Br().search,fee=TD().update,Eee=Jv.callbackify(fee),hee=RD().convertDelete,yi=require("alasql"),mee=Hf(),xf=$(),pee=fd(),See=Q(),il=M(),{hdb_errors:Tee,handleHDBError:Lg}=ne(),{HTTP_STATUS_CODES:Mg}=Tee;pee(yi);var gee=403,Ree="There was a problem performing this insert. Please check the logs and try again.",Ug=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Aee(e,t){let r=e.parsed_sql_object;if(!r){r=Xv(e.sql);let n,s=r.ast.statements[0];if(s instanceof yi.yy.Insert?n=s.into.databaseid:s instanceof yi.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof yi.yy.Update||s instanceof yi.yy.Delete?n=s.table.databaseid:xf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof yi.yy.Select)&&See.isEmptyOrZeroLength(n))return t("No schema specified",null)}Zv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Aee,"evaluateSQL");function jv(e,t){let r;try{r=mee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(jv,"checkASTPermissions");function Xv(e){let t=new Ug;if(!e)throw Lg(new Error,"The 'sql' parameter is missing from the request body",Mg.BAD_REQUEST);try{let r=e.trim(),n=yi.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
19
- `);throw n[1]?Lg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Mg.BAD_REQUEST):Lg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Mg.BAD_REQUEST)}return t}a(Xv,"convertSQLToAST");function Zv(e,t,r){try{let n=Oee;if(!e.bypass_auth&&!t.permissions_checked){let i=jv(e,t);if(i&&i.length>0)return r(gee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case il.VALID_SQL_OPS_ENUM.SELECT:n=dee,s=t.ast.statements[0];break;case il.VALID_SQL_OPS_ENUM.INSERT:n=bee;break;case il.VALID_SQL_OPS_ENUM.UPDATE:n=Eee;break;case il.VALID_SQL_OPS_ENUM.DELETE:n=hee;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(Zv,"processAST");function Oee(e,t){xf.info(e),t("unknown sql statement")}a(Oee,"nullFunction");function bee({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=Nee(i,e.values)}catch(o){return r(o)}_ee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){xf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(bee,"convertInsert");function Nee(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]]=yi.compile(`SELECT ${s.toString()} AS [${il.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw xf.error(r),new Error(Ree)}}a(Nee,"createDataObjects")});var Pg=R((wme,r0)=>{"use strict";var{S3:yee,GetObjectCommand:Iee}=require("@aws-sdk/client-s3");r0.exports={getFileStreamFromS3:wee,getS3AuthObj:t0};async function wee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await t0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Iee(r))).Body}a(wee,"getFileStreamFromS3");function t0(e,t,r){return new yee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(t0,"getS3AuthObj")});var qf=R((Dme,_0)=>{"use strict";var Bg=Br(),Cee=Gf(),Dee=Pg(),{AsyncParser:Lee,Transform:Mee}=require("json2csv"),al=require("stream"),zr=Q(),vg=require("fs-extra"),Uee=require("path"),mn=$(),{promisify:i0}=require("util"),ol=Q(),{handleHDBError:Rt,hdb_errors:Pee}=ne(),{HDB_ERROR_MSGS:yr,HTTP_STATUS_CODES:At}=Pee,{streamAsJSON:vee}=(em(),ie(Db)),{Upload:Bee}=require("@aws-sdk/lib-storage"),n0=["search_by_value","search_by_hash","sql","search_by_conditions"],s0=["json","csv"],o0="json",a0="csv",Hee="Successfully exported JSON locally.",xee="Successfully exported CSV locally.",Gee=1e3,qee=Bg.searchByHash,Fee=Bg.searchByValue,kee=i0(Cee.evaluateSQL),Vee=i0(al.finished);_0.exports={export_to_s3:Wee,export_local:$ee,toCsvStream:c0};async function $ee(e){mn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=u0(e);if(!zr.isEmpty(t))throw mn.error(t),Rt(new Error,t,At.BAD_REQUEST,void 0,void 0,!0);if(zr.isEmpty(e.path))throw mn.error(yr.MISSING_VALUE("path")),Rt(new Error,yr.MISSING_VALUE("path"),At.BAD_REQUEST,void 0,void 0,!0);let r=(zr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Uee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=zr.buildFolderPath(e.path,r);await Yee(e.path);let s=await l0(e);return await Kee(n,e.format,s)}a($ee,"export_local");async function Yee(e){if(mn.trace("in confirmPath"),zr.isEmptyOrZeroLength(e))throw Rt(new Error,`Invalid path: ${e}`,At.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await vg.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,mn.error(n),Rt(new Error,n,At.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 mn.error(r),Rt(new Error,r,At.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Yee,"confirmPath");async function Kee(e,t,r){if(mn.trace("in saveToLocal"),ol.isEmptyOrZeroLength(e))throw Rt(new Error,yr.INVALID_VALUE("file_path"),At.BAD_REQUEST,void 0,void 0,!0);if(ol.isEmptyOrZeroLength(t))throw Rt(new Error,yr.INVALID_VALUE("Source format"),At.BAD_REQUEST,void 0,void 0,!0);if(ol.isEmpty(r))throw Rt(new Error,yr.NOT_FOUND("Data"),At.BAD_REQUEST,void 0,void 0,!0);if(t===o0){let n=vg.createWriteStream(e);return vee(r).pipe(n),await Vee(n),{message:Hee,path:e}}else if(t===a0){let n=vg.createWriteStream(e),s=al.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Lee(i,c).fromInput(s).toOutput(n).promise(!1),{message:xee,path:e}}throw Rt(new Error,yr.INVALID_VALUE("format"),At.BAD_REQUEST)}a(Kee,"saveToLocal");async function Wee(e){if(!e.s3||Object.keys(e.s3).length===0)throw Rt(new Error,yr.MISSING_VALUE("S3 object"),At.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Rt(new Error,yr.MISSING_VALUE("aws_access_key_id"),At.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Rt(new Error,yr.MISSING_VALUE("aws_secret_access_key"),At.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.bucket))throw Rt(new Error,yr.MISSING_VALUE("bucket"),At.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.key))throw Rt(new Error,yr.MISSING_VALUE("key"),At.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.region))throw Rt(new Error,yr.MISSING_VALUE("region"),At.BAD_REQUEST);let t=u0(e);if(!zr.isEmpty(t))throw Rt(new Error,t,At.BAD_REQUEST);mn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await l0(e)}catch(u){throw mn.error(u),u}let n,s=await Dee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new al.PassThrough;if(e.format===a0){i=e.s3.key+".csv";let u=c0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===o0){i=e.s3.key+".json";let u=new al.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%Gee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Rt(new Error,yr.INVALID_VALUE("format"),At.BAD_REQUEST);return new Bee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Wee,"export_to_s3");function c0(e,t){let r=al.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 Mee(n,s);return r.pipe(i)}a(c0,"toCsvStream");function u0(e){if(mn.trace("in exportCoreValidation"),zr.isEmpty(e.format))return"format missing";if(s0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${s0.join(", ")}`;let t=e.search_operation.operation;if(zr.isEmpty(t))return"search_operation.operation missing";if(n0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${n0.join(", ")}`}a(u0,"exportCoreValidation");async function l0(e){mn.trace("in getRecords");let t,r;if(ol.isEmpty(e.search_operation)||ol.isEmptyOrZeroLength(e.search_operation.operation))throw Rt(new Error,yr.INVALID_VALUE("Search operation"),At.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Fee;break;case"search_by_hash":t=qee;break;case"search_by_conditions":t=Bg.searchByConditions;break;case"sql":t=kee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,mn.error(r),Rt(new Error,r,At.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(l0,"getRecords")});var T0={};qe(T0,{contentTypes:()=>qg,findBestSerializer:()=>Vf,getDeserializer:()=>Oo,registerContentHandlers:()=>Fg,serialize:()=>$f,serializeMessage:()=>To});function Qee(e){try{return e?.[0]===123?Gg(e):e}catch{return e}}function Fg(e){e.register(Jee,{serializers:[{regex:/^application\/json$/,serializer:Oc},{regex:/^application\/cbor$/,serializer:function(t){return new Ao.EncoderStream(ul).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?kf.Readable.from((0,us.encodeIter)(t,ul)):(0,us.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Ff.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,us.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ao.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Vf(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 p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=Gt.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(Gt.keys()).join(", "))}};n=Gt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function $f(e,t,r){let n=f0&&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=Vf(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,Hs.createBrotliCompress)({params:{[Hs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hs.constants.BROTLI_MODE_TEXT:Hs.constants.BROTLI_MODE_GENERIC,[Hs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>f0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function To(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return cl(e);let r=t.serialize;if(r)return r(e);let n=Vf(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 Oo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Gt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Gt.get(e)?.deserialize||E0(e,n);return o=>jee(o).then(i)}return e&&Gt.get(e)?.deserialize||E0(e,n)}function E0(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 Ff,us,Ao,Hs,kf,h0,Hg,xg,m0,p0,cl,Gg,ul,Gt,qg,d0,S0,zee,Jee,f0,Ia=Re(()=>{em();Ff=B(qf()),us=require("msgpackr"),Ao=require("cbor-x"),Hs=require("zlib"),kf=require("stream");ar();h0=require("../index"),Hg=B(Z()),xg=B(M()),m0=B(require("yaml")),p0=Hg.default.get(xg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,cl=p0?xi:JSON.stringify,Gg=p0?Zh:JSON.parse,ul={useRecords:!1,useToJSON:!0},Gt=new Map,qg=Gt;nt.contentTypes=qg;(0,h0._assignPackageExport)("contentTypes",qg);Gt.set("application/json",{serializeStream:Oc,serialize:cl,deserialize:Gg,q:.8});d0=new Ao.Encoder(ul);Gt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ao.EncoderStream(ul).end(e)},serialize:d0.encode,deserialize:d0.decode,q:1});Gt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?kf.Readable.from((0,us.encodeIter)(e,ul)):(0,us.pack)(e)},serialize:us.pack,deserialize:us.unpack,q:.9});Gt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Ff.toCsvStream)(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),(0,Ff.toCsvStream)(e,e?.getColumns?.())},q:.1});Gt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});Gt.set("text/yaml",{serialize(e){return m0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Gt.set("text/event-stream",{serializeStream:function(e){return kf.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+`
20
- `),e.data){let r=e.data;typeof r=="object"&&(r=cl(r)),t+="data: "+r+`
12
+ Database backup has not been removed and can be found here: ${s}`;ku.error(u),console.error(u)}(0,sg.get)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,mo.remove)(s))}(0,ig.updateConfigValue)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function mU(e){let t=await(0,gU.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function RU(e,t){console.log("copyDb start");let r=hr()[e],n;for(let d in r){n=r[d].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,pU.open)(new SU.default(t)),c=o.openDB(mf.INTERNAL_DBIS_NAME),u,_=0,l=s.useReadTransaction();try{for(let{key:f,value:h}of s.getRange({transaction:l})){let p=h.is_hash_attribute||h.isPrimaryKey,S,T;if(p&&(S=h.compression,T=Sf(),T?h.compression=T:delete h.compression,S?.dictionary?.toString()===T?.dictionary?.toString()&&(S=null,T=null)),c.put(f,h),!(p||h.indexed))continue;let A=new TU.default(!p,p);A.encoding="binary",A.compression=S;let R=n.openDB(f,A);R.decoder=null,A.compression=T;let C=o.openDB(f,A);C.encoder=null,console.log("copying",f,"from",e,"to",t),await E(R,C,p,l)}let d=n.openDB(mf.AUDIT_STORE_NAME,pf);console.log("copying audit log"),E(i,d,!1,l);async function E(f,h,p,S){let T=0,A=0;for(let{key:R,value:C,version:x}of f.getRange({start:null,versions:p,transaction:S}))u=h.put(R,C,x),T++,S.openTimer&&(S.openTimer=0),A+=(R?.length||10)+C.length,_++>5e3&&(await u,console.log("copied",T,"entries",A,"bytes"),_=0);console.log("finish copying, copied",T,"entries",A,"bytes")}a(E,"copyDbi"),await u,console.log("copied database "+e+" to "+t)}finally{l.done(),o.close()}}var pU,hf,mo,sg,SU,TU,mf,Ai,gU,ig,ku,OU=Ae(()=>{Oe();pU=require("lmdb"),hf=require("path"),mo=require("fs-extra"),sg=B(Z()),SU=B(Lc()),TU=B(Dc()),mf=B(_t()),Ai=B(P());ti();gU=B(As()),ig=B(fr()),ku=B($());a(c9,"compactOnStart");a(mU,"getTotalDBRecordCount");a(RU,"copyDb")});var Af=g((Yhe,DU)=>{"use strict";var u9=require("minimist"),{isMainThread:ag,parentPort:NU}=require("worker_threads"),et=P(),{PROCESS_DESCRIPTORS_VALIDATE:Vu}=et,is=$(),cg=J(),gf=eg(),Tf=ot(),$he=ke(),IU=fr(),os=hU(),bU=Ta(),{compactOnStart:l9}=(OU(),ie(AU)),_9=vh(),{restartWorkers:Rf,onMessageByType:d9}=Je(),{handleHDBError:f9,hdb_errors:E9}=ne(),{HTTP_STATUS_CODES:h9}=E9,Yu=Z();Yu.initSync();var $u=`Restarting HarperDB. This may take up to ${et.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.",yU="Clustering is not enabled so cannot be restarted",p9="Invalid service",ya,fn;DU.exports={restart:wU,restartService:ug};ag&&d9(et.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?ug({service:e.workerType}):wU({operation:"restart"})});async function wU(e){fn=Object.keys(e).length===0,ya=await os.isServiceRegistered(et.HDB_PROC_DESCRIPTOR);let t=u9(process.argv);if(t.service){await ug(t);return}if(fn&&!ya){console.error(m9);return}if(fn&&console.log($u),ya){os.enterPM2Mode(),is.notify($u);let r=_9(Object.keys(et.CONFIG_PARAM_MAP),!0);return cg.isEmptyOrZeroLength(Object.keys(r))||IU.updateConfigValue(void 0,void 0,r,!0,!0),S9(),$u}return ag?(is.notify($u),Yu.get(et.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await l9(),setTimeout(()=>{Rf()},50)):NU.postMessage({type:et.ITC_EVENT_TYPES.RESTART}),$u}a(wU,"restart");async function ug(e){let{service:t}=e;if(et.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw f9(new Error,p9,h9.BAD_REQUEST,void 0,void 0,!0);if(ya=await os.isServiceRegistered(et.HDB_PROC_DESCRIPTOR),!ag)return NU.postMessage({type:et.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Vu.clustering:if(!Yu.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=yU;break}fn&&console.log("Restarting clustering"),is.notify("Restarting clustering"),await CU();break;case Vu.clustering_config:case Vu["clustering config"]:if(!Yu.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=yU;break}fn&&console.log("Restarting clustering_config"),is.notify("Restarting clustering_config"),await os.reloadClustering();break;case"custom_functions":case"custom functions":case Vu.harperdb:case Vu.http_workers:if(fn&&!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}fn&&console.log("Restarting http_workers"),is.notify("Restarting http_workers"),fn?await os.restart(et.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Rf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(is.error(r),fn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(ug,"restartService");async function S9(){await CU(),await os.restart(et.HDB_PROC_DESCRIPTOR),await cg.async_set_timeout(2e3),Yu.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await og(),fn&&(await Tf.closeConnection(),process.exit(0))}a(S9,"restartPM2Mode");async function CU(){if(!IU.getConfigFromFile(et.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await bU.getHDBProcessInfo()).clustering.length===0)is.trace("Clustering not running, restart will start clustering services"),await gf.generateNatsConfig(!0),await os.startClusteringProcesses(),await os.startClusteringThreads(),await og(),fn&&await Tf.closeConnection();else{await gf.generateNatsConfig(!0),ya?(is.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await os.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await os.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await bU.getHDBProcessInfo()).clustering.forEach(s=>{is.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await cg.async_set_timeout(3e3),await og(),await Tf.updateLocalStreams(),fn&&await Tf.closeConnection(),is.trace("Restart clustering restarting ingest and reply service threads");let t=Rf(et.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Rf(et.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(CU,"restartClustering");async function og(){await gf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await gf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(og,"removeNatsConfig")});var FU=g((Qhe,qU)=>{"use strict";var Whe=require("lodash"),Nr=P(),{handleHDBError:LU,hdb_errors:T9}=ne(),{HDB_ERROR_MSGS:g9,HTTP_STATUS_CODES:R9}=T9,lg=$();qU.exports={getRolePermissions:O9};var po=Object.create(null),A9=a(e=>({key:e,perms:{}}),"perms_template_obj"),vU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),BU=a((e=!1,t=!1,r=!1,n=!1)=>({[Nr.PERMS_CRUD_ENUM.READ]:e,[Nr.PERMS_CRUD_ENUM.INSERT]:t,[Nr.PERMS_CRUD_ENUM.UPDATE]:r,[Nr.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),_g=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...BU(t,r,n,s)}),"table_perms_template"),MU=a((e,t=BU())=>({attribute_name:e,describe:GU(t),[Ku]:t[Ku],[dg]:t[dg],[fg]:t[fg]}),"attr_perms_template"),PU=a((e,t=!1)=>({attribute_name:e,describe:t,[Ku]:t}),"timestamp_attr_perms_template"),{READ:Ku,INSERT:dg,UPDATE:fg}=Nr.PERMS_CRUD_ENUM,HU=Object.values(Nr.PERMS_CRUD_ENUM),xU=[Ku,dg,fg];function O9(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[Nr.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(po[t]&&po[t].key===n)return po[t].perms;let s=b9(e,r);return po[t]?po[t].key=n:po[t]=A9(n),po[t].perms=s,s}catch(r){if(!e[Nr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Nr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Nr.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),LU(new Error,g9.OUTDATED_PERMS_TRANSLATION_ERROR,R9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
13
+ ${r.stack}`;throw lg.error(n),LU(new Error)}}}a(O9,"getRolePermissions");function b9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Nr.SYSTEM_SCHEMA_NAME]=n[Nr.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]=vU(),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],_=N9(c,u);r[i].describe||HU.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(b9,"translateRolePermissions");function y9(e){let t=vU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=_g(!0,!0,!0,!0,!0)}),t}a(y9,"createStructureUserPermissions");function N9(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,E=l;return Nr.TIME_STAMP_NAMES.includes(d)&&(E=PU(d,l[Ku])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=MU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=GU(l),s.attribute_permissions.push(l),c||I9(l,u)}else if(_!==o){let l;Nr.TIME_STAMP_NAMES.includes(_)?l=PU(_):l=MU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=UU(s),s}else return e.describe=UU(e),e}a(N9,"getTableAttrPerms");function UU(e){return HU.filter(t=>e[t]).length>0}a(UU,"getSchemaTableDescribePerm");function GU(e){return xU.filter(t=>e[t]).length>0}a(GU,"getAttributeDescribePerm");function I9(e,t){xU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(I9,"checkForHashPerms")});var kU={};qe(kU,{Resources:()=>Of,keyArrayToString:()=>Na,resetResources:()=>w9,resources:()=>Oi});function w9(){return Oi=new Of}function Na(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Of,Oi,Wu=Ae(()=>{ro();Of=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(w9,"resetResources");a(Na,"keyArrayToString")});var VU={};qe(VU,{Headers:()=>bi,appendHeader:()=>Eg});function Eg(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var bi,Qu=Ae(()=>{bi=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];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(Eg,"appendHeader")});var zu={};qe(zu,{authentication:()=>jU,bypassAuth:()=>v9,login:()=>H9,logout:()=>x9,start:()=>B9});function v9(){JU=!0}async function jU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?M9?L9:[]:D9?C9:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new bi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return bf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),bf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(bf){i||(i=r.host);let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let p of h)if(p.startsWith(f)){let S=p.indexOf(";");u=p.slice(f.length,S===-1?p.length:S),_=await YU.get(u);break}e.session=_||(_={})}let l=a((f,h,p)=>{let S=new Ia.AuthAuditLog(f,h,Ht.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===Ht.AUTH_AUDIT_STATUS.SUCCESS?$U.notify(S):$U.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let f=e.mtlsConfig.user;f!==null?((f===void 0||f==="Common Name"||f==="CN")&&(f=e.peerCertificate.subject.CN),e.user=await st.getUser(f,null,null),l(f,Ht.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,Ia.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=So.get(n),!d){let f=n.indexOf(" "),h=n.slice(0,f),p=n.slice(f+1),S,T;try{switch(h){case"Basic":let A=atob(p),R=A.indexOf(":");S=A.slice(0,R),T=A.slice(R+1),d=S||T?await st.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,yf.validateOperationToken)(p)}catch(C){if(C.message==="invalid token")try{return await(0,yf.validateRefreshToken)(p),c({status:-1})}catch{throw C}}break}}catch(A){return U9&&(So.get(p)||(So.set(p,p),l(S,Ht.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:To({error:A.message},e)})}So.set(n,d),P9&&l(d.username,Ht.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await st.getUser(_.user,null,e):(JU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,WU.getSuperUser)());bf&&(e.session.update=function(f){if(!u){u=(0,QU.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):E?.headers?.set&&E.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")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),f.id=u,YU.put(f)},e.login=async function(f,h){e.user=await st.getUser(f,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 E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&Oi.loginPath?(E.status=302,E.headers.set("Location",Oi.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new bi);for(let d=0;d<_;){let E=o[d++];l.set(E,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function B9({server:e,port:t}){e.http(jU,{port:t||"all"}),KU||(KU=!0,setInterval(()=>{So=new Map},En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),zU.user.addListener(()=>{So=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 WU,yf,QU,En,Ht,Ia,zU,$U,C9,D9,L9,M9,YU,bf,JU,P9,U9,So,KU,Nf=Ae(()=>{WU=B(ln());ur();Wu();yf=B(yu());Oe();QU=require("uuid"),En=B(Z()),Ht=B(P()),Ia=B($()),zU=B($c());Qu();wa();$U=(0,Ia.loggerWithTag)("auth-event");En.initSync();C9=En.get(Ht.CONFIG_PARAMS.HTTP_CORSACCESSLIST),D9=En.get(Ht.CONFIG_PARAMS.HTTP_CORS),L9=En.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),M9=En.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),YU=dt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),bf=En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,JU=En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,P9=En.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,U9=En.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,So=new Map;st.onInvalidatedUser(()=>{So=new Map});a(v9,"bypassAuth");a(jU,"authentication");a(B9,"start");a(H9,"login");a(x9,"logout")});var sv=g((ime,nv)=>{"use strict";var Ce=require("joi"),XU=require("fs-extra"),ZU=require("path"),Us=je(),ev=Z(),tv=P(),rv=$(),{hdb_errors:G9}=ne(),{HDB_ERROR_MSGS:nr}=G9,Ps=/^[a-zA-Z0-9-_]+$/;nv.exports={getDropCustomFunctionValidator:F9,setCustomFunctionValidator:k9,addComponentValidator:K9,dropCustomFunctionProjectValidator:W9,packageComponentValidator:Q9,deployComponentValidator:z9,setComponentFileValidator:V9,getComponentFileValidator:Y9,dropComponentFileValidator:$9};function If(e,t,r){try{let n=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),s=ZU.join(n,t);return XU.existsSync(s)?e?t:r.message(nr.PROJECT_EXISTS):e?r.message(nr.NO_PROJECT):t}catch(n){return rv.error(n),r.message(nr.VALIDATION_ERR)}}a(If,"checkProjectExists");function Ju(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Ju,"checkFilePath");function q9(e,t,r,n){try{let s=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),i=ZU.join(s,e,t,r+".js");return XU.existsSync(i)?r:n.message(nr.NO_FILE)}catch(s){return rv.error(s),n.message(nr.VALIDATION_ERR)}}a(q9,"checkFileExists");function F9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().pattern(Ps).custom(q9.bind(null,e.project,e.type)).custom(Ju).required().messages({"string.pattern.base":nr.BAD_FILE_NAME})});return Us.validateBySchema(e,t)}a(F9,"getDropCustomFunctionValidator");function k9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().custom(Ju).required(),function_content:Ce.string().required()});return Us.validateBySchema(e,t)}a(k9,"setCustomFunctionValidator");function V9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),file:Ce.string().custom(Ju).required(),payload:Ce.string().allow("").optional(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Us.validateBySchema(e,t)}a(V9,"setComponentFileValidator");function $9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),file:Ce.string().custom(Ju).optional()});return Us.validateBySchema(e,t)}a($9,"dropComponentFileValidator");function Y9(e){let t=Ce.object({project:Ce.string().required(),file:Ce.string().custom(Ju).required(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Us.validateBySchema(e,t)}a(Y9,"getComponentFileValidator");function K9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!1)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME})});return Us.validateBySchema(e,t)}a(K9,"addComponentValidator");function W9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME})});return Us.validateBySchema(e,t)}a(W9,"dropCustomFunctionProjectValidator");function Q9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),skip_node_modules:Ce.boolean()});return Us.validateBySchema(e,t)}a(Q9,"packageComponentValidator");function z9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),payload:Ce.string().optional().messages({"string.pattern.base":nr.BAD_PACKAGE}),package:Ce.string().optional()});return Us.validateBySchema(e,t)}a(z9,"deployComponentValidator")});var Lf=g((ame,_v)=>{"use strict";var wf=require("joi"),Cf=require("path"),iv=require("fs-extra"),{exec:J9}=require("child_process"),j9=require("util"),ov=j9.promisify(J9),ju=P(),{handleHDBError:Ca,hdb_errors:X9}=ne(),{HTTP_STATUS_CODES:Da}=X9,Xu=Z(),Z9=je(),La=$();Xu.initSync();var hg=Xu.get(ju.CONFIG_PARAMS.COMPONENTSROOT),av="npm install --omit=dev --json",e7=`${av} --dry-run`;_v.exports={installModules:s7,auditModules:i7,installAllRootModules:t7,uninstallRootModule:r7,linkHarperdb:n7};async function t7(e=!1){await Df(),await Zu(e?"npm install --ignore-scripts":"npm install",Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(t7,"installAllRootModules");async function r7(e){await Zu(`npm uninstall ${e}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(r7,"uninstallRootModule");async function n7(){await Df(),await Zu(`npm link ${ju.PACKAGE_ROOT}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(n7,"linkHarperdb");async function Zu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await ov(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
14
+ `,""))}return n&&!n.includes("Debugger listening")&&La.error("Error running NPM command:",e,n),La.trace(r,n),r?.replace(`
15
+ `,"")}a(Zu,"runCommand");async function s7(e){La.info(`starting installModules for request: ${e}`);let t=lv(e);if(t)throw Ca(t,t.message,Da.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?e7:av;await Df(),await uv(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 _=Cf.join(hg,u),l,d=null;try{let{stdout:E,stderr:f}=await ov(s,{cwd:_});l=E?E.replace(`
16
+ `,""):null,d=f?f.replace(`
17
+ `,""):null}catch(E){E.stderr?i[u].npm_error=cv(E.stderr):i[u].npm_error=E.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 La.info(`finished installModules with response ${i}`),i}a(s7,"installModules");function cv(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
18
+ `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(cv,"parseNPMStdErr");async function i7(e){La.info(`starting auditModules for request: ${e}`);let t=lv(e);if(t)throw Ca(t,t.message,Da.BAD_REQUEST);let{projects:r}=e;await Df(),await uv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Cf.join(hg,o);n[o]={npm_output:null,npm_error:null};try{let u=await Zu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=cv(u.stderr)}}return La.info(`finished auditModules with response ${n}`),n}a(i7,"auditModules");async function Df(){try{return await Zu("npm -v"),!0}catch{throw Ca(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Da.BAD_REQUEST,void 0,void 0,!0)}}a(Df,"checkNPMInstalled");async function uv(e){if(!Array.isArray(e)||e.length===0)throw Ca(new Error,"projects argument must be an array with at least 1 element",Da.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=Cf.join(hg,i.toString());if(!await iv.pathExists(o)){t.push(i);continue}let u=Cf.join(o,"package.json");await iv.pathExists(u)||r.push(i)}if(t.length>0)throw Ca(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Da.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ca(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Da.BAD_REQUEST,void 0,void 0,!0)}a(uv,"checkProjectPaths");function lv(e){let t=wf.object({projects:wf.array().min(1).items(wf.string()).required(),dry_run:wf.boolean().default(!1)});return Z9.validateBySchema(e,t)}a(lv,"modulesValidator")});var pg=g((ume,mv)=>{"use strict";var Ma=require("fs-extra"),mg=require("path"),Mf=$(),dv=J(),Pf=P(),hv=Z(),o7=fr();mv.exports=a7;async function a7(){let e=c7(),t=hv.get(Pf.CONFIG_PARAMS.ROOTPATH),r=mg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Pf.PACKAGE_ROOT}},s=mg.join(t,"node_modules");await Ma.ensureDir(s);let i,o=!0,c=!1;try{i=await Ma.readJson(r)}catch(u){if(dv.isEmptyOrZeroLength(e))return;if(u.code!==Pf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!dv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await fv(_);n.dependencies[u]=l+_}if(!o){Mf.notify("Installing components"),await Ev(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await fv(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Mf.notify("Removing component",u),c=!0);c&&(Mf.notify("Updating components."),await Ev(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 fv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":mg.extname(e)||await Ma.pathExists(e)?"file:":"github:"}a(fv,"getPkgPrefix");async function Ev(e,t,r){Mf.trace("npm installing components package.json",t),await Ma.writeFile(e,JSON.stringify(t,null," "));try{await Lf().installAllRootModules(hv.get(Pf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Ma.writeFile(e,JSON.stringify(r,null," ")):await Ma.unlink(e),n}}a(Ev,"installPackages")});var gg=g((dme,gv)=>{"use strict";var Ve=require("fs-extra"),Sg=require("fast-glob"),Re=require("path"),Sv=require("tar-fs"),_me=require("uuid").v4,Tg=require("normalize-path"),as=sv(),wt=$(),We=P(),Rt=Z(),el=fr(),u7=J(),{PACKAGE_ROOT:l7}=P(),{handleHDBError:xt,hdb_errors:_7}=ne(),{basename:d7}=require("path"),f7=pg(),Tv=Z(),E7=P(),{Readable:h7}=require("stream"),{isMainThread:m7}=require("worker_threads"),{HDB_ERROR_MSGS:go,HTTP_STATUS_CODES:Gt}=_7,p7=Re.join(l7,"application-template"),pv=Re.join(Rt.get(We.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function S7(){wt.trace("getting custom api status");let e={};try{e={port:Rt.get(We.CONFIG_PARAMS.HTTP_PORT),directory:Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw xt(new Error,go.FUNCTION_STATUS,Gt.INTERNAL_SERVER_ERROR,wt.ERR,t)}return e}a(S7,"customFunctionsStatus");function T7(){wt.trace("getting custom api endpoints");let e={},t=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT);try{Sg.sync(Tg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:Sg.sync(Tg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:Sg.sync(Tg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw xt(new Error,go.GET_FUNCTIONS,Gt.INTERNAL_SERVER_ERROR,wt.ERR,r)}return e}a(T7,"getCustomFunctions");function g7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("getting custom api endpoint file content");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Re.join(r,n,s,i+".js");try{return Ve.readFileSync(o,{encoding:"utf8"})}catch(c){throw xt(new Error,go.GET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,wt.ERR,c)}}a(g7,"getCustomFunction");function R7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=as.setCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("setting custom function file content");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Ve.outputFileSync(Re.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw xt(new Error,go.SET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,wt.ERR,c)}}a(R7,"setCustomFunction");function A7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("dropping custom function file");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Ve.unlinkSync(Re.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw xt(new Error,go.DROP_FUNCTION,Gt.INTERNAL_SERVER_ERROR,wt.ERR,o)}}a(A7,"dropCustomFunction");function O7(e){e.project&&(e.project=Re.parse(e.project).name);let t=as.addComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("adding component");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Re.join(r,n);return Ve.mkdirSync(s,{recursive:!0}),Ve.copySync(p7,s),`Successfully added project: ${n}`}catch(s){throw xt(new Error,go.ADD_FUNCTION,Gt.INTERNAL_SERVER_ERROR,wt.ERR,s)}}a(O7,"addComponent");function b7(e){e.project&&(e.project=Re.parse(e.project).name);let t=as.dropCustomFunctionProjectValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("dropping custom function project");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Rt.get(We.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 el.updateConfigValue(We.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Re.join(r,n);return Ve.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw xt(new Error,go.DROP_FUNCTION_PROJECT,Gt.INTERNAL_SERVER_ERROR,wt.ERR,i)}}a(b7,"dropCustomFunctionProject");async function y7(e){e.project&&(e.project=Re.parse(e.project).name);let t=as.packageComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;wt.trace("packaging component",n);let s;try{s=await Ve.realpath(Re.join(r,n))}catch(u){if(u.code!==We.NODE_ERROR_CODES.ENOENT)throw u;try{s=await Ve.realpath(Re.join(Rt.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===We.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Ve.ensureDir(pv);let i=Re.join(pv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Re.join(s,"node_modules"))}),Sv.pack(s,o).pipe(Ve.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Ve.readFileSync(i,{encoding:"base64"});return await Ve.remove(i),{project:n,payload:c}}a(y7,"packageComponent");async function N7(e){e.project&&(e.project=Re.parse(e.project).name);let t=as.deployComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(wt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Re.join(r,n),i="file:"+o,await Ve.ensureDir(o);let E=h7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(Sv.extract(o,{finish:h})).on("error",p)});let f=await Ve.readdir(o);f.length===1&&f[0]==="package"&&(await Ve.copy(Re.join(o,"package"),o),await Ve.remove(Re.join(o,"package")))}if(await el.addConfig(n,{package:i}),!s){await f7();let E=Tv.get(E7.CONFIG_PARAMS.ROOTPATH);o=Re.join(E,"node_modules",n)}if(m7)return;let c=new Map;c.isWorker=!0;let u=(vf(),ie(Uf)),_;u.setErrorReporter(E=>_=E);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 wt.info("Installed component"),`Successfully deployed: ${n}`}a(N7,"deployComponent");async function I7(){let e=el.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 Ve.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Re.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let E={name:l,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await Ve.stat(d),f={name:Re.basename(l),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(u){return wt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{name:Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT).split(Re.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Re.join(Rt.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(vf(),ie(Uf)).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=as.getComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let n=el.getConfigObj()[e.project]||e.project==="harperdb"?Re.join(Tv.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules"):Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ve.stat(Re.join(n,e.project,e.file));return{message:await Ve.readFile(Re.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===We.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Re.join(e.project,e.file)}'`):i}}a(w7,"getComponentFile");async function C7(e){let t=as.setComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Re.join(Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Ve.ensureFile(n),await Ve.outputFile(n,e.payload,r)):await Ve.ensureDir(n),"Successfully set component: "+e.file}a(C7,"setComponentFile");async function D7(e){let t=as.dropComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=e.file?Re.join(e.project,e.file):e.project,n=Re.join(Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ve.pathExists(n)&&await Ve.remove(n),el.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(D7,"dropComponent");gv.exports={customFunctionsStatus:S7,getCustomFunctions:T7,getCustomFunction:g7,setCustomFunction:R7,dropCustomFunction:A7,addComponent:O7,dropCustomFunctionProject:b7,packageComponent:y7,deployComponent:N7,getComponents:I7,getComponentFile:w7,setComponentFile:C7,dropComponent:D7}});var Rg=g((Eme,Av)=>{"use strict";var cs=require("joi"),Rv=je();Av.exports={readTransactionLogValidator:L7,deleteTransactionLogsBeforeValidator:M7};function L7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),from:cs.date().timestamp(),to:cs.date().timestamp(),limit:cs.number().min(1)});return Rv.validateBySchema(e,t)}a(L7,"readTransactionLogValidator");function M7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),timestamp:cs.date().timestamp().required()});return Rv.validateBySchema(e,t)}a(M7,"deleteTransactionLogsBeforeValidator")});var Bf=g((mme,Iv)=>{"use strict";var Ag=P(),tl=ot(),Ov=J(),bv=Z(),yv=Rs(),{handleHDBError:Pa,hdb_errors:P7}=ne(),{HTTP_STATUS_CODES:Ua}=P7,{readTransactionLogValidator:U7,deleteTransactionLogsBeforeValidator:v7}=Rg(),Nv="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.";Iv.exports={readTransactionLog:x7,deleteTransactionLogsBefore:G7};async function*x7(e){let t=U7(e);if(t)throw Pa(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(Ag.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Pa(new Error,Nv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Ov.checkSchemaTableExist(r,n);if(s)throw Pa(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=yv.createNatsTableStreamName(r,n),o=await tl.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===Ag.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(x7,"readTransactionLog");async function G7(e){let t=v7(e);if(t)throw Pa(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(Ag.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Pa(new Error,Nv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Ov.checkSchemaTableExist(r,n);if(i)throw Pa(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=yv.createNatsTableStreamName(r,n),{jsm:c}=await tl.getNATSReferences(),u=await tl.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=B7,d,E=new Date(u.state.last_ts).getTime();return s>E?(d=u.state.last_seq+1,l=H7):d=(await tl.viewStream(o,parseInt(s),1))[0].nats_sequence,await tl.purgeTableStream(r,n,{seq:d}),l}a(G7,"deleteTransactionLogsBefore")});var Cv=g((Sme,wv)=>{"use strict";var Og=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}};wv.exports=Og});var Lv=g((gme,Dv)=>{"use strict";var bg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Dv.exports=bg});var Ng=g((Ame,Pv)=>{"use strict";var Mv=Cv(),q7=Lv(),{HDB_ERROR_MSGS:F7}=Ur(),yg=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,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 Mv(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 Mv(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}};Pv.exports=yg});var qf=g((bme,zv)=>{"use strict";var Ig=qr(),Hf=Gr(),mn=Tu(),sl=As(),wg=oi(),k7=qS(),V7=vL(),il=ln(),xf=zS(),Ct=$(),$7=XS(),Y7=Xd(),K7=LT(),W7=ef(),Q7=PT(),z7=UT(),J7=HT(),j7=GT(),Cg=kT(),vs=J(),X7=PP(),Dg=WT(),Bv=Af(),hn=P(),Hv=FU(),Z7=Ta(),xv=yu(),Gv=(Nf(),ie(zu)),qv=fr(),Jr=gg(),eee=require("alasql"),Fv=Bf(),kv=Lf(),Vv=Ng(),{handleHDBError:Ir,hdb_errors:$v}=ne(),{HDB_ERROR_MSGS:Kt,HTTP_STATUS_CODES:rl}=$v,V=new Map,Yv="delete",yi="insert",Bs="read",Ro="update",nl="describe",Uv=sl.describeSchema.name,vv=sl.describeTable.name,Kv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},tee="catchup",ree="handleGetJob",nee="handleGetJobsByStartDate",Gf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},see=[mn.createTable.name,mn.createAttribute.name,mn.dropTable.name,mn.dropAttribute.name],Wv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(Ig.insert.name,new W(!1,[yi]));V.set(Ig.update.name,new W(!1,[Ro]));V.set(Ig.upsert.name,new W(!1,[yi,Ro]));V.set(Hf.searchByConditions.name,new W(!1,[Bs]));V.set(Hf.searchByHash.name,new W(!1,[Bs]));V.set(Hf.searchByValue.name,new W(!1,[Bs]));V.set(Hf.search.name,new W(!1,[Bs]));V.set(mn.createSchema.name,new W(!0,[]));V.set(mn.createTable.name,new W(!0,[]));V.set(mn.createAttribute.name,new W(!1,[yi]));V.set(mn.dropSchema.name,new W(!0,[]));V.set(mn.dropTable.name,new W(!0,[]));V.set(mn.dropAttribute.name,new W(!0,[]));V.set(sl.describeSchema.name,new W(!1,[Bs]));V.set(sl.describeTable.name,new W(!1,[Bs]));V.set(wg.deleteRecord.name,new W(!1,[Yv]));V.set(il.addUser.name,new W(!0,[]));V.set(il.alterUser.name,new W(!0,[]));V.set(il.dropUser.name,new W(!0,[]));V.set(il.listUsersExternal.name,new W(!0,[]));V.set(xf.listRoles.name,new W(!0,[]));V.set(xf.addRole.name,new W(!0,[]));V.set(xf.alterRole.name,new W(!0,[]));V.set(xf.dropRole.name,new W(!0,[]));V.set($7.name,new W(!0,[]));V.set(Y7.name,new W(!0,[]));V.set(K7.name,new W(!0,[]));V.set(W7.name,new W(!0,[]));V.set(Q7.name,new W(!0,[]));V.set(z7.name,new W(!0,[]));V.set(Cg.setRoutes.name,new W(!0,[]));V.set(Cg.getRoutes.name,new W(!0,[]));V.set(Cg.deleteRoutes.name,new W(!0,[]));V.set(qv.setConfiguration.name,new W(!0,[]));V.set(J7.clusterStatus.name,new W(!0,[]));V.set(j7.name,new W(!0,[]));V.set(Dg.getFingerprint.name,new W(!0,[]));V.set(Dg.setLicense.name,new W(!0,[]));V.set(wg.deleteFilesBefore.name,new W(!0,[]));V.set(wg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Bv.restart.name,new W(!0,[]));V.set(Bv.restartService.name,new W(!0,[]));V.set(k7.name,new W(!0,[]));V.set(V7.name,new W(!0,[Bs]));V.set(Z7.systemInformation.name,new W(!0,[]));V.set(qv.getConfiguration.name,new W(!0,[]));V.set(Fv.readTransactionLog.name,new W(!0,[]));V.set(Fv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(kv.installModules.name,new W(!0,[]));V.set(kv.auditModules.name,new W(!0,[]));V.set(xv.createTokens.name,new W(!1,[]));V.set(xv.refreshOperationToken.name,new W(!1,[]));V.set(Gv.login.name,new W(!1,[]));V.set(Gv.logout.name,new W(!1,[]));V.set(Jr.customFunctionsStatus.name,new W(!0,[]));V.set(Jr.getCustomFunctions.name,new W(!0,[]));V.set(Jr.getComponents.name,new W(!0,[]));V.set(Jr.getComponentFile.name,new W(!0,[]));V.set(Jr.setComponentFile.name,new W(!0,[]));V.set(Jr.dropComponent.name,new W(!0,[]));V.set(Jr.getCustomFunction.name,new W(!0,[]));V.set(Jr.setCustomFunction.name,new W(!0,[]));V.set(Jr.dropCustomFunction.name,new W(!0,[]));V.set(Jr.addComponent.name,new W(!0,[]));V.set(Jr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Jr.packageComponent.name,new W(!0,[]));V.set(Jr.deployComponent.name,new W(!0,[]));V.set(Dg.getRegistrationInfo.name,new W(!1,[]));V.set(il.userInfo.name,new W(!1,[]));V.set(sl.describeAll.name,new W(!1,[]));V.set(ree,new W(!1,[]));V.set(nee,new W(!0,[]));V.set(tee,new W(!0,[]));V.set(Gf.CSV_DATA_LOAD,new W(!1,[yi,Ro]));V.set(Gf.CSV_URL_LOAD,new W(!1,[yi,Ro]));V.set(Gf.CSV_FILE_LOAD,new W(!1,[yi,Ro]));V.set(Gf.IMPORT_FROM_S3,new W(!1,[yi,Ro]));V.set(Wv.EXPORT_TO_S3,new W(!0,[]));V.set(Wv.EXPORT_LOCAL,new W(!0,[]));V.set(hn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Yv]));V.set(hn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bs]));V.set(hn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[yi]));V.set(hn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ro]));zv.exports={verifyPerms:oee,verifyPermsAst:iee,verifyBulkLoadAttributePerms:cee};function iee(e,t,r){if(vs.isEmptyOrZeroLength(e))throw Ct.info("verify_perms_ast has an empty user parameter"),Ir(new Error);if(vs.isEmptyOrZeroLength(t))throw Ct.info("verify_perms_ast has an empty user parameter"),Ir(new Error);if(vs.isEmptyOrZeroLength(r))throw Ct.info("verify_perms_ast has a null operation parameter"),Ir(new Error);try{let n=new Vv,s=new X7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Ct.info("No schemas defined in verifyPermsAst(), will not continue."),Ir(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Kv[r])throw Ir(new Error,Kt.DROP_SYSTEM,rl.FORBIDDEN);if(c&&!u)return null;let _=Hv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof eee.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let E=s.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let l=Qv(t,r,o,n);return l||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),p=Mg(t.role.permission,E,d[f]);Lg(h,p,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw Ir(n)}}a(iee,"verifyPermsAst");function oee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Ct.info("null required parameter in verifyPerms"),Ir(new Error,Kt.DEFAULT_INVALID_REQUEST,rl.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 Vv;if(vs.isEmptyOrZeroLength(e.hdb_user.role)||vs.isEmptyOrZeroLength(e.hdb_user.role.permission))return Ct.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Kt.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(hn.SYSTEM_SCHEMA_NAME)||s===hn.SYSTEM_SCHEMA_NAME;if(l&&Kv[r])throw Ir(new Error,Kt.DROP_SYSTEM,rl.FORBIDDEN);if(u&&!l||_===!0&&(r===mn.createSchema.name||r===mn.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=Hv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Uv||r===vv){if(s===hn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Kt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Uv&&(!d[s]||!d[s][nl]))return c.handleInvalidItem(Kt.SCHEMA_NOT_FOUND(s));if(r===vv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][nl]))return c.handleInvalidItem(Kt.TABLE_NOT_FOUND(s,i))}}let E=Qv(e.hdb_user,r,o,c,n);if(E)return E;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&hn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[hn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(A=>A[hn.PERMS_CRUD_ENUM.READ]).forEach(A=>{p.push(A.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let f=aee(e),h=Mg(e.hdb_user.role.permission,s,i);return Lg(f,h,r,i,s,c,n),c.getPermsResponse()}a(oee,"verifyPerms");function Qv(e,t,r,n,s){if(vs.arrayHasEmptyValues([e,t,r]))throw Ct.info("hasPermissions has an invalid parameter"),Ir(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw Ct.info(`operation ${t} not found.`),Ir(new Error,Kt.OP_NOT_FOUND(t),rl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return Ct.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Kt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][nl]===!1){n.addInvalidItem(Kt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Kt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[nl]===!1)n.addInvalidItem(Kt.TABLE_NOT_FOUND(u,l));else try{let E=[],f=V.get(t).perms;!vs.isEmpty(s)&&f.includes(s)&&(f=[s]);for(let h=0;h<f.length;h++){let p=f[h],S=d[p];(S==null||S===!1)&&(Ct.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(p))}E.length>0&&n.addUnauthorizedTable(u,l,E)}catch(E){let f=Kt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Ct.error(f),Ct.error(E),Ir($v.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(Qv,"hasPermissions");function Lg(e,t,r,n,s,i,o){if(!e||!t)throw Ct.info("no attributes specified in checkAttributePerms."),Ir(new Error);let c=V.get(r).perms;if(!c||c==="")throw Ct.info(`no permissions found for ${r} in checkAttributePerms().`),Ir(new Error);if(vs.isEmptyOrZeroLength(t))return Ct.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[nl]===!1){i.addInvalidItem(Kt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let E of c){if(hn.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Bs)throw Ir(new Error,Kt.SYSTEM_TIMESTAMP_PERMS_ERR,rl.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(Kt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Lg,"checkAttributePerms");function aee(e){let t=new Set;try{if(e.action)return t;if(e.operation===hn.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){Ct.info(r)}return t}a(aee,"getRecordAttributes");function Mg(e,t,r){let n=new Map;if(vs.isEmpty(e))return Ct.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{Ct.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Mg,"getAttributePermissions");function cee(e,t,r,n,s,i,o){let c=new Set(i),u=Mg(e,n,s);Lg(c,u,t,s,n,o,r)}a(cee,"verifyBulkLoadAttributePerms")});var kf=g((Nme,e0)=>{"use strict";e0.exports={evaluateSQL:Ree,processAST:Zv,convertSQLToAST:Xv,checkASTPermissions:jv};var uee=qr(),Jv=require("util"),lee=Jv.callbackify(uee.insert),_ee=Gr().search,dee=gD().update,fee=Jv.callbackify(dee),Eee=AD().convertDelete,Ni=require("alasql"),hee=qf(),Ff=$(),mee=md(),pee=J(),ol=P(),{hdb_errors:See,handleHDBError:Pg}=ne(),{HTTP_STATUS_CODES:Ug}=See;mee(Ni);var Tee=403,gee="There was a problem performing this insert. Please check the logs and try again.",vg=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=Xv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ni.yy.Insert?n=s.into.databaseid:s instanceof Ni.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ni.yy.Update||s instanceof Ni.yy.Delete?n=s.table.databaseid:Ff.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ni.yy.Select)&&pee.isEmptyOrZeroLength(n))return t("No schema specified",null)}Zv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Ree,"evaluateSQL");function jv(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(jv,"checkASTPermissions");function Xv(e){let t=new vg;if(!e)throw Pg(new Error,"The 'sql' parameter is missing from the request body",Ug.BAD_REQUEST);try{let r=e.trim(),n=Ni.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
19
+ `);throw n[1]?Pg(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):Pg(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(Xv,"convertSQLToAST");function Zv(e,t,r){try{let n=Aee;if(!e.bypass_auth&&!t.permissions_checked){let i=jv(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 ol.VALID_SQL_OPS_ENUM.SELECT:n=_ee,s=t.ast.statements[0];break;case ol.VALID_SQL_OPS_ENUM.INSERT:n=Oee;break;case ol.VALID_SQL_OPS_ENUM.UPDATE:n=fee;break;case ol.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(Zv,"processAST");function Aee(e,t){Ff.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){Ff.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]]=Ni.compile(`SELECT ${s.toString()} AS [${ol.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Ff.error(r),new Error(gee)}}a(bee,"createDataObjects")});var Bg=g((wme,r0)=>{"use strict";var{S3:yee,GetObjectCommand:Nee}=require("@aws-sdk/client-s3");r0.exports={getFileStreamFromS3:Iee,getS3AuthObj:t0};async function Iee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await t0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Nee(r))).Body}a(Iee,"getFileStreamFromS3");function t0(e,t,r){return new yee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(t0,"getS3AuthObj")});var Vf=g((Dme,_0)=>{"use strict";var xg=Gr(),wee=kf(),Cee=Bg(),{AsyncParser:Dee,Transform:Lee}=require("json2csv"),cl=require("stream"),jr=J(),Hg=require("fs-extra"),Mee=require("path"),pn=$(),{promisify:i0}=require("util"),al=J(),{handleHDBError:At,hdb_errors:Pee}=ne(),{HDB_ERROR_MSGS:wr,HTTP_STATUS_CODES:Ot}=Pee,{streamAsJSON:Uee}=(rm(),ie(Lb)),{Upload:vee}=require("@aws-sdk/lib-storage"),n0=["search_by_value","search_by_hash","sql","search_by_conditions"],s0=["json","csv"],o0="json",a0="csv",Bee="Successfully exported JSON locally.",Hee="Successfully exported CSV locally.",xee=1e3,Gee=xg.searchByHash,qee=xg.searchByValue,Fee=i0(wee.evaluateSQL),kee=i0(cl.finished);_0.exports={export_to_s3:Kee,export_local:Vee,toCsvStream:c0};async function Vee(e){pn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=u0(e);if(!jr.isEmpty(t))throw pn.error(t),At(new Error,t,Ot.BAD_REQUEST,void 0,void 0,!0);if(jr.isEmpty(e.path))throw pn.error(wr.MISSING_VALUE("path")),At(new Error,wr.MISSING_VALUE("path"),Ot.BAD_REQUEST,void 0,void 0,!0);let r=(jr.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=jr.buildFolderPath(e.path,r);await $ee(e.path);let s=await l0(e);return await Yee(n,e.format,s)}a(Vee,"export_local");async function $ee(e){if(pn.trace("in confirmPath"),jr.isEmptyOrZeroLength(e))throw At(new Error,`Invalid path: ${e}`,Ot.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Hg.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,pn.error(n),At(new Error,n,Ot.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 pn.error(r),At(new Error,r,Ot.BAD_REQUEST,void 0,void 0,!0)}return!0}a($ee,"confirmPath");async function Yee(e,t,r){if(pn.trace("in saveToLocal"),al.isEmptyOrZeroLength(e))throw At(new Error,wr.INVALID_VALUE("file_path"),Ot.BAD_REQUEST,void 0,void 0,!0);if(al.isEmptyOrZeroLength(t))throw At(new Error,wr.INVALID_VALUE("Source format"),Ot.BAD_REQUEST,void 0,void 0,!0);if(al.isEmpty(r))throw At(new Error,wr.NOT_FOUND("Data"),Ot.BAD_REQUEST,void 0,void 0,!0);if(t===o0){let n=Hg.createWriteStream(e);return Uee(r).pipe(n),await kee(n),{message:Bee,path:e}}else if(t===a0){let n=Hg.createWriteStream(e),s=cl.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 At(new Error,wr.INVALID_VALUE("format"),Ot.BAD_REQUEST)}a(Yee,"saveToLocal");async function Kee(e){if(!e.s3||Object.keys(e.s3).length===0)throw At(new Error,wr.MISSING_VALUE("S3 object"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw At(new Error,wr.MISSING_VALUE("aws_access_key_id"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw At(new Error,wr.MISSING_VALUE("aws_secret_access_key"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.bucket))throw At(new Error,wr.MISSING_VALUE("bucket"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.key))throw At(new Error,wr.MISSING_VALUE("key"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.region))throw At(new Error,wr.MISSING_VALUE("region"),Ot.BAD_REQUEST);let t=u0(e);if(!jr.isEmpty(t))throw At(new Error,t,Ot.BAD_REQUEST);pn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await l0(e)}catch(u){throw pn.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 cl.PassThrough;if(e.format===a0){i=e.s3.key+".csv";let u=c0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===o0){i=e.s3.key+".json";let u=new cl.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";l+=f,d!==0&&d%xee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw At(new Error,wr.INVALID_VALUE("format"),Ot.BAD_REQUEST);return new vee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Kee,"export_to_s3");function c0(e,t){let r=cl.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(c0,"toCsvStream");function u0(e){if(pn.trace("in exportCoreValidation"),jr.isEmpty(e.format))return"format missing";if(s0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${s0.join(", ")}`;let t=e.search_operation.operation;if(jr.isEmpty(t))return"search_operation.operation missing";if(n0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${n0.join(", ")}`}a(u0,"exportCoreValidation");async function l0(e){pn.trace("in getRecords");let t,r;if(al.isEmpty(e.search_operation)||al.isEmptyOrZeroLength(e.search_operation.operation))throw At(new Error,wr.INVALID_VALUE("Search operation"),Ot.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=qee;break;case"search_by_hash":t=Gee;break;case"search_by_conditions":t=xg.searchByConditions;break;case"sql":t=Fee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,pn.error(r),At(new Error,r,Ot.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(l0,"getRecords")});var T0={};qe(T0,{contentTypes:()=>kg,findBestSerializer:()=>Kf,getDeserializer:()=>Oo,registerContentHandlers:()=>Vg,serialize:()=>Wf,serializeMessage:()=>To});function Wee(e){try{return e?.[0]===123?Fg(e):e}catch{return e}}function Vg(e){e.register(zee,{serializers:[{regex:/^application\/json$/,serializer:bc},{regex:/^application\/cbor$/,serializer:function(t){return new Ao.EncoderStream(ll).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Yf.Readable.from((0,us.encodeIter)(t,ll)):(0,us.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,$f.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,us.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ao.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Kf(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,E={q:1};for(let h of l){let p=h.indexOf("=");E[h.substring(0,p)]=h.substring(p+1)}d=+E.q;let f=qt.get(_);if(f){let h=(f.q||1)*d;h>s&&(n=f,i=f.type||_,s=h,o=E)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(qt.keys()).join(", "))}};n=qt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Wf(e,t,r){let n=f0&&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=Kf(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,Hs.createBrotliCompress)({params:{[Hs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hs.constants.BROTLI_MODE_TEXT:Hs.constants.BROTLI_MODE_GENERIC,[Hs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>f0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function To(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return ul(e);let r=t.serialize;if(r)return r(e);let n=Kf(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 Oo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=qt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=qt.get(e)?.deserialize||E0(e,n);return o=>Jee(o).then(i)}return e&&qt.get(e)?.deserialize||E0(e,n)}function E0(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 Fg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function jee(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 $f,us,Ao,Hs,Yf,h0,Gg,qg,m0,p0,ul,Fg,ll,qt,kg,d0,S0,Qee,zee,f0,wa=Ae(()=>{rm();$f=B(Vf()),us=require("msgpackr"),Ao=require("cbor-x"),Hs=require("zlib"),Yf=require("stream");ur();h0=require("../index"),Gg=B(Z()),qg=B(P()),m0=B(require("yaml")),p0=Gg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,ul=p0?xi:JSON.stringify,Fg=p0?tm:JSON.parse,ll={useRecords:!1,useToJSON:!0},qt=new Map,kg=qt;st.contentTypes=kg;(0,h0._assignPackageExport)("contentTypes",kg);qt.set("application/json",{serializeStream:bc,serialize:ul,deserialize:Fg,q:.8});d0=new Ao.Encoder(ll);qt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ao.EncoderStream(ll).end(e)},serialize:d0.encode,deserialize:d0.decode,q:1});qt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Yf.Readable.from((0,us.encodeIter)(e,ll)):(0,us.pack)(e)},serialize:us.pack,deserialize:us.unpack,q:.9});qt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,$f.toCsvStream)(e,e?.getColumns?.())},serialize(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),e&&!e[Symbol.iterator]&&(e=[e.toJSON?e.toJSON():e]),(0,$f.toCsvStream)(e,e?.getColumns?.())},q:.1});qt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});qt.set("text/yaml",{serialize(e){return m0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});qt.set("text/event-stream",{serializeStream:function(e){return Yf.Readable.from(jee(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+`
20
+ `),e.data){let r=e.data;typeof r=="object"&&(r=ul(r)),t+="data: "+r+`
21
21
  `}return e.id&&(t+="id: "+e.id+`
22
22
  `),e.retry&&(t+="retry: "+e.retry+`
23
23
  `),t+`
24
- `}else return typeof e=="object"?`data: ${cl(e)}
24
+ `}else return typeof e=="object"?`data: ${ul(e)}
25
25
 
26
26
  `:`data: ${e}
27
27
 
28
- `},compressible:!1,q:.8});Gt.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()}});S0={type:"application/json",serializeStream:Oc,serialize:cl,deserialize:Qee,q:.5};Gt.set("*/*",S0);Gt.set("",S0);a(Qee,"tryJSONParse");a(Fg,"registerContentHandlers");zee=require("fastify-plugin"),Jee=zee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Vf(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(Vf,"findBestSerializer");f0=Hg.default.get(xg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a($f,"serialize");a(To,"serializeMessage");a(jee,"streamToBuffer");a(Oo,"getDeserializer");a(E0,"deserializerUnknownType");a(Xee,"transformIterable")});function $g(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],p=_(h);d=d.concat(p)}let f=new Set;return d.filter(E=>{let h=E.key??E;return f.has(h)?!1:(f.add(h),!0)})}else{let d=_(u),f=l(e.slice(1),!0,u.estimated_count);return f.length>0?o(d,f):d}function _(d){return d.conditions?$g(d.conditions,d.operator,r,n,s,i,o,c):Ba(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let A=h.operator==="or",g=l(h.conditions,!A,E);return A?(L,v)=>g.some(P=>P(L,v)):(L,v)=>g.every(P=>P(L,v))}let S=(h.attribute||h[0])===r.primaryKey,T=Kg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=ate(r.primaryStore,h.estimated_count,E)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ba(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 A=o[0],g=Gs(n.attributes,A);if(g.relationship){if(o.length<2)throw new Jr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let L=g.definition?.tableClass||g.elements?.definition?.tableClass,v=new Map,P=Ba({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,L,s,v);if(g.relationship.to){i[o[0]]=v;let k=!!Gs(L.attributes,g.relationship.to)?.elements;P=nte(P,g,L.primaryStore,k,v)}if(g.relationship.from){let k=a(H=>Ba({attribute:g.relationship.from,value:H},t,r,n,s,v),"searchEntry");g.elements?(i[o[0]]=v,P=ste(P,g,L.primaryStore,v,k)):P=P.flatMap(k)}return P}else if(o.length===1)o=o[0];else throw new Jr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Yg[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]=ls.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"sort":case"contains":case"ends_with":_=!0,E=!0;break;default:throw new Jr.ClientError(`Unknown query comparator "${u}"`)}if(r){let A=_;_=l,l=A,A=!f,f=!d,d=A}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Jr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&E)throw new Jr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Jr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Jr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Kg(e),!S)throw new Jr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let A=p.getRange(T).map(S?function({key:g,value:L}){return this.isSync?L&&S(L)?g:Ii.SKIP:new Promise((v,P)=>setImmediate(()=>{try{v(L&&S(L)?g:Ii.SKIP)}catch(k){P(k)}}))}:g=>g.value==null?Ii.SKIP:g);return A.hasEntries=!0,A}else return p?p.getRange(T).map(S?function({key:A,value:g}){return this.isSync?S({[o]:A})?g:Ii.SKIP:new Promise((L,v)=>setImmediate(()=>{try{L(S({[o]:A})?g:Ii.SKIP)}catch(P){v(P)}}))}:({value:A})=>A):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:A,value:g}){return this.isSync?g&&S(g)?A:Ii.SKIP:new Promise((L,v)=>setImmediate(()=>{try{L(g&&S(g)?A:Ii.SKIP)}catch(P){v(P)}}))})}function Gs(e,t){if(Array.isArray(t))if(t.length>1){let r=Gs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Gs(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 nte(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,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=Hn(l),o=!0);let E=s.get(f);E?E.push(d):s.set(f,E=[d]),l!==f&&(E.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),f=d?.[u];if(f!=null&&!s.filters?.some(E=>!E(d)))if(n)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}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 ste(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 _=Hn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Hn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(f=>!f(d)))continue}_.set(Hn(l),l)}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 Kg(e,t,r,n,s,i){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=Gs(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=Kg({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 p=t.propertyResolvers?.[l],S,T=a((A,g)=>{let L,v;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let k of h.idFilter.idSet)e={attribute:p.from,value:k};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let P=S(A);return S.idFilter&&(T.idFilter=S.idFilter),P}v=p(A,r,g),L=v?.value}else L=A[l];return L?Array.isArray(L)?L.some(h):h(L,v):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Yg[o]||o){case kg.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,ls.compareKeys)(l,u[0])>=0&&(0,ls.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,ls.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,ls.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,ls.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,ls.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,ls.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Jr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&Kf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(f=!1));let p=0,S=3;function T(A){let g=A[l],L;if(typeof g!="object"||!g||E?L=d(g):Array.isArray(g)?L=g.some(d):g instanceof Date&&(L=d(g.getTime())),f&&(S++,!L&&!T.idFilter&&++p/S*(i-S)>h)){let v=Ba(e,r.transaction.getReadTxn(),!1,t).map(Hn),P=new Set(v);T.idFilter=k=>P.has(Hn(k)),T.idFilter.idSet=P}return L}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function Kf(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/xs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=Yg[n]||n,n===kg.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=Gs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Kf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*xs(e.indices[i.relationship.from])/(xs(o.primaryStore)||1):c)}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=xs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=tte*xs(e.primaryStore)+1:n==="between"?r.estimated_count=ete*xs(e.primaryStore)+1:n==="sort"?r.estimated_count=xs(e.primaryStore)+1:r.estimated_count=Zee*xs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Wf(e){if(e)if(wi=e,Pa.lastIndex=0,ite.test(e))try{let t=ll(new va,"");if(Ir!==wi.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 '${wi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function ll(e,t){let r=Pa,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(wi);){Ir=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=g0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=_l(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=rte[d],u=Vg[i]?g0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=_l(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&R0(h,l),Yf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(_l(l)),s=void 0;break;case"(":Pa.lastIndex=Ir;let E=ll(l?[]:new va,")");switch(l){case"":Yf(e,_),e.conditions.push(E);break;case"limit":switch(E.length){case 1:e.limit=+E[0];break;case 2:e.offset=+E[0],e.limit=E[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(E[0])&&E.length===1&&!E[0].name?(e.select=E[0],e.select.asArray=!0):E.length===1?e.select=E[0]:E.length===2&&E[1]===""?e.select=E.slice(0,1):e.select=E;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=A0(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}wi[Ir]===","?r.lastIndex=++Ir:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Pa.lastIndex=Ir,f=ll([],"}"),f.name=l,e.push(f),wi[Ir]===","?r.lastIndex=++Ir:o=!0;break;case"[":Pa.lastIndex=Ir,l?(f=ll(new va,"]"),f.name=l):f=ll(e.conditions?new va:[],"]"),e.conditions?(Yf(e,_),e.conditions.push(f),s=null):e.push(f),wi[Ir]===","?r.lastIndex=++Ir:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&R0(h,l),Yf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(_l(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?ote:Pa,r.lastIndex=Ir),Ir===wi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Yf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function _l(e){return e.indexOf(".")>-1?e.split(".").map(_l):decodeURIComponent(e)}function g0(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(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new Jr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function R0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Jr.ClientError("wildcard can only be used at the end of a string")}function A0(e){let t=O0(e[0]);return e.length>1&&(t.next=A0(e.slice(1))),t}function O0(e){if(Array.isArray(e)){let t=O0(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 Hn(e){return Array.isArray(e)?e.join("\0"):e}function xs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function ate(e,t,r){return t*r/xs(e)}var Jr,kg,ls,Ii,Zee,ete,tte,rte,Vg,Yg,ite,Pa,ote,Ir,wi,va,Qf=Re(()=>{Jr=B(ne()),kg=B(ut()),ls=require("ordered-binary"),Ii=require("lmdb"),Zee=.3,ete=.1,tte=.05,rte={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Vg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a($g,"executeConditions");a(Ba,"searchByIndex");a(Gs,"findAttribute");a(nte,"joinTo");a(ste,"joinFrom");Yg={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(Kg,"filterByType");a(Kf,"estimateCondition");ite=/[()[\]|!<>.]|(=\w*=)/,Pa=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,ote=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Wf,"parseQuery");a(ll,"parseBlock");a(Yf,"assignOperator");a(_l,"decodeProperty");a(g0,"typedDecoding");a(R0,"wildcardDecoding");a(A0,"toSortObject");a(O0,"toSortEntry");va=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(Hn,"flattenKey");a(xs,"estimatedEntryCount");a(ate,"intersectionEstimate")});function w0(e){let t={openapi:cte,info:{title:"HarperDB HTTP REST interface",version:(0,I0.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,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:g,name:L,elements:v,relationship:P,definition:k}of o){if(P)g==="array"?_[L]={type:"array",items:{$ref:Ci+v.type}}:_[L]={$ref:Ci+g};else{let H=k??v?.definition;if(H){if(!t.components.schemas[H.type]){let j={};H.properties.forEach(z=>{j[z.name]=new Jg(Wg[z.type],z.type)}),t.components.schemas[H.type]=new y0(j)}g==="array"?_[L]={type:"array",items:{$ref:Ci+H.type}}:_[L]={$ref:Ci+H.type}}else g==="array"?v.type==="Any"||v.type=="ID"?_[L]={type:"array",items:{format:v.type}}:_[L]={type:"array",items:new Jg(Wg[v.type],v.type)}:g==="Any"||g=="ID"?_[L]={format:g}:_[L]=new Jg(Wg[g],g)}l.push(new jg(L,"query",_[L]))}let d=Object.keys(_),f=new jg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new jg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new y0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",A="/"+s+"/";h&&(t.paths[A]={},t.paths[A].post=new ute(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[A]||(t.paths[A]={}),t.paths[A].get=new Qg(l,r,{200:new zg({$ref:Ci+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new N0(l,r,"delete all the records that match the provided query",{204:new b0})),A="/"+s+"/{"+c+"}",S&&(t.paths[A]={},t.paths[A].get=new Qg([f],r,{200:new zg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[A]||(t.paths[A]={}),t.paths[A].put=new lte([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new N0([f],r,"delete a record with the given primary key",{204:new b0})),S&&E.schema.enum.length>0&&(A="/"+s+"/{"+c+"}.{property}",t.paths[A]={},t.paths[A].get=new Qg([f,E],r,{200:new zg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function ute(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ci+e}}}},this.security=t,this.responses={200:{description:Xg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Qg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function zg(e){this.description=Xg,this.content={"application/json":{schema:e}}}function b0(){this.description="successfully processed request, no content returned to client"}function lte(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ci+r}}}},this.responses={200:{description:Xg}}}function N0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function y0(e){this.type="object",this.properties=e}function Jg(e,t){this.type=e,this.format=t}function jg(e,t,r){this.name=e,this.in=t,this.schema=r}var I0,cte,Wg,Ci,Xg,C0=Re(()=>{I0=B(Vd()),cte="3.0.3",Wg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ci="#/components/schemas/",Xg="successful operation";a(w0,"generateJsonApi");a(ute,"Post");a(Qg,"Get");a(zg,"Response200");a(b0,"Response204");a(lte,"Put");a(N0,"Delete");a(y0,"ResourceSchema");a(Jg,"Type");a(jg,"Parameter")});var Jf={};qe(Jf,{start:()=>fte});async function dte(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Wf(e);let s=new bi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==D0){let h=zf.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(r["content-length"]||r["transfer-encoding"])try{e.data=Oo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new Ha.ClientError(h,400)}if(e.authorize=!0,i===D0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return w0(zf);throw new Ha.ServerError("Forbidden",403)}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 Ha.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ha.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,Zg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){_te[0]=d;let h=String.fromCharCode(34,(Kt[0]&63)+62,(Kt[0]>>6)+(Kt[1]<<2&63)+62,(Kt[1]>>4)+(Kt[2]<<4&63)+62,(Kt[2]>>2)+62,(Kt[3]&63)+62,(Kt[3]>>6)+(Kt[4]<<2&63)+62,(Kt[4]>>4)+(Kt[5]<<4&63)+62,(Kt[5]>>2)+62,(Kt[6]&63)+62,(Kt[6]>>6)+(Kt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),Zg.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=$f(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?bo.warn(i):bo.info(i):bo.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=$f(i.contentType?i:i.toString(),e,o),o}}function fte(e){Zg=e,!L0&&(L0=!0,zf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return dte(t,r)},e),e.server.ws(async(t,r,n)=>{dl++;let s=new bn;M0||(M0=!0,lu(u=>{dl>0&&u.push({metric:"ws-connections",connections:dl,byThread:!0})}));let i;t.on("error",u=>{i=!0,bo.warn(u)});let o;t.on("message",a(function(_){o||(o=Oo(r.headers.asObject["content-type"]));let l=o(_);s.push(l)},"message"));let c;t.on("close",()=>{dl--,Yr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let u=r.url.slice(1),_=zf.getMatch(u);if(Yr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,$r(h=>({count:h.count,total:dl}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;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=To(E.value,r);t.send(h),$r(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(u){t.close(Ete[u.statusCode]||1011,u.toString()),t.close("login fialed")}t.close()},e))}var bo,Ha,Kt,_te,Zg,D0,L0,zf,M0,dl,Ete,U0=Re(()=>{Ia();ws();bo=B($()),Ha=B(ne());Qf();Rc();ro();Wu();C0();Kt=new Uint8Array(8),_te=new Float64Array(Kt.buffer,0,1),Zg={},D0="openapi";a(dte,"http");dl=0;a(fte,"start");Ete={401:3e3,403:3003}});var eR=R((Qme,P0)=>{var{recordAction:jf,recordActionBinary:hte}=(ws(),ie(_u)),mte=require("fastify-plugin"),pte=200;P0.exports=mte(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,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),jf(o,"duration",_,d,l),hte(s.raw.statusCode<400,"success",_,d,l);let f=pte;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{jf(performance.now()-c,"transfer",_,d,l),jf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,jf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var oR=R((jme,x0)=>{var tE=require("clone"),rE=je(),Ste=Q(),Zf=M(),zme=$(),tR=require("fs"),nR=require("joi"),{string:eE}=nR.types(),{hdb_errors:Tte,handleHDBError:Xf}=ne(),{HDB_ERROR_MSGS:Jme,HTTP_STATUS_CODES:rR}=Tte,{common_validators:xa}=zn(),v0=" is required",gte=["insert","update","upsert"],sR={database:{presence:!1,format:xa.schema_format,length:xa.schema_length},schema:{presence:!1,format:xa.schema_format,length:xa.schema_length},table:{presence:!0,format:xa.schema_format,length:xa.schema_length},action:{inclusion:{within:gte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Rte={schema:eE.required(),table:eE.required(),action:eE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Ate,AWS_SECRET:Ote,AWS_BUCKET:bte,AWS_FILE_KEY:Nte,REGION:yte}=Zf.S3_BUCKET_AUTH_KEYS,Ite={s3:{presence:!0},[`s3.${Ate}`]:{presence:!0,type:"String"},[`s3.${Ote}`]:{presence:!0,type:"String"},[`s3.${bte}`]:{presence:!0,type:"String"},[`s3.${Nte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${yte}`]:{presence:!0,type:"String"}},B0=tE(sR);B0.data.presence={message:v0};var H0=tE(sR);H0.file_path.presence={message:v0};var wte=Object.assign(tE(sR),Ite),iR=tE(Rte);iR.csv_url=eE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();iR.passthrough_headers=nR.object();function Cte(e){let t=rE.validateObject(e,B0);return nE(e,t)}a(Cte,"dataObject");function Dte(e){let t=rE.validateBySchema(e,nR.object(iR));return nE(e,t)}a(Dte,"urlObject");function Lte(e){let t=rE.validateObject(e,H0);return nE(e,t)}a(Lte,"fileObject");function Mte(e){let t=rE.validateObject(e,wte);return nE(e,t)}a(Mte,"s3FileObject");function nE(e,t){if(!t){let r=Ste.checkGlobalSchemaTable(e.schema,e.table);if(r)return Xf(new Error,r,rR.BAD_REQUEST);if(e.operation===Zf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{tR.accessSync(e.file_path,tR.constants.R_OK|tR.constants.F_OK)}catch(n){return n.code===Zf.NODE_ERROR_CODES.ENOENT?Xf(n,`No such file or directory ${n.path}`,rR.BAD_REQUEST):n.code===Zf.NODE_ERROR_CODES.EACCES?Xf(n,`Permission denied ${n.path}`,rR.BAD_REQUEST):Xf(n)}}return t}a(nE,"postValidateChecks");x0.exports={dataObject:Cte,urlObject:Dte,fileObject:Lte,s3FileObject:Mte}});var aR=R((Zme,G0)=>{"use strict";var fl=$(),sE=M();async function Ute(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===sE.OPERATIONS_ENUM.INSERT||t.operation===sE.OPERATIONS_ENUM.UPDATE||t.operation===sE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===sE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(fl.info(i.message),i):i.http_resp_msg?(fl.error(`Error calling operation: ${e.name}`),fl.error(i.http_resp_msg),i):(fl.error(`Error calling operation: ${e.name}`),fl.error(i),i)}}a(Ute,"callOperationFunctionAsAwait");G0.exports={callOperationFunctionAsAwait:Ute}});var F0=R((tpe,q0)=>{"use strict";var cR=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}},uR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};q0.exports={BulkLoadFileObject:cR,BulkLoadDataObject:uR}});var V0=R((npe,k0)=>{"use strict";var lR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};k0.exports=lR});var mR=R((upe,oB)=>{"use strict";var iE=Hr(),aE=oR(),Pte=require("needle"),xn=M(),ipe=ke(),Ga=Q(),{handleHDBError:ot,hdb_errors:X0}=ne(),{HTTP_STATUS_CODES:Wt,HDB_ERROR_MSGS:Ct,CHECK_LOGS_WRAPPER:yo}=X0,qa=$(),_R=require("papaparse");Ga.promisifyPapaParse();var Gn=require("fs-extra"),vte=require("path"),{chain:$0}=require("stream-chain"),Y0=require("stream-json/streamers/StreamArray"),K0=require("stream-json/utils/Batch"),W0=require("stream-chain/utils/comp"),{finished:Q0}=require("stream"),Bte=Z(),Z0=aR(),Hte=Pg(),{BulkLoadFileObject:fR,BulkLoadDataObject:xte}=F0(),ER=bg(),{verifyBulkLoadAttributePerms:eB}=Hf(),ope=V0(),ape=it(),cpe=Rs(),{databases:Gte}=(Ae(),ie(Fe)),{coerceType:qte}=(cE(),ie(pR)),z0="No records parsed from csv file.",No=`${Bte.get("HDB_ROOT")}/tmp`,{schema_regex:Fte}=zn(),J0=1024*1024*2,j0=5e3,kte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};oB.exports={csvDataLoad:Vte,csvURLLoad:$te,csvFileLoad:Yte,importFromS3:Kte};async function Vte(e,t){let r=aE.dataObject(e);if(r)throw ot(r,r.message,Wt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=nB(e.schema,e.table),i=_R.parse(e.data,{header:!0,skipEmptyLines:!0,transform:dR.bind(null,s),dynamicTyping:!1}),o=new ER;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&eB(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,Wt.BAD_REQUEST,void 0,void 0,!0);let u=new xte(e.action,e.schema,e.table,i.data);return n=await Z0.callOperationFunctionAsAwait(sB,u,null),n.message===z0?z0:iB(n.records,n.number_written)}catch(s){throw Io(s)}}a(Vte,"csvDataLoad");async function $te(e){let t=aE.urlObject(e);if(t)throw ot(t,t.message,Wt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${No}/${r}`;try{await Wte(e,r)}catch(s){throw qa.error(Ct.DOWNLOAD_FILE_ERR(r)+" - "+s),ot(s,yo(Ct.DOWNLOAD_FILE_ERR(r)))}try{let s=new fR(this.job_operation_function.name,e.action,e.schema,e.table,n,xn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await hR(s);return await oE(n),i}catch(s){throw await oE(n),Io(s)}}a($te,"csvURLLoad");async function Yte(e){let t=aE.fileObject(e);if(t)throw ot(t,t.message,Wt.BAD_REQUEST,void 0,void 0,!0);let r=new fR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,xn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await hR(r)}catch(n){throw Io(n)}}a(Yte,"csvFileLoad");async function Kte(e){let t=aE.s3FileObject(e);if(t)throw ot(t,t.message,Wt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=vte.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${No}/${s}`;let i=new fR(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 hR(i);return await oE(r),o}catch(n){throw await oE(r),Io(n)}}a(Kte,"importFromS3");async function Wte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Pte("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 ot(n,s,n.statusCode,xn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}Jte(r,e.csv_url),await zte(t,r.raw)}a(Wte,"downloadCSVFile");async function Qte(e,t){try{let r=`${No}/${e}`;await Gn.mkdirp(No),await Gn.writeFile(`${No}/${e}`,"",{flag:"a+"});let n=await Gn.createWriteStream(r),s=await Hte.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(){qa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw qa.error(Ct.S3_DOWNLOAD_ERR+" - "+r),ot(r,yo(Ct.S3_DOWNLOAD_ERR))}}a(Qte,"downloadFileFromS3");async function zte(e,t){try{await Gn.mkdirp(No),await Gn.writeFile(`${No}/${e}`,t)}catch(r){throw qa.error(Ct.WRITE_TEMP_FILE_ERR),ot(r,yo(Ct.DEFAULT_BULK_LOAD_ERR))}}a(zte,"writeFileToTempFolder");async function oE(e){if(e)try{await Gn.access(e),await Gn.unlink(e)}catch{qa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(oE,"deleteTempFile");function Jte(e,t){if(e.statusCode!==X0.HTTP_STATUS_CODES.OK)throw ot(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Wt.BAD_REQUEST);if(!kte[e.headers["content-type"]])throw ot(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Wt.BAD_REQUEST);if(!e.raw)throw ot(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Wt.BAD_REQUEST)}a(Jte,"validateURLResponse");async function hR(e){try{let t;switch(e.file_type){case xn.VALID_S3_FILE_TYPES.CSV:t=await jte(e);break;case xn.VALID_S3_FILE_TYPES.JSON:t=await Xte(e);break;default:throw ot(new Error,Ct.DEFAULT_BULK_LOAD_ERR,Wt.BAD_REQUEST,xn.LOG_LEVELS.ERROR,Ct.INVALID_FILE_EXT_ERR(e))}return iB(t.records,t.number_written)}catch(t){throw Io(t)}}a(hR,"fileLoad");async function tB(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 iE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&eB(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=ot(c);r(u)}}a(tB,"validateChunk");async function rB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Ga.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Ga.isEmpty(c)&&!Ga.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 Z0.callOperationFunctionAsAwait(sB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=ot(c,yo(Ct.INSERT_CSV_ERR),Wt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,Ct.INSERT_CSV_ERR+" - "+c);r(u)}}a(rB,"insertChunk");async function jte(e){let t={records:0,number_written:0},r=nB(e.schema,e.table);try{let n=new ER,s=Gn.createReadStream(e.file_path,{highWaterMark:J0});s.setEncoding("utf8"),await _R.parsePromise(s,tB.bind(null,e,n),dR.bind(null,r));let i=n.getPermsResponse();if(i)throw ot(new Error,i,Wt.BAD_REQUEST);return s=Gn.createReadStream(e.file_path,{highWaterMark:J0}),s.setEncoding("utf8"),await _R.parsePromise(s,rB.bind(null,e,t),dR.bind(null,r)),s.destroy(),t}catch(n){throw ot(n,yo(Ct.PAPA_PARSE_ERR),Wt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,Ct.PAPA_PARSE_ERR+n)}}a(jte,"callPapaParse");function nB(e,t){let r=Gte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>qte(i,s));return n}a(nB,"createTransformMap");function dR(e,t,r){let n=e.get(r);return n?n(t):Ga.autoCast(t)}a(dR,"typeFunction");async function Xte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new ER,s=$0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await tB(e,n,r,c)})]);await new Promise((c,u)=>{Q0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw ot(new Error,i,Wt.BAD_REQUEST);let o=$0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await rB(e,t,r,c)})]);return await new Promise((c,u)=>{Q0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw ot(n,yo(Ct.INSERT_JSON_ERR),Wt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,Ct.INSERT_JSON_ERR+n)}}a(Xte,"insertJson");async function sB(e){let t={};try{e.data&&e.data.length>0&&Zte(e.data[0])?t=await ere(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",qa.info(t.message))}catch(r){throw Io(r)}return t}a(sB,"callBulkFileLoad");function Zte(e){let t=Object.keys(e);for(let r of t)if(!Fte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Zte,"validateColumnNames");async function ere(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=iE.insert;break;case"update":i=iE.update;break;case"upsert":i=iE.upsert;break;default:throw ot(new Error,Ct.INVALID_ACTION_PARAM_ERR(n),Wt.BAD_REQUEST,xn.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=Ga.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Io(o)}}a(ere,"bulkFileLoad");function iB(e,t){return`successfully loaded ${t} of ${e} records`}a(iB,"buildResponseMsg");function Io(e){return ot(e,yo(Ct.DEFAULT_BULK_LOAD_ERR),Wt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,Ct.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Io,"buildTopLevelErrMsg")});var cB=R((_pe,aB)=>{"use strict";var SR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};aB.exports=SR});var _B=R((fpe,lB)=>{"use strict";var tre=M(),uB=require("moment"),rre=require("uuid").v4,TR=class{static{a(this,"JobObject")}constructor(){this.id=rre(),this.type=void 0,this.start_datetime=uB().valueOf(),this.created_datetime=uB().valueOf(),this.end_datetime=void 0,this.status=tre.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};lB.exports=TR});var gR=R((hpe,pB)=>{"use strict";var nre=require("uuid").v4,EB=Hr(),hB=Br(),sre=es(),ire=sa(),ore=cB(),at=M(),are=_B(),cre=Bd(),pn=$(),ure=Hc(),Fa=Q(),{promisify:lre}=require("util"),wo=require("moment"),_re=Gf(),uE=oR(),dB=Ym(),{deleteTransactionLogsBeforeValidator:dre}=Tg(),{handleHDBError:fre,hdb_errors:Ere}=ne(),{HTTP_STATUS_CODES:hre}=Ere,fB=hB.searchByValue,mre=hB.searchByHash,pre=EB.insert,Sre=lre(_re.evaluateSQL),Tre=EB.update;pB.exports={addJob:Are,updateJob:bre,handleGetJob:gre,handleGetJobsByStartDate:Rre,getJobById:mB};async function gre(e){try{let t=await mB(e.id);return Fa.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 pn.error("There was an error getting job",t),new Error(r)}}a(gre,"handleGetJob");async function Rre(e){try{let t=await Ore(e);if(pn.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=wo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=wo(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 pn.error(r),new Error(r)}}a(Rre,"handleGetJobsByStartDate");async function Are(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Fa.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return pn.info(l),t.error=l,t}if(!at.JOB_TYPE_ENUM[e.operation])return pn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case at.OPERATIONS_ENUM.CSV_FILE_LOAD:n=uE.fileObject(e);break;case at.OPERATIONS_ENUM.CSV_URL_LOAD:n=uE.urlObject(e);break;case at.OPERATIONS_ENUM.CSV_DATA_LOAD:n=uE.dataObject(e);break;case at.OPERATIONS_ENUM.IMPORT_FROM_S3:n=uE.s3FileObject(e);break;case at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=dB(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=dB(e,"timestamp");break;case at.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=dre(e);break;default:break}if(n)throw fre(n,n.message,hre.BAD_REQUEST,void 0,void 0,!0);let s=new are;s.type=e.operation===at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new sre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await fB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return pn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=nre();try{o=await fB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return pn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return pn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new ure(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await pre(u)}catch(l){return pn.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,pn.trace(l)}return t}a(Are,"addJob");async function Ore(e){let t=wo(e.from_date,wo.ISO_8601),r=wo(e.to_date,wo.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 ore(n,e.hdb_user);try{return await Sre(s)}catch(i){throw pn.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(Ore,"getJobsInDateRange");async function mB(e){if(Fa.isEmptyOrZeroLength(e))return Fa.errorizeMessage("Invalid job ID specified.");let t=new ire(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await mre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return pn.error(n),Fa.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(mB,"getJobById");async function bre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Fa.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=wo().valueOf());let t=new cre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Tre(t),r}a(bre,"updateJob")});var OB=R((ppe,AB)=>{"use strict";var SB=Q(),wr=M(),Nre=require("moment"),lE=mR(),_E=$(),TB=gR(),gB=qf(),RB=oi(),yre=Je(),Ire=Uf(),RR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function wre(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(SB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(SB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case wr.JOB_TYPE_ENUM.csv_file_load:await qs(e,lE.csvFileLoad);break;case wr.JOB_TYPE_ENUM.csv_url_load:await qs(e,lE.csvURLLoad);break;case wr.JOB_TYPE_ENUM.csv_data_load:await qs(e,lE.csvDataLoad);break;case wr.JOB_TYPE_ENUM.import_from_s3:await qs(e,lE.importFromS3);break;case wr.JOB_TYPE_ENUM.empty_trash:break;case wr.JOB_TYPE_ENUM.export_local:await qs(e,gB.export_local);break;case wr.JOB_TYPE_ENUM.export_to_s3:await qs(e,gB.export_to_s3);break;case wr.JOB_TYPE_ENUM.delete_files_before:case wr.JOB_TYPE_ENUM.delete_records_before:await qs(e,RB.deleteFilesBefore);break;case wr.JOB_TYPE_ENUM.delete_audit_logs_before:await qs(e,RB.deleteAuditLogsBefore);break;case wr.JOB_TYPE_ENUM.delete_transaction_logs_before:await qs(e,Ire.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(wre,"parseMessage");async function qs(e,t){try{e.job.status=wr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Nre().valueOf(),await TB.updateJob(e.job),await Cre(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):_E.error(`There was an error running ${t.name} job with id ${e.job.id}`),_E.error(n),e.job.message=n,e.job.status=wr.JOB_STATUS_ENUM.ERROR;try{await TB.updateJob(e.job)}catch(s){throw _E.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(qs,"runJob");async function Cre(e){_E.trace("launching job thread:",e),yre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[wr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Cre,"launchJobThread");AB.exports={parseMessage:wre,RunnerMessage:RR}});var NB=R((Tpe,bB)=>{"use strict";var AR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};bB.exports=AR});var kB=R((Rpe,wR)=>{"use strict";var mE=Br(),NR=Gf(),dE=mR(),Fs=Su(),fE=As(),hl=oi(),Dre=GS(),El=un(),EE=QS(),Qt=Sg(),hE=$(),Lre=jS(),Mre=zd(),yB=CT(),Ure=jd(),Pre=LT(),vre=MT(),Bre=vT(),Hre=HT(),OR=qT(),IB=qf(),xre=Hf(),yR=gR(),q=M(),{hdb_errors:pl,handleHDBError:ml}=ne(),{HTTP_STATUS_CODES:wB}=pl,bR=YT(),CB=Tf(),xB=require("util"),ka=Hr(),Gre=Os(),qre=Sa(),DB=OB(),LB=bu(),MB=(Of(),ie(Qu)),UB=dr(),PB=Uf(),vB=wf(),{setServerUtilities:Fre}=(cE(),ie(pR)),{CONTEXT:kre}=(Nn(),ie(Gp)),{_assignPackageExport:Vre}=require("../index"),{transformReq:$re}=Q(),{server:Yre}=(ar(),ie(Hi)),rr=hE.loggerWithTag("operation"),Kre=aR(),BB=mE.searchByHash,Wre=mE.searchByValue,Qre=xB.promisify(mE.search),zre=xB.promisify(NR.evaluateSQL),Jre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=NB();async function GB(e,t){try{if(e.body.operation!=="read_log"&&(hE.log_level===q.LOG_LEVELS.INFO||hE.log_level===q.LOG_LEVELS.DEBUG||hE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;rr.info(o)}}catch(n){rr.error(n)}let r=await Kre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Jre[e.body.operation]&&Gre.setSchemaDataToGlobal(n=>{n&&rr.error(n)}),r}a(GB,"processLocalTransaction");var HB=Xre();wR.exports={chooseOperation:qB,getOperationFunction:FB,operation:IR,processLocalTransaction:GB};Fre(wR.exports);Yre.operation=IR;function qB(e){let t;try{t=FB(e)}catch(s){throw rr.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=NR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=NR.checkASTPermissions(e,i);if(o)throw rr.error(`${wB.FORBIDDEN} from operation ${e.operation}`),rr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),ml(new Error,o,pl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.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=xre.verifyPerms(i,s);if(o)throw rr.error(`${wB.FORBIDDEN} from operation ${e.operation}`),rr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),ml(new Error,o,pl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw ml(s,"There was an error when trying to choose an operation path")}return r}a(qB,"chooseOperation");function FB(e){if(rr.trace(`getOperationFunction with operation: ${e.operation}`),HB.has(e.operation))return HB.get(e.operation);throw ml(new Error,pl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),pl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(FB,"getOperationFunction");Vre("operation",IR);function IR(e,t){e.hdb_user=this[kre]?.user,e.bypass_auth=!t;let r=qB(e);return GB({body:e},r)}a(IR,"operation");async function jre(e){rr.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[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await ka.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await ka.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await ka.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await hl.deleteRecord(i);break;default:rr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){rr.info("Invalid operation in transaction"),rr.error(o)}}a(jre,"catchup");async function _s(e){$re(e);let t,r;try{r=await yR.addJob(e),t=r.createdJob,rr.info("addJob result",r);let n=new DB.RunnerMessage(t,e);return await DB.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 rr.error(s),ml(n,s)}}a(_s,"executeJob");function Xre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y(ka.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y(ka.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y(ka.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(mE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(BB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(BB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(Wre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(Qre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(zre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(_s,dE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(_s,dE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(_s,dE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(_s,dE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Fs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(fE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(fE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(fE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(fE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(hl.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(El.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(El.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(El.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(El.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(EE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(EE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(EE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(EE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(El.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(Lre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Mre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(yB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(yB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(Ure)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Pre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(vre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(UB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Bre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Hre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(OR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(OR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(OR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(_s,IB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(_s,hl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(_s,hl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(_s,IB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(yR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(yR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(bR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(bR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(bR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(CB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(CB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(jre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(qre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(_s,hl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(Dre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(LB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(LB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(MB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(MB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(UB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Qt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Qt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Qt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Qt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Qt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Qt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Qt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Qt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Qt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Qt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Qt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Qt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Qt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Qt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Qt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Qt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(PB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(_s,PB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(vB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(vB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(Xre,"initializeOperationFunctionMap")});var SE=R((Ope,YB)=>{"use strict";var CR=M(),Zre=Q(),Sl=$(),{handleHDBError:DR,hdb_errors:pE}=ne(),{isMainThread:ene}=require("worker_threads"),{Readable:tne}=require("stream"),VB=require("os"),rne=require("util"),nne=aT(),sne=rne.promisify(nne.authorize),$B=kB(),{createGzip:ine,constants:one}=require("zlib");function ane(e){let t=`Found an uncaught exception with message: ${e.message}. ${VB.EOL}Stack: ${e.stack} ${VB.EOL}Terminating ${ene?"HDB":"thread"}.`;console.error(t),Sl.fatal(t),process.exit(1)}a(ane,"handleServerUncaughtException");function cne(e,t,r){if(Sl[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:pE.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(cne,"serverErrorHandler");function une(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=DR(new Error,"Invalid JSON.",pE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Zre.isEmpty(e.body.operation)){let n=DR(new Error,"Request body must include an 'operation' property.",pE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(une,"reqBodyValidationHandler");function lne(e,t,r){let n;e.body.operation!==CR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==CR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==CR.OPERATIONS_ENUM.LOGOUT?sne(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Sl.warn(s),Sl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(DR(s,i,pE.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(lne,"authHandler");async function _ne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=$B.chooseOperation(e.body);let s=await $B.processLocalTransaction(e,n);if(s instanceof tne&&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(ine({level:one.Z_BEST_SPEED})))}return s}catch(s){throw Sl.error(s),s}}a(_ne,"handlePostRequest");YB.exports={authHandler:lne,handlePostRequest:_ne,handleServerUncaughtException:ane,serverErrorHandler:cne,reqBodyValidationHandler:une}});var zB=R((Npe,QB)=>{"use strict";var dne=require("fastify-plugin"),{handlePostRequest:KB,authHandler:fne,reqBodyValidationHandler:Ene}=SE();async function hne(e){e.decorate("hdbCore",{preValidation:[Ene,fne],request:t=>WB(KB(t,response)),requestWithoutAuthentication:(t,r)=>WB(KB(t,r,!0))})}a(hne,"hdbCore");async function WB(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(WB,"convertAsyncIterators");QB.exports=dne(hne)});var XB=R((wpe,jB)=>{"use strict";var Ipe=require("fs"),LR=Z();LR.initSync();var{CONFIG_PARAMS:JB}=M(),mne=1024*1024*1024;function pne(e){let t=LR.get(JB.HTTP_TIMEOUT),r=LR.get(JB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:mne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(pne,"getServerOptions");jB.exports=pne});var tH=R((Dpe,eH)=>{"use strict";var MR=Z();MR.initSync();var{CONFIG_PARAMS:ZB}=M();function Sne(){let e=MR.get(ZB.HTTP_CORSACCESSLIST),t=MR.get(ZB.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(Sne,"getCORSOptions");eH.exports=Sne});var sH=R((Mpe,nH)=>{"use strict";var rH=Z();rH.initSync();var Tne=M();function gne(){return rH.get(Tne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(gne,"getHeaderTimeoutConfig");nH.exports=gne});var PR={};qe(PR,{customFunctionsServer:()=>One,ready:()=>TH,start:()=>Ane});function Ane(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=SH(t),nt.http((await ks).server));let o=await ks,c=(0,UR.dirname)(s),u=(0,UR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!iH.has(c)){iH.add(c);try{o.register(Nne(c,u))}catch(_){if(_.message==="Root plugin has already booted")$e.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:TH}}async function One(){try{$e.info("In Custom Functions Fastify server"+process.cwd()),$e.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),$e.debug(`Custom Functions server process ${process.pid} starting up.`),await bne();let e=_H.get(dH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await SH(e)}catch(r){throw $e.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw $e.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){$e.error(`Custom Functions ${process.pid} Error: ${e}`),$e.error(e),process.exit(1)}}async function bne(){try{$e.info("Custom Functions starting configuration."),await fH.setUsersToGlobal(),$e.info("Custom Functions completed configuration.")}catch(e){$e.error(e)}}function Nne(e,t){return async function(r){try{$e.info("Custom Functions starting buildRoutes"),$e.trace("Loading fastify routes folder "+e),(0,oH.existsSync)(e)&&r.register(lH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:$e.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?$e.error(s.message):s&&$e.error(s),o()})}catch(n){$e.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function SH(e){$e.info("Custom Functions starting buildServer.");let t=(0,EH.default)(e),r=(0,aH.default)(t);r.server.headersTimeout=(0,mH.default)(),r.setErrorHandler(pH.serverErrorHandler);let n=(0,hH.default)();return n&&r.register(cH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(uH.default),await r.register(Rne),await r.after(),Fg(r),$e.info("Custom Functions completed buildServer."),r}function TH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var UR,oH,aH,cH,uH,lH,_H,dH,$e,Rne,fH,EH,hH,mH,pH,ks,iH,gH=Re(()=>{UR=require("path"),oH=require("fs"),aH=B(require("fastify")),cH=B(require("@fastify/cors")),uH=B(eR()),lH=B(require("@fastify/autoload")),_H=B(Z()),dH=B(M()),$e=B($()),Rne=B(zB()),fH=B(un()),EH=B(XB()),hH=B(tH()),mH=B(sH()),pH=B(SE());Ia();ar();iH=new Set;a(Ane,"start");a(One,"customFunctionsServer");a(bne,"setUp");a(Nne,"buildRouteFolder");a(SH,"buildServer");a(TH,"ready")});var vR={};qe(vR,{start:()=>yne});function yne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,NH.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){AH||(AH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=RH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,OH.default)(s,(0,bH.realpathSync)(o))}}return i(s)},{runFirst:!0})),RH.set(r,n)}}}var OH,bH,NH,RH,AH,yH=Re(()=>{OH=B(require("send")),bH=require("fs"),NH=B(require("serve-static")),RH=new Map;a(yne,"start")});function Cne(e,t=1,r){if(BR++,(0,Co.startWorker)("server/threads/threadServer.js",{name:RE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===RE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});wne.push(s),await s,Va.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=gE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Va.indexOf(n);o>-1&&Va.splice(o,1)}if(a(i,"removeWorker"),$a){let o=$a;$a=[];for(let c of o)DH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{HR?HR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Co.shutdownWorkers)(),BR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function LH(e=0,t){if(typeof e=="string")try{(0,AE.existsSync)(e)&&(0,AE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Dne:r=Lne(t):r=GR;let n=(0,Ya.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=DH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),HR=!0,r(o,(c,u)=>{if(!c){if(IH){let l=o._socket||new Ya.Socket({handle:o,writable:!0,readable:!0});IH.deliverSocket(l,e,u),l.resume()}else BR>0?($a.length===0&&setTimeout(()=>{$a.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,$a.push(o)):(console.log("start up a dynamic thread to handle request"),Cne(0));$r(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Ya.Socket({handle:o,writable:!0,readable:!0});vne(l,c,e)}$r(!0,"socket-routed")})};let s=ou();xR.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 GR(e,t){let r,n=0;for(let s of Va){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=TE)return TE=i,t(r);n=i}TE=0,t(r)}function Dne(e,t){let r={};e.getpeername(r);let n=r.address,s=Ka.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);GR(e,o=>{Ka.set(n,{worker:o,lastUsed:i}),t(o)})}function Lne(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Ya.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ka.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);GR(n,d=>{Ka.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Une(){TE=0;for(let e of Va)e.expectedIdle=e.recentELU.idle+Mne,e.requests=1;Va.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function vne(e,t,r){let n=Pne++;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(),gE.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")),gE.delete(n)),s.event=="destroy"&&(e.destroy(),gE.delete(n))})}var Co,Ya,RE,xR,AE,CH,Ine,Va,$a,DH,IH,BR,wne,HR,TE,wH,Ka,Mne,gE,Pne,MH=Re(()=>{Co=B(Je()),Ya=require("net"),RE=B(M()),xR=B($()),AE=require("fs");ws();CH=require("worker_threads"),Ine=B(Ji()),Va=[],$a=[],DH=[],BR=0,wne=[];CH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Cne,"startHTTPWorker");a(LH,"startSocketServer");TE=0;a(GR,"findMostIdleWorker");wH=36e5,Ka=new Map;a(Dne,"findByRemoteAddressAffinity");a(Lne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ka)r.lastUsed+wH<e&&Ka.delete(t)},wH).unref();Mne=1e3;a(Une,"updateWorkerIdleness");(0,Co.setMonitorListener)(Une);gE=new Map,Pne=1;a(vne,"proxySocket")});var VR={};qe(VR,{Request:()=>qR,createReuseportFd:()=>OE});var UH,qR,FR,kR,OE,bE=Re(()=>{UH=require("os"),qR=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 kR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new 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}pipe(t,r){return this.#e.pipe(t,r)}},kR=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,UH.platform)()!="win32"&&(OE=require("node-unix-socket").createReuseportFd)});var HH=R((Wpe,BH)=>{"use strict";var Bne=require("cluster"),Do=Z();Do.initSync();var vH=M(),kpe=require("util"),Vs=$(),Vpe=require("fs"),Hne=require("fastify"),$pe=ou(),xne=require("@fastify/cors"),Gne=require("@fastify/compress"),qne=require("@fastify/static"),Fne=eR(),kne=require("path"),{PACKAGE_ROOT:Vne}=M(),$ne=Os(),Yne=Q(),Kne=un(),Wne=Ji(),{server:Qne}=(ar(),ie(Hi)),{node_request_key:Ype}=(bE(),ie(VR)),{authHandler:zne,handlePostRequest:Jne,serverErrorHandler:jne,reqBodyValidationHandler:Xne}=SE(),Kpe=require("net"),{registerContentHandlers:Zne}=(Ia(),ie(T0)),ese=6e4,tse=1024*1024*1024,rse="TRUE",{CONFIG_PARAMS:Tl}=vH,Wa;BH.exports={hdbServer:PH,start:PH};async function PH(e){try{Vs.info("In Fastify server"+process.cwd()),Vs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Bne.isMaster,await nse();let t=e.securePort>0;Wa=sse(t),await Wa.ready(),e||(e={}),e.isOperationsServer=!0;try{Qne.http(Wa.server,e),Wa.server.closeIdleConnections||await Wa.listen({port:0,host:"::"})}catch(r){throw Wa.close(),Vs.error(r),Vs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vs.fatal(t),process.exit(1)}}a(PH,"operationsServer");async function nse(){Vs.trace("Configuring HarperDB process."),$ne.setSchemaDataToGlobal(),await Kne.setUsersToGlobal(),await Wne.getLicense()}a(nse,"setUp");function sse(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=ise(e),r=Hne(t);r.server.headersTimeout=ase(),r.setErrorHandler(jne);let n=ose();n&&r.register(xne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Fne),r.register(Gne),r.register(qne,{root:kne.join(Vne,"studio/build-local")}),Zne(r);let s=Do.get(vH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Yne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Xne,zne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Jne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(sse,"buildServer");function ise(e){let t=Do.get(Tl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(Tl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:tse,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(ise,"getServerOptions");function ose(){let e=Do.get(Tl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(Tl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===rse)&&(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(ose,"getCORSOpts");function ase(){return Do.get(Tl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??ese}a(ase,"getHeaderTimeoutConfig")});var zR={};qe(zR,{disableNATS:()=>use,publishToStream:()=>IE,setNATSReplicator:()=>$R,setPublishToStream:()=>lse,setSubscription:()=>QR,start:()=>cse});function cse(){gl.default.get(Rl.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&dse()}function use(e=!0){kH=e}function lse(e,t){IE=e,QR=t}function dse(){if(kH||process.env._DISABLE_NATS)return;let e=Er(),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];$R(s,r,i)}}JR((r,n)=>{$R(r.tableName,r.databaseName,r),n&&$H(r)}),!xH&&(xH=!0)}function $R(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 kt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Le],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){$H(i)}static subscribe(){let i=new bn;return QR(t,e,i),i}static subscribeOnThisThread(i){return i<(gl.default.get(Rl.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??_se)}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=VH;return i}a(n,"getNATSTransaction")}function $H(e){let t=gl.default.get(Rl.default.CONFIG_PARAMS.CLUSTERING_NODENAME);IE(`${KR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,WR.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 GH,KR,WR,qH,FH,gl,Rl,yE,kH,IE,QR,_se,VH,xH,NE,YR,YH=Re(()=>{Ae();Nn();GH=B(it()),KR=B(ke()),WR=B(Rs());Rc();qH=B(IS()),FH=B(Mr()),gl=B(Z()),Rl=B(M()),yE=B($());a(cse,"start");a(use,"disableNATS");IE=GH.publishToStream,QR=qH.setSubscription;a(lse,"setPublishToStream");_se=2;a(dse,"assignReplicationSource");a($R,"setNATSReplicator");a($H,"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=gl.default.get(Rl.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||(yE.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(IE(`${KR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,WR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw yE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},YR=class extends NE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,FH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};VH=new YR});var ix=R(Di=>{"use strict";var{isMainThread:ZR,parentPort:Ol,threadId:wE}=require("worker_threads"),{Socket:fse,createServer:Ese}=require("net"),{createServer:hse,IncomingMessage:mse}=require("http"),{createServer:pse}=require("https"),{readFileSync:Sse,unlinkSync:KH,existsSync:Tse}=require("fs"),Dt=$(),xe=Z(),Et=M(),{server:ME}=(ar(),ie(Hi)),{WebSocketServer:gse}=require("ws"),{createSecureContext:Rse,createServer:Ase}=require("node:tls"),{getTicketKeys:JH,restartNumber:Ose,getWorkerIndex:DE}=Je(),{Headers:jH,appendHeader:bse}=(Wu(),ie(VP)),{recordAction:Al,recordActionBinary:Nse}=(ws(),ie(_u)),{Request:XH,createReuseportFd:WH}=(bE(),ie(VR)),{checkMemoryLimit:yse}=Ji(),{X509Certificate:Ise}=require("crypto"),ZH=require("tls"),wse=ZH.createSecureContext,Qa;ZH.createSecureContext=function(e){return Qa||wse(e)};var ex=xe.get(Et.CONFIG_PARAMS.THREADS_DEBUG);if(ex){let e;if(ZR)e=xe.get(Et.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Dt.info("Could not close debugger",t)}});else{let t=xe.get(Et.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&DE()>=0&&(e=t+DE())}if(e){let t=xe.get(Et.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=xe.get(Et.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Dt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&ZR)try{require("inspector").open(9229)}catch(e){Ose<=1&&Dt.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:eSe,CONFIG_PARAMS:Cse}=Et;xe.initSync();var Dse=xe.get(Cse.HTTP_SESSIONAFFINITY),ds={};Di.registerServer=nA;Di.httpServer=sA;Di.deliverSocket=rA;Di.startServers=tx;Di.when_components_loaded=null;Di.createSNICallback=iA;ME.http=sA;ME.request=Pse;ME.socket=vse;ME.ws=Bse;var jR={},CE={},Lse,$s={},LE={},Mse=[],eA=[];function tx(){return Di.when_components_loaded=oA().loadRootComponents(!0).then(()=>{Ol?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)rA(n,r,s);else if(t.requestId)Use(t);else if(t.type===Et.ITC_EVENT_TYPES.SHUTDOWN){Dt.trace("received shutdown request",wE);for(let i in ds){let o=ds[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(f=>f.description.includes("connections")),l=0,d=setInterval(()=>{l++;let f=l>=100,E=o[_][f?"all":"idle"]();if(E.length===0){f&&clearInterval(d);return}l===1?Dt.info(`Closing ${E.length} idle connections`):f&&Dt.warn(`Forcefully closing ${E.length} active connections`);for(let h=0,p=E.length;h<p;h++){let S=E[h].socket;S._httpMessage&&!S._httpMessage.finished&&!f||(f?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
28
+ `},compressible:!1,q:.8});qt.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()}});S0={type:"application/json",serializeStream:bc,serialize:ul,deserialize:Wee,q:.5};qt.set("*/*",S0);qt.set("",S0);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}=Kf(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(Kf,"findBestSerializer");f0=Gg.default.get(qg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Wf,"serialize");a(To,"serializeMessage");a(Jee,"streamToBuffer");a(Oo,"getDeserializer");a(E0,"deserializerUnknownType");a(jee,"transformIterable")});function Kg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let f=1;f<e.length;f++){let h=e[f],p=_(h);d=d.concat(p)}let E=new Set;return d.filter(f=>{let h=f.key??f;return E.has(h)?!1:(E.add(h),!0)})}else{let d=_(u),E=l(e.slice(1),!0,u.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?Kg(d.conditions,d.operator,r,n,s,i,o,c):Ha(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,E,f){return d.map((h,p)=>{if(h.conditions){let A=h.operator==="or",R=l(h.conditions,!A,f);return A?(C,x)=>R.some(v=>v(C,x)):(C,x)=>R.every(v=>v(C,x))}let S=(h.attribute||h[0])===r.primaryKey,T=Qg(h,r,i,c,S,f);return E&&p<d.length-1&&f&&(f=ote(r.primaryStore,h.estimated_count,f)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ha(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 A=o[0],R=Gs(n.attributes,A);if(R.relationship){if(o.length<2)throw new Xr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let C=R.definition?.tableClass||R.elements?.definition?.tableClass,x=new Map,v=Ha({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,C,s,x);if(R.relationship.to){i[o[0]]=x;let k=!!Gs(C.attributes,R.relationship.to)?.elements;v=rte(v,R,C.primaryStore,k,x)}if(R.relationship.from){let k=a(M=>Ha({attribute:R.relationship.from,value:M},t,r,n,s,x),"searchEntry");R.elements?(i[o[0]]=x,v=nte(v,R,C.primaryStore,x,k)):v=v.flatMap(k)}return v}else if(o.length===1)o=o[0];else throw new Xr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,E;c instanceof Date&&(c=c.getTime());let f;switch(Wg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,E=!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]=ls.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,E=!0;break}case"sort":case"contains":case"ends_with":_=!0,f=!0;break;default:throw new Xr.ClientError(`Unknown query comparator "${u}"`)}if(r){let A=_;_=l,l=A,A=!E,E=!d,d=A}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||f||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Xr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&f)throw new Xr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Xr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Xr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Qg(e),!S)throw new Xr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:E,values:!0,versions:h,transaction:t,reverse:r};if(h){let A=p.getRange(T).map(S?function({key:R,value:C}){return this.isSync?C&&S(C)?R:Ii.SKIP:new Promise((x,v)=>setImmediate(()=>{try{x(C&&S(C)?R:Ii.SKIP)}catch(k){v(k)}}))}:R=>R.value==null?Ii.SKIP:R);return A.hasEntries=!0,A}else return p?p.getRange(T).map(S?function({key:A,value:R}){return this.isSync?S({[o]:A})?R:Ii.SKIP:new Promise((C,x)=>setImmediate(()=>{try{C(S({[o]:A})?R:Ii.SKIP)}catch(v){x(v)}}))}:({value:A})=>A):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:A,value:R}){return this.isSync?R&&S(R)?A:Ii.SKIP:new Promise((C,x)=>setImmediate(()=>{try{C(R&&S(R)?A:Ii.SKIP)}catch(v){x(v)}}))})}function Gs(e,t){if(Array.isArray(t))if(t.length>1){let r=Gs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Gs(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 rte(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,_=a((l,d)=>{let E=l;Array.isArray(l)&&(E=xn(l),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),l!==E&&(f.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),E=d?.[u];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],l);else _(E,l)}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 nte(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 _=xn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(xn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(E=>!E(d)))continue}_.set(xn(l),l)}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 Qg(e,t,r,n,s,i){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=Gs(t.attributes,l),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[l],h=Qg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},E,r,f?.[l]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let p=t.propertyResolvers?.[l],S,T=a((A,R)=>{let C,x;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let k of h.idFilter.idSet)e={attribute:p.from,value:k};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let v=S(A);return S.idFilter&&(T.idFilter=S.idFilter),v}x=p(A,r,R),C=x?.value}else C=A[l];return C?Array.isArray(C)?C.some(h):h(C,x):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Wg[o]||o){case $g.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,E=u.length;d<E;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,ls.compareKeys)(l,u[0])>=0&&(0,ls.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,ls.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,ls.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,ls.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,ls.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,ls.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Xr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,E,f){let h;E=E&&!s&&t?.indices[l]&&i>3,E&&(e.estimated_count==null&&zf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function T(A){let R=A[l],C;if(typeof R!="object"||!R||f?C=d(R):Array.isArray(R)?C=R.some(d):R instanceof Date&&(C=d(R.getTime())),E&&(S++,!C&&!T.idFilter&&++p/S*(i-S)>h)){let x=Ha(e,r.transaction.getReadTxn(),!1,t).map(xn),v=new Set(x);T.idFilter=k=>v.has(xn(k)),T.idFilter.idSet=v}return C}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function zf(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/xs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=Wg[n]||n,n===$g.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=Gs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=zf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*xs(e.indices[i.relationship.from])/(xs(o.primaryStore)||1):c)}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=xs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=ete*xs(e.primaryStore)+1:n==="between"?r.estimated_count=Zee*xs(e.primaryStore)+1:n==="sort"?r.estimated_count=xs(e.primaryStore)+1:r.estimated_count=Xee*xs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jf(e){if(e)if(wi=e,va.lastIndex=0,ste.test(e))try{let t=_l(new Ba,"");if(Cr!==wi.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 ${Cr} in '${wi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function _l(e,t){let r=va,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(wi);){Cr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=g0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=dl(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=tte[d],u=Yg[i]?g0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=dl(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&R0(h,l),Qf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(dl(l)),s=void 0;break;case"(":va.lastIndex=Cr;let f=_l(l?[]:new Ba,")");switch(l){case"":Qf(e,_),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=A0(f);break;default:throw new SyntaxError(`unknown query function call ${l}`)}wi[Cr]===","?r.lastIndex=++Cr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");va.lastIndex=Cr,E=_l([],"}"),E.name=l,e.push(E),wi[Cr]===","?r.lastIndex=++Cr:o=!0;break;case"[":va.lastIndex=Cr,l?(E=_l(new Ba,"]"),E.name=l):E=_l(e.conditions?new Ba:[],"]"),e.conditions?(Qf(e,_),e.conditions.push(E),s=null):e.push(E),wi[Cr]===","?r.lastIndex=++Cr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&R0(h,l),Qf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(dl(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?ite:va,r.lastIndex=Cr),Cr===wi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Qf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function dl(e){return e.indexOf(".")>-1?e.split(".").map(dl):decodeURIComponent(e)}function g0(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(isNaN(r)?decodeURIComponent(r):+r);if(t==="string")return decodeURIComponent(r);throw new Xr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function R0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Xr.ClientError("wildcard can only be used at the end of a string")}function A0(e){let t=O0(e[0]);return e.length>1&&(t.next=A0(e.slice(1))),t}function O0(e){if(Array.isArray(e)){let t=O0(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 xn(e){return Array.isArray(e)?e.join("\0"):e}function xs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function ote(e,t,r){return t*r/xs(e)}var Xr,$g,ls,Ii,Xee,Zee,ete,tte,Yg,Wg,ste,va,ite,Cr,wi,Ba,jf=Ae(()=>{Xr=B(ne()),$g=B(_t()),ls=require("ordered-binary"),Ii=require("lmdb"),Xee=.3,Zee=.1,ete=.05,tte={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Yg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Kg,"executeConditions");a(Ha,"searchByIndex");a(Gs,"findAttribute");a(rte,"joinTo");a(nte,"joinFrom");Wg={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(Qg,"filterByType");a(zf,"estimateCondition");ste=/[()[\]|!<>.]|(=\w*=)/,va=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,ite=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jf,"parseQuery");a(_l,"parseBlock");a(Qf,"assignOperator");a(dl,"decodeProperty");a(g0,"typedDecoding");a(R0,"wildcardDecoding");a(A0,"toSortObject");a(O0,"toSortEntry");Ba=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(xn,"flattenKey");a(xs,"estimatedEntryCount");a(ote,"intersectionEstimate")});function w0(e){let t={openapi:ate,info:{title:"HarperDB HTTP REST interface",version:(0,I0.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,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:C,elements:x,relationship:v,definition:k}of o){if(v)R==="array"?_[C]={type:"array",items:{$ref:Ci+x.type}}:_[C]={$ref:Ci+R};else{let M=k??x?.definition;if(M){if(!t.components.schemas[M.type]){let Q={};M.properties.forEach(j=>{Q[j.name]=new Xg(zg[j.type],j.type)}),t.components.schemas[M.type]=new N0(Q)}R==="array"?_[C]={type:"array",items:{$ref:Ci+M.type}}:_[C]={$ref:Ci+M.type}}else R==="array"?x.type==="Any"||x.type=="ID"?_[C]={type:"array",items:{format:x.type}}:_[C]={type:"array",items:new Xg(zg[x.type],x.type)}:R==="Any"||R=="ID"?_[C]={format:R}:_[C]=new Xg(zg[R],R)}l.push(new Zg(C,"query",_[C]))}let d=Object.keys(_),E=new Zg(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new Zg("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new N0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",A="/"+s+"/";h&&(t.paths[A]={},t.paths[A].post=new cte(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[A]||(t.paths[A]={}),t.paths[A].get=new Jg(l,r,{200:new jg({$ref:Ci+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new y0(l,r,"delete all the records that match the provided query",{204:new b0})),A="/"+s+"/{"+c+"}",S&&(t.paths[A]={},t.paths[A].get=new Jg([E],r,{200:new jg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[A]||(t.paths[A]={}),t.paths[A].put=new ute([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new y0([E],r,"delete a record with the given primary key",{204:new b0})),S&&f.schema.enum.length>0&&(A="/"+s+"/{"+c+"}.{property}",t.paths[A]={},t.paths[A].get=new Jg([E,f],r,{200:new jg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function cte(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ci+e}}}},this.security=t,this.responses={200:{description:eR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Jg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function jg(e){this.description=eR,this.content={"application/json":{schema:e}}}function b0(){this.description="successfully processed request, no content returned to client"}function ute(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ci+r}}}},this.responses={200:{description:eR}}}function y0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function N0(e){this.type="object",this.properties=e}function Xg(e,t){this.type=e,this.format=t}function Zg(e,t,r){this.name=e,this.in=t,this.schema=r}var I0,ate,zg,Ci,eR,C0=Ae(()=>{I0=B(Kd()),ate="3.0.3",zg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ci="#/components/schemas/",eR="successful operation";a(w0,"generateJsonApi");a(cte,"Post");a(Jg,"Get");a(jg,"Response200");a(b0,"Response204");a(ute,"Put");a(y0,"Delete");a(N0,"ResourceSchema");a(Xg,"Type");a(Zg,"Parameter")});var Zf={};qe(Zf,{start:()=>dte});async function _te(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Jf(e);let s=new bi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==D0){let h=Xf.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(r["content-length"]||r["transfer-encoding"])try{e.data=Oo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new xa.ClientError(h,400)}if(e.authorize=!0,i===D0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return w0(Xf);throw new xa.ServerError("Forbidden",403)}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 xa.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new xa.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,tR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){lte[0]=d;let h=String.fromCharCode(34,(Wt[0]&63)+62,(Wt[0]>>6)+(Wt[1]<<2&63)+62,(Wt[1]>>4)+(Wt[2]<<4&63)+62,(Wt[2]>>2)+62,(Wt[3]&63)+62,(Wt[3]>>6)+(Wt[4]<<2&63)+62,(Wt[4]>>4)+(Wt[5]<<4&63)+62,(Wt[5]>>2)+62,(Wt[6]&63)+62,(Wt[6]>>6)+(Wt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),tR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:l,headers:s,body:void 0},f=_?.wasLoadedFromSource?.();return f!==void 0&&(E.wasCacheMiss=f,!f&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(E.body=Wf(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?bo.warn(i):bo.info(i):bo.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=Wf(i.contentType?i:i.toString(),e,o),o}}function dte(e){tR=e,!L0&&(L0=!0,Xf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return _te(t,r)},e),e.server.ws(async(t,r,n)=>{fl++;let s=new yn;M0||(M0=!0,_u(u=>{fl>0&&u.push({metric:"ws-connections",connections:fl,byThread:!0})}));let i;t.on("error",u=>{i=!0,bo.warn(u)});let o;t.on("message",a(function(_){o||(o=Oo(r.headers.asObject["content-type"]));let l=o(_);s.push(l)},"message"));let c;t.on("close",()=>{fl--,Wr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let u=r.url.slice(1),_=Xf.getMatch(u);if(Wr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,pr(h=>({count:h.count,total:fl}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Xe(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=To(f.value,r);t.send(h),pr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(u){t.close(fte[u.statusCode]||1011,u.toString()),t.close("login fialed")}t.close()},e))}var bo,xa,Wt,lte,tR,D0,L0,Xf,M0,fl,fte,P0=Ae(()=>{wa();ws();bo=B($()),xa=B(ne());jf();Ac();ro();Qu();C0();Wt=new Uint8Array(8),lte=new Float64Array(Wt.buffer,0,1),tR={},D0="openapi";a(_te,"http");fl=0;a(dte,"start");fte={401:3e3,403:3003}});var rR=g((Qme,U0)=>{var{recordAction:eE,recordActionBinary:Ete}=(ws(),ie(du)),hte=require("fastify-plugin"),mte=200;U0.exports=hte(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,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),Ete(s.raw.statusCode<400,"success",_,d,l);let E=mte;i?.pipe?(i.on("data",h=>{E+=h.length}),i.on("end",()=>{eE(performance.now()-c,"transfer",_,d,l),eE(E,"bytes-sent",_,d,l)})):(E+=i?.length||0,eE(E,"bytes-sent",_,d,l));let f=o.toFixed(3);s.header("Server-Timing",`db;dur=${f}`)}),r()},{name:"hdb-request-time"})});var cR=g((jme,x0)=>{var sE=require("clone"),iE=je(),pte=J(),rE=P(),zme=$(),nR=require("fs"),iR=require("joi"),{string:nE}=iR.types(),{hdb_errors:Ste,handleHDBError:tE}=ne(),{HDB_ERROR_MSGS:Jme,HTTP_STATUS_CODES:sR}=Ste,{common_validators:Ga}=zn(),v0=" is required",Tte=["insert","update","upsert"],oR={database:{presence:!1,format:Ga.schema_format,length:Ga.schema_length},schema:{presence:!1,format:Ga.schema_format,length:Ga.schema_length},table:{presence:!0,format:Ga.schema_format,length:Ga.schema_length},action:{inclusion:{within:Tte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},gte={schema:nE.required(),table:nE.required(),action:nE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Rte,AWS_SECRET:Ate,AWS_BUCKET:Ote,AWS_FILE_KEY:bte,REGION:yte}=rE.S3_BUCKET_AUTH_KEYS,Nte={s3:{presence:!0},[`s3.${Rte}`]:{presence:!0,type:"String"},[`s3.${Ate}`]:{presence:!0,type:"String"},[`s3.${Ote}`]:{presence:!0,type:"String"},[`s3.${bte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${yte}`]:{presence:!0,type:"String"}},B0=sE(oR);B0.data.presence={message:v0};var H0=sE(oR);H0.file_path.presence={message:v0};var Ite=Object.assign(sE(oR),Nte),aR=sE(gte);aR.csv_url=nE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();aR.passthrough_headers=iR.object();function wte(e){let t=iE.validateObject(e,B0);return oE(e,t)}a(wte,"dataObject");function Cte(e){let t=iE.validateBySchema(e,iR.object(aR));return oE(e,t)}a(Cte,"urlObject");function Dte(e){let t=iE.validateObject(e,H0);return oE(e,t)}a(Dte,"fileObject");function Lte(e){let t=iE.validateObject(e,Ite);return oE(e,t)}a(Lte,"s3FileObject");function oE(e,t){if(!t){let r=pte.checkGlobalSchemaTable(e.schema,e.table);if(r)return tE(new Error,r,sR.BAD_REQUEST);if(e.operation===rE.OPERATIONS_ENUM.CSV_FILE_LOAD)try{nR.accessSync(e.file_path,nR.constants.R_OK|nR.constants.F_OK)}catch(n){return n.code===rE.NODE_ERROR_CODES.ENOENT?tE(n,`No such file or directory ${n.path}`,sR.BAD_REQUEST):n.code===rE.NODE_ERROR_CODES.EACCES?tE(n,`Permission denied ${n.path}`,sR.BAD_REQUEST):tE(n)}}return t}a(oE,"postValidateChecks");x0.exports={dataObject:wte,urlObject:Cte,fileObject:Dte,s3FileObject:Lte}});var uR=g((Zme,G0)=>{"use strict";var El=$(),aE=P();async function Mte(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===aE.OPERATIONS_ENUM.INSERT||t.operation===aE.OPERATIONS_ENUM.UPDATE||t.operation===aE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===aE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(El.info(i.message),i):i.http_resp_msg?(El.error(`Error calling operation: ${e.name}`),El.error(i.http_resp_msg),i):(El.error(`Error calling operation: ${e.name}`),El.error(i),i)}}a(Mte,"callOperationFunctionAsAwait");G0.exports={callOperationFunctionAsAwait:Mte}});var F0=g((tpe,q0)=>{"use strict";var lR=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}},_R=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};q0.exports={BulkLoadFileObject:lR,BulkLoadDataObject:_R}});var V0=g((npe,k0)=>{"use strict";var dR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};k0.exports=dR});var SR=g((upe,oB)=>{"use strict";var cE=qr(),lE=cR(),Pte=require("needle"),Gn=P(),ipe=ke(),qa=J(),{handleHDBError:at,hdb_errors:X0}=ne(),{HTTP_STATUS_CODES:Qt,HDB_ERROR_MSGS:Dt,CHECK_LOGS_WRAPPER:No}=X0,Fa=$(),fR=require("papaparse");qa.promisifyPapaParse();var qn=require("fs-extra"),Ute=require("path"),{chain:$0}=require("stream-chain"),Y0=require("stream-json/streamers/StreamArray"),K0=require("stream-json/utils/Batch"),W0=require("stream-chain/utils/comp"),{finished:Q0}=require("stream"),vte=Z(),Z0=uR(),Bte=Bg(),{BulkLoadFileObject:hR,BulkLoadDataObject:Hte}=F0(),mR=Ng(),{verifyBulkLoadAttributePerms:eB}=qf(),ope=V0(),ape=ot(),cpe=Rs(),{databases:xte}=(Oe(),ie(Fe)),{coerceType:Gte}=(_E(),ie(TR)),z0="No records parsed from csv file.",yo=`${vte.get("HDB_ROOT")}/tmp`,{schema_regex:qte}=zn(),J0=1024*1024*2,j0=5e3,Fte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};oB.exports={csvDataLoad:kte,csvURLLoad:Vte,csvFileLoad:$te,importFromS3:Yte};async function kte(e,t){let r=lE.dataObject(e);if(r)throw at(r,r.message,Qt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=nB(e.schema,e.table),i=fR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:ER.bind(null,s),dynamicTyping:!1}),o=new mR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&eB(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,Qt.BAD_REQUEST,void 0,void 0,!0);let u=new Hte(e.action,e.schema,e.table,i.data);return n=await Z0.callOperationFunctionAsAwait(sB,u,null),n.message===z0?z0:iB(n.records,n.number_written)}catch(s){throw Io(s)}}a(kte,"csvDataLoad");async function Vte(e){let t=lE.urlObject(e);if(t)throw at(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${yo}/${r}`;try{await Kte(e,r)}catch(s){throw Fa.error(Dt.DOWNLOAD_FILE_ERR(r)+" - "+s),at(s,No(Dt.DOWNLOAD_FILE_ERR(r)))}try{let s=new hR(this.job_operation_function.name,e.action,e.schema,e.table,n,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await pR(s);return await uE(n),i}catch(s){throw await uE(n),Io(s)}}a(Vte,"csvURLLoad");async function $te(e){let t=lE.fileObject(e);if(t)throw at(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r=new hR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await pR(r)}catch(n){throw Io(n)}}a($te,"csvFileLoad");async function Yte(e){let t=lE.s3FileObject(e);if(t)throw at(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Ute.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${yo}/${s}`;let i=new hR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Wte(s,e);let o=await pR(i);return await uE(r),o}catch(n){throw await uE(r),Io(n)}}a(Yte,"importFromS3");async function Kte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Pte("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,Gn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}zte(r,e.csv_url),await Qte(t,r.raw)}a(Kte,"downloadCSVFile");async function Wte(e,t){try{let r=`${yo}/${e}`;await qn.mkdirp(yo),await qn.writeFile(`${yo}/${e}`,"",{flag:"a+"});let n=await qn.createWriteStream(r),s=await Bte.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(){Fa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Fa.error(Dt.S3_DOWNLOAD_ERR+" - "+r),at(r,No(Dt.S3_DOWNLOAD_ERR))}}a(Wte,"downloadFileFromS3");async function Qte(e,t){try{await qn.mkdirp(yo),await qn.writeFile(`${yo}/${e}`,t)}catch(r){throw Fa.error(Dt.WRITE_TEMP_FILE_ERR),at(r,No(Dt.DEFAULT_BULK_LOAD_ERR))}}a(Qte,"writeFileToTempFolder");async function uE(e){if(e)try{await qn.access(e),await qn.unlink(e)}catch{Fa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(uE,"deleteTempFile");function zte(e,t){if(e.statusCode!==X0.HTTP_STATUS_CODES.OK)throw at(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Qt.BAD_REQUEST);if(!Fte[e.headers["content-type"]])throw at(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Qt.BAD_REQUEST);if(!e.raw)throw at(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Qt.BAD_REQUEST)}a(zte,"validateURLResponse");async function pR(e){try{let t;switch(e.file_type){case Gn.VALID_S3_FILE_TYPES.CSV:t=await Jte(e);break;case Gn.VALID_S3_FILE_TYPES.JSON:t=await jte(e);break;default:throw at(new Error,Dt.DEFAULT_BULK_LOAD_ERR,Qt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Dt.INVALID_FILE_EXT_ERR(e))}return iB(t.records,t.number_written)}catch(t){throw Io(t)}}a(pR,"fileLoad");async function tB(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 cE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&eB(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(tB,"validateChunk");async function rB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;qa.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!qa.isEmpty(c)&&!qa.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 Z0.callOperationFunctionAsAwait(sB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=at(c,No(Dt.INSERT_CSV_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Dt.INSERT_CSV_ERR+" - "+c);r(u)}}a(rB,"insertChunk");async function Jte(e){let t={records:0,number_written:0},r=nB(e.schema,e.table);try{let n=new mR,s=qn.createReadStream(e.file_path,{highWaterMark:J0});s.setEncoding("utf8"),await fR.parsePromise(s,tB.bind(null,e,n),ER.bind(null,r));let i=n.getPermsResponse();if(i)throw at(new Error,i,Qt.BAD_REQUEST);return s=qn.createReadStream(e.file_path,{highWaterMark:J0}),s.setEncoding("utf8"),await fR.parsePromise(s,rB.bind(null,e,t),ER.bind(null,r)),s.destroy(),t}catch(n){throw at(n,No(Dt.PAPA_PARSE_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Dt.PAPA_PARSE_ERR+n)}}a(Jte,"callPapaParse");function nB(e,t){let r=xte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Gte(i,s));return n}a(nB,"createTransformMap");function ER(e,t,r){let n=e.get(r);return n?n(t):qa.autoCast(t)}a(ER,"typeFunction");async function jte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new mR,s=$0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await tB(e,n,r,c)})]);await new Promise((c,u)=>{Q0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw at(new Error,i,Qt.BAD_REQUEST);let o=$0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await rB(e,t,r,c)})]);return await new Promise((c,u)=>{Q0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw at(n,No(Dt.INSERT_JSON_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Dt.INSERT_JSON_ERR+n)}}a(jte,"insertJson");async function sB(e){let t={};try{e.data&&e.data.length>0&&Xte(e.data[0])?t=await Zte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Fa.info(t.message))}catch(r){throw Io(r)}return t}a(sB,"callBulkFileLoad");function Xte(e){let t=Object.keys(e);for(let r of t)if(!qte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Xte,"validateColumnNames");async function Zte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=cE.insert;break;case"update":i=cE.update;break;case"upsert":i=cE.upsert;break;default:throw at(new Error,Dt.INVALID_ACTION_PARAM_ERR(n),Qt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Dt.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=qa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Io(o)}}a(Zte,"bulkFileLoad");function iB(e,t){return`successfully loaded ${t} of ${e} records`}a(iB,"buildResponseMsg");function Io(e){return at(e,No(Dt.DEFAULT_BULK_LOAD_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Dt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Io,"buildTopLevelErrMsg")});var cB=g((_pe,aB)=>{"use strict";var gR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};aB.exports=gR});var _B=g((fpe,lB)=>{"use strict";var ere=P(),uB=require("moment"),tre=require("uuid").v4,RR=class{static{a(this,"JobObject")}constructor(){this.id=tre(),this.type=void 0,this.start_datetime=uB().valueOf(),this.created_datetime=uB().valueOf(),this.end_datetime=void 0,this.status=ere.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};lB.exports=RR});var AR=g((hpe,pB)=>{"use strict";var rre=require("uuid").v4,EB=qr(),hB=Gr(),nre=es(),sre=ia(),ire=cB(),ct=P(),ore=_B(),are=Gd(),Sn=$(),cre=xc(),ka=J(),{promisify:ure}=require("util"),wo=require("moment"),lre=kf(),dE=cR(),dB=Wm(),{deleteTransactionLogsBeforeValidator:_re}=Rg(),{handleHDBError:dre,hdb_errors:fre}=ne(),{HTTP_STATUS_CODES:Ere}=fre,fB=hB.searchByValue,hre=hB.searchByHash,mre=EB.insert,pre=ure(lre.evaluateSQL),Sre=EB.update;pB.exports={addJob:Rre,updateJob:Ore,handleGetJob:Tre,handleGetJobsByStartDate:gre,getJobById:mB};async function Tre(e){try{let t=await mB(e.id);return ka.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 Sn.error("There was an error getting job",t),new Error(r)}}a(Tre,"handleGetJob");async function gre(e){try{let t=await Are(e);if(Sn.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=wo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=wo(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 Sn.error(r),new Error(r)}}a(gre,"handleGetJobsByStartDate");async function Rre(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||ka.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Sn.info(l),t.error=l,t}if(!ct.JOB_TYPE_ENUM[e.operation])return Sn.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=dB(e,"date");break;case ct.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=dB(e,"timestamp");break;case ct.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=_re(e);break;default:break}if(n)throw dre(n,n.message,Ere.BAD_REQUEST,void 0,void 0,!0);let s=new ore;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 nre(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await fB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=rre();try{o=await fB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Sn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new cre(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await mre(u)}catch(l){return Sn.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,Sn.trace(l)}return t}a(Rre,"addJob");async function Are(e){let t=wo(e.from_date,wo.ISO_8601),r=wo(e.to_date,wo.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 ire(n,e.hdb_user);try{return await pre(s)}catch(i){throw Sn.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(Are,"getJobsInDateRange");async function mB(e){if(ka.isEmptyOrZeroLength(e))return ka.errorizeMessage("Invalid job ID specified.");let t=new sre(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await hre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Sn.error(n),ka.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(mB,"getJobById");async function Ore(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(ka.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=wo().valueOf());let t=new are(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Sre(t),r}a(Ore,"updateJob")});var OB=g((ppe,AB)=>{"use strict";var SB=J(),Dr=P(),bre=require("moment"),fE=SR(),EE=$(),TB=AR(),gB=Vf(),RB=oi(),yre=Je(),Nre=Bf(),OR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Ire(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(SB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(SB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Dr.JOB_TYPE_ENUM.csv_file_load:await qs(e,fE.csvFileLoad);break;case Dr.JOB_TYPE_ENUM.csv_url_load:await qs(e,fE.csvURLLoad);break;case Dr.JOB_TYPE_ENUM.csv_data_load:await qs(e,fE.csvDataLoad);break;case Dr.JOB_TYPE_ENUM.import_from_s3:await qs(e,fE.importFromS3);break;case Dr.JOB_TYPE_ENUM.empty_trash:break;case Dr.JOB_TYPE_ENUM.export_local:await qs(e,gB.export_local);break;case Dr.JOB_TYPE_ENUM.export_to_s3:await qs(e,gB.export_to_s3);break;case Dr.JOB_TYPE_ENUM.delete_files_before:case Dr.JOB_TYPE_ENUM.delete_records_before:await qs(e,RB.deleteFilesBefore);break;case Dr.JOB_TYPE_ENUM.delete_audit_logs_before:await qs(e,RB.deleteAuditLogsBefore);break;case Dr.JOB_TYPE_ENUM.delete_transaction_logs_before:await qs(e,Nre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Ire,"parseMessage");async function qs(e,t){try{e.job.status=Dr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=bre().valueOf(),await TB.updateJob(e.job),await wre(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=Dr.JOB_STATUS_ENUM.ERROR;try{await TB.updateJob(e.job)}catch(s){throw EE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(qs,"runJob");async function wre(e){EE.trace("launching job thread:",e),yre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Dr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(wre,"launchJobThread");AB.exports={parseMessage:Ire,RunnerMessage:OR}});var yB=g((Tpe,bB)=>{"use strict";var bR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};bB.exports=bR});var kB=g((Rpe,DR)=>{"use strict";var TE=Gr(),IR=kf(),hE=SR(),Fs=Tu(),mE=As(),ml=oi(),Cre=qS(),hl=ln(),pE=zS(),zt=gg(),SE=$(),Dre=XS(),Lre=Xd(),NB=LT(),Mre=ef(),Pre=PT(),Ure=UT(),vre=HT(),Bre=GT(),yR=kT(),IB=Vf(),Hre=qf(),wR=AR(),q=P(),{hdb_errors:Sl,handleHDBError:pl}=ne(),{HTTP_STATUS_CODES:wB}=Sl,NR=WT(),CB=Af(),xB=require("util"),Va=qr(),xre=Os(),Gre=Ta(),DB=OB(),LB=yu(),MB=(Nf(),ie(zu)),PB=fr(),UB=Bf(),vB=Lf(),{setServerUtilities:qre}=(_E(),ie(TR)),{CONTEXT:Fre}=(Nn(),ie(qp)),{_assignPackageExport:kre}=require("../index"),{transformReq:Vre}=J(),{server:$re}=(ur(),ie(Hi)),sr=SE.loggerWithTag("operation"),Yre=uR(),BB=TE.searchByHash,Kre=TE.searchByValue,Wre=xB.promisify(TE.search),Qre=xB.promisify(IR.evaluateSQL),zre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=yB();async function GB(e,t){try{if(e.body.operation!=="read_log"&&(SE.log_level===q.LOG_LEVELS.INFO||SE.log_level===q.LOG_LEVELS.DEBUG||SE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;sr.info(o)}}catch(n){sr.error(n)}let r=await Yre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return zre[e.body.operation]&&xre.setSchemaDataToGlobal(n=>{n&&sr.error(n)}),r}a(GB,"processLocalTransaction");var HB=jre();DR.exports={chooseOperation:qB,getOperationFunction:FB,operation:CR,processLocalTransaction:GB};qre(DR.exports);$re.operation=CR;function qB(e){let t;try{t=FB(e)}catch(s){throw sr.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=IR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=IR.checkASTPermissions(e,i);if(o)throw sr.error(`${wB.FORBIDDEN} from operation ${e.operation}`),sr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.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=Hre.verifyPerms(i,s);if(o)throw sr.error(`${wB.FORBIDDEN} from operation ${e.operation}`),sr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw pl(s,"There was an error when trying to choose an operation path")}return r}a(qB,"chooseOperation");function FB(e){if(sr.trace(`getOperationFunction with operation: ${e.operation}`),HB.has(e.operation))return HB.get(e.operation);throw pl(new Error,Sl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Sl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(FB,"getOperationFunction");kre("operation",CR);function CR(e,t){e.hdb_user=this[Fre]?.user,e.bypass_auth=!t;let r=qB(e);return GB({body:e},r)}a(CR,"operation");async function Jre(e){sr.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[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await Va.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await Va.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await Va.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await ml.deleteRecord(i);break;default:sr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){sr.info("Invalid operation in transaction"),sr.error(o)}}a(Jre,"catchup");async function _s(e){Vre(e);let t,r;try{r=await wR.addJob(e),t=r.createdJob,sr.info("addJob result",r);let n=new DB.RunnerMessage(t,e);return await DB.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 sr.error(s),pl(n,s)}}a(_s,"executeJob");function jre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y(Va.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y(Va.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y(Va.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(TE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(BB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(BB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(Kre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(Wre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(Qre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(_s,hE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(_s,hE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(_s,hE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(_s,hE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Fs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(mE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(mE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(mE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(mE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(ml.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(hl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(hl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(hl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(hl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(pE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(pE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(pE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(pE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(hl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(Dre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Lre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(NB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(NB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(Mre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Pre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(Ure)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(PB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(vre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Bre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(yR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(yR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(yR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(_s,IB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(_s,ml.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(_s,ml.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(_s,IB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(wR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(wR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(NR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(NR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(NR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(CB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(CB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(Jre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Gre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(_s,ml.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(Cre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(LB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(LB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(MB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(MB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(PB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(zt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(zt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(zt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(zt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(zt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(zt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(zt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(zt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(zt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(zt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(zt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(zt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(zt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(zt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(zt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(zt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(UB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(_s,UB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(vB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(vB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(jre,"initializeOperationFunctionMap")});var RE=g((Ope,YB)=>{"use strict";var LR=P(),Xre=J(),Tl=$(),{handleHDBError:MR,hdb_errors:gE}=ne(),{isMainThread:Zre}=require("worker_threads"),{Readable:ene}=require("stream"),VB=require("os"),tne=require("util"),rne=cT(),nne=tne.promisify(rne.authorize),$B=kB(),{createGzip:sne,constants:ine}=require("zlib");function one(e){let t=`Found an uncaught exception with message: ${e.message}. ${VB.EOL}Stack: ${e.stack} ${VB.EOL}Terminating ${Zre?"HDB":"thread"}.`;console.error(t),Tl.fatal(t),process.exit(1)}a(one,"handleServerUncaughtException");function ane(e,t,r){if(Tl[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:gE.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(ane,"serverErrorHandler");function cne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=MR(new Error,"Invalid JSON.",gE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Xre.isEmpty(e.body.operation)){let n=MR(new Error,"Request body must include an 'operation' property.",gE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(cne,"reqBodyValidationHandler");function une(e,t,r){let n;e.body.operation!==LR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==LR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==LR.OPERATIONS_ENUM.LOGOUT?nne(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Tl.warn(s),Tl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(MR(s,i,gE.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(une,"authHandler");async function lne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=$B.chooseOperation(e.body);let s=await $B.processLocalTransaction(e,n);if(s instanceof ene&&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(sne({level:ine.Z_BEST_SPEED})))}return s}catch(s){throw Tl.error(s),s}}a(lne,"handlePostRequest");YB.exports={authHandler:une,handlePostRequest:lne,handleServerUncaughtException:one,serverErrorHandler:ane,reqBodyValidationHandler:cne}});var zB=g((ype,QB)=>{"use strict";var _ne=require("fastify-plugin"),{handlePostRequest:KB,authHandler:dne,reqBodyValidationHandler:fne}=RE();async function Ene(e){e.decorate("hdbCore",{preValidation:[fne,dne],request:t=>WB(KB(t,response)),requestWithoutAuthentication:(t,r)=>WB(KB(t,r,!0))})}a(Ene,"hdbCore");async function WB(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(WB,"convertAsyncIterators");QB.exports=_ne(Ene)});var XB=g((wpe,jB)=>{"use strict";var Ipe=require("fs"),PR=Z();PR.initSync();var{CONFIG_PARAMS:JB}=P(),hne=1024*1024*1024;function mne(e){let t=PR.get(JB.HTTP_TIMEOUT),r=PR.get(JB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:hne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(mne,"getServerOptions");jB.exports=mne});var tH=g((Dpe,eH)=>{"use strict";var UR=Z();UR.initSync();var{CONFIG_PARAMS:ZB}=P();function pne(){let e=UR.get(ZB.HTTP_CORSACCESSLIST),t=UR.get(ZB.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(pne,"getCORSOptions");eH.exports=pne});var sH=g((Mpe,nH)=>{"use strict";var rH=Z();rH.initSync();var Sne=P();function Tne(){return rH.get(Sne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Tne,"getHeaderTimeoutConfig");nH.exports=Tne});var BR={};qe(BR,{customFunctionsServer:()=>Ane,ready:()=>TH,start:()=>Rne});function Rne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=SH(t),st.http((await ks).server));let o=await ks,c=(0,vR.dirname)(s),u=(0,vR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!iH.has(c)){iH.add(c);try{o.register(bne(c,u))}catch(_){if(_.message==="Root plugin has already booted")$e.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:TH}}async function Ane(){try{$e.info("In Custom Functions Fastify server"+process.cwd()),$e.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),$e.debug(`Custom Functions server process ${process.pid} starting up.`),await One();let e=_H.get(dH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await SH(e)}catch(r){throw $e.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw $e.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){$e.error(`Custom Functions ${process.pid} Error: ${e}`),$e.error(e),process.exit(1)}}async function One(){try{$e.info("Custom Functions starting configuration."),await fH.setUsersToGlobal(),$e.info("Custom Functions completed configuration.")}catch(e){$e.error(e)}}function bne(e,t){return async function(r){try{$e.info("Custom Functions starting buildRoutes"),$e.trace("Loading fastify routes folder "+e),(0,oH.existsSync)(e)&&r.register(lH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:$e.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?$e.error(s.message):s&&$e.error(s),o()})}catch(n){$e.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function SH(e){$e.info("Custom Functions starting buildServer.");let t=(0,EH.default)(e),r=(0,aH.default)(t);r.server.headersTimeout=(0,mH.default)(),r.setErrorHandler(pH.serverErrorHandler);let n=(0,hH.default)();return n&&r.register(cH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(uH.default),await r.register(gne),await r.after(),Vg(r),$e.info("Custom Functions completed buildServer."),r}function TH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var vR,oH,aH,cH,uH,lH,_H,dH,$e,gne,fH,EH,hH,mH,pH,ks,iH,gH=Ae(()=>{vR=require("path"),oH=require("fs"),aH=B(require("fastify")),cH=B(require("@fastify/cors")),uH=B(rR()),lH=B(require("@fastify/autoload")),_H=B(Z()),dH=B(P()),$e=B($()),gne=B(zB()),fH=B(ln()),EH=B(XB()),hH=B(tH()),mH=B(sH()),pH=B(RE());wa();ur();iH=new Set;a(Rne,"start");a(Ane,"customFunctionsServer");a(One,"setUp");a(bne,"buildRouteFolder");a(SH,"buildServer");a(TH,"ready")});var HR={};qe(HR,{start:()=>yne});function yne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,yH.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){AH||(AH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=RH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,OH.default)(s,(0,bH.realpathSync)(o))}}return i(s)},{runFirst:!0})),RH.set(r,n)}}}var OH,bH,yH,RH,AH,NH=Ae(()=>{OH=B(require("send")),bH=require("fs"),yH=B(require("serve-static")),RH=new Map;a(yne,"start")});function wne(e,t=1,r){if(xR++,(0,Co.startWorker)("server/threads/threadServer.js",{name:bE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===bE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Ine.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=OE.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)DH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{GR?GR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Co.shutdownWorkers)(),xR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function LH(e=0,t){if(typeof e=="string")try{(0,yE.existsSync)(e)&&(0,yE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Cne:r=Dne(t):r=FR;let n=(0,Ka.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=DH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),GR=!0,r(o,(c,u)=>{if(!c){if(IH){let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});IH.deliverSocket(l,e,u),l.resume()}else xR>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"),wne(0));pr(!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});Une(l,c,e)}pr(!0,"socket-routed")})};let s=au();qR.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 FR(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>=AE)return AE=i,t(r);n=i}AE=0,t(r)}function Cne(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);FR(e,o=>{Wa.set(n,{worker:o,lastUsed:i}),t(o)})}function Dne(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);FR(n,d=>{Wa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Mne(){AE=0;for(let e of $a)e.expectedIdle=e.recentELU.idle+Lne,e.requests=1;$a.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Une(e,t,r){let n=Pne++;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(),OE.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")),OE.delete(n)),s.event=="destroy"&&(e.destroy(),OE.delete(n))})}var Co,Ka,bE,qR,yE,CH,Nne,$a,Ya,DH,IH,xR,Ine,GR,AE,wH,Wa,Lne,OE,Pne,MH=Ae(()=>{Co=B(Je()),Ka=require("net"),bE=B(P()),qR=B($()),yE=require("fs");ws();CH=require("worker_threads"),Nne=B(Ji()),$a=[],Ya=[],DH=[],xR=0,Ine=[];CH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(wne,"startHTTPWorker");a(LH,"startSocketServer");AE=0;a(FR,"findMostIdleWorker");wH=36e5,Wa=new Map;a(Cne,"findByRemoteAddressAffinity");a(Dne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Wa)r.lastUsed+wH<e&&Wa.delete(t)},wH).unref();Lne=1e3;a(Mne,"updateWorkerIdleness");(0,Co.setMonitorListener)(Mne);OE=new Map,Pne=1;a(Une,"proxySocket")});var YR={};qe(YR,{Request:()=>kR,createReuseportFd:()=>NE});var PH,kR,VR,$R,NE,IE=Ae(()=>{PH=require("os"),kR=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 $R(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new VR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},VR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},$R=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,PH.platform)()!="win32"&&(NE=require("node-unix-socket").createReuseportFd)});var HH=g((Wpe,BH)=>{"use strict";var vne=require("cluster"),Do=Z();Do.initSync();var vH=P(),kpe=require("util"),Vs=$(),Vpe=require("fs"),Bne=require("fastify"),$pe=au(),Hne=require("@fastify/cors"),xne=require("@fastify/compress"),Gne=require("@fastify/static"),qne=rR(),Fne=require("path"),{PACKAGE_ROOT:kne}=P(),Vne=Os(),$ne=J(),Yne=ln(),Kne=Ji(),{server:Wne}=(ur(),ie(Hi)),{node_request_key:Ype}=(IE(),ie(YR)),{authHandler:Qne,handlePostRequest:zne,serverErrorHandler:Jne,reqBodyValidationHandler:jne}=RE(),Kpe=require("net"),{registerContentHandlers:Xne}=(wa(),ie(T0)),Zne=6e4,ese=1024*1024*1024,tse="TRUE",{CONFIG_PARAMS:gl}=vH,Qa;BH.exports={hdbServer:UH,start:UH};async function UH(e){try{Vs.info("In Fastify server"+process.cwd()),Vs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=vne.isMaster,await rse();let t=e.securePort>0;Qa=nse(t),await Qa.ready(),e||(e={}),e.isOperationsServer=!0;try{Wne.http(Qa.server,e),Qa.server.closeIdleConnections||await Qa.listen({port:0,host:"::"})}catch(r){throw Qa.close(),Vs.error(r),Vs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vs.fatal(t),process.exit(1)}}a(UH,"operationsServer");async function rse(){Vs.trace("Configuring HarperDB process."),Vne.setSchemaDataToGlobal(),await Yne.setUsersToGlobal(),await Kne.getLicense()}a(rse,"setUp");function nse(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=sse(e),r=Bne(t);r.server.headersTimeout=ose(),r.setErrorHandler(Jne);let n=ise();n&&r.register(Hne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(qne),r.register(xne),r.register(Gne,{root:Fne.join(kne,"studio/build-local")}),Xne(r);let s=Do.get(vH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!$ne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[jne,Qne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),zne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(nse,"buildServer");function sse(e){let t=Do.get(gl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(gl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:ese,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(sse,"getServerOptions");function ise(){let e=Do.get(gl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(gl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===tse)&&(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(ise,"getCORSOpts");function ose(){return Do.get(gl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Zne}a(ose,"getHeaderTimeoutConfig")});var jR={};qe(jR,{disableNATS:()=>cse,publishToStream:()=>DE,setNATSReplicator:()=>KR,setPublishToStream:()=>use,setSubscription:()=>JR,start:()=>ase});function ase(){Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&_se()}function cse(e=!0){kH=e}function use(e,t){DE=e,JR=t}function _se(){if(kH||process.env._DISABLE_NATS)return;let e=hr(),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];KR(s,r,i)}}XR((r,n)=>{KR(r.tableName,r.databaseName,r),n&&$H(r)}),!xH&&(xH=!0)}function KR(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 Vt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Le],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){$H(i)}static subscribe(){let i=new yn;return JR(t,e,i),i}static subscribeOnThisThread(i){return i<(Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??lse)}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 wE(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=VH;return i}a(n,"getNATSTransaction")}function $H(e){let t=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME);DE(`${QR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,zR.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 GH,QR,zR,qH,FH,Rl,Al,CE,kH,DE,JR,lse,VH,xH,wE,WR,YH=Ae(()=>{Oe();Nn();GH=B(ot()),QR=B(ke()),zR=B(Rs());Ac();qH=B(wS()),FH=B(vr()),Rl=B(Z()),Al=B(P()),CE=B($());a(ase,"start");a(cse,"disableNATS");DE=GH.publishToStream,JR=qH.setSubscription;a(use,"setPublishToStream");lse=2;a(_se,"assignReplicationSource");a(KR,"setNATSReplicator");a($H,"publishSchema");wE=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=Rl.default.get(Al.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,E=l.operation=="put"?"upsert":l.operation;u||(CE.trace(`Sending transaction event ${E}`),_=u={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&E!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(l.record),c.push(l.id)):_=_.next={operation:E,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(DE(`${QR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,zR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw CE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},WR=class extends wE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,FH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};VH=new WR});var ix=g(Di=>{"use strict";var{isMainThread:tA,parentPort:bl,threadId:LE}=require("worker_threads"),{Socket:dse,createServer:fse}=require("net"),{createServer:Ese,IncomingMessage:hse}=require("http"),{createServer:mse}=require("https"),{readFileSync:pse,unlinkSync:KH,existsSync:Sse}=require("fs"),Lt=$(),He=Z(),ut=P(),{server:UE}=(ur(),ie(Hi)),{WebSocketServer:Tse}=require("ws"),{createSecureContext:gse,createServer:Rse}=require("node:tls"),{getTicketKeys:JH,restartNumber:Ase,getWorkerIndex:yl}=Je(),{Headers:jH,appendHeader:Ose}=(Qu(),ie(VU)),{recordAction:Ol,recordActionBinary:bse}=(ws(),ie(du)),{Request:XH,createReuseportFd:WH}=(IE(),ie(YR)),{checkMemoryLimit:yse}=Ji(),{X509Certificate:Nse}=require("crypto"),ZH=require("tls"),Ise=ZH.createSecureContext,za;ZH.createSecureContext=function(e){return za||Ise(e)};var ex=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG);if(ex){let e;if(tA)e=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Lt.info("Could not close debugger",t)}});else{let t=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&yl()>=0&&(e=t+yl())}if(e){let t=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Lt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&tA)try{require("inspector").open(9229)}catch(e){Ase<=1&&Lt.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:eSe,CONFIG_PARAMS:wse}=ut;He.initSync();var Cse=He.get(wse.HTTP_SESSIONAFFINITY),ds={};Di.registerServer=iA;Di.httpServer=oA;Di.deliverSocket=sA;Di.startServers=tx;Di.when_components_loaded=null;Di.createSNICallback=aA;UE.http=oA;UE.request=Pse;UE.socket=Use;UE.ws=vse;var ZR={},ME={},Dse,$s={},PE={},Lse=[],rA=[];function tx(){return Di.when_components_loaded=cA().loadRootComponents(!0).then(()=>{bl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)sA(n,r,s);else if(t.requestId)Mse(t);else if(t.type===ut.ITC_EVENT_TYPES.SHUTDOWN){Lt.trace("received shutdown request",LE);for(let i in ds){let o=ds[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),l=0,d=setInterval(()=>{l++;let E=l>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}l===1?Lt.info(`Closing ${f.length} idle connections`):E&&Lt.warn(`Forcefully closing ${f.length} active connections`);for(let h=0,p=f.length;h<p;h++){let S=f[h].socket;S._httpMessage&&!S._httpMessage.finished&&!E||(E?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
29
29
  Connection: close\r
30
30
  \r
31
- `))}},25).unref()}o.close?.(()=>{if(xe.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&DE()==0)try{KH(xe.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,wE),o.cantCleanupProperly||Dt.warn("Had to forcefully exit the thread",wE),process.exit(0)},5e3).unref()})}if(ex||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Dt.info("Could not close debugger",i)}}}).ref();let e=[];if(WH&&!Dse)for(let t in ds){let r=ds[t];if(isNaN(t)&&DE()==0){Tse(t)&&KH(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),Dt.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=WH(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),Dt.trace("Listening on port "+t,wE)}).on("error",i)}))}Promise.all(e).then(()=>{Ol?.postMessage({type:Et.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(tx,"startServers");ZR||tx();function rA(e,t,r){let n=e?.read?e:new fse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=ds[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=ds[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Dt.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(rA,"deliverSocket");var QH=new Map;function Use(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=QH.get(s),r){case"connection":i=rA(void 0,t),QH.set(s,i),i.write=(c,u,_)=>(Ol.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Ol.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Ol.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(Use,"proxyRequest");function nA(e,t,r=!0){!+t&&t!==xe.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(xe.get(Et.CONFIG_PARAMS.HTTP_PORT),10));let n=ds[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",zH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else ds[t]=e;e.on("unhandled",zH)}a(nA,"registerServer");function rx(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=[],xe.get(Et.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:xe.get(Et.CONFIG_PARAMS.HTTP_PORT),secure:xe.get(Et.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),xe.get(Et.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:xe.get(Et.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&xe.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:xe.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(rx,"getPorts");function sA(e,t){for(let{port:r,secure:n}of rx(t))nx(r,n,t?.isOperationsServer),typeof e=="function"?eA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,nA(e,r,!1)),LE[r]=tA(eA,r),Lse=tA(Mse,r)}a(sA,"httpServer");function nx(e,t,r){if(!$s[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:xe.get(n+"_keepAliveTimeout"),headersTimeout:xe.get(n+"_headersTimeout"),requestTimeout:xe.get(n+"_timeout")},i=xe.get(n+"_mtls"),o=xe.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=xe.get(n+"tls");Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:JH(),maxHeaderSize:xe.get(Et.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:iA(u)})}let c=yse();$s[e]=(t?pse:hse)(s,async(u,_)=>{try{let d=performance.now(),f=new XH(u,_);r&&(f.isOperationsServer=!0);let E=await LE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=sx(f)}if(c?E.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):E.headers?.set?.("Server","HarperDB"),E.status===-1){for(let v of E.headers||[])_.setHeader(v[0],v[1]);return u.baseRequest=f,_.baseResponse=E,$s[e].emit("unhandled",u,_)}let h=E.status||200,p=performance.now(),S=p-d,T=E.body,A;if(!E.handlesHeaders){let v=E.headers||new jH;T?T.length>=0&&(typeof T=="string"?v.set("Content-Length",Buffer.byteLength(T)):v.set("Content-Length",T.length),A=!0):(v.set("Content-Length","0"),A=!0);let P=`hdb;dur=${S.toFixed(2)}`;E.wasCacheMiss&&(P+=", miss"),bse(v,"Server-Timing",P,!0),_.writeHead(h,v&&(v[Symbol.iterator]?Array.from(v):v)),A&&_.end(T)}let g=f.handlerPath,L=f.method;if(Al(S,"duration",g,L,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),Nse(h<400,"success",g,L),!A)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let v=0;T.on("data",P=>{v+=P.length}),T.on("end",()=>{Al(performance.now()-p,"transfer",g,L),Al(v,"bytes-sent",g,L)})}else T?.then?T.then(v=>{_.end(v)},l):_.end(T)}catch(d){l(d)}function l(d){let f=d.headers;_.writeHead(d.statusCode||500,f&&(f[Symbol.iterator]?Array.from(f):f)),_.end(d.toString()),d.statusCode?d.statusCode===500?Dt.warn(d):Dt.info(d):Dt.error(d)}a(l,"onError")}),i&&($s[e].mtlsConfig=i),t&&($s[e].on("secureConnection",u=>{u._parent.startTime&&Al(performance.now()-u._parent.startTime,"tls-handshake",e),Al(u.isSessionReused(),"tls-reused",e)}),$s[e].isSecure=!0,s.SNICallback(null,(u,_)=>{try{Qa=_,_&&$s[e].setSecureContext(_.options)}finally{Qa=null}})),nA($s[e],e)}return $s[e]}a(nx,"getHTTPServer");function tA(e,t){let r=sx;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(tA,"makeCallbackChain");function sx(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new jH}}a(sx,"unhandled");function Pse(e,t){sA(e,{requestOnly:!0,...t})}a(Pse,"onRequest");function vse(e,t){let r;if(t.securePort){let n=Object.assign({},xe.get("tls"));t.mtls?.certificateAuthority&&(n.certificateAuthority=t.mtls.certificateAuthority);let s={rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,SNICallback:iA(n)};r=Ase(s,e),s.SNICallback(null,(i,o)=>{try{Qa=o,o&&r.setSecureContext(o.options)}finally{Qa=null}}),ds[t.securePort]=r}return t.port&&(r=Ese(e),ds[t.port]=r),r}a(vse,"onSocket");Object.defineProperty(mse.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 Bse(e,t){let r;for(let{port:n,secure:s}of rx(t)){CE[n]||(CE[n]=new gse({server:r=nx(n,s)}),CE[n].on("connection",async(c,u)=>{try{let _=new XH(u);_.isWebSocket=!0;let l=LE[n](_),d=u.headers["sec-websocket-protocol"]||"",f=jR[n];if(d){let E;for(let h=0;h<f.length;h++){let p=f[h];p.protocol===d&&(E=!0,p.listener(c,_,l))}if(E)return}for(let E=0;E<f.length;E++){let h=f[E];h.protocol||h.listener(c,_,l)}}catch(_){Dt.warn("Error handling WebSocket connection",_)}}),CE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=jR[n];o||(o=jR[n]=[]),o.push({listener:e,protocol:i}),LE[n]=tA(eA,n)}return r}a(Bse,"onWebSocket");function zH(e,t){t.writeHead(404),t.end(`Not found
32
- `)}a(zH,"defaultNotFound");function XR(e){return e.startsWith("-----BEGIN")?e:Sse(e)}a(XR,"readPEM");function iA(e){let t=[];for(let i=0;e[i];i++)t.push(e[i]);t.length||t.push(e);let r=new Map,n,s=!1;for(let i of t){let o=XR(i.privateKey),c=XR(i.certificate),u=i.certificateAuthority&&XR(i.certificateAuthority);if(!o||!c)throw new Error("Missing private key or certificate for secure server");let _={ciphers:i.ciphers,ca:u,ticketKeys:JH()},l=Rse(_);l.options=_,_.instantiatedContext=l,l.context.setCert(c),l.context.setKey(o,void 0),_.cert=c,_.key=o,l.certStart=c.slice(0,100).toString(),n||(n=l);let d=new Ise(c),f=i.hostname??i.host??i.hostnames??i.hosts??(d.subjectAltName?d.subjectAltName.split(",").map(E=>{let h=E.indexOf(":");return E.slice(h+1)}):[d.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(f)||(f=[f]);for(let E of f)E?(E[0]==="*"&&(s=!0,E=E.slice(1)),r.has(E)||r.set(E,l)):Dt.error("No hostname found for certificate at",i.certificate)}return(i,o)=>{let c=i;for(;;){let u=r.get(c);if(u)return Dt.debug("Found certificate for",i,u.certStart),o(null,u);if(s&&c){let _=c.indexOf(".",1);_<0?c="":c=c.slice(_)}else break}Dt.debug("No certificate found to match",i,"using the first certificate"),o(null,n)}}a(iA,"createSNICallback")});async function ux({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await aA.get(e,{returnNonexistent:!0});i=new lA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await aA.get(e);o&&o.delete()}i=new PE(e,t)}return n&&(n.id=e,n.user={username:t?.username},bl.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function cA(){return UE++,UE>65500&&(UE=1),UE}function uA(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Oi.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 ox,Li,ax,cx,aA,bl,UE,PE,lA,lx=Re(()=>{Ae();Ku();ox=B(Mr()),Li=B($());ro();ax=B(Je()),cx=B(ix());ar();aA=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"}]}}]}),bl=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,ax.getWorkerIndex)()===0&&(async()=>{await cx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of bl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await nt.getUser(r.user.username)),Xe(r,()=>{try{uA(r,t,r)}catch{(0,Li.warn)("Failed to publish will",t)}bl.delete(e.id,r)})}})();a(ux,"getSession");UE=1;a(cA,"getNextMessageId");PE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;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(T=>T.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,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Li.trace)("Resuming subscription from",s,"from",o);let E=Oi.getMatch(_);if(!E){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let T=f.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,T.indexOf("+")===T.length-1)f.onlyChildren=!0,f.url="/"+T.slice(0,T.length-1);else{let A=T.split("/"),g;for(let P=0;P<A.length;P++)if(A[P].indexOf("+")>-1)if(A[P]==="+")g=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&g)throw new Error("Filters can not be combined");let L=!0;A[A.length-1]==="#"&&(A.length--,L=!1),g&&(n=a(P=>{let k=P.id;if(!Array.isArray(k)||L&&k.length!==A.length)return!1;for(let H=0;H<A.length;H++)if(A[H]!=="+"&&A[H]!==k[H])return!1;return!0},"filter"));let v=A.indexOf("+");f.url="/"+(v>-1?A.slice(0,v):A).concat("").join("/")}}let h=E.path,p=E.Resource,S=await Xe(f,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let A=await p.subscribe(f,T);if(!A)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!A[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let g of A)try{let L;if(g.type&&g.type!=="put"&&g.type!=="delete"&&g.type!=="message"&&g.type!=="patch"||n&&!n(g))continue;r?(g.topic=s,L=this.needsAcknowledge(g)):(g.acknowledge?.(),L=cA());let v=g.id;Array.isArray(v)&&(v=Na(v)),v==null&&(v=""),this.listener(h+"/"+v,g.value,L,t)}catch(L){(0,Li.warn)(L)}})(),A});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=cA();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(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return uA(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Xe(r,async()=>{try{if(!t){let n=await bl.get(this.sessionId);n?.doesExist()&&await uA(n,n.data,r)}}finally{await bl.delete(this.sessionId)}}).catch(n=>{(0,Li.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.disconnect(!1)},this.keepalive*1500))}};a(uA,"publish");lA=class extends PE{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=cA(),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,Li.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.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,ox.getNextMonotonicTime)()),(0,Li.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),aA.put(this.sessionRecord)}}});var dA={};qe(dA,{bypassAuth:()=>Hse,start:()=>xse});function Hse(){hx=!0}function xse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new Ex.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),nr.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:f,onClose:E}=dx(_,(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=>{nr.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(o.events.emit("connection",_),nr.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let E=u.user;if(E!==null){(E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN);try{l=await e.getUser(E,null,null),(0,za.get)(zt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&BE.notify({username:l?.username,status:zt.AUTH_AUDIT_STATUS.SUCCESS,type:zt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,za.get)(zt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&BE.error({username:E,status:zt.AUTH_AUDIT_STATUS.FAILURE,type:zt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else nr.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(E){o.events.emit("error",E,_),nr.error(E)}else if(u.required)return nr.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&hx&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,fx.getSuperUser)(),nr.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:f}=dx(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{nr.info("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function dx(e,t,r,n,s){_x||(_x=!0,lu(d=>{vE>0&&d.push({metric:"mqtt-connections",connections:vE,byThread:!0})}));let i;vE++;let o,c={protocolVersion:4},u=(0,HE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){vE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Yr(!1,"connection","mqtt","disconnect"),nr.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(o?.receivedPacket?.(),d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await nt.getUser(d.username,d.password.toString(),r),(0,za.get)(zt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&BE.notify({username:n?.username,status:zt.AUTH_AUDIT_STATUS.SUCCESS,type:zt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(g){return(0,za.get)(zt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&BE.error({username:d.username,status:zt.AUTH_AUDIT_STATUS.FAILURE,type:zt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,g),Yr(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Yr(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let g=e.deserialize||(e.deserialize=Oo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?g(d.will.payload):void 0,delete d.will.payload}o=ux({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(g){return nr.error(g),s.events.emit("auth-failed",d,e,g),Yr(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:g.code||5,returnCode:g.code||128})}s.events.emit("connected",o,e),Yr(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((g,L,v,P)=>{try{let k=g.indexOf("/",1),H=k>0?g.slice(0,k):g;f({cmd:"publish",topic:g,payload:E(L),messageId:v||Math.floor(Math.random()*1e8),qos:P.qos},H)}catch(k){nr.error(k),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let g of d.subscriptions){let L;try{L=(await o.addSubscription(g,g.qos>=1)).qos||0}catch(v){s.events.emit("error",v,e,g,o),nr.error(v),L=c.protocolVersion<5?128:v.statusCode===403?135:v.statusCode===404?143:128}h.push(L)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let g=[];for(let L of d.unsubscriptions)g.push(o.removeSubscription(L)?0:17);f({cmd:"unsuback",granted:g,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=Oo(r?.headers.get?.("content-type"))),T=d.payload?.length>0?S(d.payload):void 0,A;try{A=await o.publish(d,T)}catch(g){s.events.emit("error",g,e,d,o),nr.warn(g),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,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.events.emit("disconnected",o,e),s.sessions.delete(o),Yr(!0,"connection","mqtt","disconnect"),nr.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(h){s.events.emit("error",h,e,d,o),nr.error(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,HE.generate)(h,c);t(S),$r(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return To(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var HE,fx,za,zt,_A,Ex,BE,nr,hx,_x,vE,mx=Re(()=>{HE=require("mqtt-packet");lx();fx=B(un());Ia();ws();ar();za=B(Z()),zt=B(M()),_A=B($()),Ex=require("events"),BE=(0,_A.loggerWithTag)("auth-event"),nr=(0,_A.loggerWithTag)("mqtt"),hx=(0,za.get)(zt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Hse,"bypassAuth");a(xse,"start");vE=0;a(dx,"onSocket")});var Lf={};qe(Lf,{component_errors:()=>ja,loadComponent:()=>xE,loadComponentDirectories:()=>Nx,setErrorReporter:()=>kse});function Nx(e,t){t&&(EA=t),e&&(hA=e);let r=[];if((0,qn.existsSync)(fA)){let s=(0,qn.readdirSync)(fA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Ot.join)(fA,o);r.push(xE(c,EA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(xE(n,EA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{bx=!0})}function kse(e){yl=e}async function xE(e,t,r,n,s,i){if(!Sx.has(e)){Sx.set(e,!0),s&&(hA=s);try{let o;n&&(ja=new Map);let c=(0,Ot.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,qn.existsSync)(c)?o=n?(0,Ox.getConfigObj)():(0,Tx.parseDocument)((0,qn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=mA;let u=[],_=n;for(let l in o){let d=o[l];if(ja.set(n?l:(0,Ot.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let A=e,g;for(;!(0,qn.existsSync)(g=(0,Ot.join)(A,"node_modules",l));)if(A=(0,Ot.dirname)(A),A.length<(0,Ax.getHdbBasePath)().length){g=null;break}if(g)f=await xE(g,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=Fse[l];if(!f)continue;u.push(f);let h=a(A=>(A.origin=r,lt(A)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,T=!p?.https&&p?.port;if(Ja.isMainThread&&(f=await f.startOnMainThread?.({server:nt,ensureTable:h,port:T,securePort:S,resources:t,...d})||f,n&&p))for(let A of[T,S])try{if(+A&&!px.includes(A)){let g=pA.get(SA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);g&&Nl.default.warn("Session affinity is not recommended and may cause memory leaks"),(g||!OE)&&(px.push(A),LH(A,g))}}catch(g){console.error("Error listening on socket",A,g,l)}if(t.isWorker&&(f=await f.start?.({server:nt,ensureTable:h,port:T,securePort:S,resources:t,...d})||f),hA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,Rx.handleHDBError)("Can not reference parent directories");let A=(0,Ot.join)(e,d.files).replace(/\\/g,"/"),g=A.indexOf("/*");if(g>-1&&d.files!==mA[l]?.files&&!(0,qn.existsSync)(A.slice(0,g)))throw new Error(`The path '${A.slice(0,g)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let L=(0,Ot.basename)(e),v=d.path||"/";v=v.startsWith("/")?v:v.startsWith("./")?"/"+L+v.slice(2):v==="."?"/"+L:"/"+L+"/"+v;let P,k,H;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",k=(0,Ot.join)(e,z)}else(H=A.indexOf("/*"))>-1&&(k=A.slice(0,H+1),P=(0,Ot.relative)(e,k));let j=!1;if(Ja.isMainThread&&f.setupDirectory&&(j=await f.setupDirectory?.(v,k,t)),t.isWorker&&f.handleDirectory&&(j=await f.handleDirectory?.(v,k,t)),j)continue;for(let z of await(0,gx.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:J,dirent:me}=z;_=!0;let ce=(0,Ot.relative)(e,J).replace(/\\/g,"/");if(P)if(ce.startsWith(P))ce=ce.slice(P.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${ce}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let de=v+(v.endsWith("/")?"":"/")+ce;try{if(me.isFile()){let De=await qse(J);Ja.isMainThread&&await f.setupFile?.(De,de,J,t),t.isWorker&&await f.handleFile?.(De,de,J,t)}else Ja.isMainThread&&await f.setupDirectory?.(de,J,t),t.isWorker&&await f.handleDirectory?.(de,J,t)}catch(De){De.message=`Could not load ${me.isFile()?"file":"directory"} '${J}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${De.message}`,yl?.(De),((0,Xa.getWorkerIndex)()===0?console:Nl.default).error(De),t.set(d.path||"/",new Il(De)),ja.set(n?l:(0,Ot.basename)(e),De.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Ot.basename)(e)}' due to: ${h.message}`,yl?.(h),((0,Xa.getWorkerIndex)()===0?console:Nl.default).error(h),t.set(d.path||"/",new Il(h),null,!0),ja.set(n?l:(0,Ot.basename)(e),h.message)}}if(Ja.isMainThread&&!bx&&i&&(0,Xa.watchDir)(e,async()=>Nx()),o.extensionModule)return await u_((0,Ot.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;yl?.(new Error(l)),((0,Xa.getWorkerIndex)()===0?console:Nl.default).error(l),ja.set((0,Ot.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,yl?.(o),t.set("",new Il(o))}}}var qn,Ot,Ja,Tx,pA,SA,gx,Xa,Nl,Rx,Ax,Gse,Ox,qse,fA,hA,bx,EA,ja,Fse,mA,px,Sx,yl,Il,Mf=Re(()=>{qn=require("fs"),Ot=require("path"),Ja=require("worker_threads"),Tx=require("yaml"),pA=B(Z()),SA=B(M());Sb();Ab();Ob();U0();gH();yH();gx=B(require("fast-glob")),Xa=B(Je()),Nl=B($());Wh();ar();Rx=B(ne());Nn();Ae();MH();Ax=B(Z()),Gse=B(HH());Of();YH();mx();Ox=B(dr());bE();({readFile:qse}=qn.promises),fA=pA.get(SA.CONFIG_PARAMS.COMPONENTSROOT),hA=new Map,ja=new Map;a(Nx,"loadComponentDirectories");Fse={REST:Jf,rest:Jf,graphqlSchema:Kh,jsResource:zh,fastifyRoutes:PR,login:jh,static:vR,operationsApi:Gse,customFunctions:{},http:{},clustering:zR,authentication:Qu,mqtt:dA},mA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(mA,"static",{value:{files:"web/**"}});px=[],Sx=new Map;a(kse,"setErrorReporter");a(xE,"loadComponent");Il=class extends kt{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 oA=R((ySe,Ix)=>{var{isMainThread:yx}=require("worker_threads"),{getTables:Vse}=(Ae(),ie(Fe)),{loadComponentDirectories:$se,loadComponent:Yse}=(Mf(),ie(Lf)),{resetResources:Kse}=(Ku(),ie(kP)),Wse=hg(),Qse=dr(),{dirname:zse}=require("path"),{getConnection:Jse}=it(),jse=Z(),Xse=M(),TA=new Map;async function Zse(e=!1){!yx&&jse.get(Xse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Jse();try{yx&&await Wse()}catch(n){console.error(n)}let t=Kse();Vse(),t.isWorker=e,await Yse(zse(Qse.getConfigFilePath()),t,"hdb",!0,TA),await $se(TA,t);let r=[];for(let[n]of TA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Zse,"loadRootComponents");Ix.exports.loadRootComponents=Zse});var Je=R((wSe,Ui)=>{"use strict";var{Worker:eie,MessageChannel:tie,parentPort:Es,isMainThread:bA,threadId:rie,workerData:Ys}=require("worker_threads"),{PACKAGE_ROOT:nie}=M(),{join:Lx,isAbsolute:sie,extname:iie}=require("path"),{server:Mx}=(ar(),ie(Hi)),{watch:oie,readdir:aie}=require("fs/promises"),{totalmem:wx}=require("os"),wl=M(),Ux=Z(),Ks=$(),{randomBytes:cie}=require("crypto"),{_assignPackageExport:uie}=require("../index"),lie=M(),Cx=1024*1024,Mi=[],Sn=[],_ie=50,NA=1e4,die="restart",Px="request_thread_info",vx="resource_report",Bx="thread_info",Hx="added-port",fie="ack",gA;uie("threads",Sn);Ui.exports={startWorker:RA,restartWorkers:IA,shutdownWorkers:Sie,workers:Mi,setMonitorListener:yie,onMessageFromWorkers:Tie,onMessageByType:$x,broadcast:Rie,broadcastWithAcknowledgement:Oie,setChildListenerByType:pie,getWorkerIndex:xx,getWorkerCount:Gx,getTicketKeys:Fx,setMainIsWorker:hie,setTerminateTimeout:Eie,restartNumber:Ys?.restartNumber||1};Sn.onMessageByType=$x;Sn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Sn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var yA;function Eie(e){NA=e}a(Eie,"setTerminateTimeout");function xx(){return Ys?Ys.workerIndex:yA?0:void 0}a(xx,"getWorkerIndex");function Gx(){return Ys?Ys.workerCount:yA?1:void 0}a(Gx,"getWorkerCount");function hie(e){yA=e}a(hie,"setMainIsWorker");var qx=1,GE;function Fx(){return GE||(GE=bA?cie(48):Ys.ticketKeys,GE)}a(Fx,"getTicketKeys");Object.defineProperty(Mx,"workerIndex",{get(){return xx()}});Object.defineProperty(Mx,"workerCount",{get(){return Gx()}});var kx={[Px](e,t){bie(t)},[vx](e,t){Nie(t,e)}};function RA(e,t={}){let r=process.constrainedMemory?.()||wx();r=Math.min(r,wx(),2e4*Cx);let n=Ux.get(wl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Cx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of Sn){let _=new tie;_.existingPort=u,i.push(_),o.push(_.port2)}iie(e)||(e+=".js");let c=new eie(sie(e)?e:Lx(nie,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:qx=t.threadCount,name:t.name,restartNumber:Ui.exports.restartNumber,ticketKeys:Fx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Hx,port:u,threadId:c.threadId},[u]);return FE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>RA(e,t),c.on("error",u=>{Ks.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Mi.splice(Mi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<_ie?(t.unexpectedRestarts=c.unexpectedRestarts+1,RA(e,t)):Ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{kx[u.type]?.(u,c)}),Mi.push(c),wie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(RA,"startWorker");var mie=[wl.THREAD_TYPES.HTTP];async function IA(e=null,t=Math.max(qx>3,1),r=!0){if(bA){if(r){let{loadRootComponents:o}=oA();await o()}Ui.exports.restartNumber++,t<1&&(t=t*Mi.length);let n=[],s=[];for(let o of Mi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ui.exports.restartNumber,type:wl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=mie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),NA*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===lie.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}=Tf();r&&(e==="http"||!e)&&Ux.get(wl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Es.postMessage({type:die,workerType:e})}a(IA,"restartWorkers");function pie(e,t){kx[e]=t}a(pie,"setChildListenerByType");function Sie(e){return IA(e,1/0,!1)}a(Sie,"shutdownWorkers");var Vx=[];function Tie(e){Vx.push(e)}a(Tie,"onMessageFromWorkers");var AA=new Map;function $x(e,t){let r=AA.get(e);r||AA.set(e,r=[]),r.push(t)}a($x,"onMessageByType");var gie=10;async function Rie(e){let t=0;for(let r of Sn)try{r.postMessage(e),t++>gie&&(t=0,await new Promise(setImmediate))}catch(n){Ks.error("Unable to send message to worker",n)}}a(Rie,"broadcast");var qE=new Map,Aie=1;function Oie(e){return new Promise(t=>{let r=0;for(let n of Sn)try{let s=Aie++,i=a(()=>{qE.delete(s),--r===0&&t(),n!==Es&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,qE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of qE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ks.error("Unable to send message to worker",s)}r===0&&t()})}a(Oie,"broadcastWithAcknowledgement");function bie(e){e.postMessage({type:Bx,workers:Yx()})}a(bie,"sendThreadInfo");function Yx(){let e=Date.now();return Mi.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(Yx,"getChildWorkerInfo");function Nie(e,t){e.resources=t,e.resources.updated=Date.now()}a(Nie,"recordResourceReport");var OA;function yie(e){OA=e}a(yie,"setMonitorListener");var Iie=1e3,Dx=!1;function wie(){Dx||(Dx=!0,setInterval(()=>{for(let e of Mi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}OA&&OA()},Iie).unref())}a(wie,"startMonitoring");var Cie=1e3;if(Es){FE(Es);for(let e=0,t=Ys.addPorts.length;e<t;e++){let r=Ys.addPorts[e];r.threadId=Ys.addThreadIds[e],FE(r)}setInterval(()=>{let e=process.memoryUsage();Es.postMessage({type:vx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Cie).unref(),gA=a(()=>new Promise((e,t)=>{Es.on("message",r),Es.postMessage({type:Px});function r(n){n.type===Bx&&(Es.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else gA=Yx;Ui.exports.getThreadInfo=gA;function FE(e,t){Sn.push(e),e.on("message",r=>{if(r.type===Hx)r.port.threadId=r.threadId,FE(r.port);else if(r.type===fie){let n=qE.get(r.id);n&&n()}else{for(let s of Vx)s(r,e);let n=AA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ks.error(i)}}}).on("close",()=>{Sn.splice(Sn.indexOf(e),1)}).on("exit",()=>{Sn.splice(Sn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(FE,"addPort");if(bA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await aie(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Lx(s,o.name));try{for await(let{filename:o}of oie(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await IA(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");Ui.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else Es.on("message",async e=>{let{type:t}=e;t===wl.ITC_EVENT_TYPES.SHUTDOWN&&(Ui.exports.restartNumber=e.restartNumber,Es.unref(),setTimeout(()=>{Ks.warn("Thread did not voluntarily terminate",rie),process.exit(0)},NA).unref())})});var DC={};qe(DC,{AUDIT_STORE_OPTIONS:()=>Ef,createAuditEntry:()=>E_,openAuditStore:()=>YE,readAuditEntry:()=>Ut,setAuditRetention:()=>Lie,transactionKeyEncoder:()=>eG});function YE(e){let t=e.auditStore=e.openDB(jx.AUDIT_STORE_NAME,Ef);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=kE){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()-wA})){if((_[0]&15)===LA){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Die){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,wA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,$E.getWorkerIndex)()===(0,$E.getWorkerCount)()-1&&s(kE),t}function Lie(e,t=kE){wA=e,kE=t}function E_(e,t,r,n,s,i,o){let c=tG[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?Za.setFloat64(0,n):Tn.set(fm),u=9),f(0),f(t),d(r),Za.setFloat64(u,e),u+=8,s?d(s):Tn[u++]=0,Tn[n?8:0]=c;let l=Tn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,ec.writeKey)(E,Tn,u);let p=u-h-1;p>127?p>16383?(UA.error("Key or username was too large for audit entry",E),u=h+1,Tn[h]=0):(Tn.copyWithin(h+2,h+1,u),Za.setUint16(h,p|32768),u++):Tn[h]=p}function f(E){E<128?Tn[u++]=E:E<16384?(Za.setUint16(u,E|32768),u+=2):E<1056964608?(Za.setUint32(u,E|3221225472),u+=4):(Tn[u]=255,Za.setUint32(u+1,E),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new MA(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:tG[n&7],tableId:i,get recordId(){return Jx(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Jx(e,l,d):void 0},getValue(f,E,h){if(n&CA||n&DA&&!E)return f.decoder.decode(e.subarray(t.position));if(n&DA&&h)return PA(f.getEntry(this.recordId),h,f)}}}catch(t){return UA.error("Reading audit entry error",t,e),{}}}function Jx(e,t,r){let n=e.subarray(t,r);return(0,ec.readKey)(n,0,r-t)}var ec,VE,jx,Xx,$E,Zx,UA,Tn,Za,eG,Ef,wA,Die,kE,CA,DA,Kx,LA,Wx,Qx,zx,tG,MA,ti=Re(()=>{ec=require("ordered-binary"),VE=B(Z()),jx=B(ut()),Xx=B(M()),$E=B(Je()),Zx=B(Q());wc();UA=B($());KE();(0,VE.initSync)();Tn=Buffer.alloc(1024),Za=new DataView(Tn.buffer,Tn.byteOffset,1024),eG={writeKey(e,t,r){return e===Ic?(t.set(Ic,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,ec.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,ec.readKey)(e,t,r)}},Ef={encoding:"binary",keyEncoder:eG},wA=(0,Zx.convertToMS)((0,VE.get)(Xx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Die=1e3,kE=1e4;a(YE,"openAuditStore");a(Lie,"setAuditRetention");CA=16,DA=32,Kx=1,LA=2,Wx=3,Qx=4,zx=5,tG={put:Kx|CA,[Kx]:"put",delete:LA,[LA]:"delete",message:Wx|CA,[Wx]:"message",invalidate:Qx,[Qx]:"invalidate",patch:zx|DA,[zx]:"patch"};a(E_,"createAuditEntry");a(Ut,"readAuditEntry");MA=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(Jx,"readKeySafely")});var vA={};qe(vA,{add:()=>WE,applyReverse:()=>rG,getRecordAtTime:()=>PA,rebuildUpdateBefore:()=>QE});function WE(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function QE(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,WE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function rG(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=Mie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=nG}}function PA(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":rG(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===nG&&(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 Mie,nG,KE=Re(()=>{ti();a(WE,"add");WE.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};Mie={add:WE};a(QE,"rebuildUpdateBefore");a(rG,"applyReverse");nG={};a(PA,"getRecordAtTime")});function jr(e){return e[bt]||(e[bt]=Object.create(null))}function ZE(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[Ne])},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 gn.ClientError(`${c} must be a string, attempt to assign ${l}`);jr(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 gn.ClientError(`${c} must be a string, attempt to assign ${l}`);jr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="number"||l==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be a number, attempt to assign ${d}`);jr(this)[c]=l},"set");break;case"Int":u=a(function(l){let d=l?.__op__?l.value:l;if(!(d>>0===d||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new gn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);jr(this)[c]=l},"set");break;case"Long":u=a(function(l){let d=l?.__op__?l.value:l;if(!(Math.round(d)===l&&Math.abs(d)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new gn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);jr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="bigint"||l==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),l?.__op__?l.value=d:l=d;else throw new gn.ClientError(`${c} must be a number, attempt to assign ${l}`);jr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);jr(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 gn.ClientError(`${c} must be a Date, attempt to assign ${l}`);jr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);jr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){jr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be an object, attempt to assign ${l}`);jr(this)[c]=l},"set")}_={get(){let l=this[bt];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[_e]?.[c];return f.update(E)}return f}let d=this[_e]?.[c];if(d&&typeof d=="object"){let f=iG(d,o);if(f)return l||(l=this[bt]=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[bt];return u?.[o]!==void 0?u[o]:this[_e]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new gn.ClientError("Can not add a property to a sealed table schema");jr(this)[o]=c}),i("deleteProperty",function(o){jr(this)[o]=void 0}),i("toJSON",function(){let o=this[bt],c;for(let _ in o){c||(c=Object.assign({},this[_e]));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[_e])),Object.assign(c,this)),c||this[_e]}),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 iG(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=s}},ZE(r,t)),new r(e)):new zE(e);case Array:let n=new jE(e.length);n[_e]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=iG(o,t?.elements)),n[s]=o}return n;default:return e}}function ld(e){let t=e[bt],r;for(let s in t){r||(r=Object.assign({},e[_e]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=ld(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[_e])),Object.assign(r,e)),r||e[_e]}function Mo(e,t=e[bt]){let r;if(sG.call(e,_e)&&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=Mo(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[_e]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=vA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Mo(s);r[n]=s}return r?Object.freeze(r):sG.call(e,_e)?e[_e]:e}function JE(e){let t=e[_e];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Lo]||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?.[_e]===s){if(JE(i))return!0}else return!0}}else{let r=e[bt];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[_e]===i){if(JE(s))return!0}else return!0}else return!0}}return!1}var gn,bt,zE,sG,Lo,jE,XE,_d=Re(()=>{Nn();gn=B(ne());KE();bt=Symbol("own-data");a(jr,"getChanges");a(ZE,"assignTrackedAccessors");a(iG,"trackObject");zE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=t}};ZE(zE,{});a(ld,"collapseData");sG=Object.prototype.hasOwnProperty;a(Mo,"deepFreeze");a(JE,"hasChanges");Lo=Symbol.for("has-array-changes"),jE=class extends Array{static{a(this,"TrackedArray")}[Lo];constructor(t){super(t)}splice(...t){return this[Lo]=!0,super.splice(...t)}push(...t){return this[Lo]=!0,super.push(...t)}pop(){return this[Lo]=!0,super.pop()}unshift(...t){return this[Lo]=!0,super.unshift(...t)}shift(){return this[Lo]=!0,super.shift()}};jE.prototype.constructor=Array;XE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Gp={};qe(Gp,{CONTEXT:()=>Ne,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>Fn,RECORD_PROPERTY:()=>_e,Resource:()=>kt,snake_case:()=>Pie,transformForSelect:()=>th});function Pie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function oG(e,t){if(Cl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Cl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new HA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Cl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function Xr(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[Ne]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[Ne]||i):l=i:(l=s,c=l[Le]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ne]||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 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=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 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(p=>{if(!p)throw new eh(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new eh(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Zr(e,t){let r=new uG.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function BA(e,t,r){let n=e[_e];if(n){let s=e[bt];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 th(e,t){let r=t?.propertyResolvers,n=t[Ne],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):BA(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(BA(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(BA(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]=th(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var aG,cG,uG,Ne,Le,Fn,_e,Uie,kt,eh,Cl,HA,Nn=Re(()=>{aG=require("crypto");Rc();cG=require("../index"),uG=B(ne());_d();ro();Qf();Ne=Symbol.for("context"),Le=Symbol.for("primary-key"),Fn=Symbol("is-collection"),_e=Symbol("stored-record"),Uie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},kt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let n=r?.[Ne];this[Ne]=n!==void 0?n:r||null}static get=Xr(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 _=th(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Xr(function(t,r,n,s){if(Array.isArray(s)&&t[Fn]){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):Zr(t,"put")},{hasContent:!0,type:"update"});static patch=Xr(function(t,r,n,s){return t.patch?t.patch(s,r):Zr(t,"patch")},{hasContent:!0,type:"update"});static delete=Xr(function(t,r,n,s){return t.delete?t.delete(r):Zr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,aG.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),n||(n={}),Xe(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Zr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=Xr(function(t,r,n,s){return t.invalidate?t.invalidate(r):Zr(t,"delete")},{hasContent:!1,type:"update"});static post=Xr(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Xr(function(t,r,n,s){return t.connect?t.connect(s,r):Zr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Xr(function(t,r,n,s){return t.subscribe?t.subscribe(r):Zr(t,"subscribe")},{type:"read"});static publish=Xr(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.publish?t.publish(s,r):Zr(t,"publish")},{hasContent:!0,type:"create"});static search=Xr(function(t,r,n,s){let i=t.search?t.search(r):Zr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=th(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Xr(function(t,r,n,s){return t.search?t.search(s,r):Zr(t,"search")},{hasContent:!0,type:"read"});static copy=Xr(function(t,r,n,s){return t.copy?t.copy(s,r):Zr(t,"copy")},{type:"create"});static move=Xr(function(t,r,n,s){return t.move?t.move(s,r):Zr(t,"move")},{type:"delete"});post(t){if(this[Fn])return this.constructor.create(this[Le],t,this[Ne]);Zr(this,"post")}static isCollection(t){return t?.[Fn]}static coerceId(t){return t}static parseQuery(t){return Wf(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&&Uie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:oG(t,this),isCollection:Cl}}let i=oG(t,this);return Cl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Ne],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(_=>_[Le]===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[Le],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[Fn]=!0),s}subscribe(t){return new bn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new bn}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[Ne]}};kt.prototype[Ne]=null;(0,cG._assignPackageExport)("Resource",kt);a(Pie,"snake_case");eh=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(oG,"pathToId");HA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Xr,"transactional");a(Zr,"missingMethod");a(BA,"selectFromObject");a(th,"transformForSelect")});function dG(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=_G,vie(e.primaryStore,e.auditStore)):(c=lG,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{fG(lG[i])})));let u=c[i]||(c[i]=[]);u.auditStore=e.auditStore,u.lastTxnTime==null&&(u.lastTxnTime=Date.now());let _=u[o];_||(_=u[o]=new Map,_.envs=u,_.tableId=o,_.store=e.primaryStore),t=Na(t);let l=new GA(r);l.startTime=n;let d=_.get(t);return d?d.push(l):(_.set(t,d=[l]),d.tables=_,d.key=t),l.subscriptions=d,l}function fG(e){if(!e)return;let t=e.auditStore;try{t.resetReadTxn()}catch(n){throw n.message+=" in "+path,n}let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Ut(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,u,_=Na(i.recordId),l=0;do{let d=o.get(_);if(d){for(let E of d)if(!(l>0&&!(E.includeDescendants&&!(E.onlyChildren&&l>1)))){if(E.startTime>=n){(0,xA.info)("omitting",c,E.startTime,n);continue}try{let h;E.supportsTransactions&&E.txnInProgress!==i.version&&(h=!0,E.txnInProgress||(r?r.push(E):r=[E]),E.txnInProgress=i.version),E.listener(c,i,n,h)}catch(h){console.error(h),(0,xA.info)(h)}}}if(_==null)break;let f=_.lastIndexOf?.("/",_.length-2);f>-1?_=_.slice(0,f):_=null,l++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function vie(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u=_G[s];if(!u)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),u.txnTime=r.threadLocalWrites[0]||Date.now(),fG(u),r.threadLocalWrites[0]=u.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var xA,lG,_G,GA,EG=Re(()=>{xA=B($());Rc();Ku();ti();lG=Object.create(null),_G=Object.create(null);a(dG,"addSubscription");GA=class extends bn{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(fG,"notifyFromTransactionData");a(vie,"listenToCommits")});var pR={};qe(pR,{coerceType:()=>rh,makeTable:()=>ih,setServerUtilities:()=>$ie,updateResource:()=>nh});function ih(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:f,evictionMS:E,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=mm(i,n,u),A=0,g,L,v={},P=Promise.resolve(),k,H,j;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(H=K),K.expiresAt&&(j=K),K.isPrimaryKey&&(v=K);let z,J=[],me=[],ce=1,de=2,De={},ve={},Mt=864e5,Wl,Ql,zs,oO=!1,Ah,Oh,Sq=i.getRange({start:!1,end:!1}).constructor,Tq=10,gq=6;h&&uO();class Qe extends kt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=k;static updatedTimeProperty=H;static propertyResolvers;static sources=[];static get expirationMS(){return f}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,O){O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),L=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(D=>{let y=this.sources.slice(0,-1);if(y=y.filter(U=>U[D]&&(!U[D].reliesOnPrototype||U.prototype[D])),y.length>0)if(y.length===1){let U=y[0];return(F,C,x)=>{if(F?.source!==U)return U[D](C,x,F)}}else return(U,F,C)=>{let x=[];for(let G of y){if(U?.source===G)break;x.push(G[D](F,C,U))}return Promise.all(x)}},"getApplyToIntermediateSource"),N=this.sources[this.sources.length-1],b=a(D=>{if(N[D]&&(!N[D].reliesOnPrototype||N.prototype[D]))return(y,U,F)=>{if(!y?.source)return N[D](U,F,y)}},"getApplyToCanonicalSource");return De={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},ve={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let D=!1,y=a(async(U,F)=>{let C=U.value,x=U.table?st[c][U.table]:Qe;if(c===Vn.SYSTEM_SCHEMA_NAME&&(U.table===Vn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===Vn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),U.id===void 0&&(U.id=C[x.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let G=await x.getResource(U.id,F,tc);switch(U.type){case"put":return G._writeUpdate(C,!0,tc);case"patch":return G._writeUpdate(C,!1,tc);case"delete":return G._writeDelete(tc);case"publish":return G._writePublish(C,tc);case"invalidate":return G.invalidate(tc);default:tt.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let F=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Po.getWorkerIndex)()):(0,Po.getWorkerIndex)()===0,C=U&&F&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let x;for await(let G of C)try{if(!(G.type==="transaction"?G.writes[0]:G)){tt.error("Bad subscription event",G);continue}if(G.source=m,x)if(G.beginTxn)x.resolve();else{y(G,x);continue}if(G.type==="end_txn")continue;let pe=Xe(G,()=>{if(G.type==="transaction"){let te=[];for(let Ue of G.writes)try{te.push(y(Ue,G))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Ue)+" of event "+JSON.stringify(G),ae}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Ue;for(let ae of G.attributes)te.find(Ge=>Ge.name===ae.name)||(te.push(ae),Ue=!0);Ue&&(lt({table:s,database:c,attributes:te,origin:"cluster"}),Bl.signalSchemaChange(new Hl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(x=G,y(G,G),new Promise(te=>{x.resolve=te})):y(G,G)});D&&(await pe,Bl.signalUserChange(new Hl.UserEventMsg(process.pid))),G.onCommit&&(pe?.then?pe.then(G.onCommit):G.onCommit())}catch(se){tt.error("error in subscription handler",se)}}}catch(U){tt.error(U)}})(),this}static getResource(m,O,I){let N=super.getResource(m,O,I);if(m!=null){oc(m);try{if(N.hasOwnProperty(_e))return N;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!I?.async||i.cache?.get(m),D=An(O),y=D.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return bh(m,O,{transaction:y},b,U=>{if(U?nh(N,U):N[_e]=null,O.onlyIfCached&&O.noCacheStore){if(!N.doesExist())throw new tn.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let F=Nh(m,U,O,N);if(F)return D?.disregardReadTxn(),N[qA]=!0,kA(F,C=>(nh(N,C),N))}return N})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return N}ensureLoaded(){let m=Nh(this[Le],this[en],this[Ne]);if(m)return this[qA]=!0,kA(m,O=>{this[en]=O,this[_e]=O.value,this[Pl]=O.version})}static setTTLExpiration(m){if(typeof m=="number")f=m*1e3,E||(E=0);else if(m&&typeof m=="object")f=m.expiration*1e3,E=(m.eviction||0)*1e3,Mt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(f<0)throw new Error("Expiration can not be negative");Mt=Mt||(f+E)/4,Ih()}static enableAuditing(m=!0){h=m,m&&uO(),Qe.audit=m}static coerceId(m){return m===""?null:rh(m,v)}static async dropTable(){if(delete st[c][s],c===o){for(let m of S)l.remove(Qe.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Qe.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));Bl.signalSchemaChange(new Hl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Fn])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let O=Qe.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Ne]?.returnNonexistent)return this}allowRead(m,O){let I=Jl(m);if(I?.read){if(I.isSuperUser)return!0;let N=I.attribute_permissions,b=O?.select;if(N?.length>0||oO&&b){if(O||(O={}),b){let D=N?.length>0&&FA(N,"read");O.select=b.map(y=>{let U=y.name||y;if(!D||D[U]){let F=zs[U]?.definition?.tableClass;if(F){if(y.name||(y={name:y}),!F.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else O.select=N.filter(D=>D.read&&!zs[D.attribute_name]).map(D=>D.attribute_name);return O}else return!0}}allowUpdate(m,O){let I=Jl(m);if(I?.update){let N=I.attribute_permissions;if(N?.length>0){let b=FA(N,"update");for(let D in O)if(!b[D])return!1;for(let D of N){let y=D.attribute_name;!D.update&&!(y in O)&&(O[y]=this.getProperty(y))}}return!0}}allowCreate(m,O){if(this[Fn]){let I=Jl(m);if(I?.insert){let N=I.attribute_permissions;if(N?.length>0){let b=FA(N,"insert");for(let D in O)if(!b[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Jl(m)?.delete}update(m,O){if(!An(this[Ne]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let N;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[_e]={},this[bt]=m):(N=this[bt],N&&(m=Object.assign(N,m)),this[bt]=N=m)),this._writeUpdate(this[bt],O),this}addTo(m,O){if(typeof O=="number"||typeof O=="bigint")this[Dl]===mG?this.set(m,(+this.getProperty(m)||0)+O):(this[Dl]||this.update(),this.set(m,new XE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let O=this[Ne],I=this[Le];oc(I),An(this[Ne]).addWrite({key:I,store:i,invalidated:!0,entry:this[en],nodeName:this[Ne]?.nodeName,before:De.invalidate?.bind(this,O,I),beforeIntermediate:ve.invalidate?.bind(this,O,I),commit:(b,D)=>{if(D?.version>b)return;let y=null;for(let U in r)y||(y={}),y[U]=this.getProperty(U);T(I,y,this[en],b,Ll,h,this[Ne],0,"invalidate")}})}static evict(m,O,I){let N=this.Source,b;if(!((L||h)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==I))){if(L){if(i.hasLock(m,b.version))return;let D;for(let y in r)D||(D={}),D[y]=O[y];if(D)return T(m,D,b,I,Ml,null,null,0,null,!0)}return i.ifVersion(m,I,()=>{zl(m,O,null)}),h?T(m,null,b,I,Ml,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=s,m.schema||=c,AG.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,I){let N=this[Ne],b=An(N),D=this[Le];oc(D);let y=this[en];this[Dl]=O?mG:Fie;let U={key:D,store:i,entry:y,nodeName:N?.nodeName,validate:F=>{m||(m=this[bt]),O||m&&JE(this[bt]===m?this:m)?N?.source||(b.checkOverloaded(),this.validate(m,!O),H&&(m[H.name]=H.type==="Date"?new Date(F):H.type==="String"?new Date(F).toISOString():F),O&&(t&&m[t]!==D&&(m[t]=D),k&&(y?.value?m[k.name]=y?.value[k.name]:m[k.name]=k.type==="Date"?new Date(F):k.type==="String"?new Date(F).toISOString():F),m=Mo(m))):b.removeWrite(U)},before:O?De.put?()=>De.put(N,D,m):null:De.patch?()=>De.patch(N,D,m):De.put?()=>De.put(N,D,Mo(this)):null,beforeIntermediate:O?ve.put?()=>ve.put(N,D,m):null:ve.patch?()=>ve.patch(N,D,m):ve.put?()=>ve.put(N,D,Mo(this)):null,commit:(F,C,x)=>{if(x){if(N&&C?.version>(N.lastModified||0)&&(N.lastModified=C.version),this[en]=C,C?.value?.[_e])throw new Error("Can not assign a record to a record, check for circular references");O||(this[_e]=C?.value??null)}this[bt]=void 0,this[Pl]=F;let G=C?.value,se=m;if(this[Dl]=0,C?.version>=F)if(h){let ae=C.localTime,Ge=C.version;for(;se&&(ae>F||Ge>=F&&ae>0);){let re=u.get(ae);if(!re)break;let X=Ut(re);if(Ge=X.version,Ge>F){if(X.type==="patch"){let Se=X.getValue(i);se=QE(se,Se)}else if(X.type==="put"||X.type==="delete")return}else if(Ge===F)return;ae=X.previousLocalTime}}else{if(O)return;se=QE(se,G)}let pe;if(O?pe=se:(this[_e]=G,pe=O?se:Mo(this,se)),this[_e]=pe,pe?.[_e])throw new Error("Can not assign a record to a record, check for circular references");let te;O||(te=m),zl(D,G,pe);let Ue=O?"put":"patch";T(D,pe,C,F,0,h,N,N.expiresAt||(f?f+Date.now():0),Ue,!1,te)}};b.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Fn]){for await(let O of this.search(m))(await Qe.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[_e]?this._writeDelete(m):!1}_writeDelete(m){let O=An(this[Ne]),I=this[Le];oc(I);let N=this[Ne];return O.addWrite({key:I,store:i,resource:this,nodeName:N?.nodeName,before:De.delete?.bind(this,N,I),beforeIntermediate:ve.delete?.bind(this,N,I),commit:(b,D,y)=>{let U=D?.value;y&&(N&&D?.version>(N.lastModified||0)&&(N.lastModified=D.version),nh(this,D)),!(D?.version>b)&&(zl(this[Le],U),tt.trace("Write delete entry",I,b),h||p?(T(I,null,this[en],b,0,h,this[Ne],0,"delete"),h||Ih()):i.remove(this[Le]))}}),!0}search(m){let O=this[Ne],I=An(O);if(!m)throw new Error("No query provided");let N=m.conditions;N?N.length===void 0&&(N=N[Symbol.iterator]?Array.from(N):[N]):N=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(N=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(N));let b,D={};function y(X,Se){let Be;switch(Se){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Se)}let $n=Be&&{},Js;for(let Ye of X){if(Ye.conditions){Ye.conditions=y(Ye.conditions,Ye.operator);continue}let qt=Ye[0]??Ye.attribute,sn=qt==null?v:Gs(S,qt);if(sn){if(Be){let Yn=Hn(qt),Ft=$n[Yn];Ft?(Ft.push(Ye),Js=!0):$n[Yn]=[Ye]}(sn.type||Vg[Ye.comparator])&&(Ye[1]===void 0?Ye.value=F(Ye.value,sn):Ye[1]=F(Ye[1],sn))}else if(qt!=null)throw(0,tn.handleHDBError)(new Error,`${qt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(Js)for(let Ye in $n){let qt=$n[Ye],sn=qt.length;if(sn>1)for(let Yn=0;Yn<sn;Yn++){let Ft=qt[Yn];if(Ft.comparator==="ge"||Ft.comparator==="greater_than_equal")for(let js=0;js<sn;js++){let Go=qt[js];(Go.comparator==="le"||Go.comparator==="less_than_equal")&&(Ft.comparator="between",Ft.value=[Ft.value,Go.value],X.splice(X.indexOf(Go),1))}if(Ft.comparator==="equals"||!Ft.comparator){for(let js=0;js<sn;js++)if(js!==Yn){let Go=qt[js];X.splice(X.indexOf(Go),1)}break}}}return X}a(y,"prepareConditions");function U(X,Se){if(m.enforceExecutionOrder)return X;for(let Be of X)Be.conditions&&(Be.conditions=U(Be.conditions,Be.operator));return X.length>1&&Se!=="or"?(0,RG.sortBy)(X,Kf(Qe)):X}a(U,"orderConditions");function F(X,Se){return Array.isArray(X)?X.map(Be=>rh(Be,Se)):rh(X,Se)}a(F,"coerceTypedValues");let C=m.operator;(N.length>0||C)&&(N=y(N,C));let x=typeof m.sort=="object"&&m.sort,G;if(x&&C!=="or"){let X=x.attribute;if(b=N.find(Se=>Hn(Se.attribute)===Hn(X)),!b){let Se=Gs(S,X);if(!Se)throw(0,tn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);if(Se.indexed)b={attribute:X,comparator:"sort"},N.push(b);else if(N.length===0&&!m.allowFullScan)throw(0,tn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!x.descending)}N=U(N,C),x&&(b&&N[0]===b?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(b&&N.splice(N.indexOf(b),1),G=x));let se=m.select;if(N.length===0&&(N=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:N,operator:C,postOrdering:G,selectApplied:!!se};let pe=I.useReadTxn(),te=$g(N,C,Qe,pe,m,O,(X,Se)=>aO(X,se,O,pe,Se),D),Ue=m.ensureLoaded!==!1;G||(te=re(te));let ae=Qe.transformEntryForSelect(se,O,pe,D,Ue,!0),Ge=Qe.transformToOrderedSelect(te,se,G,pe,O,ae);function re(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(re,"applyOffset"),G&&(Ge=re(Ge)),Ge.onDone=()=>{Ge.onDone=null,I.doneReadTxn()},Ge.selectApplied=!0,Ge.getColumns=()=>{if(se){let X=[];for(let Se of se)Se==="*"?X.push(...S.map(Be=>Be.name)):X.push(Se.name||Se);return X}return S.map(X=>X.name)},Ge}static transformToOrderedSelect(m,O,I,N,b,D){let y=new Sq;if(I){m=aO(m,O,N,b,null);let U;y.iterate=function(){let C,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=I.dbOrderedAttribute,pe,te,Ue=!0;function ae(re){let X=re.next&&ae(re.next),Se=re.descending;return(Be,$n)=>{let Js=yh(Be,re.attribute,N),Ye=yh($n,re.attribute,N),qt=Se?(0,vo.compareKeys)(Ye,Js):(0,vo.compareKeys)(Js,Ye);return qt===0?X?.(Be,$n)||0:qt}}a(ae,"createComparator");let Ge=ae(I);return{async next(){let re;if(C)if(re=C.next(),re.done){if(G)return y.onDone&&y.onDone(),re}else return{value:await D.call(this,re.value)};U=[],pe&&U.push(pe);do if(re=await x.next(),re.done){if(G=!0,U.length)break;return y.onDone&&y.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),se){let Se=yh(X,se,N);if(Ue)Ue=!1,te=Se;else if(Se!==te){te=Se,pe=X;break}}U.push(X)}while(!0);return I.isGrouped,U.sort(Ge),C=U[Symbol.iterator](),re=C.next(),re.done?(y.onDone&&y.onDone(),re):{value:await D.call(this,re.value)}},return(){y.onDone&&y.onDone(),x.return()},throw(){y.onDone&&y.onDone(),x.throw()}}};let F=a(C=>{if(typeof O=="object"&&Array.isArray(C.attribute))for(let x=0;x<O.length;x++){let G=O[x],se;if(G.name===C.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=C.attribute.slice(1),se.descending=C.descending}else G===C.attribute[0]&&(O[x]=se={name:G,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&F(C.next)},"applySortingOnSelect");F(I)}else y.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),y=y.map(D);return y}static transformEntryForSelect(m,O,I,N,b,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(x=>(O?.transaction?.stale&&(O.transaction.stale=!1),x?.key??x),"transform");return m===t?C:m.asArray?x=>[C(x)]:x=>({[t]:C(x)})}let y;b&&L&&!m?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(y=!0);let U,F=a(function(C){let x;if(O?.transaction?.stale&&(O.transaction.stale=!1),C!=null){if(Ah=C,x=C.value||C.deref?.(),!x&&(C.key===void 0||C.deref)){if(C=bh(C.key??C,O,{transaction:I,lazy:m?.length<4},this.isSync,G=>G),C?.then)return C.then(F.bind(this));x=C?.value}if(y&&(C.metadataFlags&(Ll|Ml)||C.expiresAt&&C.expiresAt<Date.now())){let G=Nh(C.key??C,C,O);if(G?.then)return G.then(F)}}if(x==null)return D?Uo.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((te,Ue)=>{let ae;typeof te=="object"?ae=te.name:ae=te;let Ge=zs?.[ae],re;if(Ge){let X=N?.[ae];if(X)if(X.hasMappings){let Be=Ge.from?x[Ge.from]:Hn(C.key);re=X.get(Be),re||(re=[])}else re=X.fromRecord?.(x);else re=Ge(x,O,C);let Se=a(Be=>{if(Be&&typeof Be=="object"){let $n=Ge.definition?.tableClass||Qe;U||(U={});let Js=U[ae]||(U[ae]=$n.transformEntryForSelect(ae===te?null:te.select||(Array.isArray(te)?te:null),O,I,X,b));if(Array.isArray(Be)){let Ye=[],qt=$n.transformToOrderedSelect(Be,te.select,typeof te.sort=="object"&&te.sort,O,I,Js)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),sn=a(Ft=>{for(;!Ft.done;){if(Ft?.then)return Ft.then(sn);Ye.push(Ft.value),Ft=qt.next()}Ue(Ye,ae)},"nextValue"),Yn=sn(qt.next());Yn&&(G||(G=[]),G.push(Yn));return}else if(Be=Js.call(this,Be),Be?.then){G||(G=[]),G.push(Be.then(Ye=>Ue(Ye,ae)));return}}Ue(Be,ae)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(Se))):Se(re);return}else re=x[ae],re&&typeof re=="object"&&ae!==te&&(re=Qe.transformEntryForSelect(te.select||te,O,I,null)({value:re}));Ue(re,ae)},"selectAttribute"),pe;if(typeof m=="string")se(m,te=>{pe=te});else if(Array.isArray(m))if(m.asArray)pe=[],m.forEach((te,Ue)=>{te==="*"?m[Ue]=x:se(te,ae=>pe[Ue]=ae)});else{pe={};let te=m.forceNulls;for(let Ue of m)if(Ue==="*")for(let ae in x)pe[ae]=x[ae];else se(Ue,(ae,Ge)=>{ae===void 0&&te&&(ae=null),pe[Ge]=ae})}else throw new tn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>pe):pe}return x},"transform");return F}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||lt({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let O=!m.rawEvents,I=dG(Qe,this[Le]??null,function(y,U,F,C){try{let x=U.getValue?.(i,O);if(!x&&U.type==="patch"&&O){let G=i.getEntry(y);G?.version===U.version?x=G.value:x=U.getValue?.(i,!0,F),U.type="put"}this.send({id:y,timestamp:F,value:x,version:U.version,type:U.type,beginTxn:C})}catch(x){tt.error(x)}},m.startTime||0,m);this[Fn]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.supportsTransactions&&(I.supportsTransactions=!0);let N=this[Le],b=m.previousCount;b>1e3&&(b=1e3);let D=m.startTime;if(this[Fn]){if(D){if(b)throw new tn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:U}of u.getRange({start:D,exclusiveStart:!0})){let F=Ut(U);if(F.tableId!==n)continue;let C=F.recordId;if(N==null||TG(N,C)){let x=F.getValue(i,O,y);I.send({id:C,timestamp:y,value:x,version:F.version,type:F.type})}I.startTime=y}}else if(b){let y=[];for(let{key:U,value:F}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Ut(F);if(C.tableId!==n)continue;let x=C.recordId;if(N==null||TG(N,x)){let G=C.getValue(i,O,U);if(y.push({id:x,timestamp:U,value:G,version:C.version,type:C.type}),--b<=0)break}}catch(C){tt.error("Error getting history entry",U,C)}for(let U=y.length;U>0;)I.send(y[--U]);y[0]&&(I.startTime=y[0].timestamp)}else if(!m.omitCurrent)for(let{key:y,value:U,version:F,localTime:C}of i.getRange({start:N??!1,end:N==null?void 0:[N,vo.MAXIMUM_KEY],versions:!0}))U&&I.send({id:y,timestamp:C,value:U,version:F,type:"put"})}else{b&&!D&&(D=0);let y=this[en]?.localTime;if(y===hm&&(i.cache?.delete(N),this[en]=i.getEntry(N),tt.trace("re-retrieved record",y,this[en]?.localTime),y=this[en]?.localTime),tt.trace("Subscription from",D,"from",N,y),D<y){let U=[],F=y;do{let C=u.get(F);if(C){m.omitCurrent=!0;let x=Ut(C),G=x.getValue(i,O,F);O&&(x.type="put"),U.push({id:N,value:G,timestamp:F,...x}),F=x.previousLocalTime}else break;b&&b--}while(F>D&&b!==0);for(let C=U.length;C>0;)I.send(U[--C]);I.startTime=y}!m.omitCurrent&&this.doesExist()&&I.send({id:N,timestamp:y,value:this,version:this[Pl],type:"put"})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[_e]||this[Dl])}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let I=An(this[Ne]),N=this[Le]||null;oc(N);let b=this[Ne];I.addWrite({key:N,store:i,entry:this[en],nodeName:b?.nodeName,validate:()=>{b?.source||(I.checkOverloaded(),this.validate(m))},before:De.publish?.bind(this,b,N,m),beforeIntermediate:ve.publish?.bind(this,b,N,m),commit:(D,y,U)=>{y===void 0&&p&&!h&&Ih(),T(N,y?.value??null,y,y?.version||D,0,!0,b,y?.expiresAt,"message",!1,m)}})}validate(m,O){let I,N=a((b,D,y)=>{if(D.type&&b!=null)if(O&&b.__op__&&(b=b.value),D.properties){typeof b!="object"&&(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be an object${D.type?" ("+D.type+")":""}`);let U=D.properties;for(let F=0,C=U.length;F<C;F++){let x=U[F],G=N(b[x.name],x,y+"."+x.name);G&&(b[x.name]=G)}if(D.sealed&&b!=null&&typeof b=="object")for(let F in b)U.find(C=>C.name===F)||(I||(I=[])).push(`Property ${F} is not allowed within object in property ${y}`)}else switch(D.type){case"Int":(typeof b!="number"||b>>0!==b)&&(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(U=>typeof U=="string")||(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be a string`);break;case"Boolean":typeof b!="boolean"&&(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be a bigint`)}break;case"Bytes":b instanceof Uint8Array||(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(b)){if(D.elements)for(let U=0,F=b.length;U<F;U++){let C=b[U],x=N(C,D.elements,y+"[*]");x&&(b[U]=x)}}else(I||(I=[])).push(`Value ${kn(b)} in property ${y} must be a Buffer or Uint8Array`);break}D.nullable===!1&&b==null&&(I||(I=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let b=0,D=S.length;b<D;b++){let y=S[b];if(!y.relationship&&(!O||y.name in m)){let U=N(m[y.name],y,y.name);U&&(m[y.name]=U)}}if(d)for(let b in m)S.find(D=>D.name===b)||(I||(I=[])).push(`Property ${b} is not allowed`);if(I)throw new tn.ClientError(I.join(". "))}getUpdatedTime(){return this[Pl]}wasLoadedFromSource(){return L?!!this[qA]:void 0}static async addAttributes(m){let O=S.slice(0);for(let I of m){if(!I.name)throw new tn.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new tn.ClientError("Attribute names cannot include backticks or forward slashes");O.push(I)}return lt({table:s,database:c,schemaDefined:_,attributes:O}),Qe.indexingOperation}static async removeAttributes(m){let O=S.filter(I=>!m.includes(I.name));return lt({table:s,database:c,schemaDefined:_,attributes:O}),Qe.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,I=5e3,N=1e3,b;O>I&&!m?.exactCount&&(b=N);let D=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:b}))y!=null&&D++;if(b){let y=D;D=0;for(let{value:Ue}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Ue!=null&&D++;let U=b*2,F=(D+y)/U,C=Math.pow((D-y+1)/b/2,2)+F*(1-F)/U,x=Math.max(Math.sqrt(C)*O,1),G=Math.round(F*O),se=Math.max(G-1.96*x,0),pe=Math.min(G+1.96*x,O),te=Math.pow(10,Math.round(Math.log10(x)));return te>G&&(te=te/10),D=Math.round(G/te)*te,{recordCount:D,estimatedRange:[Math.round(se),Math.round(pe)]}}return{recordCount:D}}static updatedAttributes(){zs=this.propertyResolvers={$id:(m,O,I)=>({value:I.key}),$updatedtime:(m,O,I)=>I.version,$record:(m,O,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),oO=!0,O.to)m.elements?.definition?(zs[m.name]=m.resolve=(I,N,b)=>{let D=I[O.from?O.from:t],y=m.elements.definition.tableClass;return b?Ba({attribute:O.to,value:D},An(N).getReadTxn(),!1,y,!1).asArray:y.search([{attribute:O.to,value:D}],N).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.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(O.from){let I=m.definition||m.elements?.definition;I?(zs[m.name]=m.resolve=(N,b,D)=>{let y=N[O.from];if(y!==void 0){if(m.elements){let U,F=y.map(C=>{let x=D?I.tableClass.primaryStore.getEntry(C,{transaction:An(b).getReadTxn()}):I.tableClass.get(C,b);return x?.then&&(U=!0),x});return O.filterMissing?U?Promise.all(F).then(C=>C.filter(gG)):F.filter(gG):U?Promise.all(F):F}return D?I.tableClass.primaryStore.getEntry(y,{transaction:An(b).getReadTxn()}):I.tableClass.get(y,b)}},m.set=(N,b)=>{if(Array.isArray(b)){let D=b.map(y=>y[Le]||y[I.tableClass.primaryKey]);N[O.from]=D}else{let D=b[Le]||b[I.tableClass.primaryKey];N[O.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.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`)}ZE(this,this)}static async deleteHistory(m=0){let O;for(let{key:I,value:N}of u.getRange({start:0,end:m}))await Ul(),Ut(N).tableId===n&&(O=u.remove(I));await O}static async*getHistory(m=0,O=1/0){for(let{key:I,value:N}of u.getRange({start:m,end:O})){await Ul();let b=Ut(N);b.tableId===n&&(yield{id:b.recordId,localTime:I,version:b.version,type:b.type,value:b.getValue(i,!0,I),user:b.user})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return O;let N=I.localTime;if(!N)throw new Error("The entry does not have a local audit time");let b=0;do{await Ul();let D=u.get(N);if(D){let y=Ut(D);O.push({id:y.recordId,localTime:N,version:y.version,type:y.type,value:y.getValue(i,!0,N),user:y.user}),N=y.previousLocalTime}else break}while(b<1e3&&N);return O.reverse()}static cleanup(){z?.remove()}}Qe.updatedAttributes();let Rq=Qe.prototype;return Rq[qie]=!0,f&&Qe.setTTLExpiration(f/1e3),j&&Aq(),Qe;function zl(K,m,O){let I;for(let N in r){let b=r[N],D=b.isIndexing,y=O?.[N],U=m?.[N];if(y===U&&!D)continue;I=!0;let F=b.indexNulls,C=(0,vl.getIndexedValues)(y,F),x=(0,vl.getIndexedValues)(U,F);if(x?.length>0){let G=new Set(x);if(C=C?C.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],x=Array.from(G),(x.length>0||C.length>0)&&hG){let se=x.concat(C).map(pe=>({key:pe,value:K}));b.prefetch(se,SG)}for(let se=0,pe=x.length;se<pe;se++)b.remove(x[se],K)}else C?.length>0&&hG&&b.prefetch(C.map(G=>({key:G,value:K})),SG);if(C)for(let G=0,se=C.length;G<se;G++)b.put(C[G],K)}return I}a(zl,"updateIndices");function oc(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>pG)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,vo.writeKey)(K,kie,0)>pG)throw new Error("Primary key size is too large: "+K.length);return!0}a(oc,"checkValidId");function bh(K,m,O,I,N){let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return N(null,K);let D=i.getEntry(K,O);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),N(D,K)},"whenPrefetched");return I?b():ce>0?(ce--,b()):new Promise((D,y)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),F()})):(J.push(K),me.push(F),J.length>gq&&(ce--,U()));function U(){if(J.length>0){let C=me;i.prefetch(J,()=>{ce===-1?U():ce++;for(let x of C)x()}),J=[],me=[],de>2&&de--}else ce=de,de<Tq&&de++}a(U,"prefetch");function F(){try{D(b())}catch(C){y(C)}}a(F,"load")})}a(bh,"loadLocalRecord");function Jl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return Vie;let O=m[c],I,N=O?.tables;if(N)return N[s];if(c==="data"&&(I=m[s])&&!I.tables)return I}a(Jl,"getTablePermissions");function Nh(K,m,O,I){if(L){let N;if(O.noCache?N=!0:(m?(!m.value||m.metadataFlags&(Ll|Ml)||m.expiresAt&&m.expiresAt<Date.now())&&(N=!0):N=!0,Yr(!N,"cache-hit",s)),N){let b=cO(K,m,O).then(D=>(D?.value?.[_e]&&tt.error("Can not assign a record with a record property"),O&&(D?.version>(O.lastModified||0)&&(O.lastModified=D.version),O.lastRefreshed=Date.now()),D));if(O?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,K)){if(b.catch(D=>tt.warn(D)),O?.onlyIfCached&&!I.doesExist())throw new tn.ServerError("Entry is not cached",504);return}else return b}}}a(Nh,"ensureLoadedFromSource");function An(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 O=m.next;if(!O)return m=m.next=new to,m.lmdbDb=i,m;m=O}while(!0)}else return new cd}a(An,"txnForContext");function yh(K,m,O){if(!K)return;Ah=K;let I=K.value||K.deref?.()||(Ah=i.getEntry(K.key))?.value;if(typeof m=="object"){let b=zs,D=I;for(let y=0,U=m.length;y<U;y++){let F=m[y],C=b?.[F];D=C&&D?C(D,O,!0)?.value:D?.[F],b=C?.definition?.tableClass?.propertyResolvers}return D}let N=zs[m];return N?N(I,O):I[m]}a(yh,"getAttributeValue");function aO(K,m,O,I,N){let b=N?.length,D={transaction:I,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},y;function U(F,C){let x=F?.value;if(!x)return Uo.SKIP;for(let G=0;G<b;G++)if(!y?.includes(G)&&!N[G](x,F))return Uo.SKIP;return C!==void 0&&(F.key=C),F}if(a(U,"processEntry"),b>0||!K.hasEntries){let F=K.map(C=>{if(y=null,typeof C=="object"&&C?.key!==void 0)return b>0?U(C):C;if(C==null)return Uo.SKIP;for(let x=0;x<b;x++){let se=N[x].idFilter;if(se){if(!se(C))return Uo.SKIP;y||(y=[]),y.push(x)}}return bh(C,O,D,!1,U)});return Array.isArray(K)&&(F=F.filter(C=>C!==Uo.SKIP)),F.hasEntries=!0,F}return K}a(aO,"transformToEntries");async function cO(K,m,O){let I=m?.metadataFlags,N=m?.version,b,D;if(!i.attemptLock(K,N,()=>{clearTimeout(D);let C=i.getEntry(K);!C||!C.value||C.metadataFlags&(Ll|Ml)?b(cO(K,i.getEntry(K),O)):b(C)}))return new Promise(C=>{b=C,D=setTimeout(()=>{i.unlock(K,N)},Gie)});let y=m?.value,U={requestContext:O,replacingRecord:y,replacingVersion:N,source:null,resourceCache:O?.resourceCache},F=O?.responseHeaders;return new Promise((C,x)=>{let G;kA(Xe(U,async se=>{let pe=performance.now(),te,Ue,ae;try{for(let Se of Qe.sources)if(Se.get&&(!Se.get.reliesOnPrototype||Se.prototype.get)&&(U.source=Se,te=await Se.get(K,U),te))break;ae=I&Ll;let re=U.lastModified||ae&&N;Ue=ae||re>N||!y,re||(re=(0,vl.getNextMonotonicTime)());let X=performance.now()-pe;if($r(X,"cache-resolution",s),F&&dg(F,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=re,f&&!U.expiresAt&&(U.expiresAt=Date.now()+f),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]!==K&&(te[t]=K)}G=!0,C({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} for ${s}`,y&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(C({version:N,value:y}),tt.trace(re.message,"(returned stale record)")):x(re),U.transaction.abort();return}if(O?.noCacheStore){U.transaction.abort();return}An(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==N)return;let Se=zl(K,y,te);te?(ve.put?.(U,K,te),T(K,te,X,re,0,h&&Ue||null,U,U.expiresAt,"put",!!ae)):(ve.delete?.(U,K),h||p?T(K,null,X,re,0,h&&Ue||null,U,0,"delete",!!ae):i.remove(K,N))}})}),()=>{i.unlock(K,N)},se=>{i.unlock(K,N),G&&tt.error("Error committing cache update",se)})})}a(cO,"getFromSource");function Ih(){if(Mt!==Wl&&(Wl=Mt,(0,Po.getWorkerIndex)()===(0,Po.getWorkerCount)()-1)){if(Ql&&clearTimeout(Ql),!Mt)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())/Mt)*Mt+K.getTime(),O=a(I=>{tt.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),Ql=setTimeout(()=>P=P.then(async()=>{if(O(Math.max(I+Mt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Ql);return}let N=50,b=new Array(N),D=0;tt.trace(`Starting cleanup scan for ${s}`);try{let y=0;for(let{key:U,value:F,version:C,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;F===null&&!h&&C+xie<Date.now()?G=i.remove(U,C):x&&x+E<Date.now()&&(G=Qe.evict(U,F,C),y++),G&&(await b[D],b[D]=G.catch(se=>{tt.error("Cleanup error",se)}),++D>=N&&(D=0)),await Ul()}tt.trace(`Finished cleanup scan for ${s}, evicted ${y} entries`)}catch(y){tt.trace(`Error in cleanup scan for ${s}:`,y)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");O(m)}}a(Ih,"scheduleCleanup");function uO(){z=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(uO,"addDeleteRemoval");function Aq(){(0,Po.getWorkerIndex)()===0&&setInterval(async()=>{if(!Oh){Oh=!0;try{let K=j.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${j} must be indexed`);for(let O of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let I of m.getValues(O)){let N=i.getEntry(I);N?.value?N.value[K]<Date.now()&&Qe.evict(I,N.value,N.version):i.ifVersion(I,N?.version,()=>m.remove(O,I))}await Ul()}}catch(K){tt.error("Error in evicting old records",K)}finally{Oh=!1}}},Hie).unref()}a(Aq,"runRecordExpirationEviction")}function FA(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 SG(){}function $ie(e){AG=e}function rh(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?isNaN(e)?e==="null"?null:(Yie.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,sh.autoCast)(e):e}function TG(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 kA(e,t,r){return e?.then?e.then(t,r):t(e)}function nh(e,t){e[en]=t,e[_e]=t?.value??null,e[Pl]=t?.version}function gG(e){return e!=null}function kn(e){try{return JSON.stringify(e)}catch{return e}}var Vn,Uo,vl,RG,xl,tn,Bl,Hl,tt,vo,Po,sh,Bie,AG,Hie,xie,hG,Gie,Pl,qie,en,Dl,mG,Fie,qA,tc,Ll,Ml,kie,pG,Vie,dTe,Yie,Ul,cE=Re(()=>{Vn=B(M()),Uo=require("lmdb"),vl=B(Mr()),RG=require("lodash");Nn();oS();xl=B(Z());EG();tn=B(ne()),Bl=B(bs()),Hl=B(Ln());Ae();Qf();tt=B($());_d();ro();vo=require("ordered-binary"),Po=B(Je());ti();sh=B(Q());wc();ws();KE();Wu();Bie=new Uint8Array(9);Bie[8]=192;Hie=6e4,xie=864e5;xl.initSync();hG=xl.get(Vn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Gie=1e4,Pl=Symbol.for("version"),qie=Symbol.for("incremental-update"),en=Symbol("entry"),Dl=Symbol("is-saving"),mG=1,Fie=2,qA=Symbol("loaded-from-source"),tc={isNotification:!0,ensureLoaded:!1},Ll=1,Ml=8,kie=Buffer.allocUnsafeSlow(8192),pG=1978,Vie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},dTe=(0,sh.convertToMS)(xl.get(Vn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(ih,"makeTable");a(FA,"attributesAsObject");a(SG,"noop");a($ie,"setServerUtilities");Yie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(rh,"coerceType");a(TG,"isDescendantId");Ul=a(()=>new Promise(setImmediate),"rest");a(kA,"when");a(nh,"updateResource");a(gG,"exists");a(kn,"stringify")});var Fe={};qe(Fe,{database:()=>ru,databases:()=>st,dropDatabase:()=>_S,dropTableMeta:()=>Jie,getDatabases:()=>Er,getDefaultCompression:()=>hf,getTables:()=>Kie,onUpdatedTable:()=>JR,readMetaDb:()=>Gl,resetDatabases:()=>qu,table:()=>lt,tables:()=>Ur});function Kie(){return lh||Er(),Ur||{}}function Er(){if(lh)return st;lh=!0,sc=new Map;let e=(0,ht.getHdbBasePath)()&&(0,rt.join)((0,ht.getHdbBasePath)(),Lt.DATABASES_DIR_NAME),t=(0,ht.get)(Lt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,ht.get)(Lt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,rn.existsSync)(e)?e:(0,rt.join)((0,ht.getHdbBasePath)(),Lt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,rn.existsSync)(e))for(let r of(0,rn.readdirSync)(e,{withFileTypes:!0})){let n=(0,rt.basename)(r.name,".mdb");r.isFile()&&(0,rt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Gl((0,rt.join)(e,r.name),null,n)}if((0,rn.existsSync)((0,nc.getBaseSchemaPath)())){for(let r of(0,rn.readdirSync)((0,nc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,rt.join)((0,nc.getBaseSchemaPath)(),r.name),s=(0,rt.join)((0,nc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,rn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,rt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,rt.join)(s,i.name);Gl((0,rt.join)(n,i.name),(0,rt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,rn.existsSync)(s))for(let o of(0,rn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,rt.extname)(o.name).toLowerCase()===".mdb"&&Gl((0,rt.join)(s,o.name),(0,rt.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,rt.join)(c.path,(0,rt.basename)(o+".mdb"));(0,rn.existsSync)(u)&&Gl(u,o,r,null,!0)}}for(let r in st){let n=sc.get(r);if(n){let s=st[r];r.includes("delete")&&Rn.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Rn.trace(`delete table class ${i}`),delete s[i])}else if(delete st[r],r==="data"){for(let s in Ur)delete Ur[s];delete Ur[dh]}}return sc=null,st}}function qu(){lh=!1;for(let[,e]of Pi)e.needsDeletion=!0;Er();for(let[e,t]of Pi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Pi.delete(e));return st}function Gl(e,t,r=YA,n,s){let i=new VA.default(e,!1);try{let o=Pi.get(e);o?o.needsDeletion=!1:(o=(0,ah.open)(i),Pi.set(e,o));let c=new Bo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(oh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,rn.existsSync)(n)&&(i.path=n,_=(0,ah.open)(i),_.isLegacy=!0):_=YE(o));let l=yG(r),d=l[dh],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 T=f.get(p);T||f.set(p,T={attributes:[]}),(S==null||h.is_hash_attribute)&&(T.primary=h),S!=null&&T.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 J of p)if(J.is_hash_attribute||J.isPrimaryKey){S=J;break}if(!S){Rn.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[E],A={},g=[],L,v,P=typeof S.audit=="boolean"?S.audit:(0,ht.get)(Lt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=S.trackDeletes,H=S.expiration,j=S.eviction,z=S.sealed;if(T)A=T.indices,g=T.attributes,T.schemaVersion++;else{L=S.tableId,L?L>=(u.get(rc)||0)&&u.putSync(rc,L+1):(S.tableId=L=u.get(rc),L||(L=1),u.putSync(rc,L+1),u.putSync(S.key,S));let J=new Bo.default(!S.is_hash_attribute,S.is_hash_attribute);if(J.compression=S.compression,J.compression){let me=(0,ht.get)(Lt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||NG;J.compression.threshold=me}v=h_(o.openDB(S.key,J)),v.rootStore=o,v.tableId=L}for(let J of p){J.attribute=J.name;try{if(!J.is_hash_attribute&&(J.indexed||J.attribute&&!J.name)){if(!A[J.name]){let ce=new Bo.default(!J.is_hash_attribute,J.is_hash_attribute);A[J.name]=o.openDB(J.key,ce),A[J.name].indexNulls=J.indexNulls}let me=g.find(ce=>ce.name===J.name);me?g.splice(g.indexOf(me),1,J):g.push(J)}}catch(me){Rn.error("Error trying to update attribute",J,g,A,me)}}if(!T){T=IG(l,E,ih({primaryStore:v,auditStore:_,audit:P,sealed:z,expirationMS:H&&H*1e3,evictionMS:j&&j*1e3,trackDeletes:k,tableName:E,tableId:L,primaryKey:S.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:A,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let J of KA)J(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function yG(e){let t=st[e];if(t||(e==="data"?t=st[e]=Ur:e==="system"?Object.defineProperty(st,"system",{value:t=Object.create(null),configurable:!0}):t=st[e]=Object.create(null)),sc&&!sc.has(e)){let r=new Set;t[dh]=r,sc.set(e,r)}return t}function IG(e,t,r){return e[t]=r,r}function ru({database:e,table:t}){e||(e=YA),Er();let r=yG(e),n=(0,rt.join)((0,ht.getHdbBasePath)(),Lt.DATABASES_DIR_NAME),s=(0,ht.get)(Lt.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,ht.get)(Lt.CONFIG_PARAMS.STORAGE_PATH)||((0,rn.existsSync)(n)?n:(0,rt.join)((0,ht.getHdbBasePath)(),Lt.LEGACY_DATABASES_DIR_NAME));let o=(0,rt.join)(n,(i?t:e)+".mdb"),c=Pi.get(o);if(!c){let u=new VA.default(o,!1);c=(0,ah.open)(u),Pi.set(o,c)}return c}async function _S(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;Pi.delete(s.path),s.status==="open"&&(await s.close(),await _h.remove(s.path))}if(e==="data"){for(let r in Ur)delete Ur[r];delete Ur[dh]}delete st[e]}function lt({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=YA);let d=ru({database:t,table:e}),f=st[t],E=f?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let A=new Bo.default(!1);for(let H of i)H.attribute&&!H.name?(H.name=H.attribute,H.indexed=!0):H.attribute=H.name,H.expiresAt&&(H.indexed=!0);let g,L;if(E){if(h=E.primaryKey,E.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);E.attributes.splice(0,E.attributes.length,...i)}else{let H=d.auditStore;H||(H=YE(d)),p=i.find(me=>me.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=hf(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,ht.get)(Lt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),Rn.trace(`${e} table loading, opening primary store`);let j=new Bo.default(!1,!0);j.compression=p.compression;let z=e+"/",J=h_(d.openDB(z,j));J.rootStore=d,T=d.dbisDb=d.openDB(oh.INTERNAL_DBIS_NAME,A),J.tableId=T.get(rc),J.tableId||(J.tableId=1),T.putSync(rc,J.tableId+1),p.tableId=J.tableId,E=IG(f,e,ih({primaryStore:J,auditStore:H,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),E.schemaVersion=1,g=!0,k(),T.put(z,p)}S=E.indices,T=T||(d.dbisDb=d.openDB(oh.INTERNAL_DBIS_NAME,A)),E.dbisDB=T;let v=[];for(let{key:H,value:j}of T.getRange({start:!0})){let[z,J]=H.toString().split("/");if(J===""&&(J=j.name),J){if(z!==e)continue}else J=z;if(!i.find(ce=>ce.name===J)?.indexed&&j.indexed&&!j.isPrimaryKey){k(),g=!0,T.remove(H);let ce=E.indices[z];ce&&v.push(ce)}}let P=[];try{for(let H of i||[]){if(H.relationship)continue;let j=e+"/"+(H.name||"");Object.defineProperty(H,"key",{value:j,configurable:!0});let z=T.get(j);if(H.isPrimaryKey){if(z=z||T.get(j=e+"/")||{},o!==E.audit||c!==c||(+r||void 0)!==(+z.expiration||void 0)||(+n||void 0)!==(+z.eviction||void 0)){let me=Object.assign({},z);typeof o=="boolean"&&(o&&E.enableAuditing(o),me.audit=o),r&&(me.expiration=+r),n&&(me.eviction=+n),c!==void 0&&(me.sealed=c),g=!0,k(),T.put(j,me)}continue}z?.attribute&&!z.name&&(z.indexed=!0);let J=!z||z.type!==H.type||z.indexed!==H.indexed||z.nullable!==H.nullable||JSON.stringify(z.attributes)!==JSON.stringify(H.attributes)||JSON.stringify(z.elements)!==JSON.stringify(H.elements);if(H.indexed){let me=new Bo.default(!0,!1),ce=d.openDB(j,me);(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(g=!0,k(),z=T.get(j),(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(g=!0,H.indexNulls===void 0&&(H.indexNulls=!0),E.primaryStore.getStats().entryCount>0&&(H.lastIndexedKey=z?.lastIndexedKey||!1,H.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(H,"dbi",{value:ce}),P.push(H))),T.put(j,H)),z?.indexNulls&&H.indexNulls===void 0&&(H.indexNulls=!0),ce.indexNulls=H.indexNulls,S[H.name]=ce}else J&&(g=!0,k(),T.put(j,H))}}finally{L&&L()}if(g&&(E.schemaVersion++,E.updatedAttributes()),Rn.trace(`${e} table loading, running index`),P.length>0||v.length>0?E.indexingOperation=zie(E,P,v):g&&ch.signalSchemaChange(new uh.SchemaEventMsg(process.pid,"schema-change",E.databaseName,E.tableName)),E.origin=l,g)for(let H of KA)H(E,l!=="cluster");return(r||n||s)&&E.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),Rn.trace(`${e} table loaded`),E;function k(){L||d.transactionSync(()=>({then(H){L=H}}))}a(k,"startTxn")}async function zie(e,t,r){try{let n=e.schemaVersion;await ch.signalSchemaChange(new uh.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,p=(0,OG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)E.dbi.put(p[S],_)}}),s.then(()=>u--,f=>{u--,Rn.error(f)}),ql.workerData&&ql.workerData.restartNumber!==bG.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>Wie?await s:u>Qie&&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 ch.signalSchemaChange(new uh.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){Rn.error("Error in indexing",n)}}function Jie({table:e,database:t}){let r=ru({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 JR(e){KA.push(e)}function hf(){let e=(0,ht.get)(Lt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,ht.get)(Lt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,ht.get)(Lt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||NG,n={startingOffset:32};return t&&(n.dictionary=_h.readFileSync(t)),r&&(n.threshold=r),e&&n}var ht,oh,ah,rt,rn,nc,Bo,VA,Lt,_h,$A,OG,ch,uh,ql,Rn,bG,YA,dh,NG,Ur,st,rc,KA,lh,Pi,sc,Wie,Qie,Ae=Re(()=>{ht=B(Z()),oh=B(ut()),ah=require("lmdb"),rt=require("path"),rn=require("fs"),nc=B(ze());cE();Bo=B(Cc()),VA=B(Dc()),Lt=B(M()),_h=B(require("fs-extra")),$A=require("../index"),OG=B(Mr()),ch=B(bs()),uh=B(Ln()),ql=require("worker_threads"),Rn=B($()),bG=B(Je());ti();wc();YA="data",dh=Symbol("defined-tables"),NG=((0,ht.get)(Lt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,ht.initSync)();Ur=Object.create(null),st=Object.create(null);(0,$A._assignPackageExport)("databases",st);(0,$A._assignPackageExport)("tables",Ur);rc=Symbol.for("next-table-id"),KA=[],Pi=new Map;a(Kie,"getTables");a(Er,"getDatabases");a(qu,"resetDatabases");a(Gl,"readMetaDb");a(yG,"ensureDB");a(IG,"setTable");a(ru,"database");a(_S,"dropDatabase");a(lt,"table");Wie=1e3,Qie=10;a(zie,"runIndexing");a(Jie,"dropTableMeta");a(JR,"onUpdatedTable");a(hf,"getDefaultCompression")});var Q=R((RTe,FG)=>{"use strict";var vi=require("path"),MG=require("fs-extra"),Cr=$(),wG=require("fs-extra"),fh=require("os"),jie=require("net"),Xie=require("recursive-iterator"),ct=M(),Zie=kO(),CG=require("papaparse"),Eh=require("moment"),{inspect:eoe}=require("util"),DG=require("is-number"),gTe=require("lodash"),toe=require("minimist"),roe=require("https"),noe=require("http"),{hdb_errors:hh}=ne(),soe=/^((\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)))$/,UG=require("util").promisify(setTimeout),ioe=100,ooe=5,aoe="",coe=4,LG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};FG.exports={isEmpty:nn,isEmptyOrZeroLength:hs,arrayHasEmptyValues:_oe,arrayHasEmptyOrZeroLengthValues:doe,buildFolderPath:foe,isBoolean:PG,errorizeMessage:uoe,stripFileExtension:hoe,autoCast:moe,autoCastJSON:vG,autoCastJSONDeep:QA,removeDir:poe,compareVersions:Soe,isCompatibleDataVersion:Toe,escapeRawValue:goe,unescapeValue:Roe,stringifyProps:Aoe,timeoutPromise:boe,isClusterOperation:yoe,getClusterUser:woe,checkGlobalSchemaTable:Ioe,getHomeDir:HG,getPropsFilePath:Ooe,promisifyPapaParse:Coe,removeBOM:xG,createEventPromise:Doe,checkProcessRunning:Loe,checkSchemaTableExist:Moe,checkSchemaExists:GG,checkTableExists:qG,getStartOfTomorrowInSeconds:Uoe,getLimitKey:Poe,isObject:Eoe,isNotEmptyAndHasValue:loe,autoCasterIsNumberCheck:BG,backtickASTSchemaItems:voe,isPortTaken:Noe,createForkArgs:Boe,autoCastBoolean:Hoe,async_set_timeout:UG,getTableHashAttribute:xoe,doesSchemaExist:Goe,doesTableExist:qoe,stringifyObj:Foe,ms_to_time:koe,changeExtension:Voe,getEnvCliRootPath:zA,noBootFile:$oe,httpRequest:Yoe,transformReq:Koe,convertToMS:Woe,PACKAGE_ROOT:ct.PACKAGE_ROOT};function uoe(e){return e instanceof Error?e:new Error(e)}a(uoe,"errorizeMessage");function nn(e){return e==null}a(nn,"isEmpty");function loe(e){return!nn(e)&&(e||e===0||e===""||PG(e))}a(loe,"isNotEmptyAndHasValue");function hs(e){return nn(e)||e.length===0||e.size===0}a(hs,"isEmptyOrZeroLength");function _oe(e){if(nn(e))return!0;for(let t=0;t<e.length;t++)if(nn(e[t]))return!0;return!1}a(_oe,"arrayHasEmptyValues");function doe(e){if(hs(e))return!0;for(let t=0;t<e.length;t++)if(hs(e[t]))return!0;return!1}a(doe,"arrayHasEmptyOrZeroLengthValues");function foe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(foe,"buildFolderPath");function PG(e){return nn(e)?!1:e===!0||e===!1}a(PG,"isBoolean");function Eoe(e){return nn(e)?!1:typeof e=="object"}a(Eoe,"isObject");function hoe(e){return hs(e)?aoe:e.slice(0,-coe)}a(hoe,"stripFileExtension");function moe(e){return nn(e)||e===""||typeof e!="string"?e:LG[e]!==void 0?LG[e]:BG(e)===!0?Number(e):soe.test(e)?new Date(e):e}a(moe,"autoCast");function vG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(vG,"autoCastJSON");function QA(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=QA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=QA(r);n!==r&&(e[t]=n)}return e}else return vG(e)}a(QA,"autoCastJSONDeep");function BG(e){if(e.startsWith("0.")&&DG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&DG(e))}a(BG,"autoCasterIsNumberCheck");async function poe(e){if(hs(e))throw new Error(`Directory path: ${e} does not exist`);try{await wG.emptyDir(e),await wG.remove(e)}catch(t){throw Cr.error(`Error removing files in ${e} -- ${t}`),t}}a(poe,"removeDir");function Soe(e,t){if(hs(e)){Cr.info("Invalid current version sent as parameter.");return}if(hs(t)){Cr.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(Soe,"compareVersions");function Toe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Toe,"isCompatibleDataVersion");function goe(e){if(nn(e))return e;let t=String(e);return t==="."?ct.UNICODE_PERIOD:t===".."?ct.UNICODE_PERIOD+ct.UNICODE_PERIOD:t.replace(ct.FORWARD_SLASH_REGEX,ct.UNICODE_FORWARD_SLASH)}a(goe,"escapeRawValue");function Roe(e){if(nn(e))return e;let t=String(e);return t===ct.UNICODE_PERIOD?".":t===ct.UNICODE_PERIOD+ct.UNICODE_PERIOD?"..":String(e).replace(ct.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Roe,"unescapeValue");function Aoe(e,t){if(nn(e))return Cr.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+fh.EOL}!hs(n)&&n[0]===";"?r+=" "+n+s+fh.EOL:hs(n)||(r+=n+"="+s+fh.EOL)}catch{Cr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Aoe,"stringifyProps");function HG(){let e;try{e=fh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(HG,"getHomeDir");function Ooe(){let e=vi.join(HG(),ct.HDB_HOME_DIR_NAME,ct.BOOT_PROPS_FILE_NAME);return MG.existsSync(e)||(e=vi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Ooe,"getPropsFilePath");function boe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(boe,"timeoutPromise");async function Noe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=jie.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(Noe,"isPortTaken");function yoe(e){try{return ct.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Cr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(yoe,"isClusterOperation");function Ioe(e,t){let r=(Ae(),ie(Fe)).getDatabases();if(!r[e])return hh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return hh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Ioe,"checkGlobalSchemaTable");function woe(e,t){if(nn(t)){Cr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(nn(e)||hs(e)){Cr.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){Cr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Cr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(woe,"getClusterUser");function Coe(){CG.parsePromise=function(e,t,r){return new Promise(function(n,s){CG.parse(e,{header:!0,transformHeader:xG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Coe,"promisifyPapaParse");function xG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(xG,"removeBOM");function Doe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Cr.info(`Got cluster status event response: ${eoe(s)}`);try{i.cancel()}catch{Cr.error("Error trying to cancel timeout.")}n(s)})})}a(Doe,"createEventPromise");async function Loe(e){let t=!0,r=0;do await UG(ioe*r++),(await Zie.findPs(e)).length>0&&(t=!1);while(t&&r<ooe);if(t)throw new Error(`process ${e} was not started`)}a(Loe,"checkProcessRunning");function Moe(e,t){let r=GG(e);if(r)return r;let n=qG(e,t);if(n)return n}a(Moe,"checkSchemaTableExist");function GG(e){let{getDatabases:t}=(Ae(),ie(Fe));if(!t()[e])return hh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(GG,"checkSchemaExists");function qG(e,t){let{getDatabases:r}=(Ae(),ie(Fe));if(!r()[e][t])return hh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(qG,"checkTableExists");function Uoe(){let e=Eh().utc().add(1,ct.MOMENT_DAYS_TAG).startOf(ct.MOMENT_DAYS_TAG).unix(),t=Eh().utc().unix();return e-t}a(Uoe,"getStartOfTomorrowInSeconds");function Poe(){return Eh().utc().format("DD-MM-YYYY")}a(Poe,"getLimitKey");function voe(e){try{let t=new Xie(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){Cr.error("Got an error back ticking items."),Cr.error(t)}}a(voe,"backtickASTSchemaItems");function Boe(e){return[e]}a(Boe,"createForkArgs");function Hoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Hoe,"autoCastBoolean");function xoe(e,t){let{getDatabases:r}=(Ae(),ie(Fe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(xoe,"getTableHashAttribute");function Goe(e){let{getDatabases:t}=(Ae(),ie(Fe));return t()[e]!==void 0}a(Goe,"doesSchemaExist");function qoe(e,t){let{getDatabases:r}=(Ae(),ie(Fe));return r()[e]?.[t]!==void 0}a(qoe,"doesTableExist");function Foe(e){try{return JSON.stringify(e)}catch{return e}}a(Foe,"stringifyObj");function koe(e){let t=Eh.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(koe,"ms_to_time");function Voe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(Voe,"changeExtension");function zA(){if(process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=toe(process.argv);if(e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(zA,"getEnvCliRootPath");var WA;function $oe(){if(WA)return WA;let e=zA();if(zA()&&MG.pathExistsSync(vi.join(e,ct.HDB_CONFIG_FILE)))return WA=!0,!0}a($oe,"noBootFile");function Yoe(e,t){let r;return e.protocol==="http:"?r=noe:r=roe,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(Yoe,"httpRequest");function Koe(e){if(!e.schema&&!e.database){e.schema=ct.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Koe,"transformReq");function Woe(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(Woe,"convertToMS")});var Z=R((OTe,KG)=>{"use strict";var JA=require("fs-extra"),Ho=require("path"),kG=require("os"),Qoe=require("properties-reader"),kl=$(),Fl=Q(),ue=M(),mh=dr(),zoe="Error initializing environment manager",ph="BOOT_PROPS_FILE_PATH",VG=!1,Joe={[ue.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ws={};KG.exports={BOOT_PROPS_FILE_PATH:ph,getHdbBasePath:joe,setHdbBasePath:Xoe,get:$G,initSync:eae,setProperty:Me,initTestEnvironment:rae,setCloneVar:tae};function joe(){return Ws[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(joe,"getHdbBasePath");function Xoe(e){Ws[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Xoe,"setHdbBasePath");function $G(e){let t=mh.getConfigValue(e);return t===void 0?Ws[e]:t}a($G,"get");function Me(e,t){Joe[e]&&(Ws[e]=t),mh.updateConfigObject(e,t)}a(Me,"setProperty");function Zoe(){let e;try{e=Fl.getPropsFilePath(),JA.accessSync(e,JA.constants.F_OK|JA.constants.R_OK),VG=!0;let t=Qoe(e);return Ws[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Ws[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ws[ph]=e,!0}catch{return kl.trace(`Environment manager found no properties file at ${e}`),!1}}a(Zoe,"doesPropFileExist");function eae(e=!1){try{(VG||Zoe()||Fl.noBootFile())&&!YG&&(mh.initConfig(e),Ws[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=mh.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){kl.error(zoe),kl.error(t),console.error(t),process.exit(1)}}a(eae,"initSync");var YG=!1;function tae(e){YG=e}a(tae,"setCloneVar");function rae(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=Ho.join(__dirname,"../../","unitTests");Ws[ph]=Ho.join(u,"hdb_boot_properties.file"),Me(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Ho.join(u,"settings.test")),Me(ue.HDB_SETTINGS_NAMES.INSTALL_USER,kG.userInfo()?kG.userInfo().username:void 0),Me(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Ho.join(u,"envDir","log")),Me(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Ho.join(u,"envDir")),Me(ue.CONFIG_PARAMS.STORAGE_PATH,Ho.join(u,"envDir")),s&&(Me(ue.CONFIG_PARAMS.HTTP_SECUREPORT,$G(ue.CONFIG_PARAMS.HTTP_PORT)),Me(ue.CONFIG_PARAMS.HTTP_PORT,null)),Me(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Fl.isEmpty(i)?!1:i),Me(ue.CONFIG_PARAMS.HTTP_CORS,Fl.isEmpty(i)?!1:i),Me(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Ho.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Fl.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(ue.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${ph}. Please check your boot props and settings files`;kl.fatal(r),kl.error(t)}}a(rae,"initTestEnvironment")});var jG=R((NTe,JG)=>{"use strict";var zG=require("joi"),{string:Vl,boolean:WG,array:nae}=zG.types(),QG=M(),sae=je();JG.exports=iae;function iae(e){let t=zG.object({operation:Vl.valid(QG.OPERATIONS_ENUM.ADD_NODE,QG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Vl.required(),subscriptions:nae.items({schema:Vl.required(),table:Vl.optional(),hash_attribute:Vl.optional(),subscribe:WG.required(),publish:WG.required()}).min(1).required()});return sae.validateBySchema(e,t)}a(iae,"updateRemoteSourceValidator")});var $l=R((ITe,XG)=>{"use strict";var jA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};XG.exports=jA});var rq=R((CTe,tq)=>{"use strict";var oae=jG(),Qs=$(),XA=ke(),aae=M(),ZA=_n(),xo=it(),ZG=Su(),cae=id(),{Node:uae,NodeSubscription:eq}=pi(),eO=$l(),tO=Q(),lae=Z(),{cloneDeep:_ae}=require("lodash"),{broadcast:dae}=Je();tq.exports=fae;async function fae(e){try{let t=oae(e);if(t)return Qs.error(`Validation error in updateRemoteSource: ${t.message}`),new eO(XA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=_ae(await ZA.getNodeRecord(n)),c=!tO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Qs.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!tO.doesSchemaExist(f)){Qs.trace(`updateRemoteSource creating schema: ${f}`);try{await ZG.createSchema({operation:"create_schema",schema:f})}catch(h){Qs.error(h)}}if(E&&!tO.doesTableExist(f,E)){let h=new cae(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Qs.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await ZG.createTable(h)}catch(p){Qs.error(p)}}if(Qs.trace(`Creating local stream for ${f}.${E}`),await xo.createLocalTableStream(f,E),c?(await xo.updateConsumerIterator(f,E,n,"stop"),await xo.updateRemoteConsumer(d,n),d.subscribe===!0&&await xo.updateConsumerIterator(f,E,n,"start")):(await xo.updateRemoteConsumer(d,n),d.subscribe===!0?await xo.updateConsumerIterator(f,E,n,"start"):await xo.updateConsumerIterator(f,E,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===f&&T.table===E){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new eq(f,E,d.publish,d.subscribe))}else i.push(new eq(f,E,d.publish,d.subscribe))}c||(o=new uae(n,i,void 0),Qs.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await ZA.upsertNodeRecord(u),dae({type:"nats_update"}),new eO(XA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${lae.get(aae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await ZA.getSystemInfo())}catch(t){Qs.error(t);let r=t.message?t.message:t;return new eO(XA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(fae,"updateRemoteSource")});var oq=R((LTe,iq)=>{"use strict";var sq=require("joi"),{string:nq}=sq.types(),Eae=M(),hae=je();iq.exports=mae;function mae(e){let t=sq.object({operation:nq.valid(Eae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:nq.required()});return hae.validateBySchema(e,t)}a(mae,"removeRemoteSourceValidator")});var uq=R((UTe,cq)=>{"use strict";var pae=oq(),Sh=$(),Th=ke(),rO=M(),Sae=_n(),Tae=Q(),aq=it(),gae=Z(),gh=$l(),{NodeSubscription:Rae}=pi(),Aae=ia(),Oae=oi(),{broadcast:bae}=Je(),Nae=gae.get(rO.CONFIG_PARAMS.CLUSTERING_NODENAME);cq.exports=yae;async function yae(e){try{let t=pae(e);if(t)return Sh.error(`Validation error in removeRemoteSource: ${t.message}`),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await Sae.getNodeRecord(r);if(Tae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return Sh.error(i),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];Sh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Rae(c.schema,c.table,!1,!1);await aq.updateConsumerIterator(c.schema,c.table,r,"stop"),await aq.updateRemoteConsumer(u,r)}let s=new Aae(rO.SYSTEM_SCHEMA_NAME,rO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Oae.deleteRecord(s),bae({type:"nats_update"}),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Nae} successfully removed node '${r}'.`)}catch(t){Sh.error(t);let r=t.message?t.message:t;return new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(yae,"removeRemoteSource")});var fq=R((vTe,dq)=>{"use strict";var Rh=$(),Yl=M(),lq=ke(),nO=Z(),Iae=Q(),_q=$l(),wae=_n(),Cae=Bd(),Dae=Hr();dq.exports=Lae;async function Lae(e){try{Rh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Iae.ms_to_time(t),n=new Mae(nO.get(Yl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),nO.get(Yl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??nO.get(Yl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await wae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new Cae(Yl.SYSTEM_SCHEMA_NAME,Yl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await Dae.update(i)}catch(s){Rh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return Rh.trace("getRemoteSourceConfig response:",n),new _q(lq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){Rh.error(t);let r=t.message?t.message:t;return new _q(lq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Lae,"getRemoteSourceConfig");function Mae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(Mae,"ConfigResponseObject")});var pq=R((HTe,mq)=>{"use strict";var Eq=Z();Eq.initSync();var hq=it(),Kl=$(),ic=M(),sO=ke(),Uae=rq(),Pae=uq(),vae=fq(),Bae=$l(),{encode:Hae,decode:xae}=require("msgpackr"),Gae=Os(),qae=As(),Fae=require("util"),kae=M(),{isMainThread:Vae,parentPort:$ae}=require("worker_threads");Je();var Yae=Fae.promisify(Gae.setSchemaDataToGlobal),iO=Eq.get(ic.CONFIG_PARAMS.CLUSTERING_NODENAME);mq.exports=Kae;async function Kae(){try{Kl.notify("Starting reply service."),await Yae();let e=await hq.getConnection(),t=`${iO}.__request__`,r=e.subscribe(t,{queue:iO});await Wae(r)}catch(e){Kl.error(e)}}a(Kae,"initialize");async function Wae(e){for await(let t of e){let r=xae(t.data),n;switch(r.operation){case ic.OPERATIONS_ENUM.ADD_NODE:case ic.OPERATIONS_ENUM.UPDATE_NODE:n=await Uae(r);break;case ic.OPERATIONS_ENUM.REMOVE_NODE:n=await Pae(r);break;case ic.OPERATIONS_ENUM.CLUSTER_STATUS:n=await vae(r);break;case ic.OPERATIONS_ENUM.DESCRIBE_ALL:n=await Qae();break;default:let s=`node '${iO}' reply service received unrecognized request operation`;Kl.error(s),n=new Bae(sO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Kl.trace(n),t.respond(Hae(n))}}a(Wae,"handleRequest");async function Qae(){try{return{status:sO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await qae.describeAll()}}catch(e){return Kl.error(e),{status:sO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(Qae,"getRemoteDescribeAll");Vae||$ae.on("message",async e=>{let{type:t}=e;t===kae.ITC_EVENT_TYPES.SHUTDOWN&&hq.closeConnection()})});var zae=pq();(async()=>{try{await zae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
31
+ `))}},25).unref()}o.close?.(()=>{if(He.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&yl()==0)try{KH(He.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,LE),o.cantCleanupProperly||Lt.warn("Had to forcefully exit the thread",LE),process.exit(0)},5e3).unref()})}if(ex||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Lt.info("Could not close debugger",i)}}}).ref();let e=[];if(WH&&!Cse)for(let t in ds){let r=ds[t];if(isNaN(t)&&yl()==0){Sse(t)&&KH(t),e.push(new Promise((i,o)=>{r.listen({path:t},()=>{i(),Lt.info("Domain socket listening on "+t)}).on("error",o)}));continue}let n=He.get(ut.CONFIG_PARAMS.HTTP_THREADRANGE);if(n){let i=typeof n=="string"?n.split("-"):n,o=yl();if(o<i[0]||o>i[1])continue}let s;try{s=WH(+t,"::")}catch(i){console.error(`Unable to bind to port ${t}`,i);continue}e.push(new Promise((i,o)=>{r.listen({fd:s},()=>{i(),Lt.trace("Listening on port "+t,LE)}).on("error",o)}))}Promise.all(e).then(()=>{bl?.postMessage({type:ut.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(tx,"startServers");tA||tx();function sA(e,t,r){let n=e?.read?e:new dse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=ds[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=ds[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Lt.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(sA,"deliverSocket");var QH=new Map;function Mse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=QH.get(s),r){case"connection":i=sA(void 0,t),QH.set(s,i),i.write=(c,u,_)=>(bl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(bl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),bl.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(Mse,"proxyRequest");function iA(e,t,r=!0){!+t&&t!==He.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(He.get(ut.CONFIG_PARAMS.HTTP_PORT),10));let n=ds[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",zH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else ds[t]=e;e.on("unhandled",zH)}a(iA,"registerServer");function rx(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=[],He.get(ut.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:He.get(ut.CONFIG_PARAMS.HTTP_PORT),secure:He.get(ut.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),He.get(ut.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:He.get(ut.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&He.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:He.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(rx,"getPorts");function oA(e,t){for(let{port:r,secure:n}of rx(t))nx(r,n,t?.isOperationsServer),typeof e=="function"?rA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,iA(e,r,!1)),PE[r]=nA(rA,r),Dse=nA(Lse,r)}a(oA,"httpServer");function nx(e,t,r){if(!$s[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:He.get(n+"_keepAliveTimeout"),headersTimeout:He.get(n+"_headersTimeout"),requestTimeout:He.get(n+"_timeout")},i=He.get(n+"_mtls"),o=He.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=He.get(n+"tls");Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:JH(),maxHeaderSize:He.get(ut.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:aA(u)})}let c=yse();$s[e]=(t?mse:Ese)(s,async(u,_)=>{try{let d=performance.now(),E=new XH(u,_);r&&(E.isOperationsServer=!0);let f=await PE[e](E);if(!f){if(E._nodeResponse.statusCode)return;f=sx(E)}if(c?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 x of f.headers||[])_.setHeader(x[0],x[1]);return u.baseRequest=E,_.baseResponse=f,$s[e].emit("unhandled",u,_)}let h=f.status||200,p=performance.now(),S=p-d,T=f.body,A;if(!f.handlesHeaders){let x=f.headers||new jH;T?T.length>=0&&(typeof T=="string"?x.set("Content-Length",Buffer.byteLength(T)):x.set("Content-Length",T.length),A=!0):(x.set("Content-Length","0"),A=!0);let v=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(v+=", miss"),Ose(x,"Server-Timing",v,!0),_.writeHead(h,x&&(x[Symbol.iterator]?Array.from(x):x)),A&&_.end(T)}let R=E.handlerPath,C=E.method;if(Ol(S,"duration",R,C,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),bse(h<400,"success",R,C),!A)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let x=0;T.on("data",v=>{x+=v.length}),T.on("end",()=>{Ol(performance.now()-p,"transfer",R,C),Ol(x,"bytes-sent",R,C)})}else T?.then?T.then(x=>{_.end(x)},l):_.end(T)}catch(d){l(d)}function l(d){let E=d.headers;_.writeHead(d.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),_.end(d.toString()),d.statusCode?d.statusCode===500?Lt.warn(d):Lt.info(d):Lt.error(d)}a(l,"onError")}),i&&($s[e].mtlsConfig=i),t&&($s[e].on("secureConnection",u=>{u._parent.startTime&&Ol(performance.now()-u._parent.startTime,"tls-handshake",e),Ol(u.isSessionReused(),"tls-reused",e)}),$s[e].isSecure=!0,s.SNICallback(null,(u,_)=>{try{za=_,_&&$s[e].setSecureContext(_.options)}finally{za=null}})),iA($s[e],e)}return $s[e]}a(nx,"getHTTPServer");function nA(e,t){let r=sx;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(nA,"makeCallbackChain");function sx(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new jH}}a(sx,"unhandled");function Pse(e,t){oA(e,{requestOnly:!0,...t})}a(Pse,"onRequest");function Use(e,t){let r;if(t.securePort){let n=Object.assign({},He.get("tls"));t.mtls?.certificateAuthority&&(n.certificateAuthority=t.mtls.certificateAuthority);let s={rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,SNICallback:aA(n)};r=Rse(s,e),s.SNICallback(null,(i,o)=>{try{za=o,o&&r.setSecureContext(o.options)}finally{za=null}}),ds[t.securePort]=r}return t.port&&(r=fse(e),ds[t.port]=r),r}a(Use,"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 vse(e,t){let r;for(let{port:n,secure:s}of rx(t)){ME[n]||(ME[n]=new Tse({server:r=nx(n,s)}),ME[n].on("connection",async(c,u)=>{try{let _=new XH(u);_.isWebSocket=!0;let l=PE[n](_),d=u.headers["sec-websocket-protocol"]||"",E=ZR[n];if(d){let f;for(let h=0;h<E.length;h++){let p=E[h];p.protocol===d&&(f=!0,p.listener(c,_,l))}if(f)return}for(let f=0;f<E.length;f++){let h=E[f];h.protocol||h.listener(c,_,l)}}catch(_){Lt.warn("Error handling WebSocket connection",_)}}),ME[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=ZR[n];o||(o=ZR[n]=[]),o.push({listener:e,protocol:i}),PE[n]=nA(rA,n)}return r}a(vse,"onWebSocket");function zH(e,t){t.writeHead(404),t.end(`Not found
32
+ `)}a(zH,"defaultNotFound");function eA(e){return e.startsWith("-----BEGIN")?e:pse(e)}a(eA,"readPEM");function aA(e){let t=[];for(let i=0;e[i];i++)t.push(e[i]);t.length||t.push(e);let r=new Map,n,s=!1;for(let i of t){let o=eA(i.privateKey),c=eA(i.certificate),u=i.certificateAuthority&&eA(i.certificateAuthority);if(!o||!c)throw new Error("Missing private key or certificate for secure server");let _={ciphers:i.ciphers,ca:u,ticketKeys:JH()},l=gse(_);l.options=_,_.instantiatedContext=l,l.context.setCert(c),l.context.setKey(o,void 0),_.cert=c,_.key=o,l.certStart=c.slice(0,100).toString(),n||(n=l);let d=new Nse(c),E=i.hostname??i.host??i.hostnames??i.hosts??(d.subjectAltName?d.subjectAltName.split(",").map(f=>{let h=f.indexOf(":");return f.slice(h+1)}):[d.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(E)||(E=[E]);for(let f of E)f?(f[0]==="*"&&(s=!0,f=f.slice(1)),r.has(f)||r.set(f,l)):Lt.error("No hostname found for certificate at",i.certificate)}return(i,o)=>{let c=i;for(;;){let u=r.get(c);if(u)return Lt.debug("Found certificate for",i,u.certStart),o(null,u);if(s&&c){let _=c.indexOf(".",1);_<0?c="":c=c.slice(_)}else break}Lt.debug("No certificate found to match",i,"using the first certificate"),o(null,n)}}a(aA,"createSNICallback")});async function ux({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await uA.get(e,{returnNonexistent:!0});i=new dA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await uA.get(e);o&&o.delete()}i=new BE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Nl.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function lA(){return vE++,vE>65500&&(vE=1),vE}function _A(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Oi.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 ox,Li,ax,cx,uA,Nl,vE,BE,dA,lx=Ae(()=>{Oe();Wu();ox=B(vr()),Li=B($());ro();ax=B(Je()),cx=B(ix());ur();uA=dt({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"}]}}]}),Nl=dt({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,ax.getWorkerIndex)()===0&&(async()=>{await cx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Nl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await st.getUser(r.user.username)),Xe(r,()=>{try{_A(r,t,r)}catch{(0,Li.warn)("Failed to publish will",t)}Nl.delete(e.id,r)})}})();a(ux,"getSession");vE=1;a(lA,"getNextMessageId");BE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;keepalive;keepaliveTimer;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(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let E={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Li.trace)("Resuming subscription from",s,"from",o);let f=Oi.getMatch(_);if(!f){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(E.url=f.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let T=E.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,T.indexOf("+")===T.length-1)E.onlyChildren=!0,E.url="/"+T.slice(0,T.length-1);else{let A=T.split("/"),R;for(let v=0;v<A.length;v++)if(A[v].indexOf("+")>-1)if(A[v]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&R)throw new Error("Filters can not be combined");let C=!0;A[A.length-1]==="#"&&(A.length--,C=!1),R&&(n=a(v=>{let k=v.id;if(!Array.isArray(k)||C&&k.length!==A.length)return!1;for(let M=0;M<A.length;M++)if(A[M]!=="+"&&A[M]!==k[M])return!1;return!0},"filter"));let x=A.indexOf("+");E.url="/"+(x>-1?A.slice(0,x):A).concat("").join("/")}}let h=f.path,p=f.Resource,S=await Xe(E,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let A=await p.subscribe(E,T);if(!A)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!A[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let R of A)try{let C;if(R.type&&R.type!=="put"&&R.type!=="delete"&&R.type!=="message"&&R.type!=="patch"||n&&!n(R))continue;r?(R.topic=s,C=this.needsAcknowledge(R)):(R.acknowledge?.(),C=lA());let x=R.id;Array.isArray(x)&&(x=Na(x)),x==null&&(x=""),this.listener(h+"/"+x,R.value,C,t)}catch(C){(0,Li.warn)(C)}})(),A});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=lA();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(),this.subscriptions.splice(this.subscriptions.indexOf(r),1),!0}async publish(t,r){return _A(t,r,this.createContext())}createContext(){let t={session:this,socket:this.socket,user:this.user,authorize:!0};return this.request&&(t.request=this.request,t.url=this.request.url,t.headers=this.request.headers),t}setListener(t){this.listener=t}disconnect(t){this.keepaliveTimer&&clearTimeout(this.keepaliveTimer);let r=this.createContext();Xe(r,async()=>{try{if(!t){let n=await Nl.get(this.sessionId);n?.doesExist()&&await _A(n,n.data,r)}}finally{await Nl.delete(this.sessionId)}}).catch(n=>{(0,Li.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}receivedPacket(){this.keepalive&&(clearTimeout(this.keepaliveTimer),this.keepaliveTimer=setTimeout(()=>{this.socket?.destroy?this.socket.destroy(new Error("Keepalive timeout")):this.socket?.terminate()},this.keepalive*1500))}};a(_A,"publish");dA=class extends BE{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=lA(),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,Li.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.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t),n=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),n}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,ox.getNextMonotonicTime)()),(0,Li.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),uA.put(this.sessionRecord)}}});var EA={};qe(EA,{bypassAuth:()=>Bse,start:()=>Hse});function Bse(){hx=!0}function Hse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new Ex.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),ir.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=dx(_,(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",E),_.on("close",f),_.on("error",h=>{ir.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(o.events.emit("connection",_),ir.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let f=u.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{l=await e.getUser(f,null,null),(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&xE.notify({username:l?.username,status:Jt.AUTH_AUDIT_STATUS.SUCCESS,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&xE.error({username:f,status:Jt.AUTH_AUDIT_STATUS.FAILURE,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else ir.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(f){o.events.emit("error",f,_),ir.error(f)}else if(u.required)return ir.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&hx&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,fx.getSuperUser)(),ir.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:E}=dx(_,f=>_.write(f),null,l,o);_.on("data",d),_.on("close",E),_.on("error",f=>{ir.info("Socket error",f)})},{port:t,securePort:s,mtls:u})),c}function dx(e,t,r,n,s){_x||(_x=!0,_u(d=>{HE>0&&d.push({metric:"mqtt-connections",connections:HE,byThread:!0})}));let i;HE++;let o,c={protocolVersion:4},u=(0,GE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){HE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!1,"connection","mqtt","disconnect"),ir.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;let E=d.topic,f=E?.indexOf("/",1),h=f>0?E.slice(0,f):E;pr(d.length,"bytes-received",h,S(d),"mqtt");try{switch(o?.receivedPacket?.(),d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await st.getUser(d.username,d.password.toString(),r),(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&xE.notify({username:n?.username,status:Jt.AUTH_AUDIT_STATUS.SUCCESS,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(M){return(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&xE.error({username:d.username,status:Jt.AUTH_AUDIT_STATUS.FAILURE,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let M=e.deserialize||(e.deserialize=Oo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=ux({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(M){return ir.error(M),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),Wr(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,Q,j,z)=>{try{let ae=M.indexOf("/",1),ue=ae>0?M.slice(0,ae):M;p({cmd:"publish",topic:M,payload:T(Q),messageId:j||Math.floor(Math.random()*1e8),qos:z.qos},ue)}catch(ae){ir.error(ae),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let A=[];for(let M of d.subscriptions){let Q;try{Q=(await o.addSubscription(M,M.qos>=1)).qos||0}catch(j){s.events.emit("error",j,e,M,o),ir.error(j),Q=c.protocolVersion<5?128:j.statusCode===403?135:j.statusCode===404?143:128}A.push(Q)}await o.committed,p({cmd:"suback",granted:A,messageId:d.messageId});break;case"unsubscribe":{let M=[];for(let Q of d.unsubscriptions)M.push(o.removeSubscription(Q)?0:17);p({cmd:"unsuback",granted:M,messageId:d.messageId});break}case"pubrel":p({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let R=d.qos===2?"pubrec":"puback",C=e.deserialize||(e.deserialize=Oo(r?.headers.get?.("content-type"))),v=(d.payload?.length||0)>0?C(d.payload):void 0,k;try{k=await o.publish(d,v)}catch(M){s.events.emit("error",M,e,d,o),ir.warn(M),d.qos>0&&p({cmd:R,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&p({cmd:R,messageId:d.messageId,reasonCode:k===!1?144:0},d.topic);break;case"pubrec":p({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":p({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!0,"connection","mqtt","disconnect"),ir.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(A){s.events.emit("error",A,e,d,o),ir.error(A),p({cmd:"disconnect"})}function p(A,R){let C=(0,GE.generate)(A,c);t(C),pr(C.length,"bytes-sent",R,S(A),"mqtt")}a(p,"sendPacket");function S(A){return A.qos>0?A.cmd+",qos="+A.qos:A.cmd}a(S,"packetMethodName");function T(A){return To(A,r)}a(T,"serialize")}),{onMessage:_,onClose:l}}var GE,fx,Ja,Jt,fA,Ex,xE,ir,hx,_x,HE,mx=Ae(()=>{GE=require("mqtt-packet");lx();fx=B(ln());wa();ws();ur();Ja=B(Z()),Jt=B(P()),fA=B($()),Ex=require("events"),xE=(0,fA.loggerWithTag)("auth-event"),ir=(0,fA.loggerWithTag)("mqtt"),hx=(0,Ja.get)(Jt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Bse,"bypassAuth");a(Hse,"start");HE=0;a(dx,"onSocket")});var Uf={};qe(Uf,{component_errors:()=>Xa,loadComponent:()=>qE,loadComponentDirectories:()=>yx,setErrorReporter:()=>Fse});function yx(e,t){t&&(mA=t),e&&(pA=e);let r=[];if((0,bt.existsSync)(hA)){let s=(0,bt.readdirSync)(hA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,tt.join)(hA,o);r.push(qE(c,mA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(qE(n,mA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{bx=!0})}function Fse(e){Il=e}async function qE(e,t,r,n,s,i){if(!Sx.has(e)){Sx.set(e,!0),s&&(pA=s);try{let o;n&&(Xa=new Map);let c=(0,tt.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,bt.existsSync)(c)?o=n?(0,Ox.getConfigObj)():(0,Tx.parseDocument)((0,bt.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=SA;let u=(0,tt.join)(e,"node_modules","harperdb");try{Lo.isMainThread&&((0,bt.existsSync)(u)||n)&&((0,bt.rmSync)(u,{recursive:!0,force:!0}),(0,bt.existsSync)((0,tt.join)(e,"node_modules"))||(0,bt.mkdirSync)((0,tt.join)(e,"node_modules")),(0,bt.symlinkSync)(Cl.PACKAGE_ROOT,u,"dir"))}catch(d){ja.default.error("Error symlinking harperdb module",d)}let _=[],l=n;for(let d in o){let E=o[d];if(Xa.set(n?d:(0,tt.basename)(e),!1),!E)continue;let f,h=E.package;try{if(h){let R=e,C;for(;!(0,bt.existsSync)(C=(0,tt.join)(R,"node_modules",d));)if(R=(0,tt.dirname)(R),R.length<(0,Ax.getHdbBasePath)().length){C=null;break}if(C)f=await qE(C,t,r,!1),l=!0;else throw new Error(`Unable to find package ${d}:${h}`)}else f=qse[d];if(!f)continue;_.push(f);let p=a(R=>(R.origin=r,dt(R)),"ensureTable"),S=E.network||(E.port||E.securePort)&&E,T=S?.securePort||S?.https&&S.port,A=!S?.https&&S?.port;if(Lo.isMainThread&&(f=await f.startOnMainThread?.({server:st,ensureTable:p,port:A,securePort:T,resources:t,...E})||f,n&&S))for(let R of[A,T])try{if(+R&&!px.includes(R)){let C=TA.get(Cl.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);C&&ja.default.warn("Session affinity is not recommended and may cause memory leaks"),(C||!NE)&&(px.push(R),LH(R,C))}}catch(C){console.error("Error listening on socket",R,C,d)}if(t.isWorker&&(f=await f.start?.({server:st,ensureTable:p,port:A,securePort:T,resources:t,...E})||f),pA.set(f,!0),(f.handleFile||f.handleDirectory)&&E.files){if(E.files.includes(".."))throw(0,Rx.handleHDBError)("Can not reference parent directories");let R=(0,tt.join)(e,E.files).replace(/\\/g,"/"),C=R.indexOf("/*");if(C>-1&&E.files!==SA[d]?.files&&!(0,bt.existsSync)(R.slice(0,C)))throw new Error(`The path '${R.slice(0,C)}' does not exist and cannot be used as the base of the resolved 'files' path value '${E.files}'`);let x=(0,tt.basename)(e),v=E.path||"/";v=v.startsWith("/")?v:v.startsWith("./")?"/"+x+v.slice(2):v==="."?"/"+x:"/"+x+"/"+v;let k,M,Q;if(E.root){let z=E.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",M=(0,tt.join)(e,z)}else(Q=R.indexOf("/*"))>-1&&(M=R.slice(0,Q+1),k=(0,tt.relative)(e,M));let j=!1;if(Lo.isMainThread&&f.setupDirectory&&(j=await f.setupDirectory?.(v,M,t)),t.isWorker&&f.handleDirectory&&(j=await f.handleDirectory?.(v,M,t)),j)continue;for(let z of await(0,gx.default)(R,{onlyFiles:!1,objectMode:!0})){let{path:ae,dirent:ue}=z;l=!0;let de=(0,tt.relative)(e,ae).replace(/\\/g,"/");if(k)if(de.startsWith(k))de=de.slice(k.length+1);else throw new Error(`The root path '${E.root}' does not reference a valid part of the file path '${de}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let xe=v+(v.endsWith("/")?"":"/")+de;try{if(ue.isFile()){let Ee=await Gse(ae);Lo.isMainThread&&await f.setupFile?.(Ee,xe,ae,t),t.isWorker&&await f.handleFile?.(Ee,xe,ae,t)}else Lo.isMainThread&&await f.setupDirectory?.(xe,ae,t),t.isWorker&&await f.handleDirectory?.(xe,ae,t)}catch(Ee){Ee.message=`Could not load ${ue.isFile()?"file":"directory"} '${ae}'${E.module?" using '"+E.module+"'":""} for application '${e}' due to: ${Ee.message}`,Il?.(Ee),((0,Za.getWorkerIndex)()===0?console:ja.default).error(Ee),t.set(E.path||"/",new wl(Ee)),Xa.set(n?d:(0,tt.basename)(e),Ee.message)}}}}catch(p){p.message=`Could not load component '${d}' for application '${(0,tt.basename)(e)}' due to: ${p.message}`,Il?.(p),((0,Za.getWorkerIndex)()===0?console:ja.default).error(p),t.set(E.path||"/",new wl(p),null,!0),Xa.set(n?d:(0,tt.basename)(e),p.message)}}if(Lo.isMainThread&&!bx&&i&&(0,Za.watchDir)(e,async()=>yx()),o.extensionModule)return await __((0,tt.join)(e,o.extensionModule));if(!l&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;Il?.(new Error(d)),((0,Za.getWorkerIndex)()===0?console:ja.default).error(d),Xa.set((0,tt.basename)(e),d)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Il?.(o),t.set("",new wl(o))}}}var bt,tt,Lo,Tx,TA,Cl,gx,Za,ja,Rx,Ax,xse,Ox,Gse,hA,pA,bx,mA,Xa,qse,SA,px,Sx,Il,wl,vf=Ae(()=>{bt=require("fs"),tt=require("path"),Lo=require("worker_threads"),Tx=require("yaml"),TA=B(Z()),Cl=B(P());Tb();Ob();bb();P0();gH();NH();gx=B(require("fast-glob")),Za=B(Je()),ja=B($());zh();ur();Rx=B(ne());Nn();Oe();MH();Ax=B(Z()),xse=B(HH());Nf();YH();mx();Ox=B(fr());IE();({readFile:Gse}=bt.promises),hA=TA.get(Cl.CONFIG_PARAMS.COMPONENTSROOT),pA=new Map,Xa=new Map;a(yx,"loadComponentDirectories");qse={REST:Zf,rest:Zf,graphqlSchema:Qh,jsResource:jh,fastifyRoutes:BR,login:Zh,static:HR,operationsApi:xse,customFunctions:{},http:{},clustering:jR,authentication:zu,mqtt:EA},SA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(SA,"static",{value:{files:"web/**"}});px=[],Sx=new Map;a(Fse,"setErrorReporter");a(qE,"loadComponent");wl=class extends Vt{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 cA=g((OSe,Ix)=>{var{isMainThread:Nx}=require("worker_threads"),{getTables:kse}=(Oe(),ie(Fe)),{loadComponentDirectories:Vse,loadComponent:$se}=(vf(),ie(Uf)),{resetResources:Yse}=(Wu(),ie(kU)),Kse=pg(),Wse=fr(),{dirname:Qse}=require("path"),{getConnection:zse}=ot(),Jse=Z(),jse=P(),gA=new Map;async function Xse(e=!1){!Nx&&Jse.get(jse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&zse();try{Nx&&await Kse()}catch(n){console.error(n)}let t=Yse();kse(),t.isWorker=e,await $se(Qse(Wse.getConfigFilePath()),t,"hdb",!0,gA),await Vse(gA,t);let r=[];for(let[n]of gA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Xse,"loadRootComponents");Ix.exports.loadRootComponents=Xse});var Je=g((ySe,Pi)=>{"use strict";var{Worker:Zse,MessageChannel:eie,parentPort:Es,isMainThread:yA,threadId:tie,workerData:Ys}=require("worker_threads"),{PACKAGE_ROOT:rie}=P(),{join:Lx,isAbsolute:nie,extname:sie}=require("path"),{server:Mx}=(ur(),ie(Hi)),{watch:iie,readdir:oie}=require("fs/promises"),{totalmem:wx}=require("os"),Dl=P(),Px=Z(),Ks=$(),{randomBytes:aie}=require("crypto"),{_assignPackageExport:cie}=require("../index"),uie=P(),Cx=1024*1024,Mi=[],Tn=[],lie=50,NA=1e4,_ie="restart",Ux="request_thread_info",vx="resource_report",Bx="thread_info",Hx="added-port",die="ack",RA;cie("threads",Tn);Pi.exports={startWorker:AA,restartWorkers:wA,shutdownWorkers:pie,workers:Mi,setMonitorListener:yie,onMessageFromWorkers:Sie,onMessageByType:$x,broadcast:gie,broadcastWithAcknowledgement:Aie,setChildListenerByType:mie,getWorkerIndex:xx,getWorkerCount:Gx,getTicketKeys:Fx,setMainIsWorker:Eie,setTerminateTimeout:fie,restartNumber:Ys?.restartNumber||1};Tn.onMessageByType=$x;Tn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Tn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var IA;function fie(e){NA=e}a(fie,"setTerminateTimeout");function xx(){return Ys?Ys.workerIndex:IA?0:void 0}a(xx,"getWorkerIndex");function Gx(){return Ys?Ys.workerCount:IA?1:void 0}a(Gx,"getWorkerCount");function Eie(e){IA=e}a(Eie,"setMainIsWorker");var qx=1,FE;function Fx(){return FE||(FE=yA?aie(48):Ys.ticketKeys,FE)}a(Fx,"getTicketKeys");Object.defineProperty(Mx,"workerIndex",{get(){return xx()}});Object.defineProperty(Mx,"workerCount",{get(){return Gx()}});var kx={[Ux](e,t){Oie(t)},[vx](e,t){bie(t,e)}};function AA(e,t={}){let r=process.constrainedMemory?.()||wx();r=Math.min(r,wx(),2e4*Cx);let n=Px.get(Dl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Cx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of Tn){let _=new eie;_.existingPort=u,i.push(_),o.push(_.port2)}sie(e)||(e+=".js");let c=new Zse(nie(e)?e:Lx(rie,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:qx=t.threadCount,name:t.name,restartNumber:Pi.exports.restartNumber,ticketKeys:Fx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Hx,port:u,threadId:c.threadId},[u]);return VE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>AA(e,t),c.on("error",u=>{Ks.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Mi.splice(Mi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<lie?(t.unexpectedRestarts=c.unexpectedRestarts+1,AA(e,t)):Ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{kx[u.type]?.(u,c)}),Mi.push(c),Iie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(AA,"startWorker");var hie=[Dl.THREAD_TYPES.HTTP];async function wA(e=null,t=Math.max(qx>3,1),r=!0){if(yA){if(r){let{loadRootComponents:o}=cA();await o()}Pi.exports.restartNumber++,t<1&&(t=t*Mi.length);let n=[],s=[];for(let o of Mi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Pi.exports.restartNumber,type:Dl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=hie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),NA*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 E=a(f=>{f.type===uie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ks.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",E))},"startListener");Ks.trace("Waiting for worker to start",_.threadId),_.on("message",E)});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}=Af();r&&(e==="http"||!e)&&Px.get(Dl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Es.postMessage({type:_ie,workerType:e})}a(wA,"restartWorkers");function mie(e,t){kx[e]=t}a(mie,"setChildListenerByType");function pie(e){return wA(e,1/0,!1)}a(pie,"shutdownWorkers");var Vx=[];function Sie(e){Vx.push(e)}a(Sie,"onMessageFromWorkers");var OA=new Map;function $x(e,t){let r=OA.get(e);r||OA.set(e,r=[]),r.push(t)}a($x,"onMessageByType");var Tie=10;async function gie(e){let t=0;for(let r of Tn)try{r.postMessage(e),t++>Tie&&(t=0,await new Promise(setImmediate))}catch(n){Ks.error("Unable to send message to worker",n)}}a(gie,"broadcast");var kE=new Map,Rie=1;function Aie(e){return new Promise(t=>{let r=0;for(let n of Tn)try{let s=Rie++,i=a(()=>{kE.delete(s),--r===0&&t(),n!==Es&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,kE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of kE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ks.error("Unable to send message to worker",s)}r===0&&t()})}a(Aie,"broadcastWithAcknowledgement");function Oie(e){e.postMessage({type:Bx,workers:Yx()})}a(Oie,"sendThreadInfo");function Yx(){let e=Date.now();return Mi.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(Yx,"getChildWorkerInfo");function bie(e,t){e.resources=t,e.resources.updated=Date.now()}a(bie,"recordResourceReport");var bA;function yie(e){bA=e}a(yie,"setMonitorListener");var Nie=1e3,Dx=!1;function Iie(){Dx||(Dx=!0,setInterval(()=>{for(let e of Mi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}bA&&bA()},Nie).unref())}a(Iie,"startMonitoring");var wie=1e3;if(Es){VE(Es);for(let e=0,t=Ys.addPorts.length;e<t;e++){let r=Ys.addPorts[e];r.threadId=Ys.addThreadIds[e],VE(r)}setInterval(()=>{let e=process.memoryUsage();Es.postMessage({type:vx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},wie).unref(),RA=a(()=>new Promise((e,t)=>{Es.on("message",r),Es.postMessage({type:Ux});function r(n){n.type===Bx&&(Es.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else RA=Yx;Pi.exports.getThreadInfo=RA;function VE(e,t){Tn.push(e),e.on("message",r=>{if(r.type===Hx)r.port.threadId=r.threadId,VE(r.port);else if(r.type===die){let n=kE.get(r.id);n&&n()}else{for(let s of Vx)s(r,e);let n=OA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ks.error(i)}}}).on("close",()=>{Tn.splice(Tn.indexOf(e),1)}).on("exit",()=>{Tn.splice(Tn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(VE,"addPort");if(yA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await oie(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Lx(s,o.name));try{for await(let{filename:o}of iie(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await wA(),console.log("Reloaded HarperDB components, changed files:",Array.from(r)),r.clear()},100)}catch(o){console.warn("Error trying to watch component directory",s,o)}},"watch_dir");Pi.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else Es.on("message",async e=>{let{type:t}=e;t===Dl.ITC_EVENT_TYPES.SHUTDOWN&&(Pi.exports.restartNumber=e.restartNumber,Es.unref(),setTimeout(()=>{Ks.warn("Thread did not voluntarily terminate",tie),process.exit(0)},NA).unref())})});var LC={};qe(LC,{AUDIT_STORE_OPTIONS:()=>pf,createAuditEntry:()=>m_,openAuditStore:()=>WE,readAuditEntry:()=>Ut,setAuditRetention:()=>Die,transactionKeyEncoder:()=>eG});function WE(e){let t=e.auditStore=e.openDB(jx.AUDIT_STORE_NAME,pf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=$E){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()-CA})){if((_[0]&15)===MA){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Cie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,CA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,KE.getWorkerIndex)()===(0,KE.getWorkerCount)()-1&&s($E),t}function Die(e,t=$E){CA=e,$E=t}function m_(e,t,r,n,s,i,o){let c=tG[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?ec.setFloat64(0,n):gn.set(hm),u=9),E(0),E(t),d(r),ec.setFloat64(u,e),u+=8,s?d(s):gn[u++]=0,gn[n?8:0]=c;let l=gn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(f){let h=u;u+=1,u=(0,tc.writeKey)(f,gn,u);let p=u-h-1;p>127?p>16383?(UA.error("Key or username was too large for audit entry",f),u=h+1,gn[h]=0):(gn.copyWithin(h+2,h+1,u),ec.setUint16(h,p|32768),u++):gn[h]=p}function E(f){f<128?gn[u++]=f:f<16384?(ec.setUint16(u,f|32768),u+=2):f<1056964608?(ec.setUint32(u,f|3221225472),u+=4):(gn[u]=255,ec.setUint32(u+1,f),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new PA(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:tG[n&7],tableId:i,get recordId(){return Jx(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Jx(e,l,d):void 0},getValue(E,f,h){if(n&DA||n&LA&&!f)return E.decoder.decode(e.subarray(t.position));if(n&LA&&h)return vA(E.getEntry(this.recordId),h,E)}}}catch(t){return UA.error("Reading audit entry error",t,e),{}}}function Jx(e,t,r){let n=e.subarray(t,r);return(0,tc.readKey)(n,0,r-t)}var tc,YE,jx,Xx,KE,Zx,UA,gn,ec,eG,pf,CA,Cie,$E,DA,LA,Kx,MA,Wx,Qx,zx,tG,PA,ti=Ae(()=>{tc=require("ordered-binary"),YE=B(Z()),jx=B(_t()),Xx=B(P()),KE=B(Je()),Zx=B(J());Cc();UA=B($());QE();(0,YE.initSync)();gn=Buffer.alloc(1024),ec=new DataView(gn.buffer,gn.byteOffset,1024),eG={writeKey(e,t,r){return e===wc?(t.set(wc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,tc.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,tc.readKey)(e,t,r)}},pf={encoding:"binary",keyEncoder:eG},CA=(0,Zx.convertToMS)((0,YE.get)(Xx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Cie=1e3,$E=1e4;a(WE,"openAuditStore");a(Die,"setAuditRetention");DA=16,LA=32,Kx=1,MA=2,Wx=3,Qx=4,zx=5,tG={put:Kx|DA,[Kx]:"put",delete:MA,[MA]:"delete",message:Wx|DA,[Wx]:"message",invalidate:Qx,[Qx]:"invalidate",patch:zx|LA,[zx]:"patch"};a(m_,"createAuditEntry");a(Ut,"readAuditEntry");PA=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(Jx,"readKeySafely")});var BA={};qe(BA,{add:()=>zE,applyReverse:()=>rG,getRecordAtTime:()=>vA,rebuildUpdateBefore:()=>JE});function zE(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function JE(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,zE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function rG(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=Lie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=nG}}function vA(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":rG(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===nG&&(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 Lie,nG,QE=Ae(()=>{ti();a(zE,"add");zE.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};Lie={add:zE};a(JE,"rebuildUpdateBefore");a(rG,"applyReverse");nG={};a(vA,"getRecordAtTime")});function Zr(e){return e[yt]||(e[yt]=Object.create(null))}function th(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[Ne])},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 Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(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 Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="number"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a number, attempt to assign ${d}`);Zr(this)[c]=l},"set");break;case"Int":u=a(function(l){let d=l?.__op__?l.value:l;if(!(d>>0===d||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Long":u=a(function(l){let d=l?.__op__?l.value:l;if(!(Math.round(d)===l&&Math.abs(d)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="bigint"||l==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be a number, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Zr(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 Rn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Zr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be an object, attempt to assign ${l}`);Zr(this)[c]=l},"set")}_={get(){let l=this[yt];if(l&&c in l){let E=l[c];if(E?.__op__){let f=this[fe]?.[c];return E.update(f)}return E}let d=this[fe]?.[c];if(d&&typeof d=="object"){let E=iG(d,o);if(E)return l||(l=this[yt]=Object.create(null)),l[c]=E}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[yt];return u?.[o]!==void 0?u[o]:this[fe]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Rn.ClientError("Can not add a property to a sealed table schema");Zr(this)[o]=c}),i("deleteProperty",function(o){Zr(this)[o]=void 0}),i("toJSON",function(){let o=this[yt],c;for(let _ in o){c||(c=Object.assign({},this[fe]));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[fe])),Object.assign(c,this)),c||this[fe]}),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 iG(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[fe])throw new Error("Can not track an already tracked object, check for circular references");this[fe]=s}},th(r,t)),new r(e)):new jE(e);case Array:let n=new ZE(e.length);n[fe]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=iG(o,t?.elements)),n[s]=o}return n;default:return e}}function fd(e){let t=e[yt],r;for(let s in t){r||(r=Object.assign({},e[fe]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=fd(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[fe])),Object.assign(r,e)),r||e[fe]}function Po(e,t=e[yt]){let r;if(sG.call(e,fe)&&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=Po(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[fe]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=BA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Po(s);r[n]=s}return r?Object.freeze(r):sG.call(e,fe)?e[fe]:e}function XE(e){let t=e[fe];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Mo]||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?.[fe]===s){if(XE(i))return!0}else return!0}}else{let r=e[yt];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[fe]===i){if(XE(s))return!0}else return!0}else return!0}}return!1}var Rn,yt,jE,sG,Mo,ZE,eh,Ed=Ae(()=>{Nn();Rn=B(ne());QE();yt=Symbol("own-data");a(Zr,"getChanges");a(th,"assignTrackedAccessors");a(iG,"trackObject");jE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[fe])throw new Error("Can not track an already tracked object, check for circular references");this[fe]=t}};th(jE,{});a(fd,"collapseData");sG=Object.prototype.hasOwnProperty;a(Po,"deepFreeze");a(XE,"hasChanges");Mo=Symbol.for("has-array-changes"),ZE=class extends Array{static{a(this,"TrackedArray")}[Mo];constructor(t){super(t)}splice(...t){return this[Mo]=!0,super.splice(...t)}push(...t){return this[Mo]=!0,super.push(...t)}pop(){return this[Mo]=!0,super.pop()}unshift(...t){return this[Mo]=!0,super.unshift(...t)}shift(){return this[Mo]=!0,super.shift()}};ZE.prototype.constructor=Array;eh=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var qp={};qe(qp,{CONTEXT:()=>Ne,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>Fn,RECORD_PROPERTY:()=>fe,Resource:()=>Vt,snake_case:()=>Pie,transformForSelect:()=>nh});function Pie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function oG(e,t){if(Ll=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Ll=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new xA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Ll=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function en(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[Ne]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[Ne]||i):l=i:(l=s,c=l[Le]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ne]||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 f of s){if(typeof f=="object"&&f)break;c.push(f)}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 f=c.indexOf("?");if(f>-1){let p=this.parseQuery(c.slice(f+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,f)}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 f=this.getResource(c,o,d);return f.then?f.then(E):E(f)}else return Xe(o,()=>{let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)},d);function E(f){if(o.authorize){o.authorize=!1;let h=t.type==="read"?f.allowRead(o.user,u,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,l,o):f.allowUpdate(o.user,l,o):t.type==="create"?f.allowCreate(o.user,l,o):f.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new rh(o.user);return typeof l?.then=="function"?l.then(S=>e(f,u,o,S)):e(f,u,o,l)});if(!h)throw new rh(o.user)}return typeof l?.then=="function"?l.then(h=>e(f,u,o,h)):e(f,u,o,l)}a(E,"authorizeActionOnResource")}}function tn(e,t){let r=new uG.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function HA(e,t,r){let n=e[fe];if(n){let s=e[yt];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 nh(e,t){let r=t?.propertyResolvers,n=t[Ne],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):HA(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(HA(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(E=>E&&typeof E=="object"?c(E):E);let _={},l=i(HA(u,r,n)),d;for(let E of e){let f=l(E);f===void 0&&o&&(f=null),f?.then?(d||(d=[]),d.push(f.then(h=>_[E.name||E]=h))):_[E.name||E]=f}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]=nh(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var aG,cG,uG,Ne,Le,Fn,fe,Mie,Vt,rh,Ll,xA,Nn=Ae(()=>{aG=require("crypto");Ac();cG=require("../index"),uG=B(ne());Ed();ro();jf();Ne=Symbol.for("context"),Le=Symbol.for("primary-key"),Fn=Symbol("is-collection"),fe=Symbol("stored-record"),Mie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Vt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let n=r?.[Ne];this[Ne]=n!==void 0?n:r||null}static get=en(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 _=nh(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=en(function(t,r,n,s){if(Array.isArray(s)&&t[Fn]){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):tn(t,"put")},{hasContent:!0,type:"update"});static patch=en(function(t,r,n,s){return t.patch?t.patch(s,r):tn(t,"patch")},{hasContent:!0,type:"update"});static delete=en(function(t,r,n,s){return t.delete?t.delete(r):tn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,aG.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),n||(n={}),Xe(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):tn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=en(function(t,r,n,s){return t.invalidate?t.invalidate(r):tn(t,"delete")},{hasContent:!1,type:"update"});static post=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=en(function(t,r,n,s){return t.connect?t.connect(s,r):tn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=en(function(t,r,n,s){return t.subscribe?t.subscribe(r):tn(t,"subscribe")},{type:"read"});static publish=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.publish?t.publish(s,r):tn(t,"publish")},{hasContent:!0,type:"create"});static search=en(function(t,r,n,s){let i=t.search?t.search(r):tn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=nh(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=en(function(t,r,n,s){return t.search?t.search(s,r):tn(t,"search")},{hasContent:!0,type:"read"});static copy=en(function(t,r,n,s){return t.copy?t.copy(s,r):tn(t,"copy")},{type:"create"});static move=en(function(t,r,n,s){return t.move?t.move(s,r):tn(t,"move")},{type:"delete"});post(t){if(this[Fn])return this.constructor.create(this[Le],t,this[Ne]);tn(this,"post")}static isCollection(t){return t?.[Fn]}static coerceId(t){return t}static parseQuery(t){return Jf(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&&Mie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:oG(t,this),isCollection:Ll}}let i=oG(t,this);return Ll?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Ne],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(_=>_[Le]===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[Le],E=_.get(d);E?E.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[Fn]=!0),s}subscribe(t){return new yn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new yn}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[Ne]}};Vt.prototype[Ne]=null;(0,cG._assignPackageExport)("Resource",Vt);a(Pie,"snake_case");rh=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(oG,"pathToId");xA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(en,"transactional");a(tn,"missingMethod");a(HA,"selectFromObject");a(nh,"transformForSelect")});function dG(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=_G,Uie(e.primaryStore,e.auditStore)):(c=lG,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{fG(lG[i])})));let u=c[i]||(c[i]=[]);u.auditStore=e.auditStore,u.lastTxnTime==null&&(u.lastTxnTime=Date.now());let _=u[o];_||(_=u[o]=new Map,_.envs=u,_.tableId=o,_.store=e.primaryStore),t=Na(t);let l=new qA(r);l.startTime=n;let d=_.get(t);return d?d.push(l):(_.set(t,d=[l]),d.tables=_,d.key=t),l.subscriptions=d,l}function fG(e){if(!e)return;let t=e.auditStore;try{t.resetReadTxn()}catch(n){throw n.message+=" in "+path,n}let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Ut(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,u,_=Na(i.recordId),l=0;do{let d=o.get(_);if(d){for(let f of d)if(!(l>0&&!(f.includeDescendants&&!(f.onlyChildren&&l>1)))){if(f.startTime>=n){(0,GA.info)("omitting",c,f.startTime,n);continue}try{let h;f.supportsTransactions&&f.txnInProgress!==i.version&&(h=!0,f.txnInProgress||(r?r.push(f):r=[f]),f.txnInProgress=i.version),f.listener(c,i,n,h)}catch(h){console.error(h),(0,GA.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,l++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Uie(e,t){let r=t||e,n=r.env;if(!n.hasAfterCommitListener){n.hasAfterCommitListener=!0;let s=n.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u=_G[s];if(!u)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),u.txnTime=r.threadLocalWrites[0]||Date.now(),fG(u),r.threadLocalWrites[0]=u.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var GA,lG,_G,qA,EG=Ae(()=>{GA=B($());Ac();Wu();ti();lG=Object.create(null),_G=Object.create(null);a(dG,"addSubscription");qA=class extends yn{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(fG,"notifyFromTransactionData");a(Uie,"listenToCommits")});var TR={};qe(TR,{coerceType:()=>sh,makeTable:()=>ah,setServerUtilities:()=>Vie,updateResource:()=>ih});function ah(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=Sm(i,n,u),A=0,R,C,x={},v=Promise.resolve(),k,M,Q;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(M=K),K.expiresAt&&(Q=K),K.isPrimaryKey&&(x=K);let j,z=[],ae=[],ue=1,de=2,xe={},Ee={},Pt=864e5,zl,Jl,zs,aO=!1,bh,yh,Sq=i.getRange({start:!1,end:!1}).constructor,Tq=10,gq=6;h&&lO();class Qe extends Vt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=k;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,O){O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),C=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(L=>{let N=this.sources.slice(0,-1);if(N=N.filter(U=>U[L]&&(!U[L].reliesOnPrototype||U.prototype[L])),N.length>0)if(N.length===1){let U=N[0];return(F,D,H)=>{if(F?.source!==U)return U[L](D,H,F)}}else return(U,F,D)=>{let H=[];for(let G of N){if(U?.source===G)break;H.push(G[L](F,D,U))}return Promise.all(H)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],b=a(L=>{if(y[L]&&(!y[L].reliesOnPrototype||y.prototype[L]))return(N,U,F)=>{if(!N?.source)return y[L](U,F,N)}},"getApplyToCanonicalSource");return xe={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},Ee={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let L=!1,N=a(async(U,F)=>{let D=U.value,H=U.table?it[c][U.table]:Qe;if(c===Vn.SYSTEM_SCHEMA_NAME&&(U.table===Vn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===Vn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!0),U.id===void 0&&(U.id=D[H.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let G=await H.getResource(U.id,F,rc);switch(U.type){case"put":return G._writeUpdate(D,!0,rc);case"patch":return G._writeUpdate(D,!1,rc);case"delete":return G._writeDelete(rc);case"publish":return G._writePublish(D,rc);case"invalidate":return G.invalidate(rc);default:rt.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let F=m.subscribeOnThisThread?m.subscribeOnThisThread((0,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,D=U&&F&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let H;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){rt.error("Bad subscription event",G);continue}if(G.source=m,H)if(G.beginTxn)H.resolve();else{N(G,H);continue}if(G.type==="end_txn")continue;let Se=Xe(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ce){throw ce.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ce}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ce of G.attributes)te.find(Ge=>Ge.name===ce.name)||(te.push(ce),Pe=!0);Pe&&(dt({table:s,database:c,attributes:te,origin:"cluster"}),xl.signalSchemaChange(new Gl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(H=G,N(G,G),new Promise(te=>{H.resolve=te})):N(G,G)});L&&(await Se,xl.signalUserChange(new Gl.UserEventMsg(process.pid))),G.onCommit&&(Se?.then?Se.then(G.onCommit):G.onCommit())}catch(se){rt.error("error in subscription handler",se)}}}catch(U){rt.error(U)}})(),this}static getResource(m,O,w){let y=super.getResource(m,O,w);if(m!=null){ac(m);try{if(y.hasOwnProperty(fe))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!w?.async||i.cache?.get(m),L=On(O),N=L.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Nh(m,O,{transaction:N},b,U=>{if(U?ih(y,U):y[fe]=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new rn.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let F=Ih(m,U,O,y);if(F)return L?.disregardReadTxn(),y[FA]=!0,VA(F,D=>(ih(y,D),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return y}ensureLoaded(){let m=Ih(this[Le],this[Lr],this[Ne]);if(m)return this[FA]=!0,VA(m,O=>{this[Lr]=O,this[fe]=O.value,this[Bl]=O.version})}static setTTLExpiration(m){if(typeof m=="number")E=m*1e3,f||(f=0);else if(m&&typeof m=="object")E=m.expiration*1e3,f=(m.eviction||0)*1e3,Pt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(E<0)throw new Error("Expiration can not be negative");Pt=Pt||(E+f)/4,Ch()}static enableAuditing(m=!0){h=m,m&&lO(),Qe.audit=m}static coerceId(m){return m===""?null:sh(m,x)}static async dropTable(){if(delete it[c][s],c===o){for(let m of S)l.remove(Qe.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Qe.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));xl.signalSchemaChange(new Gl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Fn])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let O=Qe.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Ne]?.returnNonexistent)return this}allowRead(m,O){let w=Xl(m);if(w?.read){if(w.isSuperUser)return!0;let y=w.attribute_permissions,b=O?.select;if(y?.length>0||aO&&b){if(O||(O={}),b){let L=y?.length>0&&kA(y,"read");O.select=b.map(N=>{let U=N.name||N;if(!L||L[U]){let F=zs[U]?.definition?.tableClass;if(F){if(N.name||(N={name:N}),!F.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else O.select=y.filter(L=>L.read&&!zs[L.attribute_name]).map(L=>L.attribute_name);return O}else return!0}}allowUpdate(m,O){let w=Xl(m);if(w?.update){let y=w.attribute_permissions;if(y?.length>0){let b=kA(y,"update");for(let L in O)if(!b[L])return!1;for(let L of y){let N=L.attribute_name;!L.update&&!(N in O)&&(O[N]=this.getProperty(N))}}return!0}}allowCreate(m,O){if(this[Fn]){let w=Xl(m);if(w?.insert){let y=w.attribute_permissions;if(y?.length>0){let b=kA(y,"insert");for(let L in O)if(!b[L])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Xl(m)?.delete}update(m,O){if(!On(this[Ne]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[fe]={},this[yt]=m):(y=this[yt],y&&(m=Object.assign(y,m)),this[yt]=y=m)),this._writeUpdate(this[yt],O),this}addTo(m,O){if(typeof O=="number"||typeof O=="bigint")this[Ml]===mG?this.set(m,(+this.getProperty(m)||0)+O):(this[Ml]||this.update(),this.set(m,new eh(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Lr]}invalidate(m){let O=this[Ne],w=this[Le];ac(w),On(this[Ne]).addWrite({key:w,store:i,invalidated:!0,entry:this[Lr],nodeName:this[Ne]?.nodeName,before:xe.invalidate?.bind(this,O,w),beforeIntermediate:Ee.invalidate?.bind(this,O,w),commit:(b,L)=>{if(L?.version>b)return;let N=null;for(let U in r)N||(N={}),N[U]=this.getProperty(U);T(w,N,this[Lr],b,Pl,h,this[Ne],0,"invalidate")}})}static evict(m,O,w){let y=this.Source,b;if(!((C||h)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==w))){if(C){if(i.hasLock(m,b.version))return;let L;for(let N in r)L||(L={}),L[N]=O[N];if(L)return T(m,L,b,w,Ul,null,null,0,null,!0)}return i.ifVersion(m,w,()=>{jl(m,O,null)}),h?T(m,null,b,w,Ul,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=s,m.schema||=c,AG.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,w){let y=this[Ne],b=On(y),L=this[Le];ac(L);let N=this[Lr];this[Ml]=O?mG:qie;let U={key:L,store:i,entry:N,nodeName:y?.nodeName,validate:F=>{m||(m=this[yt]),O||m&&XE(this[yt]===m?this:m)?y?.source||(b.checkOverloaded(),this.validate(m,!O),M&&(m[M.name]=M.type==="Date"?new Date(F):M.type==="String"?new Date(F).toISOString():F),O&&(t&&m[t]!==L&&(m[t]=L),k&&(N?.value?m[k.name]=N?.value[k.name]:m[k.name]=k.type==="Date"?new Date(F):k.type==="String"?new Date(F).toISOString():F),m=Po(m))):b.removeWrite(U)},before:O?xe.put?()=>xe.put(y,L,m):null:xe.patch?()=>xe.patch(y,L,m):xe.put?()=>xe.put(y,L,Po(this)):null,beforeIntermediate:O?Ee.put?()=>Ee.put(y,L,m):null:Ee.patch?()=>Ee.patch(y,L,m):Ee.put?()=>Ee.put(y,L,Po(this)):null,commit:(F,D,H)=>{if(H){if(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),this[Lr]=D,D?.value?.[fe])throw new Error("Can not assign a record to a record, check for circular references");O||(this[fe]=D?.value??null)}this[yt]=void 0,this[Bl]=F;let G=D?.value,se=m;if(this[Ml]=0,D?.version>=F)if(h){let ce=D.localTime,Ge=D.version;for(;se&&(ce>F||Ge>=F&&ce>0);){let re=u.get(ce);if(!re)break;let X=Ut(re);if(Ge=X.version,Ge>F){if(X.type==="patch"){let Te=X.getValue(i);se=JE(se,Te)}else if(X.type==="put"||X.type==="delete")return}else if(Ge===F)return;ce=X.previousLocalTime}}else{if(O)return;se=JE(se,G)}let Se;if(O?Se=se:(this[fe]=G,Se=O?se:Po(this,se)),this[fe]=Se,Se?.[fe])throw new Error("Can not assign a record to a record, check for circular references");let te;O||(te=m),jl(L,G,Se);let Pe=O?"put":"patch";T(L,Se,D,F,0,h,y,y.expiresAt||(E?E+Date.now():0),Pe,!1,te)}};b.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Fn]){for await(let O of this.search(m))(await Qe.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[fe]?this._writeDelete(m):!1}_writeDelete(m){let O=On(this[Ne]),w=this[Le];ac(w);let y=this[Ne];return O.addWrite({key:w,store:i,resource:this,nodeName:y?.nodeName,before:xe.delete?.bind(this,y,w),beforeIntermediate:Ee.delete?.bind(this,y,w),commit:(b,L,N)=>{let U=L?.value;N&&(y&&L?.version>(y.lastModified||0)&&(y.lastModified=L.version),ih(this,L)),!(L?.version>b)&&(jl(this[Le],U),rt.trace("Write delete entry",w,b),h||p?(T(w,null,this[Lr],b,0,h,this[Ne],0,"delete"),h||Ch()):i.remove(this[Le]))}}),!0}search(m){let O=this[Ne],w=On(O);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(y=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(y));let b,L={};function N(X,Te){let ve;switch(Te){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');ve=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Te)}let $n=ve&&{},Js;for(let Ye of X){if(Ye.conditions){Ye.conditions=N(Ye.conditions,Ye.operator);continue}let Ft=Ye[0]??Ye.attribute,on=Ft==null?x:Gs(S,Ft);if(on){if(ve){let Yn=xn(Ft),kt=$n[Yn];kt?(kt.push(Ye),Js=!0):$n[Yn]=[Ye]}(on.type||Yg[Ye.comparator])&&(Ye[1]===void 0?Ye.value=F(Ye.value,on):Ye[1]=F(Ye[1],on))}else if(Ft!=null)throw(0,rn.handleHDBError)(new Error,`${Ft} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(Js)for(let Ye in $n){let Ft=$n[Ye],on=Ft.length;if(on>1)for(let Yn=0;Yn<on;Yn++){let kt=Ft[Yn];if(kt.comparator==="ge"||kt.comparator==="greater_than_equal")for(let js=0;js<on;js++){let qo=Ft[js];(qo.comparator==="le"||qo.comparator==="less_than_equal")&&(kt.comparator="between",kt.value=[kt.value,qo.value],X.splice(X.indexOf(qo),1))}if(kt.comparator==="equals"||!kt.comparator){for(let js=0;js<on;js++)if(js!==Yn){let qo=Ft[js];X.splice(X.indexOf(qo),1)}break}}}return X}a(N,"prepareConditions");function U(X,Te){if(m.enforceExecutionOrder)return X;for(let ve of X)ve.conditions&&(ve.conditions=U(ve.conditions,ve.operator));return X.length>1&&Te!=="or"?(0,RG.sortBy)(X,zf(Qe)):X}a(U,"orderConditions");function F(X,Te){return Array.isArray(X)?X.map(ve=>sh(ve,Te)):sh(X,Te)}a(F,"coerceTypedValues");let D=m.operator;(y.length>0||D)&&(y=N(y,D));let H=typeof m.sort=="object"&&m.sort,G;if(H&&D!=="or"){let X=H.attribute;if(b=y.find(Te=>xn(Te.attribute)===xn(X)),!b){let Te=Gs(S,X);if(!Te)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);if(Te.indexed)b={attribute:X,comparator:"sort"},y.push(b);else if(y.length===0&&!m.allowFullScan)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!H.descending)}y=U(y,D),H&&(b&&y[0]===b?H.next&&(G={dbOrderedAttribute:H.attribute,attribute:H.next.attribute,descending:H.next.descending,next:H.next.next}):(b&&y.splice(y.indexOf(b),1),G=H));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:D,postOrdering:G,selectApplied:!!se};let Se=w.useReadTxn(),te=Kg(y,D,Qe,Se,m,O,(X,Te)=>cO(X,se,O,Se,Te),L),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ce=Qe.transformEntryForSelect(se,O,Se,L,Pe,!0),Ge=Qe.transformToOrderedSelect(te,se,G,Se,O,ce);function re(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(re,"applyOffset"),G&&(Ge=re(Ge)),Ge.onDone=()=>{Ge.onDone=null,w.doneReadTxn()},Ge.selectApplied=!0,Ge.getColumns=()=>{if(se){let X=[];for(let Te of se)Te==="*"?X.push(...S.map(ve=>ve.name)):X.push(Te.name||Te);return X}return S.map(X=>X.name)},Ge}static transformToOrderedSelect(m,O,w,y,b,L){let N=new Sq;if(w){m=cO(m,O,y,b,null);let U;N.iterate=function(){let D,H=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=w.dbOrderedAttribute,Se,te,Pe=!0;function ce(re){let X=re.next&&ce(re.next),Te=re.descending;return(ve,$n)=>{let Js=wh(ve,re.attribute,y),Ye=wh($n,re.attribute,y),Ft=Te?(0,Bo.compareKeys)(Ye,Js):(0,Bo.compareKeys)(Js,Ye);return Ft===0?X?.(ve,$n)||0:Ft}}a(ce,"createComparator");let Ge=ce(w);return{async next(){let re;if(D)if(re=D.next(),re.done){if(G)return N.onDone&&N.onDone(),re}else return{value:await L.call(this,re.value)};U=[],Se&&U.push(Se);do if(re=await H.next(),re.done){if(G=!0,U.length)break;return N.onDone&&N.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),se){let Te=wh(X,se,y);if(Pe)Pe=!1,te=Te;else if(Te!==te){te=Te,Se=X;break}}U.push(X)}while(!0);return w.isGrouped,U.sort(Ge),D=U[Symbol.iterator](),re=D.next(),re.done?(N.onDone&&N.onDone(),re):{value:await L.call(this,re.value)}},return(){N.onDone&&N.onDone(),H.return()},throw(){N.onDone&&N.onDone(),H.throw()}}};let F=a(D=>{if(typeof O=="object"&&Array.isArray(D.attribute))for(let H=0;H<O.length;H++){let G=O[H],se;if(G.name===D.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=D.attribute.slice(1),se.descending=D.descending}else G===D.attribute[0]&&(O[H]=se={name:G,sort:{attribute:D.attribute.slice(1),descending:D.descending}})}D.next&&F(D.next)},"applySortingOnSelect");F(w)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(L);return N}static transformEntryForSelect(m,O,w,y,b,L){if(m&&(m===t||m?.length===1&&m[0]===t)){let D=a(H=>(O?.transaction?.stale&&(O.transaction.stale=!1),H?.key??H),"transform");return m===t?D:m.asArray?H=>[D(H)]:H=>({[t]:D(H)})}let N;b&&C&&!m?.every(D=>{let H;return typeof D=="object"?H=D.name:H=D,r[H]||H===t})&&(N=!0);let U,F=a(function(D){let H;if(O?.transaction?.stale&&(O.transaction.stale=!1),D!=null){if(bh=D,H=D.value||D.deref?.(),!H&&(D.key===void 0||D.deref)){if(D=Nh(D.key??D,O,{transaction:w,lazy:m?.length<4},this.isSync,G=>G),D?.then)return D.then(F.bind(this));H=D?.value}if(N&&(D.metadataFlags&(Pl|Ul)||D.expiresAt&&D.expiresAt<Date.now())){let G=Ih(D.key??D,D,O);if(G?.then)return G.then(F)}}if(H==null)return L?Uo.SKIP:H;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((te,Pe)=>{let ce;typeof te=="object"?ce=te.name:ce=te;let Ge=zs?.[ce],re;if(Ge){let X=y?.[ce];if(X)if(X.hasMappings){let ve=Ge.from?H[Ge.from]:xn(D.key);re=X.get(ve),re||(re=[])}else re=X.fromRecord?.(H);else re=Ge(H,O,D);let Te=a(ve=>{if(ve&&typeof ve=="object"){let $n=Ge.definition?.tableClass||Qe;U||(U={});let Js=U[ce]||(U[ce]=$n.transformEntryForSelect(ce===te?null:te.select||(Array.isArray(te)?te:null),O,w,X,b));if(Array.isArray(ve)){let Ye=[],Ft=$n.transformToOrderedSelect(ve,te.select,typeof te.sort=="object"&&te.sort,O,w,Js)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),on=a(kt=>{for(;!kt.done;){if(kt?.then)return kt.then(on);Ye.push(kt.value),kt=Ft.next()}Pe(Ye,ce)},"nextValue"),Yn=on(Ft.next());Yn&&(G||(G=[]),G.push(Yn));return}else if(ve=Js.call(this,ve),ve?.then){G||(G=[]),G.push(ve.then(Ye=>Pe(Ye,ce)));return}}Pe(ve,ce)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(Te))):Te(re);return}else re=H[ce],re&&typeof re=="object"&&ce!==te&&(re=Qe.transformEntryForSelect(te.select||te,O,w,null)({value:re}));Pe(re,ce)},"selectAttribute"),Se;if(typeof m=="string")se(m,te=>{Se=te});else if(Array.isArray(m))if(m.asArray)Se=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=H:se(te,ce=>Se[Pe]=ce)});else{Se={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ce in H)Se[ce]=H[ce];else se(Pe,(ce,Ge)=>{ce===void 0&&te&&(ce=null),Se[Ge]=ce})}else throw new rn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>Se):Se}return H},"transform");return F}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||dt({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let O=!m.rawEvents,w=dG(Qe,this[Le]??null,function(N,U,F,D){try{let H=U.getValue?.(i,O);if(!H&&U.type==="patch"&&O){let G=i.getEntry(N);G?.version===U.version?H=G.value:H=U.getValue?.(i,!0,F),U.type="put"}this.send({id:N,timestamp:F,value:H,version:U.version,type:U.type,beginTxn:D})}catch(H){rt.error(H)}},m.startTime||0,m);this[Fn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.supportsTransactions&&(w.supportsTransactions=!0);let y=this[Le],b=m.previousCount;b>1e3&&(b=1e3);let L=m.startTime;if(this[Fn]){if(L){if(b)throw new rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:L,exclusiveStart:!0})){let F=Ut(U);if(F.tableId!==n)continue;let D=F.recordId;if(y==null||TG(y,D)){let H=F.getValue(i,O,N);w.send({id:D,timestamp:N,value:H,version:F.version,type:F.type})}w.startTime=N}}else if(b){let N=[];for(let{key:U,value:F}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Ut(F);if(D.tableId!==n)continue;let H=D.recordId;if(y==null||TG(y,H)){let G=D.getValue(i,O,U);if(N.push({id:H,timestamp:U,value:G,version:D.version,type:D.type}),--b<=0)break}}catch(D){rt.error("Error getting history entry",U,D)}for(let U=N.length;U>0;)w.send(N[--U]);N[0]&&(w.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:F,localTime:D}of i.getRange({start:y??!1,end:y==null?void 0:[y,Bo.MAXIMUM_KEY],versions:!0}))U&&w.send({id:N,timestamp:D,value:U,version:F,type:"put"})}else{b&&!L&&(L=0);let N=this[Lr]?.localTime;if(N===pm&&(i.cache?.delete(y),this[Lr]=i.getEntry(y),rt.trace("re-retrieved record",N,this[Lr]?.localTime),N=this[Lr]?.localTime),rt.trace("Subscription from",L,"from",y,N),L<N){let U=[],F=N;do{let D=u.get(F);if(D){m.omitCurrent=!0;let H=Ut(D),G=H.getValue(i,O,F);O&&(H.type="put"),U.push({id:y,value:G,timestamp:F,...H}),F=H.previousLocalTime}else break;b&&b--}while(F>L&&b!==0);for(let D=U.length;D>0;)w.send(U[--D]);w.startTime=N}!m.omitCurrent&&this.doesExist()&&w.send({id:y,timestamp:N,value:this,version:this[Bl],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[fe]||this[Ml])}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let w=On(this[Ne]),y=this[Le]||null;ac(y);let b=this[Ne];w.addWrite({key:y,store:i,entry:this[Lr],nodeName:b?.nodeName,validate:()=>{b?.source||(w.checkOverloaded(),this.validate(m))},before:xe.publish?.bind(this,b,y,m),beforeIntermediate:Ee.publish?.bind(this,b,y,m),commit:(L,N,U)=>{N===void 0&&p&&!h&&Ch(),T(y,N?.value??null,N,N?.version||L,0,!0,b,N?.expiresAt,"message",!1,m)}})}validate(m,O){let w,y=a((b,L,N)=>{if(L.type&&b!=null)if(O&&b.__op__&&(b=b.value),L.properties){typeof b!="object"&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be an object${L.type?" ("+L.type+")":""}`);let U=L.properties;for(let F=0,D=U.length;F<D;F++){let H=U[F],G=y(b[H.name],H,N+"."+H.name);G&&(b[H.name]=G)}if(L.sealed&&b!=null&&typeof b=="object")for(let F in b)U.find(D=>D.name===F)||(w||(w=[])).push(`Property ${F} is not allowed within object in property ${N}`)}else switch(L.type){case"Int":(typeof b!="number"||b>>0!==b)&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(U=>typeof U=="string")||(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a string`);break;case"Boolean":typeof b!="boolean"&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a bigint`)}break;case"Bytes":b instanceof Uint8Array||(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(b)){if(L.elements)for(let U=0,F=b.length;U<F;U++){let D=b[U],H=y(D,L.elements,N+"[*]");H&&(b[U]=H)}}else(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a Buffer or Uint8Array`);break}L.nullable===!1&&b==null&&(w||(w=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let b=0,L=S.length;b<L;b++){let N=S[b];if(!N.relationship&&(!O||N.name in m)){let U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}if(d)for(let b in m)S.find(L=>L.name===b)||(w||(w=[])).push(`Property ${b} is not allowed`);if(w)throw new rn.ClientError(w.join(". "))}getUpdatedTime(){return this[Bl]}wasLoadedFromSource(){return C?!!this[FA]:void 0}static async addAttributes(m){let O=S.slice(0);for(let w of m){if(!w.name)throw new rn.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new rn.ClientError("Attribute names cannot include backticks or forward slashes");O.push(w)}return dt({table:s,database:c,schemaDefined:_,attributes:O}),Qe.indexingOperation}static async removeAttributes(m){let O=S.filter(w=>!m.includes(w.name));return dt({table:s,database:c,schemaDefined:_,attributes:O}),Qe.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,w=5e3,y=1e3,b;O>w&&!m?.exactCount&&(b=y);let L=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:b}))N!=null&&L++;if(b){let N=L;L=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Pe!=null&&L++;let U=b*2,F=(L+N)/U,D=Math.pow((L-N+1)/b/2,2)+F*(1-F)/U,H=Math.max(Math.sqrt(D)*O,1),G=Math.round(F*O),se=Math.max(G-1.96*H,0),Se=Math.min(G+1.96*H,O),te=Math.pow(10,Math.round(Math.log10(H)));return te>G&&(te=te/10),L=Math.round(G/te)*te,{recordCount:L,estimatedRange:[Math.round(se),Math.round(Se)]}}return{recordCount:L}}static updatedAttributes(){zs=this.propertyResolvers={$id:(m,O,w)=>({value:w.key}),$updatedtime:(m,O,w)=>w.version,$record:(m,O,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),aO=!0,O.to)m.elements?.definition?(zs[m.name]=m.resolve=(w,y,b)=>{let L=w[O.from?O.from:t],N=m.elements.definition.tableClass;return b?Ha({attribute:O.to,value:L},On(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:O.to,value:L}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.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(O.from){let w=m.definition||m.elements?.definition;w?(zs[m.name]=m.resolve=(y,b,L)=>{let N=y[O.from];if(N!==void 0){if(m.elements){let U,F=N.map(D=>{let H=L?w.tableClass.primaryStore.getEntry(D,{transaction:On(b).getReadTxn()}):w.tableClass.get(D,b);return H?.then&&(U=!0),H});return O.filterMissing?U?Promise.all(F).then(D=>D.filter(gG)):F.filter(gG):U?Promise.all(F):F}return L?w.tableClass.primaryStore.getEntry(N,{transaction:On(b).getReadTxn()}):w.tableClass.get(N,b)}},m.set=(y,b)=>{if(Array.isArray(b)){let L=b.map(N=>N[Le]||N[w.tableClass.primaryKey]);y[O.from]=L}else{let L=b[Le]||b[w.tableClass.primaryKey];y[O.from]=L}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.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`)}th(this,this)}static async deleteHistory(m=0){let O;for(let{key:w,value:y}of u.getRange({start:0,end:m}))await vl(),Ut(y).tableId===n&&(O=u.remove(w));await O}static async*getHistory(m=0,O=1/0){for(let{key:w,value:y}of u.getRange({start:m,end:O})){await vl();let b=Ut(y);b.tableId===n&&(yield{id:b.recordId,localTime:w,version:b.version,type:b.type,value:b.getValue(i,!0,w),user:b.user})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return O;let y=w.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await vl();let L=u.get(y);if(L){let N=Ut(L);O.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){j?.remove()}}Qe.updatedAttributes();let Rq=Qe.prototype;return Rq[Gie]=!0,E&&Qe.setTTLExpiration(E/1e3),Q&&Aq(),Qe;function jl(K,m,O){let w;for(let y in r){let b=r[y],L=b.isIndexing,N=O?.[y],U=m?.[y];if(N===U&&!L)continue;w=!0;let F=b.indexNulls,D=(0,Hl.getIndexedValues)(N,F),H=(0,Hl.getIndexedValues)(U,F);if(H?.length>0){let G=new Set(H);if(D=D?D.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],H=Array.from(G),(H.length>0||D.length>0)&&hG){let se=H.concat(D).map(Se=>({key:Se,value:K}));b.prefetch(se,SG)}for(let se=0,Se=H.length;se<Se;se++)b.remove(H[se],K)}else D?.length>0&&hG&&b.prefetch(D.map(G=>({key:G,value:K})),SG);if(D)for(let G=0,se=D.length;G<se;G++)b.put(D[G],K)}return w}a(jl,"updateIndices");function ac(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>pG)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,Bo.writeKey)(K,Fie,0)>pG)throw new Error("Primary key size is too large: "+K.length);return!0}a(ac,"checkValidId");function Nh(K,m,O,w,y){let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let L=i.getEntry(K,O);return L&&m&&(L?.version>(m.lastModified||0)&&(m.lastModified=L.version),L?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=L.localTime)),y(L,K)},"whenPrefetched");return w?b():ue>0?(ue--,b()):new Promise((L,N)=>{ue===0?(ue--,i.prefetch([K],()=>{U(),F()})):(z.push(K),ae.push(F),z.length>gq&&(ue--,U()));function U(){if(z.length>0){let D=ae;i.prefetch(z,()=>{ue===-1?U():ue++;for(let H of D)H()}),z=[],ae=[],de>2&&de--}else ue=de,de<Tq&&de++}a(U,"prefetch");function F(){try{L(b())}catch(D){N(D)}}a(F,"load")})}a(Nh,"loadLocalRecord");function Xl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return kie;let O=m[c],w,y=O?.tables;if(y)return y[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(Xl,"getTablePermissions");function Ih(K,m,O,w){if(C){let y;if(O.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Pl|Ul)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,Wr(!y,"cache-hit",s)),y){let b=uO(K,m,O).then(L=>(L?.value?.[fe]&&rt.error("Can not assign a record with a record property"),O&&(L?.version>(O.lastModified||0)&&(O.lastModified=L.version),O.lastRefreshed=Date.now()),L));if(O?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,K)){if(b.catch(L=>rt.warn(L)),O?.onlyIfCached&&!w.doesExist())throw new rn.ServerError("Entry is not cached",504);return}else return b}}}a(Ih,"ensureLoadedFromSource");function On(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 O=m.next;if(!O)return m=m.next=new to,m.lmdbDb=i,m;m=O}while(!0)}else return new _d}a(On,"txnForContext");function wh(K,m,O){if(!K)return;bh=K;let w=K.value||K.deref?.()||(bh=i.getEntry(K.key))?.value;if(typeof m=="object"){let b=zs,L=w;for(let N=0,U=m.length;N<U;N++){let F=m[N],D=b?.[F];L=D&&L?D(L,O,!0)?.value:L?.[F],b=D?.definition?.tableClass?.propertyResolvers}return L}let y=zs[m];return y?y(w,O):w[m]}a(wh,"getAttributeValue");function cO(K,m,O,w,y){let b=y?.length,L={transaction:w,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(F,D){let H=F?.value;if(!H)return Uo.SKIP;for(let G=0;G<b;G++)if(!N?.includes(G)&&!y[G](H,F))return Uo.SKIP;return D!==void 0&&(F.key=D),F}if(a(U,"processEntry"),b>0||!K.hasEntries){let F=K.map(D=>{if(N=null,typeof D=="object"&&D?.key!==void 0)return b>0?U(D):D;if(D==null)return Uo.SKIP;for(let H=0;H<b;H++){let se=y[H].idFilter;if(se){if(!se(D))return Uo.SKIP;N||(N=[]),N.push(H)}}return Nh(D,O,L,!1,U)});return Array.isArray(K)&&(F=F.filter(D=>D!==Uo.SKIP)),F.hasEntries=!0,F}return K}a(cO,"transformToEntries");async function uO(K,m,O){let w=m?.metadataFlags,y=m?.version,b,L;if(!i.attemptLock(K,y,()=>{clearTimeout(L);let D=i.getEntry(K);!D||!D.value||D.metadataFlags&(Pl|Ul)?b(uO(K,i.getEntry(K),O)):b(D)}))return new Promise(D=>{b=D,L=setTimeout(()=>{i.unlock(K,y)},xie)});let N=m?.value,U={requestContext:O,replacingRecord:N,replacingVersion:y,source:null,resourceCache:O?.resourceCache},F=O?.responseHeaders;return new Promise((D,H)=>{let G;VA(Xe(U,async se=>{let Se=performance.now(),te,Pe,ce;try{for(let Te of Qe.sources)if(Te.get&&(!Te.get.reliesOnPrototype||Te.prototype.get)&&(U.source=Te,te=await Te.get(K,U),te))break;ce=w&Pl;let re=U.lastModified||ce&&y;Pe=ce||re>y||!N,re||(re=(0,Hl.getNextMonotonicTime)());let X=performance.now()-Se;if(pr(X,"cache-resolution",s),F&&Eg(F,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=re,E&&!U.expiresAt&&(U.expiresAt=Date.now()+E),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]!==K&&(te[t]=K)}G=!0,D({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} for ${s}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(D({version:y,value:N}),rt.trace(re.message,"(returned stale record)")):H(re),U.transaction.abort();return}if(O?.noCacheStore){U.transaction.abort();return}On(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==y)return;let Te=jl(K,N,te);te?(Ee.put?.(U,K,te),T(K,te,X,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ce)):(Ee.delete?.(U,K),h||p?T(K,null,X,re,0,h&&Pe||null,U,0,"delete",!!ce):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&rt.error("Error committing cache update",se)})})}a(uO,"getFromSource");function Ch(){if(Pt!==zl&&(zl=Pt,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(Jl&&clearTimeout(Jl),!Pt)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())/Pt)*Pt+K.getTime(),O=a(w=>{rt.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),Jl=setTimeout(()=>v=v.then(async()=>{if(O(Math.max(w+Pt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Jl);return}let y=50,b=new Array(y),L=0;rt.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:U,value:F,version:D,expiresAt:H}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;F===null&&!h&&D+Hie<Date.now()?G=i.remove(U,D):H&&H+f<Date.now()&&(G=Qe.evict(U,F,D),N++),G&&(await b[L],b[L]=G.catch(se=>{rt.error("Cleanup error",se)}),++L>=y&&(L=0)),await vl()}rt.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){rt.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");O(m)}}a(Ch,"scheduleCleanup");function lO(){j=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(lO,"addDeleteRemoval");function Aq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!yh){yh=!0;try{let K=Q.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${Q} must be indexed`);for(let O of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let w of m.getValues(O)){let y=i.getEntry(w);y?.value?y.value[K]<Date.now()&&Qe.evict(w,y.value,y.version):i.ifVersion(w,y?.version,()=>m.remove(O,w))}await vl()}}catch(K){rt.error("Error in evicting old records",K)}finally{yh=!1}}},Bie).unref()}a(Aq,"runRecordExpirationEviction")}function kA(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 SG(){}function Vie(e){AG=e}function sh(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?isNaN(e)?e==="null"?null:($ie.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,oh.autoCast)(e):e}function TG(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 VA(e,t,r){return e?.then?e.then(t,r):t(e)}function ih(e,t){e[Lr]=t,e[fe]=t?.value??null,e[Bl]=t?.version}function gG(e){return e!=null}function kn(e){try{return JSON.stringify(e)}catch{return e}}var Vn,Uo,Hl,RG,ql,rn,xl,Gl,rt,Bo,vo,oh,vie,AG,Bie,Hie,hG,xie,Bl,Gie,Lr,Ml,mG,qie,FA,rc,Pl,Ul,Fie,pG,kie,uTe,$ie,vl,_E=Ae(()=>{Vn=B(P()),Uo=require("lmdb"),Hl=B(vr()),RG=require("lodash");Nn();aS();ql=B(Z());EG();rn=B(ne()),xl=B(bs()),Gl=B(Mn());Oe();jf();rt=B($());Ed();ro();Bo=require("ordered-binary"),vo=B(Je());ti();oh=B(J());Cc();ws();QE();Qu();vie=new Uint8Array(9);vie[8]=192;Bie=6e4,Hie=864e5;ql.initSync();hG=ql.get(Vn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),xie=1e4,Bl=Symbol.for("version"),Gie=Symbol.for("incremental-update"),Lr=Symbol("entry"),Ml=Symbol("is-saving"),mG=1,qie=2,FA=Symbol("loaded-from-source"),rc={isNotification:!0,ensureLoaded:!1},Pl=1,Ul=8,Fie=Buffer.allocUnsafeSlow(8192),pG=1978,kie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},uTe=(0,oh.convertToMS)(ql.get(Vn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(ah,"makeTable");a(kA,"attributesAsObject");a(SG,"noop");a(Vie,"setServerUtilities");$ie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(sh,"coerceType");a(TG,"isDescendantId");vl=a(()=>new Promise(setImmediate),"rest");a(VA,"when");a(ih,"updateResource");a(gG,"exists");a(kn,"stringify")});var Fe={};qe(Fe,{database:()=>nu,databases:()=>it,dropDatabase:()=>dS,dropTableMeta:()=>zie,getDatabases:()=>hr,getDefaultCompression:()=>Sf,getTables:()=>Yie,onUpdatedTable:()=>XR,readMetaDb:()=>Fl,resetDatabases:()=>Fu,table:()=>dt,tables:()=>Br});function Yie(){return dh||hr(),Br||{}}function hr(){if(dh)return it;dh=!0,ic=new Map;let e=(0,mt.getHdbBasePath)()&&(0,nt.join)((0,mt.getHdbBasePath)(),Mt.DATABASES_DIR_NAME),t=(0,mt.get)(Mt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,nn.existsSync)(e)?e:(0,nt.join)((0,mt.getHdbBasePath)(),Mt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,nn.existsSync)(e))for(let r of(0,nn.readdirSync)(e,{withFileTypes:!0})){let n=(0,nt.basename)(r.name,".mdb");r.isFile()&&(0,nt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Fl((0,nt.join)(e,r.name),null,n)}if((0,nn.existsSync)((0,sc.getBaseSchemaPath)())){for(let r of(0,nn.readdirSync)((0,sc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,nt.join)((0,sc.getBaseSchemaPath)(),r.name),s=(0,nt.join)((0,sc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,nn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,nt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,nt.join)(s,i.name);Fl((0,nt.join)(n,i.name),(0,nt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,nn.existsSync)(s))for(let o of(0,nn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,nt.extname)(o.name).toLowerCase()===".mdb"&&Fl((0,nt.join)(s,o.name),(0,nt.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,nt.join)(c.path,(0,nt.basename)(o+".mdb"));(0,nn.existsSync)(u)&&Fl(u,o,r,null,!0)}}for(let r in it){let n=ic.get(r);if(n){let s=it[r];r.includes("delete")&&An.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(An.trace(`delete table class ${i}`),delete s[i])}else if(delete it[r],r==="data"){for(let s in Br)delete Br[s];delete Br[Eh]}}return ic=null,it}}function Fu(){dh=!1;for(let[,e]of Ui)e.needsDeletion=!0;hr();for(let[e,t]of Ui)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Ui.delete(e));return it}function Fl(e,t,r=KA,n,s){let i=new $A.default(e,!1);try{let o=Ui.get(e);o?o.needsDeletion=!1:(o=(0,uh.open)(i),Ui.set(e,o));let c=new Ho.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(ch.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,nn.existsSync)(n)&&(i.path=n,_=(0,uh.open)(i),_.isLegacy=!0):_=WE(o));let l=NG(r),d=l[Eh],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[p,S]=f.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 T=E.get(p);T||E.set(p,T={attributes:[]}),(S==null||h.is_hash_attribute)&&(T.primary=h),S!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:p,primary:S}=h;if(!S){for(let z of p)if(z.is_hash_attribute||z.isPrimaryKey){S=z;break}if(!S){An.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[f],A={},R=[],C,x,v=typeof S.audit=="boolean"?S.audit:(0,mt.get)(Mt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=S.trackDeletes,M=S.expiration,Q=S.eviction,j=S.sealed;if(T)A=T.indices,R=T.attributes,T.schemaVersion++;else{C=S.tableId,C?C>=(u.get(nc)||0)&&u.putSync(nc,C+1):(S.tableId=C=u.get(nc),C||(C=1),u.putSync(nc,C+1),u.putSync(S.key,S));let z=new Ho.default(!S.is_hash_attribute,S.is_hash_attribute);if(z.compression=S.compression,z.compression){let ae=(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||yG;z.compression.threshold=ae}x=p_(o.openDB(S.key,z)),x.rootStore=o,x.tableId=C}for(let z of p){z.attribute=z.name;try{if(!z.is_hash_attribute&&(z.indexed||z.attribute&&!z.name)){if(!A[z.name]){let ue=new Ho.default(!z.is_hash_attribute,z.is_hash_attribute);A[z.name]=o.openDB(z.key,ue),A[z.name].indexNulls=z.indexNulls}let ae=R.find(ue=>ue.name===z.name);ae?R.splice(R.indexOf(ae),1,z):R.push(z)}}catch(ae){An.error("Error trying to update attribute",z,R,A,ae)}}if(!T){T=IG(l,f,ah({primaryStore:x,auditStore:_,audit:v,sealed:j,expirationMS:M&&M*1e3,evictionMS:Q&&Q*1e3,trackDeletes:k,tableName:f,tableId:C,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:A,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let z of WA)z(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function NG(e){let t=it[e];if(t||(e==="data"?t=it[e]=Br:e==="system"?Object.defineProperty(it,"system",{value:t=Object.create(null),configurable:!0}):t=it[e]=Object.create(null)),ic&&!ic.has(e)){let r=new Set;t[Eh]=r,ic.set(e,r)}return t}function IG(e,t,r){return e[t]=r,r}function nu({database:e,table:t}){e||(e=KA),hr();let r=NG(e),n=(0,nt.join)((0,mt.getHdbBasePath)(),Mt.DATABASES_DIR_NAME),s=(0,mt.get)(Mt.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,mt.get)(Mt.CONFIG_PARAMS.STORAGE_PATH)||((0,nn.existsSync)(n)?n:(0,nt.join)((0,mt.getHdbBasePath)(),Mt.LEGACY_DATABASES_DIR_NAME));let o=(0,nt.join)(n,(i?t:e)+".mdb"),c=Ui.get(o);if(!c){let u=new $A.default(o,!1);c=(0,uh.open)(u),Ui.set(o,c)}return c}async function dS(e){if(!it[e])throw new Error("Schema does not exist");let t=it[e];for(let r in t){let s=t[r].primaryStore.rootStore;Ui.delete(s.path),s.status==="open"&&(await s.close(),await fh.remove(s.path))}if(e==="data"){for(let r in Br)delete Br[r];delete Br[Eh]}delete it[e]}function dt({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=KA);let d=nu({database:t,table:e}),E=it[t],f=E?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let A=new Ho.default(!1);for(let M of i)M.attribute&&!M.name?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let R,C;if(f){if(h=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 M=d.auditStore;M||(M=WE(d)),p=i.find(ae=>ae.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=Sf(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,mt.get)(Mt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),An.trace(`${e} table loading, opening primary store`);let Q=new Ho.default(!1,!0);Q.compression=p.compression;let j=e+"/",z=p_(d.openDB(j,Q));z.rootStore=d,T=d.dbisDb=d.openDB(ch.INTERNAL_DBIS_NAME,A),z.tableId=T.get(nc),z.tableId||(z.tableId=1),T.putSync(nc,z.tableId+1),p.tableId=z.tableId,f=IG(E,e,ah({primaryStore:z,auditStore:M,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:z.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),f.schemaVersion=1,R=!0,k(),T.put(j,p)}S=f.indices,T=T||(d.dbisDb=d.openDB(ch.INTERNAL_DBIS_NAME,A)),f.dbisDB=T;let x=[];for(let{key:M,value:Q}of T.getRange({start:!0})){let[j,z]=M.toString().split("/");if(z===""&&(z=Q.name),z){if(j!==e)continue}else z=j;if(!i.find(ue=>ue.name===z)?.indexed&&Q.indexed&&!Q.isPrimaryKey){k(),R=!0,T.remove(M);let ue=f.indices[j];ue&&x.push(ue)}}let v=[];try{for(let M of i||[]){if(M.relationship)continue;let Q=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:Q,configurable:!0});let j=T.get(Q);if(M.isPrimaryKey){if(j=j||T.get(Q=e+"/")||{},o!==f.audit||c!==c||(+r||void 0)!==(+j.expiration||void 0)||(+n||void 0)!==(+j.eviction||void 0)){let ae=Object.assign({},j);typeof o=="boolean"&&(o&&f.enableAuditing(o),ae.audit=o),r&&(ae.expiration=+r),n&&(ae.eviction=+n),c!==void 0&&(ae.sealed=c),R=!0,k(),T.put(Q,ae)}continue}j?.attribute&&!j.name&&(j.indexed=!0);let z=!j||j.type!==M.type||j.indexed!==M.indexed||j.nullable!==M.nullable||JSON.stringify(j.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(j.elements)!==JSON.stringify(M.elements);if(M.indexed){let ae=new Ho.default(!0,!1),ue=d.openDB(Q,ae);(z||j.indexingPID&&j.indexingPID!==process.pid||j.restartNumber<kl.workerData?.restartNumber)&&(R=!0,k(),j=T.get(Q),(z||j.indexingPID&&j.indexingPID!==process.pid||j.restartNumber<kl.workerData?.restartNumber)&&(R=!0,M.indexNulls===void 0&&(M.indexNulls=!0),f.primaryStore.getStats().entryCount>0&&(M.lastIndexedKey=j?.lastIndexedKey||!1,M.indexingPID=process.pid,ue.isIndexing=!0,Object.defineProperty(M,"dbi",{value:ue}),v.push(M))),T.put(Q,M)),j?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),ue.indexNulls=M.indexNulls,S[M.name]=ue}else z&&(R=!0,k(),T.put(Q,M))}}finally{C&&C()}if(R&&(f.schemaVersion++,f.updatedAttributes()),An.trace(`${e} table loading, running index`),v.length>0||x.length>0?f.indexingOperation=Qie(f,v,x):R&&lh.signalSchemaChange(new _h.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=l,R)for(let M of WA)M(f,l!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),An.trace(`${e} table loaded`),f;function k(){C||d.transactionSync(()=>({then(M){C=M}}))}a(k,"startTxn")}async function Qie(e,t,r){try{let n=e.schemaVersion;await lh.signalSchemaChange(new _h.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 E=0;E<c;E++){let f=t[E],h=f.name,p=(0,OG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)f.dbi.put(p[S],_)}}),s.then(()=>u--,E=>{u--,An.error(E)}),kl.workerData&&kl.workerData.restartNumber!==bG.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}u>Kie?await s:u>Wie&&await new Promise(E=>setImmediate(E))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await lh.signalSchemaChange(new _h.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){An.error("Error in indexing",n)}}function zie({table:e,database:t}){let r=nu({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 XR(e){WA.push(e)}function Sf(){let e=(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||yG,n={startingOffset:32};return t&&(n.dictionary=fh.readFileSync(t)),r&&(n.threshold=r),e&&n}var mt,ch,uh,nt,nn,sc,Ho,$A,Mt,fh,YA,OG,lh,_h,kl,An,bG,KA,Eh,yG,Br,it,nc,WA,dh,Ui,ic,Kie,Wie,Oe=Ae(()=>{mt=B(Z()),ch=B(_t()),uh=require("lmdb"),nt=require("path"),nn=require("fs"),sc=B(ze());_E();Ho=B(Dc()),$A=B(Lc()),Mt=B(P()),fh=B(require("fs-extra")),YA=require("../index"),OG=B(vr()),lh=B(bs()),_h=B(Mn()),kl=require("worker_threads"),An=B($()),bG=B(Je());ti();Cc();KA="data",Eh=Symbol("defined-tables"),yG=((0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,mt.initSync)();Br=Object.create(null),it=Object.create(null);(0,YA._assignPackageExport)("databases",it);(0,YA._assignPackageExport)("tables",Br);nc=Symbol.for("next-table-id"),WA=[],Ui=new Map;a(Yie,"getTables");a(hr,"getDatabases");a(Fu,"resetDatabases");a(Fl,"readMetaDb");a(NG,"ensureDB");a(IG,"setTable");a(nu,"database");a(dS,"dropDatabase");a(dt,"table");Kie=1e3,Wie=10;a(Qie,"runIndexing");a(zie,"dropTableMeta");a(XR,"onUpdatedTable");a(Sf,"getDefaultCompression")});var J=g((STe,FG)=>{"use strict";var vi=require("path"),MG=require("fs-extra"),Mr=$(),wG=require("fs-extra"),hh=require("os"),Jie=require("net"),jie=require("recursive-iterator"),lt=P(),Xie=VO(),CG=require("papaparse"),mh=require("moment"),{inspect:Zie}=require("util"),DG=require("is-number"),pTe=require("lodash"),eoe=require("minimist"),toe=require("https"),roe=require("http"),{hdb_errors:ph}=ne(),noe=/^((\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)))$/,PG=require("util").promisify(setTimeout),soe=100,ioe=5,ooe="",aoe=4,LG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};FG.exports={isEmpty:sn,isEmptyOrZeroLength:hs,arrayHasEmptyValues:loe,arrayHasEmptyOrZeroLengthValues:_oe,buildFolderPath:doe,isBoolean:UG,errorizeMessage:coe,stripFileExtension:Eoe,autoCast:hoe,autoCastJSON:vG,autoCastJSONDeep:zA,removeDir:moe,compareVersions:poe,isCompatibleDataVersion:Soe,escapeRawValue:Toe,unescapeValue:goe,stringifyProps:Roe,timeoutPromise:Ooe,isClusterOperation:yoe,getClusterUser:Ioe,checkGlobalSchemaTable:Noe,getHomeDir:HG,getPropsFilePath:Aoe,promisifyPapaParse:woe,removeBOM:xG,createEventPromise:Coe,checkProcessRunning:Doe,checkSchemaTableExist:Loe,checkSchemaExists:GG,checkTableExists:qG,getStartOfTomorrowInSeconds:Moe,getLimitKey:Poe,isObject:foe,isNotEmptyAndHasValue:uoe,autoCasterIsNumberCheck:BG,backtickASTSchemaItems:Uoe,isPortTaken:boe,createForkArgs:voe,autoCastBoolean:Boe,async_set_timeout:PG,getTableHashAttribute:Hoe,doesSchemaExist:xoe,doesTableExist:Goe,stringifyObj:qoe,ms_to_time:Foe,changeExtension:koe,getEnvCliRootPath:JA,noBootFile:Voe,httpRequest:$oe,transformReq:Yoe,convertToMS:Koe,PACKAGE_ROOT:lt.PACKAGE_ROOT};function coe(e){return e instanceof Error?e:new Error(e)}a(coe,"errorizeMessage");function sn(e){return e==null}a(sn,"isEmpty");function uoe(e){return!sn(e)&&(e||e===0||e===""||UG(e))}a(uoe,"isNotEmptyAndHasValue");function hs(e){return sn(e)||e.length===0||e.size===0}a(hs,"isEmptyOrZeroLength");function loe(e){if(sn(e))return!0;for(let t=0;t<e.length;t++)if(sn(e[t]))return!0;return!1}a(loe,"arrayHasEmptyValues");function _oe(e){if(hs(e))return!0;for(let t=0;t<e.length;t++)if(hs(e[t]))return!0;return!1}a(_oe,"arrayHasEmptyOrZeroLengthValues");function doe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(doe,"buildFolderPath");function UG(e){return sn(e)?!1:e===!0||e===!1}a(UG,"isBoolean");function foe(e){return sn(e)?!1:typeof e=="object"}a(foe,"isObject");function Eoe(e){return hs(e)?ooe:e.slice(0,-aoe)}a(Eoe,"stripFileExtension");function hoe(e){return sn(e)||e===""||typeof e!="string"?e:LG[e]!==void 0?LG[e]:BG(e)===!0?Number(e):noe.test(e)?new Date(e):e}a(hoe,"autoCast");function vG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(vG,"autoCastJSON");function zA(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=zA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=zA(r);n!==r&&(e[t]=n)}return e}else return vG(e)}a(zA,"autoCastJSONDeep");function BG(e){if(e.startsWith("0.")&&DG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&DG(e))}a(BG,"autoCasterIsNumberCheck");async function moe(e){if(hs(e))throw new Error(`Directory path: ${e} does not exist`);try{await wG.emptyDir(e),await wG.remove(e)}catch(t){throw Mr.error(`Error removing files in ${e} -- ${t}`),t}}a(moe,"removeDir");function poe(e,t){if(hs(e)){Mr.info("Invalid current version sent as parameter.");return}if(hs(t)){Mr.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(poe,"compareVersions");function Soe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Soe,"isCompatibleDataVersion");function Toe(e){if(sn(e))return e;let t=String(e);return t==="."?lt.UNICODE_PERIOD:t===".."?lt.UNICODE_PERIOD+lt.UNICODE_PERIOD:t.replace(lt.FORWARD_SLASH_REGEX,lt.UNICODE_FORWARD_SLASH)}a(Toe,"escapeRawValue");function goe(e){if(sn(e))return e;let t=String(e);return t===lt.UNICODE_PERIOD?".":t===lt.UNICODE_PERIOD+lt.UNICODE_PERIOD?"..":String(e).replace(lt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(goe,"unescapeValue");function Roe(e,t){if(sn(e))return Mr.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+hh.EOL}!hs(n)&&n[0]===";"?r+=" "+n+s+hh.EOL:hs(n)||(r+=n+"="+s+hh.EOL)}catch{Mr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Roe,"stringifyProps");function HG(){let e;try{e=hh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(HG,"getHomeDir");function Aoe(){let e=vi.join(HG(),lt.HDB_HOME_DIR_NAME,lt.BOOT_PROPS_FILE_NAME);return MG.existsSync(e)||(e=vi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Aoe,"getPropsFilePath");function Ooe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Ooe,"timeoutPromise");async function boe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Jie.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(boe,"isPortTaken");function yoe(e){try{return lt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(yoe,"isClusterOperation");function Noe(e,t){let r=(Oe(),ie(Fe)).getDatabases();if(!r[e])return ph.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return ph.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Noe,"checkGlobalSchemaTable");function Ioe(e,t){if(sn(t)){Mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(sn(e)||hs(e)){Mr.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){Mr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Ioe,"getClusterUser");function woe(){CG.parsePromise=function(e,t,r){return new Promise(function(n,s){CG.parse(e,{header:!0,transformHeader:xG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(woe,"promisifyPapaParse");function xG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(xG,"removeBOM");function Coe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Mr.info(`Got cluster status event response: ${Zie(s)}`);try{i.cancel()}catch{Mr.error("Error trying to cancel timeout.")}n(s)})})}a(Coe,"createEventPromise");async function Doe(e){let t=!0,r=0;do await PG(soe*r++),(await Xie.findPs(e)).length>0&&(t=!1);while(t&&r<ioe);if(t)throw new Error(`process ${e} was not started`)}a(Doe,"checkProcessRunning");function Loe(e,t){let r=GG(e);if(r)return r;let n=qG(e,t);if(n)return n}a(Loe,"checkSchemaTableExist");function GG(e){let{getDatabases:t}=(Oe(),ie(Fe));if(!t()[e])return ph.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(GG,"checkSchemaExists");function qG(e,t){let{getDatabases:r}=(Oe(),ie(Fe));if(!r()[e][t])return ph.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(qG,"checkTableExists");function Moe(){let e=mh().utc().add(1,lt.MOMENT_DAYS_TAG).startOf(lt.MOMENT_DAYS_TAG).unix(),t=mh().utc().unix();return e-t}a(Moe,"getStartOfTomorrowInSeconds");function Poe(){return mh().utc().format("DD-MM-YYYY")}a(Poe,"getLimitKey");function Uoe(e){try{let t=new jie(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){Mr.error("Got an error back ticking items."),Mr.error(t)}}a(Uoe,"backtickASTSchemaItems");function voe(e){return[e]}a(voe,"createForkArgs");function Boe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Boe,"autoCastBoolean");function Hoe(e,t){let{getDatabases:r}=(Oe(),ie(Fe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Hoe,"getTableHashAttribute");function xoe(e){let{getDatabases:t}=(Oe(),ie(Fe));return t()[e]!==void 0}a(xoe,"doesSchemaExist");function Goe(e,t){let{getDatabases:r}=(Oe(),ie(Fe));return r()[e]?.[t]!==void 0}a(Goe,"doesTableExist");function qoe(e){try{return JSON.stringify(e)}catch{return e}}a(qoe,"stringifyObj");function Foe(e){let t=mh.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(Foe,"ms_to_time");function koe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(koe,"changeExtension");function JA(){if(process.env[lt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[lt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=eoe(process.argv);if(e[lt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[lt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(JA,"getEnvCliRootPath");var QA;function Voe(){if(QA)return QA;let e=JA();if(JA()&&MG.pathExistsSync(vi.join(e,lt.HDB_CONFIG_FILE)))return QA=!0,!0}a(Voe,"noBootFile");function $oe(e,t){let r;return e.protocol==="http:"?r=roe:r=toe,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($oe,"httpRequest");function Yoe(e){if(!e.schema&&!e.database){e.schema=lt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Yoe,"transformReq");function Koe(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(Koe,"convertToMS")});var Z=g((gTe,KG)=>{"use strict";var jA=require("fs-extra"),xo=require("path"),kG=require("os"),Woe=require("properties-reader"),$l=$(),Vl=J(),le=P(),Sh=fr(),Qoe="Error initializing environment manager",Th="BOOT_PROPS_FILE_PATH",VG=!1,zoe={[le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ws={};KG.exports={BOOT_PROPS_FILE_PATH:Th,getHdbBasePath:Joe,setHdbBasePath:joe,get:$G,initSync:Zoe,setProperty:Me,initTestEnvironment:tae,setCloneVar:eae};function Joe(){return Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Joe,"getHdbBasePath");function joe(e){Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(joe,"setHdbBasePath");function $G(e){let t=Sh.getConfigValue(e);return t===void 0?Ws[e]:t}a($G,"get");function Me(e,t){zoe[e]&&(Ws[e]=t),Sh.updateConfigObject(e,t)}a(Me,"setProperty");function Xoe(){let e;try{e=Vl.getPropsFilePath(),jA.accessSync(e,jA.constants.F_OK|jA.constants.R_OK),VG=!0;let t=Woe(e);return Ws[le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(le.HDB_SETTINGS_NAMES.INSTALL_USER),Ws[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ws[Th]=e,!0}catch{return $l.trace(`Environment manager found no properties file at ${e}`),!1}}a(Xoe,"doesPropFileExist");function Zoe(e=!1){try{(VG||Xoe()||Vl.noBootFile())&&!YG&&(Sh.initConfig(e),Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Sh.getConfigValue(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){$l.error(Qoe),$l.error(t),console.error(t),process.exit(1)}}a(Zoe,"initSync");var YG=!1;function eae(e){YG=e}a(eae,"setCloneVar");function tae(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=xo.join(__dirname,"../../","unitTests");Ws[Th]=xo.join(u,"hdb_boot_properties.file"),Me(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xo.join(u,"settings.test")),Me(le.HDB_SETTINGS_NAMES.INSTALL_USER,kG.userInfo()?kG.userInfo().username:void 0),Me(le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xo.join(u,"envDir","log")),Me(le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xo.join(u,"envDir")),Me(le.CONFIG_PARAMS.STORAGE_PATH,xo.join(u,"envDir")),s&&(Me(le.CONFIG_PARAMS.HTTP_SECUREPORT,$G(le.CONFIG_PARAMS.HTTP_PORT)),Me(le.CONFIG_PARAMS.HTTP_PORT,null)),Me(le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Vl.isEmpty(i)?!1:i),Me(le.CONFIG_PARAMS.HTTP_CORS,Vl.isEmpty(i)?!1:i),Me(le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Vl.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Th}. Please check your boot props and settings files`;$l.fatal(r),$l.error(t)}}a(tae,"initTestEnvironment")});var jG=g((ATe,JG)=>{"use strict";var zG=require("joi"),{string:Yl,boolean:WG,array:rae}=zG.types(),QG=P(),nae=je();JG.exports=sae;function sae(e){let t=zG.object({operation:Yl.valid(QG.OPERATIONS_ENUM.ADD_NODE,QG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Yl.required(),subscriptions:rae.items({schema:Yl.required(),table:Yl.optional(),hash_attribute:Yl.optional(),subscribe:WG.required(),publish:WG.required()}).min(1).required()});return nae.validateBySchema(e,t)}a(sae,"updateRemoteSourceValidator")});var Kl=g((bTe,XG)=>{"use strict";var XA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};XG.exports=XA});var rq=g((NTe,tq)=>{"use strict";var iae=jG(),Qs=$(),ZA=ke(),oae=P(),eO=dn(),Go=ot(),ZG=Tu(),aae=cd(),{Node:cae,NodeSubscription:eq}=pi(),tO=Kl(),rO=J(),uae=Z(),{cloneDeep:lae}=require("lodash"),{broadcast:_ae}=Je();tq.exports=dae;async function dae(e){try{let t=iae(e);if(t)return Qs.error(`Validation error in updateRemoteSource: ${t.message}`),new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=lae(await eO.getNodeRecord(n)),c=!rO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Qs.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],E=d.schema,f=d.table;if(!rO.doesSchemaExist(E)){Qs.trace(`updateRemoteSource creating schema: ${E}`);try{await ZG.createSchema({operation:"create_schema",schema:E})}catch(h){Qs.error(h)}}if(f&&!rO.doesTableExist(E,f)){let h=new aae(E,f,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Qs.trace(`updateRemoteSource creating table: ${f} in schema: ${E} with attributes: ${JSON.stringify(d.attributes)}`);try{await ZG.createTable(h)}catch(p){Qs.error(p)}}if(Qs.trace(`Creating local stream for ${E}.${f}`),await Go.createLocalTableStream(E,f),c?(await Go.updateConsumerIterator(E,f,n,"stop"),await Go.updateRemoteConsumer(d,n),d.subscribe===!0&&await Go.updateConsumerIterator(E,f,n,"start")):(await Go.updateRemoteConsumer(d,n),d.subscribe===!0?await Go.updateConsumerIterator(E,f,n,"start"):await Go.updateConsumerIterator(E,f,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===E&&T.table===f){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new eq(E,f,d.publish,d.subscribe))}else i.push(new eq(E,f,d.publish,d.subscribe))}c||(o=new cae(n,i,void 0),Qs.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await eO.upsertNodeRecord(u),_ae({type:"nats_update"}),new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${uae.get(oae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await eO.getSystemInfo())}catch(t){Qs.error(t);let r=t.message?t.message:t;return new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(dae,"updateRemoteSource")});var oq=g((wTe,iq)=>{"use strict";var sq=require("joi"),{string:nq}=sq.types(),fae=P(),Eae=je();iq.exports=hae;function hae(e){let t=sq.object({operation:nq.valid(fae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:nq.required()});return Eae.validateBySchema(e,t)}a(hae,"removeRemoteSourceValidator")});var uq=g((DTe,cq)=>{"use strict";var mae=oq(),gh=$(),Rh=ke(),nO=P(),pae=dn(),Sae=J(),aq=ot(),Tae=Z(),Ah=Kl(),{NodeSubscription:gae}=pi(),Rae=oa(),Aae=oi(),{broadcast:Oae}=Je(),bae=Tae.get(nO.CONFIG_PARAMS.CLUSTERING_NODENAME);cq.exports=yae;async function yae(e){try{let t=mae(e);if(t)return gh.error(`Validation error in removeRemoteSource: ${t.message}`),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await pae.getNodeRecord(r);if(Sae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return gh.error(i),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];gh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new gae(c.schema,c.table,!1,!1);await aq.updateConsumerIterator(c.schema,c.table,r,"stop"),await aq.updateRemoteConsumer(u,r)}let s=new Rae(nO.SYSTEM_SCHEMA_NAME,nO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Aae.deleteRecord(s),Oae({type:"nats_update"}),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${bae} successfully removed node '${r}'.`)}catch(t){gh.error(t);let r=t.message?t.message:t;return new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(yae,"removeRemoteSource")});var fq=g((MTe,dq)=>{"use strict";var Oh=$(),Wl=P(),lq=ke(),sO=Z(),Nae=J(),_q=Kl(),Iae=dn(),wae=Gd(),Cae=qr();dq.exports=Dae;async function Dae(e){try{Oh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Nae.ms_to_time(t),n=new Lae(sO.get(Wl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),sO.get(Wl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??sO.get(Wl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Iae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new wae(Wl.SYSTEM_SCHEMA_NAME,Wl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await Cae.update(i)}catch(s){Oh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return Oh.trace("getRemoteSourceConfig response:",n),new _q(lq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){Oh.error(t);let r=t.message?t.message:t;return new _q(lq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Dae,"getRemoteSourceConfig");function Lae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(Lae,"ConfigResponseObject")});var pq=g((UTe,mq)=>{"use strict";var Eq=Z();Eq.initSync();var hq=ot(),Ql=$(),oc=P(),iO=ke(),Mae=rq(),Pae=uq(),Uae=fq(),vae=Kl(),{encode:Bae,decode:Hae}=require("msgpackr"),xae=Os(),Gae=As(),qae=require("util"),Fae=P(),{isMainThread:kae,parentPort:Vae}=require("worker_threads");Je();var $ae=qae.promisify(xae.setSchemaDataToGlobal),oO=Eq.get(oc.CONFIG_PARAMS.CLUSTERING_NODENAME);mq.exports=Yae;async function Yae(){try{Ql.notify("Starting reply service."),await $ae();let e=await hq.getConnection(),t=`${oO}.__request__`,r=e.subscribe(t,{queue:oO});await Kae(r)}catch(e){Ql.error(e)}}a(Yae,"initialize");async function Kae(e){for await(let t of e){let r=Hae(t.data),n;switch(r.operation){case oc.OPERATIONS_ENUM.ADD_NODE:case oc.OPERATIONS_ENUM.UPDATE_NODE:n=await Mae(r);break;case oc.OPERATIONS_ENUM.REMOVE_NODE:n=await Pae(r);break;case oc.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Uae(r);break;case oc.OPERATIONS_ENUM.DESCRIBE_ALL:n=await Wae();break;default:let s=`node '${oO}' reply service received unrecognized request operation`;Ql.error(s),n=new vae(iO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Ql.trace(n),t.respond(Bae(n))}}a(Kae,"handleRequest");async function Wae(){try{return{status:iO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Gae.describeAll()}}catch(e){return Ql.error(e),{status:iO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(Wae,"getRemoteDescribeAll");kae||Vae.on("message",async e=>{let{type:t}=e;t===Fae.ITC_EVENT_TYPES.SHUTDOWN&&hq.closeConnection()})});var Qae=pq();(async()=>{try{await Qae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();