harperdb 4.3.13 → 4.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +23 -23
- package/bin/lite.js +19 -19
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +19 -19
- package/launchServiceScripts/launchNatsReplyService.js +17 -17
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +17 -17
- package/npm-shrinkwrap.json +77 -74
- package/package.json +1 -1
- package/server/jobs/jobProcess.js +17 -17
- package/server/threads/threadServer.js +19 -19
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.f2650b6b.js → main.df87fe42.js} +2 -2
- package/utility/scripts/restartHdb.js +19 -19
- /package/studio/build-local/static/js/{main.f2650b6b.js.LICENSE.txt → main.df87fe42.js.LICENSE.txt} +0 -0
|
@@ -1,22 +1,22 @@
|
|
|
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})},cO=(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)):{},cO(t||!e||!e.__esModule?ac(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>cO(ac({},"__esModule",{value:!0}),e);var _O=R((Xae,lO)=>{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:uO}=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=lO.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=uO(On,n[0]),o;i.startsWith(cc)?o=Xs(On,uO(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,NO)=>{"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(),dO="js",Xl=dO,Fq="harperdb-config.yaml",kq="defaultConfig.yaml",Vq="hdb",fO=`harperdb.${Xl}`,EO=`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,fO),CUSTOM_FUNCTIONS:on.join(Lh.CUSTOM_FUNCTIONS,EO)},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"},hO="support@harperdb.io",sF="customer-success@harperdb.io",mO=1,iF=4141,pO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",oF="https://www.harperdb.io/product",aF=`For support, please submit a request at ${pO} or contact ${hO}`,SO=`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 ${mO} role. ${SO}`,_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",TO={SETTINGS_PATH_KEY:"settings_path"},gO=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"},RO={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=gO.invert(RO),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"},AO={settings_path:TO.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,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];AO[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"},OO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},pk=Symbol("metadata"),Sk="__clustering__",Tk=Object.values(OO),gk=15984864e5,bO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Rk=gO.invert(bO),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"};
|
|
3
|
-
`}a(Ss,"createLogRecord");function Ec(e){ms&&
|
|
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,kO)=>{"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",FO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},hV=Object.values(FO);kO.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:FO,TRANSACTIONS_DBIS:hV,OVERFLOW_MARKER:EV}});var Lr=R((lce,jO)=>{"use strict";var VO=M(),$O=ut(),YO={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},KO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),WO={500:KO("There was an error processing your request."),400:"Invalid request"},mV=WO[YO.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 ${$O.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${$O.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 ${VO.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 ${VO.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"},QO={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`},zO={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.`},JO={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={...QO,...TV,...pV,...AV,...OV,...bV,...NV,...yV,...RV,...zO,...JO,...IV,...wV,...SV};jO.exports={CHECK_LOGS_WRAPPER:KO,HDB_ERROR_MSGS:CV,DEFAULT_ERROR_MSGS:WO,DEFAULT_ERROR_RESP:mV,HTTP_STATUS_CODES:YO,LMDB_ERRORS_ENUM:gV,AUTHENTICATION_ERROR_MSGS:QO,VALIDATION_ERROR_MSGS:zO,ITC_ERRORS:JO}});var ne=R((dce,eb)=>{"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,XO),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 XO(e,t,r,n=LV.LOG_LEVELS.ERROR,s=null,i=!1){if(ZO(e))return e;let o=new i_(e,t,r,n,s);return i&&delete o.stack,o}a(XO,"handleHDBError");function ZO(e){return e.__proto__.constructor.name===i_.name}a(ZO,"isHDBError");eb.exports={isHDBError:ZO,handleHDBError:XO,ClientError:Fh,ServerError:kh,hdb_errors:ko}});var ze=R((Ece,ab)=>{"use strict";var Tc=M(),MV=Q(),or=Z(),gc=require("path"),UV=require("minimist"),tb=require("fs-extra"),rb=require("lodash");or.initSync();var{CONFIG_PARAMS:ei,DATABASES_PARAM_CONFIG:hc,SYSTEM_SCHEMA_NAME:o_}=Tc,mc,pc,Sc;function nb(){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(nb,"getBaseSchemaPath");function sb(){if(pc!==void 0)return pc;if(or.getHdbBasePath()!==void 0)return pc=ob(o_),pc}a(sb,"getSystemSchemaPath");function ib(){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(ib,"getTransactionAuditStoreBasePath");function PV(e,t){let r=or.get(ei.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||gc.join(ib(),e.toString())}a(PV,"getTransactionAuditStorePath");function ob(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(nb(),e)}a(ob,"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 rb.set(u,[o_,hc.TABLES,t,hc.PATH],_),or.setProperty(ei.DATABASES,u),_;let l=c?.[hc.PATH];if(l)return rb.set(u,[o_,hc.PATH],l),or.setProperty(ei.DATABASES,u),l}}let s=r[ei.STORAGE_PATH.toUpperCase()];if(s){if(!tb.pathExistsSync(s))throw new Error(s+" does not exist");let i=gc.join(s,e);return tb.mkdirsSync(i),or.setProperty(ei.STORAGE_PATH,s),i}return sb()}a(vV,"initSystemSchemaPaths");function BV(){mc=void 0,pc=void 0,Sc=void 0}a(BV,"resetPaths");ab.exports={getBaseSchemaPath:nb,getSystemSchemaPath:sb,getTransactionAuditStorePath:PV,getTransactionAuditStoreBasePath:ib,getSchemaPath:ob,initSystemSchemaPaths:vV,resetPaths:BV}});var Mr=R((Sce,db)=>{"use strict";var HV=Lr().LMDB_ERRORS_ENUM,mce=require("lmdb"),xV=ut(),pce=require("buffer").Buffer,{OVERFLOW_MARKER:cb,MAX_SEARCH_KEY_LENGTH:a_}=xV,ub=["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(ub.includes(typeof e))return e.length>a_?[e.slice(0,a_)+cb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(ub.includes(typeof i))i.length>a_?r.push(i.slice(0,a_)+cb):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,lb=0;function _b(){lb=Date.now()-performance.now()}a(_b,"adjustStartTime");_b();var VV=6e4;setInterval(_b,VV).unref();function $V(){let e=performance.now()+lb;return e>c_?(c_=e,e):(c_+=488e-6,c_)}a($V,"getNextMonotonicTime");db.exports={validateEnv:GV,stringifyData:qV,convertKeyValueToWrite:FV,getNextMonotonicTime:$V,getIndexedValues:kV}});var fb,bn,Vh,Rc=Re(()=>{fb=require("events"),bn=class extends fb.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 Bi={};qe(Bi,{server:()=>nt});var Eb,nt,ar=Re(()=>{Eb=require("../index"),nt={};(0,Eb._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,hb.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,hb,YV,KV,WV,mb=Re(()=>{$h=require("path");Ae();hb=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,Sb.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,pb.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 pb,Sb,QV,Ac,Wh=Re(()=>{Nn();Ae();pb=require("fs/promises"),Sb=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,Tb.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 Tb,Qh,gb=Re(()=>{Tb=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,Rb=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 wb={};qe(wb,{parse:()=>Zh,streamAsJSON:()=>Oc,stringify:()=>Hi});function Oc(e){return new Xh({value:e})}function Ab(e){return console.error(e),JSON.stringify(e.toString())}function Ob(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Hi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===yb)return Ib(e);if(t.resolution)return t.resolution.then(()=>Hi(e));throw t}}function Ib(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+=Ib(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Hi(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 bb,Nb,e$,t$,yb,Xh,r$,em=Re(()=>{bb=require("stream"),Nb=B(require("json-bigint-fixes")),e$=(0,Nb.default)({useNativeBigInt:!0}),t$=1e4,yb={};BigInt.prototype.toJSON=function(){throw yb};a(Oc,"streamAsJSON");Xh=class extends bb.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),Ab)}catch(s){yield Ab(s)}else yield Hi(t)}else yield Hi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Ob(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 Ob(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(Ab,"handleError");a(Ob,"when");a(Hi,"stringify");a(Ib,"jsStringify");r$=/[[,:]\s*-?\d{16,}/;a(Zh,"parse")});var Fb=R((Pce,qb)=>{"use strict";var tm=require("recursive-iterator"),n$=require("alasql"),rm=require("clone"),Cb=Q(),{handleHDBError:Db,hdb_errors:s$}=ne(),{HDB_ERROR_MSGS:Lb,HTTP_STATUS_CODES:Mb}=s$,{getDatabases:i$}=(Ae(),ie(Fe)),o$=["DISTINCT_ARRAY"],Ub=Symbol("validateTables"),nm=Symbol("validateTable"),Uce=Symbol("getAllColumns"),Pb=Symbol("validateAllColumns"),l_=Symbol("findColumn"),vb=Symbol("validateOrderBy"),bc=Symbol("validateSegment"),sm=Symbol("validateColumn"),Bb=Symbol("setColumnsForTable"),Hb=Symbol("checkColumnsForAsterisk"),xb=Symbol("validateGroupBy"),Gb=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[Ub](),this[Hb](),this[Pb]()}[Ub](){if(this[Gb]()){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)})}}[Gb](){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 Db(new Error,Lb.SCHEMA_NOT_FOUND(t.databaseid),Mb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Db(new Error,Lb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Mb.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)}[Hb](){let t=new tm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Bb](r.tableid)}[Bb](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}))})}[Pb](){this[bc](this.statement.columns,!1),this[bc](this.statement.joins,!1),this[bc](this.statement.where,!1),this[xb](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)!Cb.isEmpty(i)&&!Cb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[vb](i):s.push(this[sm](i)));return s}[xb](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`}[vb](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]}};qb.exports=im});var Vb=R((Bce,kb)=>{"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")}};kb.exports=om});var Yb=R((xce,$b)=>{"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}};$b.exports=am});var zb={};qe(zb,{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:()=>Wb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Qb,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,xi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<xi.length;u++){let _=xi[u].deref();(!_||_.isDone||_.isCommitted)&&xi.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|Qb:um:Vo=u?i?.localTime?lm|16384:Wb|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 Kb,cm,__,Ic,fm,a$,Nc,yc,c$,um,Wb,u$,Qb,lm,Em,hm,l$,d_,Vo,f_,_m,dm,xi,wc=Re(()=>{Kb=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,Wb=0,u$=1,Qb=3,lm=4,Em=16,hm=1,Vo=0,f_=-1,_m=0,dm=class extends Kb.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");xi=[];setInterval(()=>{for(let e=0;e<xi.length;e++){let t=xi[e].deref();!t||t.isDone||t.isCommitted?xi.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,jb)=>{"use strict";var Jb=Z(),d$=M(),{RecordEncoder:f$}=(wc(),ie(zb)),kce=require("fs");Jb.initSync();var E$=Jb.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$})}};jb.exports=pm});var Dc=R((Yce,Xb)=>{"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)}};Xb.exports=m_;m_.MAX_DBS=1e4});var Ke=R((Wce,cN)=>{"use strict";var Tm=require("lmdb"),yn=require("fs-extra"),vr=require("path"),p_=Mr(),tN=$(),cr=Lr().LMDB_ERRORS_ENUM,S_=Yb(),gm=Cc(),rN=Dc(),ri=ut(),Zb=M(),{table:h$,resetDatabases:m$}=(Ae(),ie(Fe)),eN=Z(),In=ri.INTERNAL_DBIS_NAME,nN=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=eN.get(Zb.CONFIG_PARAMS.DATABASES);i||eN.setProperty(Zb.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Rm(e,t,n),sN(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 rN(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 sN(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 rN(s,o),u=Tm.open(c);u.dbis=Object.create(null);let _=oN(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(sN,"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 iN(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 iN(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(iN,"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{tN.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(O$,"listDBIDefinitions");function oN(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(oN,"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{tN.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(b$,"getDBIDefinition");function aN(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[nN]=c,cn(e,In).putSync(t,c),e.dbis[t]=o,o}throw s}}a(aN,"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[nN]=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)aN(e,i,i!==t,i===t),n=!0;else throw o}}n&&m$()}a(w$,"initializeDBIs");cN.exports={openDBI:cn,openEnvironment:sN,createEnvironment:g$,listDBIs:oN,listDBIDefinitions:O$,createDBI:aN,dropDBI:I$,statDBI:N$,deleteEnvironment:A$,initializeDBIs:w$,TransactionCursor:Sm,environmentDataSize:y$,copyEnvironment:R$,closeEnvironment:iN}});var lN=R((zce,uN)=>{"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}};uN.exports=Om});var dN=R((jce,_N)=>{"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}};_N.exports=bm});var EN=R((Zce,fN)=>{"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}};fN.exports=Nm});var $o=R((sue,pN)=>{"use strict";var C$=Ke(),D$=lN(),L$=dN(),M$=EN(),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$,hN=Z();hN.initSync();var R_=hN.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),ym=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Gi=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];mN(_,!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[Gi])})}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 mN(e,t,r){let n=r>0;(n||!Number.isInteger(e[Gi]))&&(e[Gi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[ym]))&&(e[ym]=r||Wn.getNextMonotonicTime()):delete e[ym]}a(mN,"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(mN(r,!l,o),Number.isInteger(r[Gi])&&_[Gi]>r[Gi])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[Gi])},"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");pN.exports={insertRecords:x$,updateRecords:F$,upsertRecords:k$}});var qi=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,gN)=>{"use strict";var TN=Q(),SN=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 TN.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 TN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(J$,"validateTableExists");function j$(e,t){return e.toLowerCase()===SN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${SN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(j$,"validateSchemaName");gN.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,RN)=>{"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};RN.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,AN)=>{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");AN.exports={schema_object:t1,create_table_object:n1,table_object:r1,attribute_object:s1,describe_table:i1,validateTableResidence:o1}});var bN=R((fue,ON)=>{"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}`}};ON.exports=Lm});var b_=R((hue,NN)=>{"use strict";var c1=bN(),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}};NN.exports=Mm});var IN=R((pue,yN)=>{"use strict";yN.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,MN)=>{"use strict";var _1=M(),Um=Ke(),d1=$o(),{getSystemSchemaPath:f1,getSchemaPath:E1}=ze(),h1=qi(),m1=O_(),p1=b_(),S1=IN(),{handleHDBError:wN,hdb_errors:DN}=ne(),CN=Q(),{HTTP_STATUS_CODES:T1}=DN,Pm=h1.hdb_attribute,LN=[];for(let e=0;e<Pm.attributes.length;e++)LN.push(Pm.attributes[e].attribute);var g1="inserted";MN.exports=R1;async function R1(e){let t=m1.attribute_object(e);if(t)throw wN(new Error,t.message,DN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&CN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw wN(new Error,r,T1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=CN.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,LN,[s]);return S1(g1,c,{records:[s]},u)}catch(i){throw i}}a(R1,"lmdbCreateAttribute")});var Bm=R((Rue,PN)=>{var{hdb_table:A1,hdb_database:UN}=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:UN,schema:UN,table:A1,records:vm.array().items(vm.object().custom(N1)).required()});PN.exports=function(e){return O1.validateBySchema(e,y1)}});var Bc=R((bue,BN)=>{"use strict";var gs=Q(),vN=$(),Oue=Bm(),{getDatabases:I1}=(Ae(),ie(Fe)),{ClientError:Fi}=ne();BN.exports=w1;function w1(e){if(gs.isEmpty(e))throw new Fi("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new Fi("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new Fi("invalid table specified.");if(!Array.isArray(e.records))throw new Fi("records must be an array");let t=I1()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new Fi(`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 vN.error("a valid hash attribute must be provided with update record:",o),new Fi("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 vN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Fi(`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,HN)=>{"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}};HN.exports=Hm});var xc=R((Cue,GN)=>{"use strict";var wue=Hc(),y_=M(),xm=Q(),xN=$(),D1=require("uuid"),{handleHDBError:I_,hdb_errors:L1}=ne(),{HDB_ERROR_MSGS:w_,HTTP_STATUS_CODES:C_}=L1;GN.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 xN.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 xN.error(e),I_(new Error,w_.HASH_VAL_LENGTH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}a(P1,"validateHash")});var FN=R((Lue,qN)=>{"use strict";var Gm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};qN.exports=Gm});var $N=R((Uue,VN)=>{"use strict";var qm=Ke(),v1=$(),kN=Lr().LMDB_ERRORS_ENUM;VN.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!==kN.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!==kN.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,QN)=>{"use strict";var Gc=require("crypto"),H1=Z(),{CONFIG_PARAMS:x1}=M(),KN="aes-256-cbc",G1=32,q1=16,Fm=64,WN=32,F1=Fm+WN,YN=new Map;QN.exports={encrypt:k1,decrypt:V1,createNatsTableStreamName:$1};function k1(e){let t=Gc.randomBytes(G1),r=Gc.randomBytes(q1),n=Gc.createCipheriv(KN,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,WN),n=e.substr(F1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Gc.createDecipheriv(KN,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=YN.get(r);return n||(n=Gc.createHash("md5").update(r).digest("hex"),YN.set(r,n)),n}a($1,"createNatsTableStreamName")});var As=R((xue,JN)=>{"use strict";var Hue=Br(),D_=$(),zN=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));JN.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=zN.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=zN.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,ty)=>{var J1=qi(),{callbackify:XN,promisify:j1}=require("util"),{getDatabases:ZN}=(Ae(),ie(Fe));ty.exports={setSchemaDataToGlobal:jN,getTableSchema:X1,getSystemSchema:Z1,setSchemaDataToGlobalAsync:j1(jN)};var ey=As(),que=XN(ey.describeAll),Fue=XN(ey.describeTable);function jN(e){global.hdb_schema=ZN(),e&&e()}a(jN,"setSchemaDataToGlobal");function X1(e,t,r){let n=ZN()[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,iy)=>{"use strict";var B_=Bm(),Vt=Q(),eY=require("util"),H_=wn(),tY=Os(),ry=$(),{handleHDBError:ki,hdb_errors:rY}=ne(),{HTTP_STATUS_CODES:Vi}=rY,nY=eY.promisify(tY.getTableSchema),sY="updated",ny="inserted",sy="upserted";iy.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 ry.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 ry.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 ki(new Error,t.message,Vi.BAD_REQUEST);Vt.transformReq(e);let r=Vt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await H_.createRecords(e);return v_(ny,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 ki(new Error,t.message,Vi.BAD_REQUEST);Vt.transformReq(e);let r=Vt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.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 ki(new Error,"invalid operation, must be upsert",Vi.INTERNAL_SERVER_ERROR);let t=B_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);Vt.transformReq(e);let r=Vt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await H_.upsertRecords(e);return v_(sy,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===ny?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===sy?(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,cy)=>{var lY=je(),$m=require("joi"),{hdb_table:_Y,hdb_database:oy}=zn(),ay={schema:oy,database:oy,table:_Y},dY={date:$m.date().iso().required()},fY={timestamp:$m.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};cy.exports=function(e,t){let r=t==="timestamp"?{...ay,...fY}:{...ay,...dY},n=$m.object(r);return lY.validateBySchema(e,n)}});var _y=R((Wue,ly)=>{var EY=je(),Km=require("joi"),{hdb_table:hY,hdb_database:uy}=zn(),mY=Km.object({schema:uy,database:uy,table:hY,hash_values:Km.array().required(),ids:Km.array()});ly.exports=function(e){return EY.validateBySchema(e,mY)}});var fy=R((Que,dy)=>{"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=[]}};dy.exports={InsertObject:Wm,NoSQLSeachObject:Qm,DeleteResponseObject:zm}});var oi=R((Jue,Sy)=>{"use strict";var hy=Ym(),pY=_y(),$i=Q(),Ey=require("moment"),my=$(),{promisify:SY,callbackify:TY}=require("util"),Yi=M(),gY=Os(),Jm=SY(gY.getTableSchema),jm=wn(),{DeleteResponseObject:RY}=fy(),{handleHDBError:si,hdb_errors:AY}=ne(),{HDB_ERROR_MSGS:x_,HTTP_STATUS_CODES:ii}=AY,OY="records successfully deleted",bY=TY(py);Sy.exports={delete:bY,deleteRecord:py,deleteFilesBefore:NY,deleteAuditLogsBefore:yY};async function NY(e){let t=hy(e,"date");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if($i.transformReq(e),!Ey(e.date,Ey.ISO_8601).isValid())throw si(new Error,x_.INVALID_DATE,ii.BAD_REQUEST,Yi.LOG_LEVELS.ERROR,x_.INVALID_DATE,!0);let n=$i.checkSchemaTableExist(e.schema,e.table);if(n)throw si(new Error,n,ii.NOT_FOUND,Yi.LOG_LEVELS.ERROR,n,!0);let s=await jm.deleteRecordsBefore(e);if(await Jm(e.schema,e.table),my.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(NY,"deleteFilesBefore");async function yY(e){let t=hy(e,"timestamp");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if($i.transformReq(e),isNaN(e.timestamp))throw si(new Error,x_.INVALID_VALUE("Timestamp"),ii.BAD_REQUEST,Yi.LOG_LEVELS.ERROR,x_.INVALID_VALUE("Timestamp"),!0);let r=$i.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Yi.LOG_LEVELS.ERROR,r,!0);let n=await jm.deleteAuditLogsBefore(e);return await Jm(e.schema,e.table),my.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(yY,"deleteAuditLogsBefore");async function py(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);$i.transformReq(e);let r=$i.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Yi.LOG_LEVELS.ERROR,r,!0);try{await Jm(e.schema,e.table);let n=await jm.deleteRecords(e);return $i.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${OY}`),n}catch(n){if(n.message===Yi.SEARCH_NOT_FOUND_MESSAGE){let s=new RY;return s.message=Yi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(py,"deleteRecord")});var G_=R((Xue,Ry)=>{var IY=require("crypto"),Ty=9;function wY(e){let t=DY(Ty),r=gy(e+t);return t+r}a(wY,"createHash");function CY(e,t){let r=e?.substr(0,Ty),n=r+gy(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 gy(e){return IY.createHash("md5").update(e).digest("hex")}a(gy,"md5");Ry.exports={hash:wY,validate:CY}});var Oy=R((ele,Ay)=>{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");Ay.exports={addUserValidation:LY,alterUserValidation:MY,dropUserValidation:UY}});var ke=R((nle,Ny)=>{"use strict";var{platform:rle}=require("os"),PY="nats-server.zip",Zm="nats-server",vY=process.platform==="win32"?`${Zm}.exe`:Zm,BY=/^[^\s.,*>]+$/,by="__request__",HY=a(e=>`${e}.${by}`,"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"};Ny.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:by,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 Iy=R((ile,yy)=>{"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 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})},uO=(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)):{},uO(t||!e||!e.__esModule?ac(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>uO(ac({},"__esModule",{value:!0}),e);var dO=R((Xae,_O)=>{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:lO}=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=_O.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=lO(On,n[0]),o;i.startsWith(cc)?o=Xs(On,lO(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,yO)=>{"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(),fO="js",Xl=fO,Fq="harperdb-config.yaml",kq="defaultConfig.yaml",Vq="hdb",EO=`harperdb.${Xl}`,hO=`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,EO),CUSTOM_FUNCTIONS:on.join(Lh.CUSTOM_FUNCTIONS,hO)},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"},mO="support@harperdb.io",sF="customer-success@harperdb.io",pO=1,iF=4141,SO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",oF="https://www.harperdb.io/product",aF=`For support, please submit a request at ${SO} or contact ${mO}`,TO=`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 ${pO} role. ${TO}`,_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",gO={SETTINGS_PATH_KEY:"settings_path"},RO=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"},AO={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=RO.invert(AO),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"},OO={settings_path:gO.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,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];OO[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"},bO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},pk=Symbol("metadata"),Sk="__clustering__",Tk=Object.values(bO),gk=15984864e5,NO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Rk=RO.invert(NO),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"};yO.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:mO,HDB_SUPPORT_URL:SO,HDB_PRICING_URL:oF,SUPPORT_HELP_MSG:aF,LICENSE_HELP_MSG:TO,HDB_PROC_NAME:EO,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:AO,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:bO,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:pO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:iF,VALUE_SEARCH_COMPARATORS:NO,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:fO,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:hO,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:OO,CONFIG_PARAMS:w,HDB_CONFIG_FILE:Fq,HDB_DEFAULT_CONFIG_FILE:kq,ROLE_TYPES_ENUM:nF,BOOT_PROP_PARAMS:gO,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};dO()});var Uh=R((nce,CO)=>{"use strict";var IO=require("minimist");CO.exports=xk;function xk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=wO(process.env),n=wO(IO(process.argv))):(r=process.env,n=IO(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 wO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(wO,"objKeysToLowerCase")});var $=R((ice,qh)=>{"use strict";var Bi=require("fs-extra"),{workerData:Gk,threadId:qk}=require("worker_threads"),ps=require("path"),MO=require("yaml"),UO=require("properties-reader"),mt=M(),DO=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},PO={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&&vO();qh.exports={notify:xO,fatal:GO,error:fc,warn:Gh,info:n_,debug:xh,trace:Hh,setLogLevel:Xk,log_level:sr,loggerWithTag:Kk,suppressLogging:Wk,initLogSettings:vO,setupConsoleLogging:BO,logCustomLevel:Jk,closeLogFile:Bh,getLogFilePath:()=>dc,OUTPUTS:PO,AuthAuditLog:tV};kk("logger",qh.exports);function vO(e=!1){try{if(lc===void 0||e){Bh();let t=jk(),r=DO(["ROOTPATH"]);try{lc=UO(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=DO(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=LO(ms),Kn=Kn===void 0?i:Kn,Kn=LO(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),BO()}a(vO,"initLogSettings");var Ph=!0;function BO(){qo("error",fc),qo("warn",Gh),qo("log",n_),qo("info",n_),qo("debug",xh),qo("trace",Hh)}a(BO,"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(xO),fatal:r(GO),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&&HO(e),Kn&&process.stdout.write(e)}a(Ec,"logStdOut");function s_(e){ms&&HO(e),Kn&&process.stderr.write(e)}a(s_,"logStdErr");function HO(e){zk(),Fo?Bi.appendFileSync(Fo,e):_c.log(e)}a(HO,"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 xO(...e){ir[sr]<=ir.notify&&Ec(Ss("notify",e))}a(xO,"notify");function GO(...e){ir[sr]<=ir.fatal&&s_(Ss("fatal",e))}a(GO,"fatal");function Gh(...e){ir[sr]<=ir.warn&&s_(Ss("warn",e))}a(Gh,"warn");function Jk(e,t,...r){t===PO.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 LO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(LO,"autoCastBoolean");function Zk(e){try{if(e.includes("config/settings.js")){let o=UO(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=MO.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=MO.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 FO=R((ace,qO)=>{"use strict";var rV=require("util"),nV=require("path"),sV=require("child_process"),iV=rV.promisify(sV.execFile),oV=1e3*1e3*10;qO.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,VO)=>{"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",kO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},hV=Object.values(kO);VO.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:kO,TRANSACTIONS_DBIS:hV,OVERFLOW_MARKER:EV}});var Lr=R((lce,XO)=>{"use strict";var $O=M(),YO=ut(),KO={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},WO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),QO={500:WO("There was an error processing your request."),400:"Invalid request"},mV=QO[KO.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 ${YO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${YO.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 ${$O.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 ${$O.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"},zO={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.`},jO={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={...zO,...TV,...pV,...AV,...OV,...bV,...NV,...yV,...RV,...JO,...jO,...IV,...wV,...SV};XO.exports={CHECK_LOGS_WRAPPER:WO,HDB_ERROR_MSGS:CV,DEFAULT_ERROR_MSGS:QO,DEFAULT_ERROR_RESP:mV,HTTP_STATUS_CODES:KO,LMDB_ERRORS_ENUM:gV,AUTHENTICATION_ERROR_MSGS:zO,VALIDATION_ERROR_MSGS:JO,ITC_ERRORS:jO}});var ne=R((dce,tb)=>{"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,ZO),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 ZO(e,t,r,n=LV.LOG_LEVELS.ERROR,s=null,i=!1){if(eb(e))return e;let o=new i_(e,t,r,n,s);return i&&delete o.stack,o}a(ZO,"handleHDBError");function eb(e){return e.__proto__.constructor.name===i_.name}a(eb,"isHDBError");tb.exports={isHDBError:eb,handleHDBError:ZO,ClientError:Fh,ServerError:kh,hdb_errors:ko}});var ze=R((Ece,cb)=>{"use strict";var Tc=M(),MV=Q(),or=Z(),gc=require("path"),UV=require("minimist"),rb=require("fs-extra"),nb=require("lodash");or.initSync();var{CONFIG_PARAMS:ei,DATABASES_PARAM_CONFIG:hc,SYSTEM_SCHEMA_NAME:o_}=Tc,mc,pc,Sc;function sb(){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(sb,"getBaseSchemaPath");function ib(){if(pc!==void 0)return pc;if(or.getHdbBasePath()!==void 0)return pc=ab(o_),pc}a(ib,"getSystemSchemaPath");function ob(){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(ob,"getTransactionAuditStoreBasePath");function PV(e,t){let r=or.get(ei.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||gc.join(ob(),e.toString())}a(PV,"getTransactionAuditStorePath");function ab(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(sb(),e)}a(ab,"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 nb.set(u,[o_,hc.TABLES,t,hc.PATH],_),or.setProperty(ei.DATABASES,u),_;let l=c?.[hc.PATH];if(l)return nb.set(u,[o_,hc.PATH],l),or.setProperty(ei.DATABASES,u),l}}let s=r[ei.STORAGE_PATH.toUpperCase()];if(s){if(!rb.pathExistsSync(s))throw new Error(s+" does not exist");let i=gc.join(s,e);return rb.mkdirsSync(i),or.setProperty(ei.STORAGE_PATH,s),i}return ib()}a(vV,"initSystemSchemaPaths");function BV(){mc=void 0,pc=void 0,Sc=void 0}a(BV,"resetPaths");cb.exports={getBaseSchemaPath:sb,getSystemSchemaPath:ib,getTransactionAuditStorePath:PV,getTransactionAuditStoreBasePath:ob,getSchemaPath:ab,initSystemSchemaPaths:vV,resetPaths:BV}});var Mr=R((Sce,fb)=>{"use strict";var HV=Lr().LMDB_ERRORS_ENUM,mce=require("lmdb"),xV=ut(),pce=require("buffer").Buffer,{OVERFLOW_MARKER:ub,MAX_SEARCH_KEY_LENGTH:a_}=xV,lb=["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(lb.includes(typeof e))return e.length>a_?[e.slice(0,a_)+ub]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(lb.includes(typeof i))i.length>a_?r.push(i.slice(0,a_)+ub):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,_b=0;function db(){_b=Date.now()-performance.now()}a(db,"adjustStartTime");db();var VV=6e4;setInterval(db,VV).unref();function $V(){let e=performance.now()+_b;return e>c_?(c_=e,e):(c_+=488e-6,c_)}a($V,"getNextMonotonicTime");fb.exports={validateEnv:GV,stringifyData:qV,convertKeyValueToWrite:FV,getNextMonotonicTime:$V,getIndexedValues:kV}});var Eb,bn,Vh,Rc=Re(()=>{Eb=require("events"),bn=class extends Eb.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 hb,nt,ar=Re(()=>{hb=require("../index"),nt={};(0,hb._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,mb.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,mb,YV,KV,WV,pb=Re(()=>{$h=require("path");Ae();mb=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,Tb.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,Sb.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 Sb,Tb,QV,Ac,Wh=Re(()=>{Nn();Ae();Sb=require("fs/promises"),Tb=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,gb.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 gb,Qh,Rb=Re(()=>{gb=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,Ab=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 Cb={};qe(Cb,{parse:()=>Zh,streamAsJSON:()=>Oc,stringify:()=>xi});function Oc(e){return new Xh({value:e})}function Ob(e){return console.error(e),JSON.stringify(e.toString())}function bb(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===Ib)return wb(e);if(t.resolution)return t.resolution.then(()=>xi(e));throw t}}function wb(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+=wb(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 Nb,yb,e$,t$,Ib,Xh,r$,em=Re(()=>{Nb=require("stream"),yb=B(require("json-bigint-fixes")),e$=(0,yb.default)({useNativeBigInt:!0}),t$=1e4,Ib={};BigInt.prototype.toJSON=function(){throw Ib};a(Oc,"streamAsJSON");Xh=class extends Nb.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),Ob)}catch(s){yield Ob(s)}else yield xi(t)}else yield xi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);bb(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 bb(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(Ob,"handleError");a(bb,"when");a(xi,"stringify");a(wb,"jsStringify");r$=/[[,:]\s*-?\d{16,}/;a(Zh,"parse")});var kb=R((Pce,Fb)=>{"use strict";var tm=require("recursive-iterator"),n$=require("alasql"),rm=require("clone"),Db=Q(),{handleHDBError:Lb,hdb_errors:s$}=ne(),{HDB_ERROR_MSGS:Mb,HTTP_STATUS_CODES:Ub}=s$,{getDatabases:i$}=(Ae(),ie(Fe)),o$=["DISTINCT_ARRAY"],Pb=Symbol("validateTables"),nm=Symbol("validateTable"),Uce=Symbol("getAllColumns"),vb=Symbol("validateAllColumns"),l_=Symbol("findColumn"),Bb=Symbol("validateOrderBy"),bc=Symbol("validateSegment"),sm=Symbol("validateColumn"),Hb=Symbol("setColumnsForTable"),xb=Symbol("checkColumnsForAsterisk"),Gb=Symbol("validateGroupBy"),qb=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[Pb](),this[xb](),this[vb]()}[Pb](){if(this[qb]()){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)})}}[qb](){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 Lb(new Error,Mb.SCHEMA_NOT_FOUND(t.databaseid),Ub.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Lb(new Error,Mb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Ub.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)}[xb](){let t=new tm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Hb](r.tableid)}[Hb](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}))})}[vb](){this[bc](this.statement.columns,!1),this[bc](this.statement.joins,!1),this[bc](this.statement.where,!1),this[Gb](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)!Db.isEmpty(i)&&!Db.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Bb](i):s.push(this[sm](i)));return s}[Gb](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`}[Bb](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]}};Fb.exports=im});var $b=R((Bce,Vb)=>{"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")}};Vb.exports=om});var Kb=R((xce,Yb)=>{"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}};Yb.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:()=>Qb,TIMESTAMP_ASSIGN_PREVIOUS:()=>zb,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|zb:um:Vo=u?i?.localTime?lm|16384:Qb|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 Wb,cm,__,Ic,fm,a$,Nc,yc,c$,um,Qb,u$,zb,lm,Em,hm,l$,d_,Vo,f_,_m,dm,Gi,wc=Re(()=>{Wb=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,Qb=0,u$=1,zb=3,lm=4,Em=16,hm=1,Vo=0,f_=-1,_m=0,dm=class extends Wb.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,Xb)=>{"use strict";var jb=Z(),d$=M(),{RecordEncoder:f$}=(wc(),ie(Jb)),kce=require("fs");jb.initSync();var E$=jb.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$})}};Xb.exports=pm});var Dc=R((Yce,Zb)=>{"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)}};Zb.exports=m_;m_.MAX_DBS=1e4});var Ke=R((Wce,uN)=>{"use strict";var Tm=require("lmdb"),yn=require("fs-extra"),vr=require("path"),p_=Mr(),rN=$(),cr=Lr().LMDB_ERRORS_ENUM,S_=Kb(),gm=Cc(),nN=Dc(),ri=ut(),eN=M(),{table:h$,resetDatabases:m$}=(Ae(),ie(Fe)),tN=Z(),In=ri.INTERNAL_DBIS_NAME,sN=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=tN.get(eN.CONFIG_PARAMS.DATABASES);i||tN.setProperty(eN.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Rm(e,t,n),iN(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 nN(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 iN(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 nN(s,o),u=Tm.open(c);u.dbis=Object.create(null);let _=aN(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(iN,"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 oN(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 oN(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(oN,"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{rN.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(O$,"listDBIDefinitions");function aN(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(aN,"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{rN.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(b$,"getDBIDefinition");function cN(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[sN]=c,cn(e,In).putSync(t,c),e.dbis[t]=o,o}throw s}}a(cN,"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[sN]=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)cN(e,i,i!==t,i===t),n=!0;else throw o}}n&&m$()}a(w$,"initializeDBIs");uN.exports={openDBI:cn,openEnvironment:iN,createEnvironment:g$,listDBIs:aN,listDBIDefinitions:O$,createDBI:cN,dropDBI:I$,statDBI:N$,deleteEnvironment:A$,initializeDBIs:w$,TransactionCursor:Sm,environmentDataSize:y$,copyEnvironment:R$,closeEnvironment:oN}});var _N=R((zce,lN)=>{"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}};lN.exports=Om});var fN=R((jce,dN)=>{"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}};dN.exports=bm});var hN=R((Zce,EN)=>{"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}};EN.exports=Nm});var $o=R((sue,SN)=>{"use strict";var C$=Ke(),D$=_N(),L$=fN(),M$=hN(),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$,mN=Z();mN.initSync();var R_=mN.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];pN(_,!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 pN(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(pN,"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(pN(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");SN.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,RN)=>{"use strict";var gN=Q(),TN=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 gN.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 gN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(J$,"validateTableExists");function j$(e,t){return e.toLowerCase()===TN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${TN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(j$,"validateSchemaName");RN.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,AN)=>{"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};AN.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,ON)=>{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");ON.exports={schema_object:t1,create_table_object:n1,table_object:r1,attribute_object:s1,describe_table:i1,validateTableResidence:o1}});var NN=R((fue,bN)=>{"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}`}};bN.exports=Lm});var b_=R((hue,yN)=>{"use strict";var c1=NN(),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}};yN.exports=Mm});var wN=R((pue,IN)=>{"use strict";IN.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,UN)=>{"use strict";var _1=M(),Um=Ke(),d1=$o(),{getSystemSchemaPath:f1,getSchemaPath:E1}=ze(),h1=Fi(),m1=O_(),p1=b_(),S1=wN(),{handleHDBError:CN,hdb_errors:LN}=ne(),DN=Q(),{HTTP_STATUS_CODES:T1}=LN,Pm=h1.hdb_attribute,MN=[];for(let e=0;e<Pm.attributes.length;e++)MN.push(Pm.attributes[e].attribute);var g1="inserted";UN.exports=R1;async function R1(e){let t=m1.attribute_object(e);if(t)throw CN(new Error,t.message,LN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&DN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw CN(new Error,r,T1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=DN.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,MN,[s]);return S1(g1,c,{records:[s]},u)}catch(i){throw i}}a(R1,"lmdbCreateAttribute")});var Bm=R((Rue,vN)=>{var{hdb_table:A1,hdb_database:PN}=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:PN,schema:PN,table:A1,records:vm.array().items(vm.object().custom(N1)).required()});vN.exports=function(e){return O1.validateBySchema(e,y1)}});var Bc=R((bue,HN)=>{"use strict";var gs=Q(),BN=$(),Oue=Bm(),{getDatabases:I1}=(Ae(),ie(Fe)),{ClientError:ki}=ne();HN.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 BN.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 BN.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,xN)=>{"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}};xN.exports=Hm});var xc=R((Cue,qN)=>{"use strict";var wue=Hc(),y_=M(),xm=Q(),GN=$(),D1=require("uuid"),{handleHDBError:I_,hdb_errors:L1}=ne(),{HDB_ERROR_MSGS:w_,HTTP_STATUS_CODES:C_}=L1;qN.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 GN.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 GN.error(e),I_(new Error,w_.HASH_VAL_LENGTH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}a(P1,"validateHash")});var kN=R((Lue,FN)=>{"use strict";var Gm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};FN.exports=Gm});var YN=R((Uue,$N)=>{"use strict";var qm=Ke(),v1=$(),VN=Lr().LMDB_ERRORS_ENUM;$N.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!==VN.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!==VN.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,zN)=>{"use strict";var Gc=require("crypto"),H1=Z(),{CONFIG_PARAMS:x1}=M(),WN="aes-256-cbc",G1=32,q1=16,Fm=64,QN=32,F1=Fm+QN,KN=new Map;zN.exports={encrypt:k1,decrypt:V1,createNatsTableStreamName:$1};function k1(e){let t=Gc.randomBytes(G1),r=Gc.randomBytes(q1),n=Gc.createCipheriv(WN,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,QN),n=e.substr(F1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Gc.createDecipheriv(WN,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=KN.get(r);return n||(n=Gc.createHash("md5").update(r).digest("hex"),KN.set(r,n)),n}a($1,"createNatsTableStreamName")});var As=R((xue,jN)=>{"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));jN.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,ry)=>{var J1=Fi(),{callbackify:ZN,promisify:j1}=require("util"),{getDatabases:ey}=(Ae(),ie(Fe));ry.exports={setSchemaDataToGlobal:XN,getTableSchema:X1,getSystemSchema:Z1,setSchemaDataToGlobalAsync:j1(XN)};var ty=As(),que=ZN(ty.describeAll),Fue=ZN(ty.describeTable);function XN(e){global.hdb_schema=ey(),e&&e()}a(XN,"setSchemaDataToGlobal");function X1(e,t,r){let n=ey()[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,oy)=>{"use strict";var B_=Bm(),Vt=Q(),eY=require("util"),H_=wn(),tY=Os(),ny=$(),{handleHDBError:Vi,hdb_errors:rY}=ne(),{HTTP_STATUS_CODES:$i}=rY,nY=eY.promisify(tY.getTableSchema),sY="updated",sy="inserted",iy="upserted";oy.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 ny.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 ny.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_(sy,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_(iy,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===sy?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===iy?(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,uy)=>{var lY=je(),$m=require("joi"),{hdb_table:_Y,hdb_database:ay}=zn(),cy={schema:ay,database:ay,table:_Y},dY={date:$m.date().iso().required()},fY={timestamp:$m.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};uy.exports=function(e,t){let r=t==="timestamp"?{...cy,...fY}:{...cy,...dY},n=$m.object(r);return lY.validateBySchema(e,n)}});var dy=R((Wue,_y)=>{var EY=je(),Km=require("joi"),{hdb_table:hY,hdb_database:ly}=zn(),mY=Km.object({schema:ly,database:ly,table:hY,hash_values:Km.array().required(),ids:Km.array()});_y.exports=function(e){return EY.validateBySchema(e,mY)}});var Ey=R((Que,fy)=>{"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=[]}};fy.exports={InsertObject:Wm,NoSQLSeachObject:Qm,DeleteResponseObject:zm}});var oi=R((Jue,Ty)=>{"use strict";var my=Ym(),pY=dy(),Yi=Q(),hy=require("moment"),py=$(),{promisify:SY,callbackify:TY}=require("util"),Ki=M(),gY=Os(),Jm=SY(gY.getTableSchema),jm=wn(),{DeleteResponseObject:RY}=Ey(),{handleHDBError:si,hdb_errors:AY}=ne(),{HDB_ERROR_MSGS:x_,HTTP_STATUS_CODES:ii}=AY,OY="records successfully deleted",bY=TY(Sy);Ty.exports={delete:bY,deleteRecord:Sy,deleteFilesBefore:NY,deleteAuditLogsBefore:yY};async function NY(e){let t=my(e,"date");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!hy(e.date,hy.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),py.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(NY,"deleteFilesBefore");async function yY(e){let t=my(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),py.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(yY,"deleteAuditLogsBefore");async function Sy(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(Sy,"deleteRecord")});var G_=R((Xue,Ay)=>{var IY=require("crypto"),gy=9;function wY(e){let t=DY(gy),r=Ry(e+t);return t+r}a(wY,"createHash");function CY(e,t){let r=e?.substr(0,gy),n=r+Ry(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 Ry(e){return IY.createHash("md5").update(e).digest("hex")}a(Ry,"md5");Ay.exports={hash:wY,validate:CY}});var by=R((ele,Oy)=>{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");Oy.exports={addUserValidation:LY,alterUserValidation:MY,dropUserValidation:UY}});var ke=R((nle,yy)=>{"use strict";var{platform:rle}=require("os"),PY="nats-server.zip",Zm="nats-server",vY=process.platform==="win32"?`${Zm}.exe`:Zm,BY=/^[^\s.,*>]+$/,Ny="__request__",HY=a(e=>`${e}.${Ny}`,"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"};yy.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:Ny,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 wy=R((ile,Iy)=>{"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";yy.exports={CERTIFICATE_VALUES:WY,CERTIFICATE_PEM_NAME:QY,PRIVATEKEY_PEM_NAME:zY,CA_PEM_NAME:JY}});var tp=R((ale,Uy)=>{"use strict";var Ly=require("fs-extra"),oe=require("joi"),jY=require("os"),{boolean:be,string:lr,number:Ze,array:ep}=oe.types(),{totalmem:wy}=require("os"),Ki=require("path"),XY=$(),q_=Q(),ole=Iy(),Cy=M(),ZY=je(),Dy="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",Wi=Ze.min(0).required(),F_=ep.items({host:lr.required(),port:Wi}).empty(null),jn,My=!1;Uy.exports={configValidator:aK,routesValidator:fK,route_constraints:F_};function aK(e,t=!1){if(My=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:Wi,routes:F_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:Wi}).required()}).required(),network:oe.object({port:Wi}).required()}).required(),leafServer:oe.object({network:oe.object({port:Wi,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:Wi,securePort:Wi,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 My||Ly.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?.()||wy();return i=Math.round(Math.min(i,wy())/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 Ki.join(jn,eK);case"logging.root":return Ki.join(jn,Dy);case"clustering.leafServer.streams.path":return Ki.join(jn,"clustering","leaf");case"storage.path":let n=Ki.join(jn,Cy.LEGACY_DATABASES_DIR_NAME);return Ly.existsSync(n)?n:Ki.join(jn,Cy.DATABASES_DIR_NAME);case"logging.rotation.path":return Ki.join(jn,Dy);case"operationsApi.network.domainSocket":return r==null?null:Ki.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,ky)=>{"use strict";var Gr=M(),Pt=Q(),Nt=$(),{configValidator:EK,routesValidator:Py}=tp(),_r=require("fs-extra"),hK=require("yaml"),Cn=require("path"),mK=require("is-number"),By=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(Bi)),{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",Hy=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.",vy={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,$_;ky.exports={createConfigFile:yK,getDefaultConfig:IK,getConfigValue:Gy,initConfig:np,flattenConfig:Wo,updateConfigValue:qy,updateConfigObject:CK,getConfiguration:MK,setConfiguration:UK,readConfigFile:ip,getClusteringRoutes:PK,initOldConfig:Fy,getConfigFromFile:vK,getConfigFilePath:Qi,addConfig:BK,deleteConfigFromFile:HK,getConfigObj:xK};function yK(e,t=!1){let r=ai(Hy);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&&xy(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 xy(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(xy,"setSchemasConfig");function IK(e){if(V_===void 0){let r=ai(Hy);V_=Wo(r.toJSON())}let t=Dn[e.toLowerCase()];if(t!==void 0)return V_[t.toLowerCase()]}a(IK,"getDefaultConfig");function Gy(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(Gy,"getConfigValue");function Qi(e=Pt.getPropsFilePath()){let t=Pt.getEnvCliRootPath();return t?Cn.join(t,Gr.HDB_CONFIG_FILE):By(e).get(Gr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Qi,"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=Qi(t),n;if(r.includes("config/settings.js"))try{Fy(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 vy)yt[i]&&Nt.error(`Config ${vy[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 qy(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&np();let o=Gy(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)}}}_&&xy(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(qy,"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=Qi(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 qy(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=Qi(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=Py(t);if(r)throw k_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Pt.isEmptyOrZeroLength(n)?[]:n;let s=Py(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 Fy(e){let t=By(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(Fy,"initOldConfig");function vK(e){let t=ip();return pK.get(t,e.replaceAll("_","."))}a(vK,"getConfigFromFile");async function BK(e,t){let r=ai(Qi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await _r.writeFile(Qi(),String(r))}a(BK,"addConfig");function HK(e){let t=Qi(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 $y=R((dle,Vy)=>{"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}};Vy.exports={BaseLicense:K_,ExtendedLicense:op}});var zi=R((Ele,Jy)=>{"use strict";var zo=require("fs-extra"),Ky=G_(),Wy=require("crypto"),GK=require("moment"),qK=require("uuid").v4,jt=$(),cp=require("path"),FK=Q(),ci=M(),{totalmem:Yy}=require("os"),kK=$y().ExtendedLicense,Qo="invalid license key format",VK="061183",$K="mofi25",YK="aes-256-cbc",KK=16,WK=32,Qy=Z();Qy.initSync();var ap;Jy.exports={validateLicense:zy,generateFingerPrint:zK,licenseSearch:_p,getLicense:XK,checkMemoryLimit:ZK};function up(){return cp.join(Qy.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=Ky.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 zy(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),_=Wy.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),Ky.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(zy,"validateLicense");function jK(e,t){try{let r=Wy.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=zy(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?.()||Yy();if(t=Math.round(Math.min(t,Yy())/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,dI)=>{"use strict";var eI="username is required",tI="nothing to update, must supply active, role or password to update",rI="password cannot be an empty string",nI="If role is specified, it cannot be empty.",sI="active must be true or false";dI.exports={addUser:cW,alterUser:uW,dropUser:_W,getSuperUser:hW,userInfo:dW,listUsers:Q_,listUsersExternal:fW,setUsersToGlobal:jo,findAndValidateUser:lI,getClusterUser:mW,USERNAME_REQUIRED:eI,ALTERUSER_NOTHING_TO_UPDATE:tI,EMPTY_PASSWORD:rI,EMPTY_ROLE:nI,ACTIVE_BOOLEAN:sI};var iI=Hr(),eW=oi(),Ep=G_(),oI=Oy(),aI=Br(),hp=bs(),qr=Q(),cI=require("validate.js"),Oe=$(),{promisify:tW}=require("util"),mp=Rs(),jy=M(),Xy=ke(),rW=dr(),mle=Z(),ple=zi(),nW=qi(),{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(Bi)),iW=$();Sp.getUser=(e,t)=>lI(e,t,t!=null);var uI={username:!0,active:!0,role:!0,password:!0},Zy=new Map,W_=aI.searchByValue,oW=aI.searchByHash,aW=tW(eW.delete);async function cW(e){let t=cI.cleanAttributes(e,uI),r=oI.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 iI.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=cI.cleanAttributes(e,uI);if(qr.isEmptyOrZeroLength(t.username))throw new Error(eI);if(qr.isEmptyOrZeroLength(t.password)&&qr.isEmptyOrZeroLength(t.role)&&qr.isEmptyOrZeroLength(t.active))throw new Error(tI);if(!qr.isEmpty(t.password)&&qr.isEmptyOrZeroLength(t.password.trim()))throw new Error(rI);if(!qr.isEmpty(t.active)&&!qr.isBoolean(t.active))throw new Error(sI);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(nI);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 iI.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=oI.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 lI(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(Zy.get(t)===n.password)return s;if(Ep.validate(n.password,t))Zy.set(t,n.password);else throw Xn(new Error,dp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(lI,"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(jy.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!qr.isEmpty(r)&&r?.role?.role===jy.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+Xy.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+Xy.SERVER_SUFFIX.ADMIN,r}a(mW,"getClusterUser");var _I=[];Sp.invalidateUser=function(e){for(let t of _I)try{t(e)}catch(r){iW.error("Error invalidating user",r)}};Sp.onInvalidatedUser=function(e){_I.push(e)}});var Vc=R((Ole,mI)=>{"use strict";var Ji=$(),Fr=M(),pW=$N(),Rle=Os(),Ale=As(),SW=un(),{validateEvent:fI}=Ln(),kc=wn(),TW=require("process"),{resetDatabases:gW}=(Ae(),ie(Fe)),RW={[Fr.ITC_EVENT_TYPES.SCHEMA]:AW,[Fr.ITC_EVENT_TYPES.USER]:hI};async function AW(e){let t=fI(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 EI=[];async function hI(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=fI(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 EI)r()}catch(t){Ji.error(t)}}a(hI,"userHandler");hI.addListener=function(e){EI.push(e)};mI.exports=RW});var Ln=R((Cle,SI)=>{"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();SI.exports={sendItcEvent:CW,validateEvent:pI,SchemaEventMsg:DW,UserEventMsg:LW};var z_;IW(async(e,t)=>{z_=z_||Vc(),pI(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 pI(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(pI,"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,AI)=>{"use strict";var TI=M(),Lle=Q(),J_=$(),gI=FN(),Xo,{sendItcEvent:RI}=Ln();function MW(e){try{J_.trace("signalSchemaChange called with message:",e),Xo=Xo||Vc();let t=new gI(TI.ITC_EVENT_TYPES.SCHEMA,e);return Xo.schema(t),RI(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 gI(TI.ITC_EVENT_TYPES.USER,e);return Xo.user(t),RI(t)}catch(t){J_.error(t)}}a(UW,"signalUserChange");AI.exports={signalSchemaChange:MW,signalUserChange:UW}});var j_=R((Ple,bI)=>{"use strict";var OI=Q(),PW=M(),vW=$(),BW=N_(),HW=b_(),xW=bs(),{SchemaEventMsg:GW}=Ln(),qW="already exists in";bI.exports=FW;async function FW(e,t,r){if(OI.isEmptyOrZeroLength(r))return r;let n=[];OI.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,NI)=>{"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}};NI.exports=gp});var II=R((xle,yI)=>{"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}};yI.exports=Rp});var CI=R((qle,wI)=>{"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}};wI.exports=Ap});var LI=R((kle,DI)=>{"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}};DI.exports=Op});var UI=R(($le,MI)=>{"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}};MI.exports=bp});var Yc=R((Wle,HI)=>{"use strict";var Kle=require("path"),PI=Ke(),XW=II(),ZW=CI(),eQ=LI(),tQ=UI(),ea=ut(),vI=Q(),{CONFIG_PARAMS:rQ}=M(),BI=Z();BI.initSync();var X_=M().OPERATIONS_ENUM,{getTransactionAuditStorePath:nQ}=ze();HI.exports=sQ;async function sQ(e,t){if(BI.get(rQ.LOGGING_AUDITLOG)===!1)return;let r=nQ(e.schema,e.table),n=await PI.openEnvironment(r,e.table,!0),s=iQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){PI.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),vI.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=vI.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,xI)=>{"use strict";var oQ=Bc(),zle=Hc(),Kc=M(),aQ=xc(),cQ=$o().insertRecords,uQ=Ke(),lQ=$(),_Q=j_(),{getSchemaPath:dQ}=ze(),fQ=Yc();xI.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 FI=R((Xle,qI)=>{"use strict";var GI=M(),hQ=Np(),mQ=Hc(),pQ=require("fs-extra"),{getSchemaPath:SQ}=ze();qI.exports=TQ;async function TQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new mQ(GI.SYSTEM_SCHEMA_NAME,GI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await hQ(r),await pQ.mkdirp(SQ(e.schema))}a(TQ,"lmdbCreateSchema")});var VI=R((e_e,kI)=>{"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}};kI.exports=yp});var WI=R((i_e,KI)=>{"use strict";var $I=Ke(),Ip=Mr(),wp=Lr().LMDB_ERRORS_ENUM,gQ=ut(),YI=$(),r_e=Q(),RQ=require("lmdb"),AQ=VI(),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=$I.listDBIs(e);$I.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{YI.warn(`cannot delete from attribute: ${T}, ${g}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){YI.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");KI.exports={deleteRecords:NQ}});var Wc=R((a_e,zI)=>{"use strict";var ta=Q(),yQ=WI(),IQ=Ke(),{getSchemaPath:wQ}=ze(),CQ=Yc(),DQ=$();zI.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 QI([],[]);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 QI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(LQ,"lmdbDeleteRecords");function QI(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(QI,"createDeleteResponse")});var Dp=R((l_e,JI)=>{"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 ji(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(ji,"pushResults");function BQ(e,t,r,n,s,i){t.toString().endsWith(e)&&ji(t,r,n,s,i)}a(BQ,"endsWith");function HQ(e,t,r,n,s,i){t.toString().includes(e)&&ji(t,r,n,s,i)}a(HQ,"contains");function xQ(e,t,r,n,s,i){t>e&&ji(t,r,n,s,i)}a(xQ,"greaterThanCompare");function GQ(e,t,r,n,s,i){t>=e&&ji(t,r,n,s,i)}a(GQ,"greaterThanEqualCompare");function qQ(e,t,r,n,s,i){t<e&&ji(t,r,n,s,i)}a(qQ,"lessThanCompare");function FQ(e,t,r,n,s,i){t<=e&&ji(t,r,n,s,i)}a(FQ,"lessThanEqualCompare");JI.exports={parseRow:Cp,searchAll:UQ,searchAllToMap:PQ,iterateDBI:vQ,endsWith:BQ,contains:HQ,greaterThanCompare:xQ,greaterThanEqualCompare:GQ,lessThanCompare:qQ,lessThanEqualCompare:FQ,pushResults:ji}});var ra=R((h_e,nw)=>{"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:jI,MAX_SEARCH_KEY_LENGTH:$Q}=Z_;function XI(e,t,r,n=!1,s=void 0,i=void 0){return Xi(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(XI,"iterateFullIndex");function Qc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Xi(e,t,r,(l,d,f,E)=>{let A={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(A.values=!1,d.getRange(A).map(g=>({value:g}))):d.getRange(A)})}a(Qc,"iterateRangeBetween");function Xi(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(Xi,"setupTransaction");function ZI(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(jI)){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(ZI,"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 Xi(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 XI(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=XI(e,void 0,t,r,n,s),c=o.transaction,u=ZI(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),Xi(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),Xi(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 ew(e,t,r,n,s,i,o,!0)}a(XQ,"endsWith");function ew(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return li(e,r,n),Xi(e,null,r,(u,_,l,d)=>{let f=ZI(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(jI)?_.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(ew,"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 rw(e,t,r,n,s),tw(e,t,r,n,s).map(i=>i[1])}a(oz,"batchSearchByHash");function az(e,t,r,n,s=[]){rw(e,t,r,n,s);let i=new Map;for(let[o,c]of tw(e,t,r,n,s))i.set(o,c);return i}a(az,"batchSearchByHashToMap");function tw(e,t,r,n,s=[]){return Xi(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(tw,"batchHashSearch");function rw(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(rw,"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");nw.exports={searchAll:YQ,searchAllToMap:KQ,count:JQ,countAll:QQ,equals:zQ,startsWith:jQ,endsWith:XQ,contains:ew,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,cw)=>{var sw=require("lodash"),iw=je(),fe=require("joi"),cz=Q(),{hdb_schema_table:Jc,checkValidTable:ow,hdb_table:aw,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:aw,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:aw,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()});cw.exports=function(e,t){let r=null;switch(t){case"value":r=iw.validateBySchema(e,fz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(ow("database",e.schema)),i(ow("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=iw.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 _=sw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!sw.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,uw)=>{"use strict";var hz=Ke(),mz=na(),{getSchemaPath:pz}=ze();uw.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,lw)=>{"use strict";var Tz=ra(),gz=Lp();lw.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,_w)=>{"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}};_w.exports=Up});var fw=R((y_e,dw)=>{"use strict";var N_e=sa(),Az=ra(),Oz=Lp();dw.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,Ew)=>{"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}};Ew.exports=Pp});var nd=R((D_e,gw)=>{"use strict";var Xt=ra(),Nz=Ke(),yz=Q(),Ee=ut(),Zi=M(),Iz=qi(),hw=Lr().LMDB_ERRORS_ENUM,{getSchemaPath:wz}=ze(),Ns=Zi.SEARCH_WILDCARDS;async function Cz(e,t,r){let n;e.schema===Zi.SYSTEM_SCHEMA_NAME?n=Iz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Tw(e,n.hash_attribute,r,t);return pw(e,s,n.hash_attribute,r)}a(Cz,"prepSearch");async function pw(e,t,r,n){let s=wz(e.schema,e.table),i=await Nz.openEnvironment(s,e.table),o=Sw(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?mw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?mw(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(pw,"executeSearch");function Sw(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(Sw,"searchByType");function mw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(mw,"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 Tw(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(hw.UNKNOWN_SEARCH_TYPE)}else switch(n){case Zi.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case Zi.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case Zi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case Zi.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case Zi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(hw.UNKNOWN_SEARCH_TYPE)}}a(Tw,"createSearchTypeFromSearchObject");gw.exports={executeSearch:pw,createSearchTypeFromSearchObject:Tw,prepSearch:Cz,searchByType:Sw}});var Aw=R((U_e,Rw)=>{"use strict";var M_e=es(),Lz=na(),Mz=Q(),Uz=M(),Pz=nd();Rw.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,Ow)=>{"use strict";var v_e=es(),Bz=na(),Hz=Q(),xz=M(),Gz=nd();Ow.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 Nw=R((G_e,bw)=>{"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}};bw.exports={SearchByConditionsObject:vp,SearchCondition:Bp,SortAttribute:Hp}});var Dw=R((V_e,Cw)=>{"use strict";var F_e=Nw().SearchByConditionsObject,Fz=es(),kz=na(),xp=ra(),sd=ut(),{Resource:k_e}=(Nn(),ie(Gp)),ww=nd(),Vz=Dp(),$z=require("lodash"),{getSchemaPath:Yz}=ze(),yw=Ke(),{handleHDBError:Kz,hdb_errors:Wz}=ne(),{HTTP_STATUS_CODES:Qz}=Wz,zz=1e8;Cw.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 yw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)yw.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 Iw(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(ww.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 Iw(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 Iw(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,ww.searchByType(e,s,i,n).map(o=>o.value)}a(Iw,"executeConditionSearch")});var ia=R((Y_e,Lw)=>{"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}};Lw.exports=qp});var Fp=R((W_e,Gw)=>{"use strict";var vw=es(),Bw=ia(),Hw=jc(),xw=Wc(),fr=M(),Mw=Q(),Uw=Ke(),{getTransactionAuditStorePath:Xz,getSchemaPath:Zz}=ze(),Pw=$();Gw.exports=e2;async function e2(e){try{if(Mw.isEmpty(global.hdb_schema[e.schema])||Mw.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 Uw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Pw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Xz(e.schema,e.table);await Uw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Pw.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 vw(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 Hw(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 Bw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await xw(s)}a(t2,"deleteAttributesFromSystem");async function r2(e){let t=new vw(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 Hw(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 Bw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await xw(s)}catch(i){throw i}}a(r2,"dropTableFromSystem")});var Fw=R((z_e,qw)=>{"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;qw.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,kw)=>{"use strict";var kp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};kw.exports=kp});var $w=R((ede,Vw)=>{"use strict";var S2=require("fs-extra"),od=Ke(),{getTransactionAuditStorePath:T2}=ze(),Vp=ut(),Z_e=id();Vw.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 Qw=R((rde,Ww)=>{"use strict";var $p=M(),Yw=Ke(),R2=$o(),{getSystemSchemaPath:A2,getSchemaPath:O2}=ze(),b2=qi(),N2=N_(),Yp=b_(),y2=$(),I2=$w(),Wp=b2.hdb_table,Kw=[];for(let e=0;e<Wp.attributes.length;e++)Kw.push(Wp.attributes[e].attribute);Ww.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 Yw.createEnvironment(r,t.table),e!==void 0){let o=await Yw.openEnvironment(A2(),$p.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await R2.insertRecords(o,Wp.hash_attribute,Kw,[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 Jw=R((sde,zw)=>{"use strict";var C2=Bc(),D2=xc(),L2=j_(),Xc=M(),M2=$o().updateRecords,U2=Ke(),{getSchemaPath:P2}=ze(),v2=Yc(),B2=$();zw.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 Xw=R((ode,jw)=>{"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}};jw.exports=Qp});var eC=R((ude,Zw)=>{"use strict";var cde=Xw(),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();Zw.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 rC=R((_de,tC)=>{"use strict";var zp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};tC.exports=zp});var sC=R((fde,nC)=>{"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}};nC.exports=Jp});var aC=R((mde,oC)=>{"use strict";var jp=Ke(),{getTransactionAuditStorePath:J2}=ze(),hde=rC(),eu=ut(),j2=Q(),iC=sC(),X2=require("util").promisify,Z2=X2(setTimeout),eJ=1e4,tJ=100;oC.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 iC;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 iC;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 uC=R((Sde,cC)=>{"use strict";var Xp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};cC.exports=Xp});var _C=R((Rde,lC)=>{"use strict";var sJ=es(),iJ=ia(),gde=uC(),ts=M(),oJ=Q(),Zp=Ke(),aJ=qi(),cJ=jc(),uJ=Wc(),{getSchemaPath:lJ}=ze();lC.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 pC=R((bde,mC)=>{"use strict";var eS=Ke(),oa=ut(),Ode=Mr(),tS=M(),dC=Q(),{getTransactionAuditStorePath:EJ}=ze(),hJ=ra(),ad=Zo(),mJ=$();mC.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 fC(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 fC(r)}}a(pJ,"readAuditLog");function fC(e,t=[0,Date.now()]){dC.isEmpty(t[0])&&(t[0]=0),dC.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(fC,"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,hC(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=hC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);EC(u,"records",r,l,o),EC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(TJ,"searchTransactionsByHashValues");function EC(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(EC,"loopRecords");function hC(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(hC,"batchSearchTransactions")});var TC=R((wde,SC)=>{"use strict";var{getSchemaPath:yde}=ze(),Ide=Ke(),{database:gJ}=(Ae(),ie(Fe));SC.exports={writeTransaction:RJ};async function RJ(e,t,r){return gJ({database:e,table:t}).transaction(r)}a(RJ,"writeTransaction")});var OC=R((Dde,AC)=>{"use strict";var{getSchemaPath:gC}=ze(),RC=Ke();AC.exports={flush:AJ,resetReadTxn:OJ};async function AJ(e,t){return(await RC.openEnvironment(gC(e,t),t.toString())).flushed}a(AJ,"flush");async function OJ(e,t){try{(await RC.openEnvironment(gC(e,t),t.toString())).resetReadTxn()}catch{}}a(OJ,"resetReadTxn")});var IC=R((Mde,yC)=>{"use strict";var{Readable:bJ}=require("stream"),{getDatabases:NJ}=(Ae(),ie(Fe)),{readSync:yJ,openSync:IJ,createReadStream:bC}=require("fs"),{open:wJ}=require("lmdb"),NC=Cc(),CJ=Dc(),{AUDIT_STORE_OPTIONS:DJ}=(ti(),ie(wC)),{INTERNAL_DBIS_NAME:LJ,AUDIT_STORE_NAME:MJ}=ut();yC.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 NC(!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 NC(!v,v);await S(A,P)}e.include_audit&&await S(MJ,Object.assign({},DJ)),await f;let T=bC(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=bC(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 LC=R((Pde,DC)=>{"use strict";var vJ=$(),{handleHDBError:BJ}=ne(),HJ=Vb(),xJ=N_(),GJ=Np(),qJ=FI(),FJ=Wc(),kJ=Mp(),VJ=fw(),$J=Aw(),YJ=jc(),KJ=Dw(),WJ=Fw(),QJ=Qw(),zJ=Jw(),JJ=eC(),jJ=aC(),XJ=Fp(),ZJ=_C(),e4=pC(),t4=TC(),CC=OC(),r4=IC(),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 CC.flush(t,r)}resetReadTxn(t,r){return CC.resetReadTxn(t,r)}getBackup(t){return r4(t)}};DC.exports=nS});function o4(){i4=setInterval(function(){for(let e of sS)if(e.stale){let t=e[Ne]?.url;vC.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,PC,vC,BC,HC,xC,MC,sS,n4,tu,UC,eo,cd,s4,i4,oS=Re(()=>{iS=B(Mr()),PC=B(ne()),vC=B($());Nn();BC=B(Z()),HC=B(M()),xC=B(Q()),MC=100,sS=new Set,n4=(0,xC.convertToMS)(BC.get(HC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,eo=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()-UC>n4)throw new PC.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)<MC>>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,UC=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)+MC/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 eo{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 eo;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 GC,to=Re(()=>{GC=require("../index");Nn();oS();a(Xe,"transaction");(0,GC._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 QC={};qe(QC,{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 FC(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 kC(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*VC(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 $C,ud,Mn,YC,KC,Un,aS,cS,WC,a4,c4,u4,l4,qC,uS,zC=Re(()=>{"use strict";$C=B(LC()),ud=B(na()),Mn=B(ne());Ae();YC=B(Bc()),KC=B(xc()),Un=B(M()),aS=B(bs()),cS=B(Ln()),WC=B(Q());to();_d();({HDB_ERROR_MSGS:a4}=Mn.hdb_errors),c4="data",u4=1e4,l4=10,uS=class extends $C.default{static{a(this,"ResourceBridge")}constructor(t){super(t),qC=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,qC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,YC.default)(t);(0,KC.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 kC(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,WC.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?kC(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 FC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of FC(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 VC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return VC(r,t.search_values?.[0],t.search_values?.[1])}}};a(lS,"getSelect");a(FC,"getRecords");a(rs,"getTable");a(kC,"createDeleteResponse");a(VC,"groupRecordsInHistory")});var wn=R((zde,JC)=>{"use strict";var{ResourceBridge:_4}=(zC(),ie(QC)),d4=Z();d4.initSync();var dd;function f4(){return dd||(dd=new _4,dd)}a(f4,"getBridge");JC.exports=f4()});var eD=R((jde,ZC)=>{"use strict";var jC=require("lodash"),nu=require("mathjs"),E4=require("jsonata"),XC=Q();ZC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?jC.uniqWith(e,jC.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(XC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),XC.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 rD=R((Zde,tD)=>{"use strict";var St=require("moment"),dS="YYYY-MM-DDTHH:mm:ss.SSSZZ";St.suppressDeprecationWarnings=!0;tD.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 oD=R((efe,iD)=>{"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"),nD=M(),Te=Q(),Is=$();iD.exports={geoArea:N4,geoLength:y4,geoCircle:I4,geoDifference:w4,geoDistance:sD,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 sD(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(sD,"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 sD(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(nD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(nD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Te.autoCastJSON(e)),b4[t](e,r)}a(U4,"geoConvert")});var fd=R((rfe,aD)=>{var ro=eD(),Vr=rD(),ns=oD();aD.exports=e=>{e.aggr.mad=e.aggr.MAD=ro.mad,e.aggr.mean=e.aggr.MEAN=ro.mean,e.aggr.mode=e.aggr.MODE=ro.mode,e.aggr.prod=e.aggr.PROD=ro.prod,e.aggr.median=e.aggr.MEDIAN=ro.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ro.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ro.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 _D=R((nfe,lD)=>{"use strict";var iu=require("lodash"),hr=require("alasql");hr.options.cache=!1;var P4=fd(),cD=require("clone"),Ed=require("recursive-iterator"),le=$(),Ce=Q(),aa=wn(),v4=M(),{hdb_errors:B4}=ne(),{getDatabases:uD}=(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(cD(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=uD()[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(cD(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:uD()[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)}};lD.exports=fS});var Br=R((ife,dD)=>{"use strict";var x4=Fb();dD.exports={searchByConditions:q4,searchByHash:F4,searchByValue:k4,search:V4};var ES=wn(),{transformReq:hS}=Q(),G4=_D();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,fD)=>{"use strict";var $4=wn();fD.exports={writeTransaction:Y4};function Y4(e,t,r){return $4.writeTransaction(e,t,r)}a(Y4,"writeTransaction")});var pD=R((lfe,mD)=>{"use strict";var K4=Br(),W4=Os(),ED=$(),Q4=Hr(),ufe=hd(),z4=require("clone"),pS=require("alasql"),J4=fd(),hD=require("util"),j4=hD.promisify(W4.getTableSchema),X4=hD.promisify(K4.search),Z4=M(),mS=Q();J4(pS);mD.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 ED.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){ED.error(`Error delete new_attributes from update response: ${i}`)}return s}a(s3,"updateRecords")});var TD=R((Efe,SD)=>{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);SD.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 bD=R((mfe,OD)=>{"use strict";var S3=As(),{hdb_errors:gD}=ne(),{getDatabases:RD}=(Ae(),ie(Fe));OD.exports={checkSchemaExists:AD,checkSchemaTableExists:T3,schema_describe:S3};async function AD(e){if(!RD()[e])return gD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(AD,"checkSchemaExists");async function T3(e,t){let r=await AD(e);if(r)return r;if(!RD()[e][t])return gD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(T3,"checkSchemaTableExists")});var ou=R((Sfe,g3)=>{g3.exports={name:"harperdb",version:"4.3.13",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){UD=e}function $r(e,t,r,n,s){if(!UD)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){BD.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:no.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 HD){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 xD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:no.threadId,byThread:!0,...n});for(let s of BD)s(t);Sd=new Map,no.parentPort?no.parentPort.postMessage({type:vD,report:r}):FD({report:r})},PD).unref()}async function O3(e,t=6e4){let r=AS(),n=GD(),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 xD()}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 HD){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-ND,active:h-yD,taskQueueLatency:await s,time:f,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}ND=E,yD=h}async function ID(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 wD||(wD=lt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function GD(){return CD||(CD=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(){qD=!0;let e=(0,uu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await O3(PD,e),await ID(AS(),b3),await ID(GD(),N3)},Math.min(e/2,2147483647)).unref()}function FD(e,t){let r=e.report;r.threadId=t?.threadId||no.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(DD+=n.mean*n.count);r.totalBytesProcessed=DD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(LD.get(t))}),LD.set(t,t.performance.eventLoopUtilization())),r.id=(0,pd.getNextMonotonicTime)(),AS().primaryStore.put(r.id,r),qD||y3(),I3&&(kD=C3(r))}async function C3(e){if(await kD,!_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
|
|
6
|
+
`)},QY="certificate.pem",zY="privateKey.pem",JY="ca.pem";Iy.exports={CERTIFICATE_VALUES:WY,CERTIFICATE_PEM_NAME:QY,PRIVATEKEY_PEM_NAME:zY,CA_PEM_NAME:JY}});var tp=R((ale,Py)=>{"use strict";var My=require("fs-extra"),oe=require("joi"),jY=require("os"),{boolean:be,string:lr,number:Ze,array:ep}=oe.types(),{totalmem:Cy}=require("os"),Wi=require("path"),XY=$(),q_=Q(),ole=wy(),Dy=M(),ZY=je(),Ly="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,Uy=!1;Py.exports={configValidator:aK,routesValidator:fK,route_constraints:F_};function aK(e,t=!1){if(Uy=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 Uy||My.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?.()||Cy();return i=Math.round(Math.min(i,Cy())/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,Ly);case"clustering.leafServer.streams.path":return Wi.join(jn,"clustering","leaf");case"storage.path":let n=Wi.join(jn,Dy.LEGACY_DATABASES_DIR_NAME);return My.existsSync(n)?n:Wi.join(jn,Dy.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(jn,Ly);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,Vy)=>{"use strict";var Gr=M(),Pt=Q(),Nt=$(),{configValidator:EK,routesValidator:vy}=tp(),_r=require("fs-extra"),hK=require("yaml"),Cn=require("path"),mK=require("is-number"),Hy=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",xy=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.",By={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,$_;Vy.exports={createConfigFile:yK,getDefaultConfig:IK,getConfigValue:qy,initConfig:np,flattenConfig:Wo,updateConfigValue:Fy,updateConfigObject:CK,getConfiguration:MK,setConfiguration:UK,readConfigFile:ip,getClusteringRoutes:PK,initOldConfig:ky,getConfigFromFile:vK,getConfigFilePath:zi,addConfig:BK,deleteConfigFromFile:HK,getConfigObj:xK};function yK(e,t=!1){let r=ai(xy);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&&Gy(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 Gy(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(Gy,"setSchemasConfig");function IK(e){if(V_===void 0){let r=ai(xy);V_=Wo(r.toJSON())}let t=Dn[e.toLowerCase()];if(t!==void 0)return V_[t.toLowerCase()]}a(IK,"getDefaultConfig");function qy(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(qy,"getConfigValue");function zi(e=Pt.getPropsFilePath()){let t=Pt.getEnvCliRootPath();return t?Cn.join(t,Gr.HDB_CONFIG_FILE):Hy(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{ky(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 By)yt[i]&&Nt.error(`Config ${By[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 Fy(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&np();let o=qy(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)}}}_&&Gy(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(Fy,"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 Fy(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=vy(t);if(r)throw k_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Pt.isEmptyOrZeroLength(n)?[]:n;let s=vy(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 ky(e){let t=Hy(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(ky,"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 Yy=R((dle,$y)=>{"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}};$y.exports={BaseLicense:K_,ExtendedLicense:op}});var Ji=R((Ele,jy)=>{"use strict";var zo=require("fs-extra"),Wy=G_(),Qy=require("crypto"),GK=require("moment"),qK=require("uuid").v4,jt=$(),cp=require("path"),FK=Q(),ci=M(),{totalmem:Ky}=require("os"),kK=Yy().ExtendedLicense,Qo="invalid license key format",VK="061183",$K="mofi25",YK="aes-256-cbc",KK=16,WK=32,zy=Z();zy.initSync();var ap;jy.exports={validateLicense:Jy,generateFingerPrint:zK,licenseSearch:_p,getLicense:XK,checkMemoryLimit:ZK};function up(){return cp.join(zy.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=Wy.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),_=Qy.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),Wy.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=Qy.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?.()||Ky();if(t=Math.round(Math.min(t,Ky())/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,fI)=>{"use strict";var tI="username is required",rI="nothing to update, must supply active, role or password to update",nI="password cannot be an empty string",sI="If role is specified, it cannot be empty.",iI="active must be true or false";fI.exports={addUser:cW,alterUser:uW,dropUser:_W,getSuperUser:hW,userInfo:dW,listUsers:Q_,listUsersExternal:fW,setUsersToGlobal:jo,findAndValidateUser:_I,getClusterUser:mW,USERNAME_REQUIRED:tI,ALTERUSER_NOTHING_TO_UPDATE:rI,EMPTY_PASSWORD:nI,EMPTY_ROLE:sI,ACTIVE_BOOLEAN:iI};var oI=Hr(),eW=oi(),Ep=G_(),aI=by(),cI=Br(),hp=bs(),qr=Q(),uI=require("validate.js"),Oe=$(),{promisify:tW}=require("util"),mp=Rs(),Xy=M(),Zy=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)=>_I(e,t,t!=null);var lI={username:!0,active:!0,role:!0,password:!0},eI=new Map,W_=cI.searchByValue,oW=cI.searchByHash,aW=tW(eW.delete);async function cW(e){let t=uI.cleanAttributes(e,lI),r=aI.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 oI.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=uI.cleanAttributes(e,lI);if(qr.isEmptyOrZeroLength(t.username))throw new Error(tI);if(qr.isEmptyOrZeroLength(t.password)&&qr.isEmptyOrZeroLength(t.role)&&qr.isEmptyOrZeroLength(t.active))throw new Error(rI);if(!qr.isEmpty(t.password)&&qr.isEmptyOrZeroLength(t.password.trim()))throw new Error(nI);if(!qr.isEmpty(t.active)&&!qr.isBoolean(t.active))throw new Error(iI);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(sI);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 oI.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=aI.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 _I(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(eI.get(t)===n.password)return s;if(Ep.validate(n.password,t))eI.set(t,n.password);else throw Xn(new Error,dp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(_I,"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(Xy.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!qr.isEmpty(r)&&r?.role?.role===Xy.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+Zy.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+Zy.SERVER_SUFFIX.ADMIN,r}a(mW,"getClusterUser");var dI=[];Sp.invalidateUser=function(e){for(let t of dI)try{t(e)}catch(r){iW.error("Error invalidating user",r)}};Sp.onInvalidatedUser=function(e){dI.push(e)}});var Vc=R((Ole,pI)=>{"use strict";var ji=$(),Fr=M(),pW=YN(),Rle=Os(),Ale=As(),SW=un(),{validateEvent:EI}=Ln(),kc=wn(),TW=require("process"),{resetDatabases:gW}=(Ae(),ie(Fe)),RW={[Fr.ITC_EVENT_TYPES.SCHEMA]:AW,[Fr.ITC_EVENT_TYPES.USER]:mI};async function AW(e){let t=EI(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 hI=[];async function mI(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=EI(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 hI)r()}catch(t){ji.error(t)}}a(mI,"userHandler");mI.addListener=function(e){hI.push(e)};pI.exports=RW});var Ln=R((Cle,TI)=>{"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();TI.exports={sendItcEvent:CW,validateEvent:SI,SchemaEventMsg:DW,UserEventMsg:LW};var z_;IW(async(e,t)=>{z_=z_||Vc(),SI(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 SI(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(SI,"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,OI)=>{"use strict";var gI=M(),Lle=Q(),J_=$(),RI=kN(),Xo,{sendItcEvent:AI}=Ln();function MW(e){try{J_.trace("signalSchemaChange called with message:",e),Xo=Xo||Vc();let t=new RI(gI.ITC_EVENT_TYPES.SCHEMA,e);return Xo.schema(t),AI(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 RI(gI.ITC_EVENT_TYPES.USER,e);return Xo.user(t),AI(t)}catch(t){J_.error(t)}}a(UW,"signalUserChange");OI.exports={signalSchemaChange:MW,signalUserChange:UW}});var j_=R((Ple,NI)=>{"use strict";var bI=Q(),PW=M(),vW=$(),BW=N_(),HW=b_(),xW=bs(),{SchemaEventMsg:GW}=Ln(),qW="already exists in";NI.exports=FW;async function FW(e,t,r){if(bI.isEmptyOrZeroLength(r))return r;let n=[];bI.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,yI)=>{"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}};yI.exports=gp});var wI=R((xle,II)=>{"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}};II.exports=Rp});var DI=R((qle,CI)=>{"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}};CI.exports=Ap});var MI=R((kle,LI)=>{"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}};LI.exports=Op});var PI=R(($le,UI)=>{"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}};UI.exports=bp});var Yc=R((Wle,xI)=>{"use strict";var Kle=require("path"),vI=Ke(),XW=wI(),ZW=DI(),eQ=MI(),tQ=PI(),ea=ut(),BI=Q(),{CONFIG_PARAMS:rQ}=M(),HI=Z();HI.initSync();var X_=M().OPERATIONS_ENUM,{getTransactionAuditStorePath:nQ}=ze();xI.exports=sQ;async function sQ(e,t){if(HI.get(rQ.LOGGING_AUDITLOG)===!1)return;let r=nQ(e.schema,e.table),n=await vI.openEnvironment(r,e.table,!0),s=iQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){vI.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),BI.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=BI.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,GI)=>{"use strict";var oQ=Bc(),zle=Hc(),Kc=M(),aQ=xc(),cQ=$o().insertRecords,uQ=Ke(),lQ=$(),_Q=j_(),{getSchemaPath:dQ}=ze(),fQ=Yc();GI.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 kI=R((Xle,FI)=>{"use strict";var qI=M(),hQ=Np(),mQ=Hc(),pQ=require("fs-extra"),{getSchemaPath:SQ}=ze();FI.exports=TQ;async function TQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new mQ(qI.SYSTEM_SCHEMA_NAME,qI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await hQ(r),await pQ.mkdirp(SQ(e.schema))}a(TQ,"lmdbCreateSchema")});var $I=R((e_e,VI)=>{"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}};VI.exports=yp});var QI=R((i_e,WI)=>{"use strict";var YI=Ke(),Ip=Mr(),wp=Lr().LMDB_ERRORS_ENUM,gQ=ut(),KI=$(),r_e=Q(),RQ=require("lmdb"),AQ=$I(),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=YI.listDBIs(e);YI.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{KI.warn(`cannot delete from attribute: ${T}, ${g}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){KI.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");WI.exports={deleteRecords:NQ}});var Wc=R((a_e,JI)=>{"use strict";var ta=Q(),yQ=QI(),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 zI([],[]);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 zI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(LQ,"lmdbDeleteRecords");function zI(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(zI,"createDeleteResponse")});var Dp=R((l_e,jI)=>{"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");jI.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,sw)=>{"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:XI,MAX_SEARCH_KEY_LENGTH:$Q}=Z_;function ZI(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(ZI,"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 ew(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(XI)){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(ew,"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 ZI(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=ZI(e,void 0,t,r,n,s),c=o.transaction,u=ew(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 tw(e,t,r,n,s,i,o,!0)}a(XQ,"endsWith");function tw(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=ew(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(XI)?_.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(tw,"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 nw(e,t,r,n,s),rw(e,t,r,n,s).map(i=>i[1])}a(oz,"batchSearchByHash");function az(e,t,r,n,s=[]){nw(e,t,r,n,s);let i=new Map;for(let[o,c]of rw(e,t,r,n,s))i.set(o,c);return i}a(az,"batchSearchByHashToMap");function rw(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(rw,"batchHashSearch");function nw(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(nw,"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");sw.exports={searchAll:YQ,searchAllToMap:KQ,count:JQ,countAll:QQ,equals:zQ,startsWith:jQ,endsWith:XQ,contains:tw,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,uw)=>{var iw=require("lodash"),ow=je(),fe=require("joi"),cz=Q(),{hdb_schema_table:Jc,checkValidTable:aw,hdb_table:cw,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:cw,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:cw,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()});uw.exports=function(e,t){let r=null;switch(t){case"value":r=ow.validateBySchema(e,fz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(aw("database",e.schema)),i(aw("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=ow.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 _=iw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!iw.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,lw)=>{"use strict";var hz=Ke(),mz=na(),{getSchemaPath:pz}=ze();lw.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,_w)=>{"use strict";var Tz=ra(),gz=Lp();_w.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,dw)=>{"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}};dw.exports=Up});var Ew=R((y_e,fw)=>{"use strict";var N_e=sa(),Az=ra(),Oz=Lp();fw.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,hw)=>{"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}};hw.exports=Pp});var nd=R((D_e,Rw)=>{"use strict";var Xt=ra(),Nz=Ke(),yz=Q(),Ee=ut(),eo=M(),Iz=Fi(),mw=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=gw(e,n.hash_attribute,r,t);return Sw(e,s,n.hash_attribute,r)}a(Cz,"prepSearch");async function Sw(e,t,r,n){let s=wz(e.schema,e.table),i=await Nz.openEnvironment(s,e.table),o=Tw(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?pw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?pw(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(Sw,"executeSearch");function Tw(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(Tw,"searchByType");function pw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(pw,"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 gw(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(mw.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(mw.UNKNOWN_SEARCH_TYPE)}}a(gw,"createSearchTypeFromSearchObject");Rw.exports={executeSearch:Sw,createSearchTypeFromSearchObject:gw,prepSearch:Cz,searchByType:Tw}});var Ow=R((U_e,Aw)=>{"use strict";var M_e=es(),Lz=na(),Mz=Q(),Uz=M(),Pz=nd();Aw.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,bw)=>{"use strict";var v_e=es(),Bz=na(),Hz=Q(),xz=M(),Gz=nd();bw.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 yw=R((G_e,Nw)=>{"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}};Nw.exports={SearchByConditionsObject:vp,SearchCondition:Bp,SortAttribute:Hp}});var Lw=R((V_e,Dw)=>{"use strict";var F_e=yw().SearchByConditionsObject,Fz=es(),kz=na(),xp=ra(),sd=ut(),{Resource:k_e}=(Nn(),ie(Gp)),Cw=nd(),Vz=Dp(),$z=require("lodash"),{getSchemaPath:Yz}=ze(),Iw=Ke(),{handleHDBError:Kz,hdb_errors:Wz}=ne(),{HTTP_STATUS_CODES:Qz}=Wz,zz=1e8;Dw.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 Iw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Iw.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 ww(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(Cw.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 ww(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 ww(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,Cw.searchByType(e,s,i,n).map(o=>o.value)}a(ww,"executeConditionSearch")});var ia=R((Y_e,Mw)=>{"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}};Mw.exports=qp});var Fp=R((W_e,qw)=>{"use strict";var Bw=es(),Hw=ia(),xw=jc(),Gw=Wc(),fr=M(),Uw=Q(),Pw=Ke(),{getTransactionAuditStorePath:Xz,getSchemaPath:Zz}=ze(),vw=$();qw.exports=e2;async function e2(e){try{if(Uw.isEmpty(global.hdb_schema[e.schema])||Uw.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 Pw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")vw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Xz(e.schema,e.table);await Pw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")vw.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 Bw(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 xw(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 Hw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Gw(s)}a(t2,"deleteAttributesFromSystem");async function r2(e){let t=new Bw(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 xw(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 Hw(fr.SYSTEM_SCHEMA_NAME,fr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Gw(s)}catch(i){throw i}}a(r2,"dropTableFromSystem")});var kw=R((z_e,Fw)=>{"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;Fw.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,Vw)=>{"use strict";var kp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Vw.exports=kp});var Yw=R((ede,$w)=>{"use strict";var S2=require("fs-extra"),od=Ke(),{getTransactionAuditStorePath:T2}=ze(),Vp=ut(),Z_e=id();$w.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 zw=R((rde,Qw)=>{"use strict";var $p=M(),Kw=Ke(),R2=$o(),{getSystemSchemaPath:A2,getSchemaPath:O2}=ze(),b2=Fi(),N2=N_(),Yp=b_(),y2=$(),I2=Yw(),Wp=b2.hdb_table,Ww=[];for(let e=0;e<Wp.attributes.length;e++)Ww.push(Wp.attributes[e].attribute);Qw.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 Kw.createEnvironment(r,t.table),e!==void 0){let o=await Kw.openEnvironment(A2(),$p.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await R2.insertRecords(o,Wp.hash_attribute,Ww,[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 jw=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 Zw=R((ode,Xw)=>{"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}};Xw.exports=Qp});var tC=R((ude,eC)=>{"use strict";var cde=Zw(),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();eC.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 nC=R((_de,rC)=>{"use strict";var zp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};rC.exports=zp});var iC=R((fde,sC)=>{"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}};sC.exports=Jp});var cC=R((mde,aC)=>{"use strict";var jp=Ke(),{getTransactionAuditStorePath:J2}=ze(),hde=nC(),eu=ut(),j2=Q(),oC=iC(),X2=require("util").promisify,Z2=X2(setTimeout),eJ=1e4,tJ=100;aC.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 oC;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 oC;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 lC=R((Sde,uC)=>{"use strict";var Xp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};uC.exports=Xp});var dC=R((Rde,_C)=>{"use strict";var sJ=es(),iJ=ia(),gde=lC(),ts=M(),oJ=Q(),Zp=Ke(),aJ=Fi(),cJ=jc(),uJ=Wc(),{getSchemaPath:lJ}=ze();_C.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 SC=R((bde,pC)=>{"use strict";var eS=Ke(),oa=ut(),Ode=Mr(),tS=M(),fC=Q(),{getTransactionAuditStorePath:EJ}=ze(),hJ=ra(),ad=Zo(),mJ=$();pC.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 EC(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 EC(r)}}a(pJ,"readAuditLog");function EC(e,t=[0,Date.now()]){fC.isEmpty(t[0])&&(t[0]=0),fC.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(EC,"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,mC(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=mC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);hC(u,"records",r,l,o),hC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(TJ,"searchTransactionsByHashValues");function hC(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(hC,"loopRecords");function mC(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(mC,"batchSearchTransactions")});var gC=R((wde,TC)=>{"use strict";var{getSchemaPath:yde}=ze(),Ide=Ke(),{database:gJ}=(Ae(),ie(Fe));TC.exports={writeTransaction:RJ};async function RJ(e,t,r){return gJ({database:e,table:t}).transaction(r)}a(RJ,"writeTransaction")});var bC=R((Dde,OC)=>{"use strict";var{getSchemaPath:RC}=ze(),AC=Ke();OC.exports={flush:AJ,resetReadTxn:OJ};async function AJ(e,t){return(await AC.openEnvironment(RC(e,t),t.toString())).flushed}a(AJ,"flush");async function OJ(e,t){try{(await AC.openEnvironment(RC(e,t),t.toString())).resetReadTxn()}catch{}}a(OJ,"resetReadTxn")});var wC=R((Mde,IC)=>{"use strict";var{Readable:bJ}=require("stream"),{getDatabases:NJ}=(Ae(),ie(Fe)),{readSync:yJ,openSync:IJ,createReadStream:NC}=require("fs"),{open:wJ}=require("lmdb"),yC=Cc(),CJ=Dc(),{AUDIT_STORE_OPTIONS:DJ}=(ti(),ie(CC)),{INTERNAL_DBIS_NAME:LJ,AUDIT_STORE_NAME:MJ}=ut();IC.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 yC(!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 yC(!v,v);await S(A,P)}e.include_audit&&await S(MJ,Object.assign({},DJ)),await f;let T=NC(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=NC(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 MC=R((Pde,LC)=>{"use strict";var vJ=$(),{handleHDBError:BJ}=ne(),HJ=$b(),xJ=N_(),GJ=Np(),qJ=kI(),FJ=Wc(),kJ=Mp(),VJ=Ew(),$J=Ow(),YJ=jc(),KJ=Lw(),WJ=kw(),QJ=zw(),zJ=jw(),JJ=tC(),jJ=cC(),XJ=Fp(),ZJ=dC(),e4=SC(),t4=gC(),DC=bC(),r4=wC(),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 DC.flush(t,r)}resetReadTxn(t,r){return DC.resetReadTxn(t,r)}getBackup(t){return r4(t)}};LC.exports=nS});function o4(){i4=setInterval(function(){for(let e of sS)if(e.stale){let t=e[Ne]?.url;BC.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,vC,BC,HC,xC,GC,UC,sS,n4,tu,PC,to,cd,s4,i4,oS=Re(()=>{iS=B(Mr()),vC=B(ne()),BC=B($());Nn();HC=B(Z()),xC=B(M()),GC=B(Q()),UC=100,sS=new Set,n4=(0,GC.convertToMS)(HC.get(xC.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()-PC>n4)throw new vC.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)<UC>>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,PC=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)+UC/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 qC,ro=Re(()=>{qC=require("../index");Nn();oS();a(Xe,"transaction");(0,qC._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 zC={};qe(zC,{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 kC(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 VC(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*$C(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 YC,ud,Mn,KC,WC,Un,aS,cS,QC,a4,c4,u4,l4,FC,uS,JC=Re(()=>{"use strict";YC=B(MC()),ud=B(na()),Mn=B(ne());Ae();KC=B(Bc()),WC=B(xc()),Un=B(M()),aS=B(bs()),cS=B(Ln()),QC=B(Q());ro();_d();({HDB_ERROR_MSGS:a4}=Mn.hdb_errors),c4="data",u4=1e4,l4=10,uS=class extends YC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),FC=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,FC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,KC.default)(t);(0,WC.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 VC(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,QC.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?VC(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 kC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of kC(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 $C(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return $C(r,t.search_values?.[0],t.search_values?.[1])}}};a(lS,"getSelect");a(kC,"getRecords");a(rs,"getTable");a(VC,"createDeleteResponse");a($C,"groupRecordsInHistory")});var wn=R((zde,jC)=>{"use strict";var{ResourceBridge:_4}=(JC(),ie(zC)),d4=Z();d4.initSync();var dd;function f4(){return dd||(dd=new _4,dd)}a(f4,"getBridge");jC.exports=f4()});var tD=R((jde,eD)=>{"use strict";var XC=require("lodash"),nu=require("mathjs"),E4=require("jsonata"),ZC=Q();eD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?XC.uniqWith(e,XC.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(ZC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),ZC.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 nD=R((Zde,rD)=>{"use strict";var St=require("moment"),dS="YYYY-MM-DDTHH:mm:ss.SSSZZ";St.suppressDeprecationWarnings=!0;rD.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 aD=R((efe,oD)=>{"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"),sD=M(),Te=Q(),Is=$();oD.exports={geoArea:N4,geoLength:y4,geoCircle:I4,geoDifference:w4,geoDistance:iD,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 iD(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(iD,"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 iD(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(sD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(sD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Te.autoCastJSON(e)),b4[t](e,r)}a(U4,"geoConvert")});var fd=R((rfe,cD)=>{var no=tD(),Vr=nD(),ns=aD();cD.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 dD=R((nfe,_D)=>{"use strict";var iu=require("lodash"),hr=require("alasql");hr.options.cache=!1;var P4=fd(),uD=require("clone"),Ed=require("recursive-iterator"),le=$(),Ce=Q(),aa=wn(),v4=M(),{hdb_errors:B4}=ne(),{getDatabases:lD}=(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(uD(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=lD()[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(uD(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:lD()[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)}};_D.exports=fS});var Br=R((ife,fD)=>{"use strict";var x4=kb();fD.exports={searchByConditions:q4,searchByHash:F4,searchByValue:k4,search:V4};var ES=wn(),{transformReq:hS}=Q(),G4=dD();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,ED)=>{"use strict";var $4=wn();ED.exports={writeTransaction:Y4};function Y4(e,t,r){return $4.writeTransaction(e,t,r)}a(Y4,"writeTransaction")});var SD=R((lfe,pD)=>{"use strict";var K4=Br(),W4=Os(),hD=$(),Q4=Hr(),ufe=hd(),z4=require("clone"),pS=require("alasql"),J4=fd(),mD=require("util"),j4=mD.promisify(W4.getTableSchema),X4=mD.promisify(K4.search),Z4=M(),mS=Q();J4(pS);pD.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 hD.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){hD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(s3,"updateRecords")});var gD=R((Efe,TD)=>{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);TD.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 ND=R((mfe,bD)=>{"use strict";var S3=As(),{hdb_errors:RD}=ne(),{getDatabases:AD}=(Ae(),ie(Fe));bD.exports={checkSchemaExists:OD,checkSchemaTableExists:T3,schema_describe:S3};async function OD(e){if(!AD()[e])return RD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(OD,"checkSchemaExists");async function T3(e,t){let r=await OD(e);if(r)return r;if(!AD()[e][t])return RD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(T3,"checkSchemaTableExists")});var ou=R((Sfe,g3)=>{g3.exports={name:"harperdb",version:"4.3.15",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){PD=e}function $r(e,t,r,n,s){if(!PD)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){HD.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 xD){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 GD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:so.threadId,byThread:!0,...n});for(let s of HD)s(t);Sd=new Map,so.parentPort?so.parentPort.postMessage({type:BD,report:r}):kD({report:r})},vD).unref()}async function O3(e,t=6e4){let r=AS(),n=qD(),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 GD()}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 xD){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-yD,active:h-ID,taskQueueLatency:await s,time:f,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}yD=E,ID=h}async function wD(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 CD||(CD=lt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function qD(){return DD||(DD=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(){FD=!0;let e=(0,uu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await O3(vD,e),await wD(AS(),b3),await wD(qD(),N3)},Math.min(e/2,2147483647)).unref()}function kD(e,t){let r=e.report;r.threadId=t?.threadId||so.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(LD+=n.mean*n.count);r.totalBytesProcessed=LD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(MD.get(t))}),MD.set(t,t.performance.eventLoopUtilization())),r.id=(0,pd.getNextMonotonicTime)(),AS().primaryStore.put(r.id,r),FD||y3(),I3&&(VD=C3(r))}async function C3(e){if(await VD,!_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,UD,au,cu,gS,pd,uu,RS,Sd,PD,md,vD,BD,HD,xD,yD,ID,GD,b3,N3,CD,DD,FD,LD,MD,I3,VD,_i,w3,ws=Re(()=>{so=require("worker_threads"),UD=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,PD=(0,uu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(R3,"setAnalyticsEnabled");a($r,"recordAction");nt.recordAnalytics=$r;a(Yr,"recordActionBinary");md=0,vD=1e3,BD="analytics-report",HD=[];a(lu,"addAnalyticsListener");xD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(A3,"sendAnalytics");a(O3,"aggregation");yD=0,ID=0,GD=a(()=>new Promise(setImmediate),"rest");a(wD,"cleanup");b3=36e5,N3=31536e6;a(AS,"getRawAnalyticsTable");a(qD,"getAnalyticsTable");(0,UD.setChildListenerByType)(BD,kD);a(y3,"startScheduledTasks");LD=0,MD=new Map,I3=!1;a(kD,"recordAnalytics");w3=1e6;a(C3,"logAnalytics")});var IS=R((Lfe,eL)=>{"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(),KD=Rs(),{recordAction:U3,recordActionBinary:P3}=(ws(),ie(_u)),{publishToStream:v3}=Rd,{ConsumerEvents:$D}=require("nats"),B3=Br(),{promisify:H3}=require("util"),WD=H3(setTimeout),Ad=1e4,Od,gd,x3,G3,QD,du=new Map,ua=new Map;eL.exports={initialize:zD,ingestConsumer:yS,setSubscription:q3,setIgnoreOrigin:V3,getDatabaseSubscriptions:k3,updateConsumer:JD};async function zD(){M3(NS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await JD(n)}),QD=!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(zD,"initialize");async function JD(e){if(e.status==="start"){let{js:t,jsm:r}=await jD(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),QD||zD().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 jD(r),!n))break;let{schema:o,table:c}=i,u=KD.createNatsTableStreamName(o,c);yS(u,n,s,r)}}}a(F3,"accessConsumers");async function jD(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 WD(i)}return{js:t,jsm:r}}a(jD,"connectToRemoteJS");function k3(){return bd}a(k3,"getDatabaseSubscriptions");var XD;function V3(e){XD=e}a(V3,"setIgnoreOrigin");var ZD=100,YD=new Array(ZD),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 WD(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===$D.ConsumerDeleted&&(await u.close(),c=!0),l.type===$D.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 YD[Td],YD[Td]=$3(l).catch(d=>{Zt.error(d)}),++Td>=ZD&&(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&&!XD),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("."),KD.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,pL)=>{"use strict";var vt=Z();vt.initSync();var Y3=require("fs-extra"),K3=require("semver"),hu=require("path"),{monotonicFactory:W3}=require("ulidx"),rL=W3(),Q3=require("util"),nL=require("child_process"),z3=Q3.promisify(nL.exec),J3=nL.spawn,$t=ke(),ye=M(),Nd=Q(),vn=$(),yd=Rs(),j3=hd(),fu=dr(),{broadcast:X3,onMessageByType:Z3,getWorkerIndex:ej}=Je(),{isMainThread:sL}=require("worker_threads"),{Encoder:tj,decode:LS}=require("msgpackr"),iL=new tj,{isEmpty:co}=Nd,oL=un(),Ufe=48*36e11;sL&&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:tL}=require("nats"),{PACKAGE_ROOT:cj}=M(),uj=ou(),{recordAction:lj}=(ws(),ie(_u)),aL=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;pL.exports={runCommand:cL,checkNATSServerInstalled:Ej,createConnection:vS,getConnection:mu,getJetStreamManager:pu,getJetStream:lL,getNATSReferences:ss,getServerList:mj,createLocalStream:BS,listStreams:_L,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:hL,createTableStreams:Dj,purgeTableStream:mL,purgeSchemaTableStreams:Lj,getStreamInfo:Mj,updateLocalStreams:Pj,closeConnection:hj,getJsmServerName:Id,addNatsMsgHeader:dL,clearClientCache:uL,updateRemoteConsumer:wj,createConsumer:fL,updateConsumerIterator:Cj};async function cL(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(aL,"runCommand");async function Ej(){try{await Y3.access(DS)}catch{return!1}let e=await aL(`${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 iL.getClusterUser();if(ao(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),cL()}),i}a(vS,"createConnection");function cL(){mr=void 0,so=void 0,io=void 0,oo=void 0}a(cL,"clearClientCache");async function hj(){mr&&(await mr.drain(),mr=void 0,so=void 0,io=void 0,oo=void 0)}a(hj,"closeConnection");var mr,oo;async function mu(){return oo||(oo=vS(vt.get(ye.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),mr=await oo),mr||oo}a(mu,"getConnection");async function pu(){if(so)return so;ao(mr)&&await mu();let{domain:e}=la(ye.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ao(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return so=await mr.jetstreamManager({domain:e,timeout:6e4}),so}a(pu,"getJetStreamManager");async function uL(){if(io)return io;ao(mr)&&await mu();let{domain:e}=la(ye.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ao(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=mr.jetstream({domain:e,timeout:6e4}),io}a(uL,"getJetStream");async function ss(){let e=mr||await mu(),t=so||await pu(),r=io||await uL();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 iL.getClusterUser(),s=await vS(t,r,n),i=PS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=oL.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 lL(){let{jsm:e}=await ss(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(lL,"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(oL.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=tL(),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=tL(),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=_L(n,r);let{js:s}=await ss(),i=await Id(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:sL.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 fL(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 _L(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(_L,"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 ao(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 ao(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 dL(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(dL,"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=sL.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 eL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case eL.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 fL(async()=>{if(e.subscribe===!0)await dL(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(!nL&&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 fL(e){return j3.writeTransaction(ye.SYSTEM_SCHEMA_NAME,ye.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(fL,"exclusiveLock");async function EL(e,t){let r=yd.createNatsTableStreamName(e,t),n=await Id(),s=Uj(e,t,n);await BS(r,[s])}a(EL,"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 EL(n,s)}}a(Dj,"createTableStreams");async function hL(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(hL,"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 hL(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 lL();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,gL)=>{"use strict";var _a=O_(),da=bD(),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(),pL=it(),{getDatabases:Fj}=(Ae(),ie(Fe)),{transformReq:Ea}=Q();gL.exports={createSchema:kj,createSchemaStructure:SL,createTable:Vj,createTableStructure:TL,createAttribute:Qj,dropSchema:$j,dropTable:Yj,dropAttribute:Kj,getBackup:zj};async function kj(e){let t=await SL(e);return Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),t}a(kj,"createSchema");async function SL(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(SL,"createSchemaStructure");async function Vj(e){return Ea(e),e.hash_attribute=e.primary_key??e.hash_attribute,await TL(e)}a(Vj,"createTable");async function TL(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(TL,"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 pL.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 pL.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 AL=R((Vfe,RL)=>{"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}};RL.exports=xS});var GS=R((Kfe,IL)=>{"use strict";var jj=wn(),Yfe=AL(),Ld=Q(),Md=M(),Xj=Z(),{handleHDBError:OL,hdb_errors:Zj}=ne(),{HDB_ERROR_MSGS:bL,HTTP_STATUS_CODES:NL}=Zj,eX=Object.values(Md.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),yL="To use this operation audit log must be enabled in harperdb-config.yaml";IL.exports=tX;async function tX(e){if(Ld.isEmpty(e.schema))throw new Error(bL.SCHEMA_REQUIRED_ERR);if(Ld.isEmpty(e.table))throw new Error(bL.TABLE_REQUIRED_ERR);if(!Xj.get(Md.CONFIG_PARAMS.LOGGING_AUDITLOG))throw OL(new Error,yL,NL.BAD_REQUEST,Md.LOG_LEVELS.ERROR,yL,!0);let t=Ld.checkSchemaTableExist(e.schema,e.table);if(t)throw OL(new Error,t,NL.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 CL=R((Qfe,wL)=>{"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}};wL.exports=qS});var ML=R((Xfe,LL)=>{"use strict";var nX=wn(),Jfe=CL(),FS=Q(),sX=M(),jfe=Z(),{handleHDBError:iX,hdb_errors:oX}=ne(),{HDB_ERROR_MSGS:DL,HTTP_STATUS_CODES:aX}=oX;LL.exports=cX;async function cX(e){if(FS.isEmpty(e.schema))throw new Error(DL.SCHEMA_REQUIRED_ERR);if(FS.isEmpty(e.table))throw new Error(DL.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 xL=R((eEe,HL)=>{var fi=require("validate.js"),PL=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"},UL=Object.values(ha.ROLE_TYPES_ENUM),fX="attribute_permissions",EX="attribute_name",{PERMS_CRUD_ENUM:ma}=ha,hX=[fX,...Object.values(ma)],vL=[ma.READ,ma.INSERT,ma.UPDATE],mX=[EX,...vL];function pX(e){let t=kS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,BL(e,t)}a(pX,"addRoleValidation");function SX(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,BL(e,t)}a(SX,"alterRoleValidation");function TX(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,PL.validateObject(e,t)}a(TX,"dropRoleValidation");var gX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function BL(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=PL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Tt(o,r)}),e.permission){let o=RX(e);o&&Tt(o,r),UL.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(UL.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}vL.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(BL,"customValidate");HL.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,kL)=>{"use strict";var GL=Hr(),qL=Br(),OX=oi(),$S=xL(),YS=bs(),bX=require("uuid").v4,NX=require("util"),Ud=M(),yX=Q(),KS=qL.searchByValue,IX=qL.searchByHash,wX=NX.promisify(OX.delete),CX=es(),DX=sa(),{hdb_errors:LX,handleHDBError:co}=ne(),{HDB_ERROR_MSGS:FL,HTTP_STATUS_CODES:Tu}=LX,{UserEventMsg:WS}=Ln();kL.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 co(i)}if(n&&n.length>0)throw co(new Error,FL.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 GL.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 GL.update(r)}catch(s){throw co(s)}if(n&&n?.message==="updated 0 of 1 records")throw co(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 co(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 co(new Error,FL.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 co(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 KL=R((sEe,YL)=>{"use strict";var BX=Z(),Ei=require("joi"),HX=je(),VL=require("moment"),xX=require("fs-extra"),zS=require("path"),GX=require("lodash"),gu=M(),{LOG_LEVELS:uo}=M(),qX="YYYY-MM-DD hh:mm:ss",FX=zS.resolve(__dirname,"../logs");YL.exports=function(e){return HX.validateBySchema(e,kX)};var kX=Ei.object({from:Ei.custom($L),until:Ei.custom($L),level:Ei.valid(uo.NOTIFY,uo.FATAL,uo.ERROR,uo.WARN,uo.INFO,uo.DEBUG,uo.TRACE),order:Ei.valid("asc","desc"),limit:Ei.number().min(1),start:Ei.number().min(0),log_name:Ei.custom(VX)});function $L(e,t){if(VL(e,VL.ISO_8601).format(qX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a($L,"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,QL)=>{"use strict";var Pd=M(),$X=$(),YX=Z(),KX=KL(),JS=require("path"),WL=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;QL.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(WL.statSync(s).size-(h+5)*ZX,0));let S=WL.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,XL)=>{"use strict";var XS=require("joi"),{string:Ru,boolean:zL,date:nZ}=XS.types(),sZ=je(),{validateSchemaExists:cEe,validateTableExists:uEe,validateSchemaName:lEe}=zn(),iZ=M(),oZ=ke(),JL=Z();JL.initSync();var aZ=Ru.invalid(JL.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(),jL={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:zL.required(),publish:zL.required().custom(uZ),start_time:nZ.iso()}).min(1).required()};function cZ(e){return sZ.validateBySchema(e,XS.object(jL))}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");XL.exports={addUpdateNodeValidator:cZ,validation_schema:jL}});var eM=R((fEe,ZL)=>{var lZ=je(),_Z={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};ZL.exports=function(e){return lZ.validateObject(e,_Z)}});var Bd=R((EEe,tM)=>{"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}};tM.exports=ZS});var nM=R((mEe,rM)=>{"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}};rM.exports={JWTTokens:eT,TOKEN_TYPE_ENUM:fZ,JWTRSAKeys:tT}});var bu=R((SEe,aM)=>{"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=$(),sM=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}=nM(),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;aM.exports={createTokens:OZ,validateOperationToken:NZ,refreshOperationToken:bZ,validateRefreshToken:oM};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 iM(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=sM.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 iM(e,t,r){return await Ou.sign(e,{key:t,passphrase:r},{expiresIn:RZ,algorithm:xd,subject:Hd.OPERATION})}a(iM,"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 oM(e.refresh_token);let t=await Gd(),r=await Ou.decode(e.refresh_token);return{operation_token:await iM({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 oM(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(!sM.validate(t.refresh_token,e))throw Tr(new Error,Rr.INVALID_TOKEN,gr.UNAUTHORIZED);return t}a(oM,"validateRefreshToken")});var aT=R((REe,lM)=>{"use strict";var yZ=eM(),pa=require("passport"),IZ=require("passport-local").Strategy,wZ=require("passport-http").BasicStrategy,CZ=require("util"),DZ=un(),uM=CZ.callbackify(DZ.findAndValidateUser),gEe=Lr(),LZ=M(),cM=bu();pa.use(new IZ(function(e,t,r){uM(e,t,r)}));pa.use(new wZ(function(e,t,r){uM(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?cM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):cM.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");lM.exports={authorize:MZ,checkPermissions:UZ}});var pi=R((OEe,_M)=>{"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}};_M.exports={Node:cT,NodeSubscription:uT}});var fM=R((NEe,dM)=>{"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}};dM.exports=lT});var Nu=R((IEe,EM)=>{"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)}};EM.exports={RemotePayloadObject:_T,RemotePayloadSubscription:dT}});var mM=R((CEe,hM)=>{"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}};hM.exports=fT});var TM=R((PEe,SM)=>{"use strict";var vZ=mM(),LEe=ut(),pM=Ke(),BZ=$(),{getSchemaPath:MEe,getTransactionAuditStorePath:UEe}=ze(),{getDatabases:HZ}=(Ae(),ie(Fe));SM.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 pM.environmentDataSize(schema_path,e.name),o=await pM.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 RM=R((BEe,gM)=>{"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}};gM.exports=ET});var Sa=R((FEe,yM)=>{"use strict";var GZ=require("fs-extra"),qZ=require("path"),er=require("systeminformation"),Si=$(),AM=it(),xEe=ke(),Fd=M(),FZ=TM(),kZ=As(),{getThreadInfo:OM}=Je(),bT=Z();bT.initSync();var VZ=RM(),{openEnvironment:GEe}=Ke(),{getSchemaPath:qEe}=ze(),{database:$Z,databases:bM}=(Ae(),ie(Fe)),qd;yM.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 bM){let r=e[t]={};for(let n in bM[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 NM(){if(bT.get(Fd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await AM.getNATSReferences(),t=await AM.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(NM,"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 OM(),t.replication=await NM(),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 OM();break;case"replication":t.replication=await NM();break;default:break}return t}a(YZ,"systemInformation")});var Vd=R((VEe,IM)=>{"use strict";IM.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,LM)=>{"use strict";var QZ=Hr(),NT=Q(),zZ=require("util"),lo=M(),wM=Z();wM.initSync();var JZ=aT(),CM=Br(),{Node:YEe,NodeSubscription:KEe}=pi(),jZ=sa(),XZ=fM(),{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=CM.searchByHash,_5=CM.searchByValue;LM.exports={authHeaderToUser:d5,isEmpty:f5,getNodeRecord:E5,upsertNodeRecord:h5,buildNodePayloads:m5,checkClusteringEnabled:p5,getAllNodeRecords:S5,getSystemInfo:T5,reverseSubscription:DM};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(lo.SYSTEM_SCHEMA_NAME,lo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return l5(t)}a(E5,"getNodeRecord");async function h5(e){let t=new XZ(lo.SYSTEM_SCHEMA_NAME,lo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return QZ.upsert(t)}a(h5,"upsertNodeRecord");function DM(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(DM,"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}=DM(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(!wM.get(lo.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(lo.SYSTEM_SCHEMA_NAME,lo.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,GM)=>{"use strict";var $d=it(),MM=Q(),UM=ke(),PM=M(),Yd=$(),vM=Su(),g5=id(),{RemotePayloadObject:R5}=Nu(),{handleHDBError:BM,hdb_errors:A5}=ne(),{HTTP_STATUS_CODES:HM}=A5,{NodeSubscription:xM}=pi();GM.exports=O5;async function O5(e,t){let r;try{r=await $d.request(`${t}.${UM.REQUEST_SUFFIX}`,new R5(PM.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 BM(new Error,c,HM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===UM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw BM(new Error,o,HM.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===PM.SYSTEM_SCHEMA_NAME){await $d.createLocalTableStream(u,c);let h=new xM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=MM.doesSchemaExist(u),l=n[u]!==void 0,d=c?MM.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 vM.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 vM.createTable(h)}await $d.createLocalTableStream(u,c);let E=new xM(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,kM)=>{"use strict";var{handleHDBError:Kd,hdb_errors:b5}=ne(),{HTTP_STATUS_CODES:Wd}=b5,{addUpdateNodeValidator:N5}=vd(),Qd=$(),FM=M(),qM=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(FM.CONFIG_PARAMS.CLUSTERING_NODENAME);kM.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,FM.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}.${qM.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===qM.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,YM)=>{"use strict";var{handleHDBError:IT,hdb_errors:B5}=ne(),{HTTP_STATUS_CODES:wT}=B5,{addUpdateNodeValidator:H5}=vd(),wu=$(),$M=M(),VM=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($M.CONFIG_PARAMS.CLUSTERING_NODENAME);YM.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,$M.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}.${VM.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===VM.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 JM=R((rhe,zM)=>{"use strict";var QM=require("joi"),{string:KM}=QM.types(),z5=je(),WM=M(),J5=Z(),j5=ke();zM.exports=X5;function X5(e){let t=KM.invalid(J5.get(WM.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=QM.object({operation:KM.valid(WM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return z5.validateBySchema(e,r)}a(X5,"removeNodeValidator")});var jd=R((she,tU)=>{"use strict";var{handleHDBError:jM,hdb_errors:Z5}=ne(),{HTTP_STATUS_CODES:XM}=Z5,e8=JM(),Lu=$(),ZM=_n(),t8=Q(),Jd=M(),eU=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);tU.exports=u8;async function u8(e){Lu.trace("removeNode called with:",e),ZM.checkClusteringEnabled();let t=e8(e);if(t)throw jM(t,t.message,XM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await ZM.getNodeRecord(r);if(t8.isEmptyOrZeroLength(n))throw jM(new Error,`Node '${r}' was not found.`,XM.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}.${eU.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===eU.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 sU=R((ohe,nU)=>{"use strict";var rU=require("joi"),{string:l8,array:_8}=rU.types(),d8=je(),f8=vd();nU.exports=E8;function E8(e){let t=rU.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,uU)=>{"use strict";var h8=M(),Xd=$(),m8=Q(),p8=jd(),S8=zd(),iU=_n(),T8=sU(),{handleHDBError:oU,hdb_errors:g8}=ne(),{HTTP_STATUS_CODES:aU}=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.";uU.exports=b8;async function b8(e){Xd.trace("configure cluster called with:",e),iU.checkClusteringEnabled();let t=T8(e);if(t)throw oU(t,t.message,aU.BAD_REQUEST,void 0,void 0,!0);let r=await iU.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let f=await cU(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 cU(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 oU(new Error,A8,aU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(b8,"configureCluster");async function cU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(cU,"functionWrapper")});var fU=R((lhe,dU)=>{"use strict";var Mu=require("joi"),N8=je(),{validateSchemaExists:lU,validateTableExists:y8,validateSchemaName:_U}=zn(),I8=Mu.object({operation:Mu.string().valid("purge_stream"),schema:Mu.string().custom(lU).custom(_U).optional(),database:Mu.string().custom(lU).custom(_U).optional(),table:Mu.string().custom(y8).required()});function w8(e){return N8.validateBySchema(e,I8)}a(w8,"purgeStreamValidator");dU.exports=w8});var MT=R((dhe,EU)=>{"use strict";var{handleHDBError:C8,hdb_errors:D8}=ne(),{HTTP_STATUS_CODES:L8}=D8,M8=fU(),U8=it(),P8=_n();EU.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,gU)=>{"use strict";var PT=_n(),B8=it(),pU=Z(),Zd=M(),_o=ke(),H8=Q(),UT=$(),{RemotePayloadObject:x8}=Nu(),{ErrorCode:hU}=require("nats"),mU=pU.get(Zd.CONFIG_PARAMS.CLUSTERING_ENABLED),SU=pU.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);gU.exports={clusterStatus:G8,buildNodeStatus:TU};async function G8(){let e={node_name:SU,is_enabled:mU,connections:[]};if(!mU)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(TU(t[n],e.connections));return await Promise.allSettled(r),e}a(G8,"clusterStatus");async function TU(e,t){let r=e.name,n=new x8(Zd.OPERATIONS_ENUM.CLUSTER_STATUS,SU,void 0,await PT.getSystemInfo()),s,i,o=_o.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await B8.request(_o.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===_o.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=_o.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===hU.NoResponders?o=_o.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===hU.Timeout?o=_o.CLUSTER_STATUS_STATUSES.TIMEOUT:o=_o.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(TU,"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,RU)=>{"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()});RU.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 NU=R((She,bU)=>{"use strict";var xT=require("joi"),AU=je(),{route_constraints:OU}=tp();bU.exports={setRoutesValidator:J8,deleteRoutesValidator:j8};function J8(e){let t=xT.object({server:xT.valid("hub","leaf").required(),routes:OU.required()});return AU.validateBySchema(e,t)}a(J8,"setRoutesValidator");function j8(e){let t=xT.object({routes:OU.required()});return AU.validateBySchema(e,t)}a(j8,"deleteRoutesValidator")});var qT=R((ghe,CU)=>{"use strict";var fo=dr(),GT=Q(),tf=M(),yU=NU(),{handleHDBError:IU,hdb_errors:X8}=ne(),{HTTP_STATUS_CODES:wU}=X8,Z8="cluster routes successfully set",e6="cluster routes successfully deleted";CU.exports={setRoutes:t6,getRoutes:r6,deleteRoutes:n6};function t6(e){let t=yU.setRoutesValidator(e);if(t)throw IU(t,t.message,wU.BAD_REQUEST,void 0,void 0,!0);let r=fo.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"?fo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):fo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:Z8,set:o,skipped:i}}a(t6,"setRoutes");function r6(){let e=fo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(r6,"getRoutes");function n6(e){let t=yU.deleteRoutesValidator(e);if(t)throw IU(t,t.message,wU.BAD_REQUEST,void 0,void 0,!0);let r=fo.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,fo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=GT.isEmptyOrZeroLength(s)?null:s,fo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:e6,deleted:i,skipped:o}}a(n6,"deleteRoutes")});var LU=R((Ahe,DU)=>{"use strict";var Uu=require("alasql"),Eo=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 Eo(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 Eo(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 Eo(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 Eo(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 Eo(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 Eo(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 Eo(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");DU.exports=FT});var YT=R((bhe,vU)=>{var rf=zi(),MU=require("chalk"),Kr=$(),UU=require("prompt"),{promisify:d6}=require("util"),VT=M(),f6=require("fs-extra"),E6=require("path"),h6=Q(),m6=Vd(),PU=Z();PU.initSync();var p6=require("moment"),S6=d6(UU.get),T6=E6.join(PU.getHdbBasePath(),VT.LICENSE_KEY_DIR_NAME,VT.LICENSE_FILE_NAME,VT.LICENSE_FILE_NAME);vU.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:MU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:MU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{UU.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 HU=R((yhe,BU)=>{"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"}};BU.exports=KT});var qU=R((whe,GU)=>{"use strict";var xU=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+xU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+xU.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"}};GU.exports=WT});var kU=R((Dhe,FU)=>{"use strict";var QT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};FU.exports=QT});var $U=R((Mhe,VU)=>{"use strict";var y6=ke(),zT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+y6.SERVER_SUFFIX.ADMIN,this.password=r}};VU.exports=zT});var XT=R((Phe,WU)=>{"use strict";var Ta=require("path"),of=require("fs-extra"),I6=HU(),w6=qU(),C6=kU(),D6=$U(),JT=un(),Ra=Q(),Ar=dr(),sf=M(),Bu=ke(),{CONFIG_PARAMS:ft}=sf,Aa=$(),Hu=Z(),YU=Rs(),jT=it(),ga="clustering",L6=1e4,KU=50;WU.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,YU.decrypt(J.hash))),g.push(new C6(J.username,YU.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<KU;){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>=KU)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 ZU=R((Bhe,XU)=>{"use strict";var Wr=Z(),v6=zi(),he=M(),xu=ke(),Cs=require("path"),{PACKAGE_ROOT:uf}=M(),QU=Z(),cf=Q(),Oa="/dev/null",B6=Cs.join(uf,"launchServiceScripts"),zU=Cs.join(uf,"utility/scripts"),H6=Cs.join(zU,he.HDB_RESTART_SCRIPT),JU=Cs.resolve(uf,"dependencies",`${process.platform}-${process.arch}`,xu.NATS_BINARY_NAME);function jU(){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(jU,"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=QU.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:JU,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=QU.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:JU,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:zU},script:H6}}a(V6,"generateRestart");function $6(){return{apps:[jU()]}}a($6,"generateAllServiceConfigs");XU.exports={generateAllServiceConfigs:$6,generateMainServerConfig:jU,generateRestart:V6,generateNatsHubServerConfig:G6,generateNatsLeafServerConfig:F6,generateClusteringUpgradeV4ServiceConfig:k6}});var fP=R((Ghe,dP)=>{"use strict";var Pe=M(),Y6=Q(),Ls=XT(),lf=it(),Ds=ke(),Ti=ZU(),_f=Z(),gi=$(),K6=_n(),{startWorker:eP,onMessageFromWorkers:W6}=Je(),Q6=Sa(),xhe=require("util"),z6=require("child_process"),J6=require("fs"),{execFile:j6}=z6,Ie;dP.exports={enterPM2Mode:X6,start:Ri,stop:ZT,reload:rP,restart:nP,list:eg,describe:iP,connect:Ms,kill:n9,startAllServices:s9,startService:tg,getUniqueServicesList:oP,restartAllServices:i9,isServiceRegistered:aP,reloadStopStart:cP,restartHdb:sP,deleteProcess:t9,startClusteringProcesses:lP,startClusteringThreads:_P,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,tP;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),!tP&&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(()=>{tP=!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 rP(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(rP,"reload");function nP(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(nP,"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 sP(){await Ri(Ti.generateRestart())}a(sP,"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 iP(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(iP,"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 lP(),await _P(),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 oP(){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(oP,"getUniqueServicesList");async function i9(e=[]){try{let t=!1,r=await oP();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 nP(o))}t&&await cP(Pe.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ie?.disconnect(),t}}a(i9,"restartAllServices");async function aP(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(aP,"isServiceRegistered");async function cP(e){let t=_f.get(Pe.CONFIG_PARAMS.THREADS_COUNT)??_f.get(Pe.CONFIG_PARAMS.THREADS),r=await iP(e),n=Y6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await ZT(e),await tg(e)):e===Pe.PROCESS_DESCRIPTORS.HDB?await sP():await rP(e)}a(cP,"reloadStopStart");var uP;async function lP(e=!1){for(let t in Pe.CLUSTERING_PROCESSES){let r=Pe.CLUSTERING_PROCESSES[t];await tg(r,e)}}a(lP,"startClusteringProcesses");async function _P(){uP=eP(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"),eP(Pe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(_P,"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 uP.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 aP(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 gP={};qe(gP,{compactOnStart:()=>u9,copyDb:()=>TP});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 EP(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 TP(n,o),console.log("Backing up",n,"to",i),await(0,ho.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,ho.move)(i,s,{overwrite:!0}),await(0,ho.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,ho.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 EP(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(cL,"runCommand");async function Ej(){try{await Y3.access(DS)}catch{return!1}let e=await cL(`${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 oL.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),uL()}),i}a(vS,"createConnection");function uL(){mr=void 0,io=void 0,oo=void 0,ao=void 0}a(uL,"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 lL(){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(lL,"getJetStream");async function ss(){let e=mr||await mu(),t=io||await pu(),r=oo||await lL();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 oL.getClusterUser(),s=await vS(t,r,n),i=PS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=aL.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 _L(){let{jsm:e}=await ss(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(_L,"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(aL.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=rL(),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=rL(),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=dL(n,r);let{js:s}=await ss(),i=await Id(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:iL.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 EL(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 dL(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(dL,"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 fL(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(fL,"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=iL.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 tL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case tL.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 EL(async()=>{if(e.subscribe===!0)await fL(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(!sL&&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 EL(e){return j3.writeTransaction(ye.SYSTEM_SCHEMA_NAME,ye.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(EL,"exclusiveLock");async function hL(e,t){let r=yd.createNatsTableStreamName(e,t),n=await Id(),s=Uj(e,t,n);await BS(r,[s])}a(hL,"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 hL(n,s)}}a(Dj,"createTableStreams");async function mL(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(mL,"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 mL(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 _L();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,RL)=>{"use strict";var _a=O_(),da=ND(),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(),SL=it(),{getDatabases:Fj}=(Ae(),ie(Fe)),{transformReq:Ea}=Q();RL.exports={createSchema:kj,createSchemaStructure:TL,createTable:Vj,createTableStructure:gL,createAttribute:Qj,dropSchema:$j,dropTable:Yj,dropAttribute:Kj,getBackup:zj};async function kj(e){let t=await TL(e);return Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),t}a(kj,"createSchema");async function TL(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(TL,"createSchemaStructure");async function Vj(e){return Ea(e),e.hash_attribute=e.primary_key??e.hash_attribute,await gL(e)}a(Vj,"createTable");async function gL(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(gL,"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 SL.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 SL.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 OL=R((Vfe,AL)=>{"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}};AL.exports=xS});var GS=R((Kfe,wL)=>{"use strict";var jj=wn(),Yfe=OL(),Ld=Q(),Md=M(),Xj=Z(),{handleHDBError:bL,hdb_errors:Zj}=ne(),{HDB_ERROR_MSGS:NL,HTTP_STATUS_CODES:yL}=Zj,eX=Object.values(Md.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),IL="To use this operation audit log must be enabled in harperdb-config.yaml";wL.exports=tX;async function tX(e){if(Ld.isEmpty(e.schema))throw new Error(NL.SCHEMA_REQUIRED_ERR);if(Ld.isEmpty(e.table))throw new Error(NL.TABLE_REQUIRED_ERR);if(!Xj.get(Md.CONFIG_PARAMS.LOGGING_AUDITLOG))throw bL(new Error,IL,yL.BAD_REQUEST,Md.LOG_LEVELS.ERROR,IL,!0);let t=Ld.checkSchemaTableExist(e.schema,e.table);if(t)throw bL(new Error,t,yL.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 DL=R((Qfe,CL)=>{"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}};CL.exports=qS});var UL=R((Xfe,ML)=>{"use strict";var nX=wn(),Jfe=DL(),FS=Q(),sX=M(),jfe=Z(),{handleHDBError:iX,hdb_errors:oX}=ne(),{HDB_ERROR_MSGS:LL,HTTP_STATUS_CODES:aX}=oX;ML.exports=cX;async function cX(e){if(FS.isEmpty(e.schema))throw new Error(LL.SCHEMA_REQUIRED_ERR);if(FS.isEmpty(e.table))throw new Error(LL.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 GL=R((eEe,xL)=>{var fi=require("validate.js"),vL=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"},PL=Object.values(ha.ROLE_TYPES_ENUM),fX="attribute_permissions",EX="attribute_name",{PERMS_CRUD_ENUM:ma}=ha,hX=[fX,...Object.values(ma)],BL=[ma.READ,ma.INSERT,ma.UPDATE],mX=[EX,...BL];function pX(e){let t=kS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,HL(e,t)}a(pX,"addRoleValidation");function SX(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,HL(e,t)}a(SX,"alterRoleValidation");function TX(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,vL.validateObject(e,t)}a(TX,"dropRoleValidation");var gX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function HL(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=vL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Tt(o,r)}),e.permission){let o=RX(e);o&&Tt(o,r),PL.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(PL.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}BL.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(HL,"customValidate");xL.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,VL)=>{"use strict";var qL=Hr(),FL=Br(),OX=oi(),$S=GL(),YS=bs(),bX=require("uuid").v4,NX=require("util"),Ud=M(),yX=Q(),KS=FL.searchByValue,IX=FL.searchByHash,wX=NX.promisify(OX.delete),CX=es(),DX=sa(),{hdb_errors:LX,handleHDBError:uo}=ne(),{HDB_ERROR_MSGS:kL,HTTP_STATUS_CODES:Tu}=LX,{UserEventMsg:WS}=Ln();VL.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,kL.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 qL.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 qL.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,kL.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 WL=R((sEe,KL)=>{"use strict";var BX=Z(),Ei=require("joi"),HX=je(),$L=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");KL.exports=function(e){return HX.validateBySchema(e,kX)};var kX=Ei.object({from:Ei.custom(YL),until:Ei.custom(YL),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 YL(e,t){if($L(e,$L.ISO_8601).format(qX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(YL,"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,zL)=>{"use strict";var Pd=M(),$X=$(),YX=Z(),KX=WL(),JS=require("path"),QL=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;zL.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(QL.statSync(s).size-(h+5)*ZX,0));let S=QL.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,ZL)=>{"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(),jL=Z();jL.initSync();var aZ=Ru.invalid(jL.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(),XL={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(XL))}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");ZL.exports={addUpdateNodeValidator:cZ,validation_schema:XL}});var tM=R((fEe,eM)=>{var lZ=je(),_Z={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};eM.exports=function(e){return lZ.validateObject(e,_Z)}});var Bd=R((EEe,rM)=>{"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}};rM.exports=ZS});var sM=R((mEe,nM)=>{"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}};nM.exports={JWTTokens:eT,TOKEN_TYPE_ENUM:fZ,JWTRSAKeys:tT}});var bu=R((SEe,cM)=>{"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=$(),iM=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}=sM(),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;cM.exports={createTokens:OZ,validateOperationToken:NZ,refreshOperationToken:bZ,validateRefreshToken:aM};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 oM(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=iM.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 oM(e,t,r){return await Ou.sign(e,{key:t,passphrase:r},{expiresIn:RZ,algorithm:xd,subject:Hd.OPERATION})}a(oM,"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 aM(e.refresh_token);let t=await Gd(),r=await Ou.decode(e.refresh_token);return{operation_token:await oM({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 aM(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(!iM.validate(t.refresh_token,e))throw Tr(new Error,Rr.INVALID_TOKEN,gr.UNAUTHORIZED);return t}a(aM,"validateRefreshToken")});var aT=R((REe,_M)=>{"use strict";var yZ=tM(),pa=require("passport"),IZ=require("passport-local").Strategy,wZ=require("passport-http").BasicStrategy,CZ=require("util"),DZ=un(),lM=CZ.callbackify(DZ.findAndValidateUser),gEe=Lr(),LZ=M(),uM=bu();pa.use(new IZ(function(e,t,r){lM(e,t,r)}));pa.use(new wZ(function(e,t,r){lM(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?uM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):uM.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");_M.exports={authorize:MZ,checkPermissions:UZ}});var pi=R((OEe,dM)=>{"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}};dM.exports={Node:cT,NodeSubscription:uT}});var EM=R((NEe,fM)=>{"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}};fM.exports=lT});var Nu=R((IEe,hM)=>{"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)}};hM.exports={RemotePayloadObject:_T,RemotePayloadSubscription:dT}});var pM=R((CEe,mM)=>{"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}};mM.exports=fT});var gM=R((PEe,TM)=>{"use strict";var vZ=pM(),LEe=ut(),SM=Ke(),BZ=$(),{getSchemaPath:MEe,getTransactionAuditStorePath:UEe}=ze(),{getDatabases:HZ}=(Ae(),ie(Fe));TM.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 SM.environmentDataSize(schema_path,e.name),o=await SM.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 AM=R((BEe,RM)=>{"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}};RM.exports=ET});var Sa=R((FEe,IM)=>{"use strict";var GZ=require("fs-extra"),qZ=require("path"),er=require("systeminformation"),Si=$(),OM=it(),xEe=ke(),Fd=M(),FZ=gM(),kZ=As(),{getThreadInfo:bM}=Je(),bT=Z();bT.initSync();var VZ=AM(),{openEnvironment:GEe}=Ke(),{getSchemaPath:qEe}=ze(),{database:$Z,databases:NM}=(Ae(),ie(Fe)),qd;IM.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 NM){let r=e[t]={};for(let n in NM[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 yM(){if(bT.get(Fd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await OM.getNATSReferences(),t=await OM.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(yM,"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 bM(),t.replication=await yM(),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 bM();break;case"replication":t.replication=await yM();break;default:break}return t}a(YZ,"systemInformation")});var Vd=R((VEe,wM)=>{"use strict";wM.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,MM)=>{"use strict";var QZ=Hr(),NT=Q(),zZ=require("util"),_o=M(),CM=Z();CM.initSync();var JZ=aT(),DM=Br(),{Node:YEe,NodeSubscription:KEe}=pi(),jZ=sa(),XZ=EM(),{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=DM.searchByHash,_5=DM.searchByValue;MM.exports={authHeaderToUser:d5,isEmpty:f5,getNodeRecord:E5,upsertNodeRecord:h5,buildNodePayloads:m5,checkClusteringEnabled:p5,getAllNodeRecords:S5,getSystemInfo:T5,reverseSubscription:LM};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 LM(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(LM,"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}=LM(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(!CM.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,qM)=>{"use strict";var $d=it(),UM=Q(),PM=ke(),vM=M(),Yd=$(),BM=Su(),g5=id(),{RemotePayloadObject:R5}=Nu(),{handleHDBError:HM,hdb_errors:A5}=ne(),{HTTP_STATUS_CODES:xM}=A5,{NodeSubscription:GM}=pi();qM.exports=O5;async function O5(e,t){let r;try{r=await $d.request(`${t}.${PM.REQUEST_SUFFIX}`,new R5(vM.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 HM(new Error,c,xM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===PM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw HM(new Error,o,xM.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===vM.SYSTEM_SCHEMA_NAME){await $d.createLocalTableStream(u,c);let h=new GM(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,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 BM.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 BM.createTable(h)}await $d.createLocalTableStream(u,c);let E=new GM(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,VM)=>{"use strict";var{handleHDBError:Kd,hdb_errors:b5}=ne(),{HTTP_STATUS_CODES:Wd}=b5,{addUpdateNodeValidator:N5}=vd(),Qd=$(),kM=M(),FM=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(kM.CONFIG_PARAMS.CLUSTERING_NODENAME);VM.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,kM.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}.${FM.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===FM.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,KM)=>{"use strict";var{handleHDBError:IT,hdb_errors:B5}=ne(),{HTTP_STATUS_CODES:wT}=B5,{addUpdateNodeValidator:H5}=vd(),wu=$(),YM=M(),$M=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(YM.CONFIG_PARAMS.CLUSTERING_NODENAME);KM.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,YM.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}.${$M.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===$M.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 jM=R((rhe,JM)=>{"use strict";var zM=require("joi"),{string:WM}=zM.types(),z5=je(),QM=M(),J5=Z(),j5=ke();JM.exports=X5;function X5(e){let t=WM.invalid(J5.get(QM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(j5.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=zM.object({operation:WM.valid(QM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return z5.validateBySchema(e,r)}a(X5,"removeNodeValidator")});var jd=R((she,rU)=>{"use strict";var{handleHDBError:XM,hdb_errors:Z5}=ne(),{HTTP_STATUS_CODES:ZM}=Z5,e8=jM(),Lu=$(),eU=_n(),t8=Q(),Jd=M(),tU=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);rU.exports=u8;async function u8(e){Lu.trace("removeNode called with:",e),eU.checkClusteringEnabled();let t=e8(e);if(t)throw XM(t,t.message,ZM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await eU.getNodeRecord(r);if(t8.isEmptyOrZeroLength(n))throw XM(new Error,`Node '${r}' was not found.`,ZM.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}.${tU.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===tU.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 iU=R((ohe,sU)=>{"use strict";var nU=require("joi"),{string:l8,array:_8}=nU.types(),d8=je(),f8=vd();sU.exports=E8;function E8(e){let t=nU.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,lU)=>{"use strict";var h8=M(),Xd=$(),m8=Q(),p8=jd(),S8=zd(),oU=_n(),T8=iU(),{handleHDBError:aU,hdb_errors:g8}=ne(),{HTTP_STATUS_CODES:cU}=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.";lU.exports=b8;async function b8(e){Xd.trace("configure cluster called with:",e),oU.checkClusteringEnabled();let t=T8(e);if(t)throw aU(t,t.message,cU.BAD_REQUEST,void 0,void 0,!0);let r=await oU.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let f=await uU(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 uU(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 aU(new Error,A8,cU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(b8,"configureCluster");async function uU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(uU,"functionWrapper")});var EU=R((lhe,fU)=>{"use strict";var Mu=require("joi"),N8=je(),{validateSchemaExists:_U,validateTableExists:y8,validateSchemaName:dU}=zn(),I8=Mu.object({operation:Mu.string().valid("purge_stream"),schema:Mu.string().custom(_U).custom(dU).optional(),database:Mu.string().custom(_U).custom(dU).optional(),table:Mu.string().custom(y8).required()});function w8(e){return N8.validateBySchema(e,I8)}a(w8,"purgeStreamValidator");fU.exports=w8});var MT=R((dhe,hU)=>{"use strict";var{handleHDBError:C8,hdb_errors:D8}=ne(),{HTTP_STATUS_CODES:L8}=D8,M8=EU(),U8=it(),P8=_n();hU.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,RU)=>{"use strict";var PT=_n(),B8=it(),SU=Z(),Zd=M(),fo=ke(),H8=Q(),UT=$(),{RemotePayloadObject:x8}=Nu(),{ErrorCode:mU}=require("nats"),pU=SU.get(Zd.CONFIG_PARAMS.CLUSTERING_ENABLED),TU=SU.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);RU.exports={clusterStatus:G8,buildNodeStatus:gU};async function G8(){let e={node_name:TU,is_enabled:pU,connections:[]};if(!pU)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(gU(t[n],e.connections));return await Promise.allSettled(r),e}a(G8,"clusterStatus");async function gU(e,t){let r=e.name,n=new x8(Zd.OPERATIONS_ENUM.CLUSTER_STATUS,TU,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===mU.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===mU.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(gU,"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,AU)=>{"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()});AU.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 yU=R((She,NU)=>{"use strict";var xT=require("joi"),OU=je(),{route_constraints:bU}=tp();NU.exports={setRoutesValidator:J8,deleteRoutesValidator:j8};function J8(e){let t=xT.object({server:xT.valid("hub","leaf").required(),routes:bU.required()});return OU.validateBySchema(e,t)}a(J8,"setRoutesValidator");function j8(e){let t=xT.object({routes:bU.required()});return OU.validateBySchema(e,t)}a(j8,"deleteRoutesValidator")});var qT=R((ghe,DU)=>{"use strict";var Eo=dr(),GT=Q(),tf=M(),IU=yU(),{handleHDBError:wU,hdb_errors:X8}=ne(),{HTTP_STATUS_CODES:CU}=X8,Z8="cluster routes successfully set",e6="cluster routes successfully deleted";DU.exports={setRoutes:t6,getRoutes:r6,deleteRoutes:n6};function t6(e){let t=IU.setRoutesValidator(e);if(t)throw wU(t,t.message,CU.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=IU.deleteRoutesValidator(e);if(t)throw wU(t,t.message,CU.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 MU=R((Ahe,LU)=>{"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");LU.exports=FT});var YT=R((bhe,BU)=>{var rf=Ji(),UU=require("chalk"),Kr=$(),PU=require("prompt"),{promisify:d6}=require("util"),VT=M(),f6=require("fs-extra"),E6=require("path"),h6=Q(),m6=Vd(),vU=Z();vU.initSync();var p6=require("moment"),S6=d6(PU.get),T6=E6.join(vU.getHdbBasePath(),VT.LICENSE_KEY_DIR_NAME,VT.LICENSE_FILE_NAME,VT.LICENSE_FILE_NAME);BU.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:UU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:UU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{PU.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 xU=R((yhe,HU)=>{"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"}};HU.exports=KT});var FU=R((whe,qU)=>{"use strict";var GU=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+GU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+GU.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"}};qU.exports=WT});var VU=R((Dhe,kU)=>{"use strict";var QT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};kU.exports=QT});var YU=R((Mhe,$U)=>{"use strict";var y6=ke(),zT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+y6.SERVER_SUFFIX.ADMIN,this.password=r}};$U.exports=zT});var XT=R((Phe,QU)=>{"use strict";var Ta=require("path"),of=require("fs-extra"),I6=xU(),w6=FU(),C6=VU(),D6=YU(),JT=un(),Ra=Q(),Ar=dr(),sf=M(),Bu=ke(),{CONFIG_PARAMS:ft}=sf,Aa=$(),Hu=Z(),KU=Rs(),jT=it(),ga="clustering",L6=1e4,WU=50;QU.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,KU.decrypt(J.hash))),g.push(new C6(J.username,KU.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<WU;){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>=WU)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 eP=R((Bhe,ZU)=>{"use strict";var Wr=Z(),v6=Ji(),he=M(),xu=ke(),Cs=require("path"),{PACKAGE_ROOT:uf}=M(),zU=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),jU=Cs.resolve(uf,"dependencies",`${process.platform}-${process.arch}`,xu.NATS_BINARY_NAME);function XU(){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(XU,"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=zU.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:jU,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=zU.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:jU,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:[XU()]}}a($6,"generateAllServiceConfigs");ZU.exports={generateAllServiceConfigs:$6,generateMainServerConfig:XU,generateRestart:V6,generateNatsHubServerConfig:G6,generateNatsLeafServerConfig:F6,generateClusteringUpgradeV4ServiceConfig:k6}});var EP=R((Ghe,fP)=>{"use strict";var Pe=M(),Y6=Q(),Ls=XT(),lf=it(),Ds=ke(),Ti=eP(),_f=Z(),gi=$(),K6=_n(),{startWorker:tP,onMessageFromWorkers:W6}=Je(),Q6=Sa(),xhe=require("util"),z6=require("child_process"),J6=require("fs"),{execFile:j6}=z6,Ie;fP.exports={enterPM2Mode:X6,start:Ri,stop:ZT,reload:nP,restart:sP,list:eg,describe:oP,connect:Ms,kill:n9,startAllServices:s9,startService:tg,getUniqueServicesList:aP,restartAllServices:i9,isServiceRegistered:cP,reloadStopStart:uP,restartHdb:iP,deleteProcess:t9,startClusteringProcesses:_P,startClusteringThreads:dP,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,rP;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),!rP&&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(()=>{rP=!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 nP(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(nP,"reload");function sP(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(sP,"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 iP(){await Ri(Ti.generateRestart())}a(iP,"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 oP(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(oP,"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 _P(),await dP(),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 aP(){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(aP,"getUniqueServicesList");async function i9(e=[]){try{let t=!1,r=await aP();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 sP(o))}t&&await uP(Pe.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ie?.disconnect(),t}}a(i9,"restartAllServices");async function cP(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(cP,"isServiceRegistered");async function uP(e){let t=_f.get(Pe.CONFIG_PARAMS.THREADS_COUNT)??_f.get(Pe.CONFIG_PARAMS.THREADS),r=await oP(e),n=Y6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await ZT(e),await tg(e)):e===Pe.PROCESS_DESCRIPTORS.HDB?await iP():await nP(e)}a(uP,"reloadStopStart");var lP;async function _P(e=!1){for(let t in Pe.CLUSTERING_PROCESSES){let r=Pe.CLUSTERING_PROCESSES[t];await tg(r,e)}}a(_P,"startClusteringProcesses");async function dP(){lP=tP(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"),tP(Pe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(dP,"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 lP.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 cP(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 RP={};qe(RP,{compactOnStart:()=>u9,copyDb:()=>gP});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 hP(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 gP(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 hP(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,
|
|
13
|
-
${r.stack}`;throw cg.error(n),CP(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]=UP(),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||vP.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=UP(!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=LP(d,l[Yu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=DP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=HP(l),s.attribute_permissions.push(l),c||w9(l,u)}else if(_!==o){let l;br.TIME_STAMP_NAMES.includes(_)?l=LP(_):l=DP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=MP(s),s}else return e.describe=MP(e),e}a(I9,"getTableAttrPerms");function MP(e){return vP.filter(t=>e[t]).length>0}a(MP,"getSchemaTableDescribePerm");function HP(e){return BP.filter(t=>e[t]).length>0}a(HP,"getAttributeDescribePerm");function w9(e,t){BP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(w9,"checkForHashPerms")});var qP={};qe(qP,{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(()=>{to();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 FP={};qe(FP,{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:()=>zP,bypassAuth:()=>B9,login:()=>x9,logout:()=>G9,start:()=>H9});function B9(){QP=!0}async function zP(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 VP.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?kP.notify(S):kP.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=po.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&&(po.get(p)||(po.set(p,p),l(S,Bt.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:So({error:A.message},e)})}po.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):(QP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,YP.getSuperUser)());Rf&&(e.session.update=function(E){if(!u){u=(0,KP.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,VP.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(zP,{port:t||"all"}),$P||($P=!0,setInterval(()=>{po=new Map},fn.get(Bt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),WP.user.addListener(()=>{po=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 YP,Af,KP,fn,Bt,ya,WP,kP,D9,L9,M9,U9,VP,Rf,QP,P9,v9,po,$P,Of=Re(()=>{YP=B(un());ar();Ku();Af=B(bu());Ae();KP=require("uuid"),fn=B(Z()),Bt=B(M()),ya=B($()),WP=B(Vc());Wu();Ia();kP=(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),VP=lt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Rf=fn.get(Bt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,QP=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,po=new Map;nt.onInvalidatedUser(()=>{po=new Map});a(B9,"bypassAuth");a(zP,"authentication");a(H9,"start");a(x9,"login");a(G9,"logout")});var rv=R((ime,tv)=>{"use strict";var we=require("joi"),JP=require("fs-extra"),jP=require("path"),Ps=je(),XP=Z(),ZP=M(),ev=$(),{hdb_errors:q9}=ne(),{HDB_ERROR_MSGS:tr}=q9,Us=/^[a-zA-Z0-9-_]+$/;tv.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=XP.get(ZP.CONFIG_PARAMS.COMPONENTSROOT),s=jP.join(n,t);return JP.existsSync(s)?e?t:r.message(tr.PROJECT_EXISTS):e?r.message(tr.NO_PROJECT):t}catch(n){return ev.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=XP.get(ZP.CONFIG_PARAMS.COMPONENTSROOT),i=jP.join(s,e,t,r+".js");return JP.existsSync(i)?r:n.message(tr.NO_FILE)}catch(s){return ev.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,uv)=>{"use strict";var Nf=require("joi"),yf=require("path"),nv=require("fs-extra"),{exec:j9}=require("child_process"),X9=require("util"),sv=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),iv="npm install --omit=dev --json",t7=`${iv} --dry-run`;uv.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 sv(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
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 hP(e){let t=await(0,TP.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function gP(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,mP.open)(new pP.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 SP.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 mP,df,mo,rg,pP,SP,ff,Ai,TP,ng,Fu,AP=Re(()=>{Ae();mP=require("lmdb"),df=require("path"),mo=require("fs-extra"),rg=B(Z()),pP=B(Dc()),SP=B(Cc()),ff=B(ut()),Ai=B(M());ti();TP=B(As()),ng=B(dr()),Fu=B($());a(u9,"compactOnStart");a(hP,"getTotalDBRecordCount");a(gP,"copyDb")});var Tf=R((Yhe,CP)=>{"use strict";var l9=require("minimist"),{isMainThread:ig,parentPort:NP}=require("worker_threads"),et=M(),{PROCESS_DESCRIPTORS_VALIDATE:ku}=et,is=$(),og=Q(),pf=XT(),mf=it(),$he=ke(),yP=dr(),os=EP(),OP=Sa(),{compactOnStart:_9}=(AP(),ie(RP)),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.",bP="Clustering is not enabled so cannot be restarted",S9="Invalid service",ba,dn;CP.exports={restart:IP,restartService:ag};ig&&f9(et.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?ag({service:e.workerType}):IP({operation:"restart"})});async function IP(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))||yP.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)):NP.postMessage({type:et.ITC_EVENT_TYPES.RESTART}),Vu}a(IP,"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 NP.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=bP;break}dn&&console.log("Restarting clustering"),is.notify("Restarting clustering"),await wP();break;case ku.clustering_config:case ku["clustering config"]:if(!$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=bP;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 wP(),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 wP(){if(!yP.getConfigFromFile(et.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await OP.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 OP.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(wP,"restartClustering");async function sg(){await pf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await pf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(sg,"removeNatsConfig")});var qP=R((Qhe,GP)=>{"use strict";var Whe=require("lodash"),br=M(),{handleHDBError:DP,hdb_errors:g9}=ne(),{HDB_ERROR_MSGS:R9,HTTP_STATUS_CODES:A9}=g9,cg=$();GP.exports={getRolePermissions:b9};var po=Object.create(null),O9=a(e=>({key:e,perms:{}}),"perms_template_obj"),PP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),vP=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,...vP(t,r,n,s)}),"table_perms_template"),LP=a((e,t=vP())=>({attribute_name:e,describe:xP(t),[Yu]:t[Yu],[lg]:t[lg],[_g]:t[_g]}),"attr_perms_template"),MP=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,BP=Object.values(br.PERMS_CRUD_ENUM),HP=[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),DP(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),DP(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]=PP(),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||BP.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=PP(!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=MP(d,l[Yu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=LP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=xP(l),s.attribute_permissions.push(l),c||w9(l,u)}else if(_!==o){let l;br.TIME_STAMP_NAMES.includes(_)?l=MP(_):l=LP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=UP(s),s}else return e.describe=UP(e),e}a(I9,"getTableAttrPerms");function UP(e){return BP.filter(t=>e[t]).length>0}a(UP,"getSchemaTableDescribePerm");function xP(e){return HP.filter(t=>e[t]).length>0}a(xP,"getAttributeDescribePerm");function w9(e,t){HP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(w9,"checkForHashPerms")});var FP={};qe(FP,{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 kP={};qe(kP,{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(){zP=!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 $P.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?VP.notify(S):VP.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):(zP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,KP.getSuperUser)());Rf&&(e.session.update=function(E){if(!u){u=(0,WP.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,$P.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"}),YP||(YP=!0,setInterval(()=>{So=new Map},fn.get(Bt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),QP.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 KP,Af,WP,fn,Bt,ya,QP,VP,D9,L9,M9,U9,$P,Rf,zP,P9,v9,So,YP,Of=Re(()=>{KP=B(un());ar();Ku();Af=B(bu());Ae();WP=require("uuid"),fn=B(Z()),Bt=B(M()),ya=B($()),QP=B(Vc());Wu();Ia();VP=(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),$P=lt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Rf=fn.get(Bt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,zP=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 nv=R((ime,rv)=>{"use strict";var we=require("joi"),jP=require("fs-extra"),XP=require("path"),Ps=je(),ZP=Z(),ev=M(),tv=$(),{hdb_errors:q9}=ne(),{HDB_ERROR_MSGS:tr}=q9,Us=/^[a-zA-Z0-9-_]+$/;rv.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=ZP.get(ev.CONFIG_PARAMS.COMPONENTSROOT),s=XP.join(n,t);return jP.existsSync(s)?e?t:r.message(tr.PROJECT_EXISTS):e?r.message(tr.NO_PROJECT):t}catch(n){return tv.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=ZP.get(ev.CONFIG_PARAMS.COMPONENTSROOT),i=XP.join(s,e,t,r+".js");return jP.existsSync(i)?r:n.message(tr.NO_FILE)}catch(s){return tv.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,lv)=>{"use strict";var Nf=require("joi"),yf=require("path"),sv=require("fs-extra"),{exec:j9}=require("child_process"),X9=require("util"),iv=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),ov="npm install --omit=dev --json",t7=`${ov} --dry-run`;lv.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 iv(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
14
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=
|
|
15
|
+
`,"")}a(Xu,"runCommand");async function i7(e){Da.info(`starting installModules for request: ${e}`);let t=uv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?t7:ov;await If(),await cv(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 iv(s,{cwd:_});l=f?f.replace(`
|
|
16
16
|
`,""):null,d=E?E.replace(`
|
|
17
|
-
`,""):null}catch(f){f.stderr?i[u].npm_error=
|
|
18
|
-
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(ov,"parseNPMStdErr");async function o7(e){Da.info(`starting auditModules for request: ${e}`);let t=cv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r}=e;await If(),await av(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=ov(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 av(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 nv.pathExists(o)){t.push(i);continue}let u=yf.join(o,"package.json");await nv.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(av,"checkProjectPaths");function cv(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(cv,"modulesValidator")});var hg=R((ume,Ev)=>{"use strict";var La=require("fs-extra"),Eg=require("path"),Cf=$(),lv=Q(),Df=M(),fv=Z(),a7=dr();Ev.exports=c7;async function c7(){let e=u7(),t=fv.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(lv.isEmptyOrZeroLength(e))return;if(u.code!==Df.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!lv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await _v(_);n.dependencies[u]=l+_}if(!o){Cf.notify("Installing components"),await dv(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await _v(_);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 dv(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 _v(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":Eg.extname(e)||await La.pathExists(e)?"file:":"github:"}a(_v,"getPkgPrefix");async function dv(e,t,r){Cf.trace("npm installing components package.json",t),await La.writeFile(e,JSON.stringify(t,null," "));try{await wf().installAllRootModules(fv.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(dv,"installPackages")});var Sg=R((dme,Sv)=>{"use strict";var Ve=require("fs-extra"),mg=require("fast-glob"),ge=require("path"),mv=require("tar-fs"),_me=require("uuid").v4,pg=require("normalize-path"),as=rv(),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(),pv=Z(),h7=M(),{Readable:m7}=require("stream"),{isMainThread:p7}=require("worker_threads"),{HDB_ERROR_MSGS:To,HTTP_STATUS_CODES:xt}=d7,S7=ge.join(_7,"application-template"),hv=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,To.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,To.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,To.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,To.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,To.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,To.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,To.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(hv);let i=ge.join(hv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(ge.join(s,"node_modules"))}),mv.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(mv.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=pv.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(pv.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");Sv.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,gv)=>{"use strict";var cs=require("joi"),Tv=je();gv.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 Tv.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 Tv.validateBySchema(e,t)}a(U7,"deleteTransactionLogsBeforeValidator")});var Uf=R((mme,Nv)=>{"use strict";var gg=M(),el=it(),Rv=Q(),Av=Z(),Ov=Rs(),{handleHDBError:Ma,hdb_errors:P7}=ne(),{HTTP_STATUS_CODES:Ua}=P7,{readTransactionLogValidator:v7,deleteTransactionLogsBeforeValidator:B7}=Tg(),bv="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.";Nv.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(!Av.get(gg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,bv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Rv.checkSchemaTableExist(r,n);if(s)throw Ma(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=Ov.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(!Av.get(gg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,bv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Rv.checkSchemaTableExist(r,n);if(i)throw Ma(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=Ov.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 Iv=R((Sme,yv)=>{"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}};yv.exports=Rg});var Cv=R((gme,wv)=>{"use strict";var Ag=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};wv.exports=Ag});var bg=R((Ame,Lv)=>{"use strict";var Dv=Iv(),F7=Cv(),{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 Dv(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 Dv(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}};Lv.exports=Og});var Hf=R((bme,Wv)=>{"use strict";var Ng=Hr(),Pf=Br(),hn=Su(),nl=As(),yg=oi(),V7=GS(),$7=ML(),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=LU(),wg=YT(),Pv=Tf(),En=M(),vv=GP(),eee=Sa(),Bv=bu(),Hv=(Of(),ie(Qu)),xv=dr(),Qr=Sg(),tee=require("alasql"),Gv=Uf(),qv=wf(),Fv=bg(),{handleHDBError:Nr,hdb_errors:kv}=ne(),{HDB_ERROR_MSGS:Yt,HTTP_STATUS_CODES:tl}=kv,V=new Map,Vv="delete",Ni="insert",Bs="read",go="update",rl="describe",Mv=nl.describeSchema.name,Uv=nl.describeTable.name,$v={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],Yv={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,[go]));V.set(Ng.upsert.name,new W(!1,[Ni,go]));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,[Vv]));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(xv.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(Pv.restart.name,new W(!0,[]));V.set(Pv.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(xv.getConfiguration.name,new W(!0,[]));V.set(Gv.readTransactionLog.name,new W(!0,[]));V.set(Gv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(qv.installModules.name,new W(!0,[]));V.set(qv.auditModules.name,new W(!0,[]));V.set(Bv.createTokens.name,new W(!1,[]));V.set(Bv.refreshOperationToken.name,new W(!1,[]));V.set(Hv.login.name,new W(!1,[]));V.set(Hv.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,go]));V.set(Bf.CSV_URL_LOAD,new W(!1,[Ni,go]));V.set(Bf.CSV_FILE_LOAD,new W(!1,[Ni,go]));V.set(Bf.IMPORT_FROM_S3,new W(!1,[Ni,go]));V.set(Yv.EXPORT_TO_S3,new W(!0,[]));V.set(Yv.EXPORT_LOCAL,new W(!0,[]));V.set(En.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Vv]));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,[go]));Wv.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 Fv,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&&$v[r])throw Nr(new Error,Yt.DROP_SYSTEM,tl.FORBIDDEN);if(c&&!u)return null;let _=vv.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=Kv(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 Fv;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&&$v[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=vv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Mv||r===Uv){if(s===En.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Yt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Mv&&(!d[s]||!d[s][rl]))return c.handleInvalidItem(Yt.SCHEMA_NOT_FOUND(s));if(r===Uv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][rl]))return c.handleInvalidItem(Yt.TABLE_NOT_FOUND(s,i))}}let f=Kv(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 Kv(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(kv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Kv,"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,Xv)=>{"use strict";Xv.exports={evaluateSQL:Aee,processAST:jv,convertSQLToAST:Jv,checkASTPermissions:zv};var lee=Hr(),Qv=require("util"),_ee=Qv.callbackify(lee.insert),dee=Br().search,fee=pD().update,Eee=Qv.callbackify(fee),hee=TD().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=Jv(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)}jv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Aee,"evaluateSQL");function zv(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(zv,"checkASTPermissions");function Jv(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(Jv,"convertSQLToAST");function jv(e,t,r){try{let n=Oee;if(!e.bypass_auth&&!t.permissions_checked){let i=zv(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(jv,"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,e0)=>{"use strict";var{S3:yee,GetObjectCommand:Iee}=require("@aws-sdk/client-s3");e0.exports={getFileStreamFromS3:wee,getS3AuthObj:Zv};async function wee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Zv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Iee(r))).Body}a(wee,"getFileStreamFromS3");function Zv(e,t,r){return new yee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Zv,"getS3AuthObj")});var qf=R((Dme,u0)=>{"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:n0}=require("util"),ol=Q(),{handleHDBError:Rt,hdb_errors:Pee}=ne(),{HDB_ERROR_MSGS:yr,HTTP_STATUS_CODES:At}=Pee,{streamAsJSON:vee}=(em(),ie(wb)),{Upload:Bee}=require("@aws-sdk/lib-storage"),t0=["search_by_value","search_by_hash","sql","search_by_conditions"],r0=["json","csv"],s0="json",i0="csv",Hee="Successfully exported JSON locally.",xee="Successfully exported CSV locally.",Gee=1e3,qee=Bg.searchByHash,Fee=Bg.searchByValue,kee=n0(Cee.evaluateSQL),Vee=n0(al.finished);u0.exports={export_to_s3:Wee,export_local:$ee,toCsvStream:o0};async function $ee(e){mn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=a0(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 c0(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===s0){let n=vg.createWriteStream(e);return vee(r).pipe(n),await Vee(n),{message:Hee,path:e}}else if(t===i0){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=a0(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 c0(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===i0){i=e.s3.key+".csv";let u=o0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===s0){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 o0(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(o0,"toCsvStream");function a0(e){if(mn.trace("in exportCoreValidation"),zr.isEmpty(e.format))return"format missing";if(r0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${r0.join(", ")}`;let t=e.search_operation.operation;if(zr.isEmpty(t))return"search_operation.operation missing";if(t0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${t0.join(", ")}`}a(a0,"exportCoreValidation");async function c0(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(c0,"getRecords")});var p0={};qe(p0,{contentTypes:()=>qg,findBestSerializer:()=>Vf,getDeserializer:()=>Ao,registerContentHandlers:()=>Fg,serialize:()=>$f,serializeMessage:()=>So});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 Ro.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,Ro.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=_0&&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>_0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function So(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 Ao(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||d0(e,n);return o=>jee(o).then(i)}return e&&Gt.get(e)?.deserialize||d0(e,n)}function d0(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,Ro,Hs,kf,f0,Hg,xg,E0,h0,cl,Gg,ul,Gt,qg,l0,m0,zee,Jee,_0,Ia=Re(()=>{em();Ff=B(qf()),us=require("msgpackr"),Ro=require("cbor-x"),Hs=require("zlib"),kf=require("stream");ar();f0=require("../index"),Hg=B(Z()),xg=B(M()),E0=B(require("yaml")),h0=Hg.default.get(xg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,cl=h0?Hi:JSON.stringify,Gg=h0?Zh:JSON.parse,ul={useRecords:!1,useToJSON:!0},Gt=new Map,qg=Gt;nt.contentTypes=qg;(0,f0._assignPackageExport)("contentTypes",qg);Gt.set("application/json",{serializeStream:Oc,serialize:cl,deserialize:Gg,q:.8});l0=new Ro.Encoder(ul);Gt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ro.EncoderStream(ul).end(e)},serialize:l0.encode,deserialize:l0.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 E0.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+`
|
|
17
|
+
`,""):null}catch(f){f.stderr?i[u].npm_error=av(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 av(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(av,"parseNPMStdErr");async function o7(e){Da.info(`starting auditModules for request: ${e}`);let t=uv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r}=e;await If(),await cv(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=av(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 cv(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 sv.pathExists(o)){t.push(i);continue}let u=yf.join(o,"package.json");await sv.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(cv,"checkProjectPaths");function uv(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(uv,"modulesValidator")});var hg=R((ume,hv)=>{"use strict";var La=require("fs-extra"),Eg=require("path"),Cf=$(),_v=Q(),Df=M(),Ev=Z(),a7=dr();hv.exports=c7;async function c7(){let e=u7(),t=Ev.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(_v.isEmptyOrZeroLength(e))return;if(u.code!==Df.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!_v.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await dv(_);n.dependencies[u]=l+_}if(!o){Cf.notify("Installing components"),await fv(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await dv(_);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 fv(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 dv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":Eg.extname(e)||await La.pathExists(e)?"file:":"github:"}a(dv,"getPkgPrefix");async function fv(e,t,r){Cf.trace("npm installing components package.json",t),await La.writeFile(e,JSON.stringify(t,null," "));try{await wf().installAllRootModules(Ev.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(fv,"installPackages")});var Sg=R((dme,Tv)=>{"use strict";var Ve=require("fs-extra"),mg=require("fast-glob"),ge=require("path"),pv=require("tar-fs"),_me=require("uuid").v4,pg=require("normalize-path"),as=nv(),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(),Sv=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"),mv=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(mv);let i=ge.join(mv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(ge.join(s,"node_modules"))}),pv.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(pv.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=Sv.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(Sv.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");Tv.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,Rv)=>{"use strict";var cs=require("joi"),gv=je();Rv.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 gv.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 gv.validateBySchema(e,t)}a(U7,"deleteTransactionLogsBeforeValidator")});var Uf=R((mme,yv)=>{"use strict";var gg=M(),el=it(),Av=Q(),Ov=Z(),bv=Rs(),{handleHDBError:Ma,hdb_errors:P7}=ne(),{HTTP_STATUS_CODES:Ua}=P7,{readTransactionLogValidator:v7,deleteTransactionLogsBeforeValidator:B7}=Tg(),Nv="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.";yv.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(!Ov.get(gg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,Nv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Av.checkSchemaTableExist(r,n);if(s)throw Ma(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=bv.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(!Ov.get(gg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,Nv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Av.checkSchemaTableExist(r,n);if(i)throw Ma(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=bv.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 wv=R((Sme,Iv)=>{"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}};Iv.exports=Rg});var Dv=R((gme,Cv)=>{"use strict";var Ag=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Cv.exports=Ag});var bg=R((Ame,Mv)=>{"use strict";var Lv=wv(),F7=Dv(),{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 Lv(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 Lv(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}};Mv.exports=Og});var Hf=R((bme,Qv)=>{"use strict";var Ng=Hr(),Pf=Br(),hn=Su(),nl=As(),yg=oi(),V7=GS(),$7=UL(),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=MU(),wg=YT(),vv=Tf(),En=M(),Bv=qP(),eee=Sa(),Hv=bu(),xv=(Of(),ie(Qu)),Gv=dr(),Qr=Sg(),tee=require("alasql"),qv=Uf(),Fv=wf(),kv=bg(),{handleHDBError:Nr,hdb_errors:Vv}=ne(),{HDB_ERROR_MSGS:Yt,HTTP_STATUS_CODES:tl}=Vv,V=new Map,$v="delete",Ni="insert",Bs="read",Ro="update",rl="describe",Uv=nl.describeSchema.name,Pv=nl.describeTable.name,Yv={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],Kv={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,[$v]));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(Gv.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(vv.restart.name,new W(!0,[]));V.set(vv.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(Gv.getConfiguration.name,new W(!0,[]));V.set(qv.readTransactionLog.name,new W(!0,[]));V.set(qv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Fv.installModules.name,new W(!0,[]));V.set(Fv.auditModules.name,new W(!0,[]));V.set(Hv.createTokens.name,new W(!1,[]));V.set(Hv.refreshOperationToken.name,new W(!1,[]));V.set(xv.login.name,new W(!1,[]));V.set(xv.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(Kv.EXPORT_TO_S3,new W(!0,[]));V.set(Kv.EXPORT_LOCAL,new W(!0,[]));V.set(En.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[$v]));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]));Qv.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 kv,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&&Yv[r])throw Nr(new Error,Yt.DROP_SYSTEM,tl.FORBIDDEN);if(c&&!u)return null;let _=Bv.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=Wv(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 kv;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&&Yv[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=Bv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Uv||r===Pv){if(s===En.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Yt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Uv&&(!d[s]||!d[s][rl]))return c.handleInvalidItem(Yt.SCHEMA_NOT_FOUND(s));if(r===Pv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][rl]))return c.handleInvalidItem(Yt.TABLE_NOT_FOUND(s,i))}}let f=Wv(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 Wv(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(Vv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Wv,"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,Zv)=>{"use strict";Zv.exports={evaluateSQL:Aee,processAST:Xv,convertSQLToAST:jv,checkASTPermissions:Jv};var lee=Hr(),zv=require("util"),_ee=zv.callbackify(lee.insert),dee=Br().search,fee=SD().update,Eee=zv.callbackify(fee),hee=gD().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=jv(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)}Xv(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 jv(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(jv,"convertSQLToAST");function Xv(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(Xv,"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,t0)=>{"use strict";var{S3:yee,GetObjectCommand:Iee}=require("@aws-sdk/client-s3");t0.exports={getFileStreamFromS3:wee,getS3AuthObj:e0};async function wee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await e0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Iee(r))).Body}a(wee,"getFileStreamFromS3");function e0(e,t,r){return new yee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(e0,"getS3AuthObj")});var qf=R((Dme,l0)=>{"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:s0}=require("util"),ol=Q(),{handleHDBError:Rt,hdb_errors:Pee}=ne(),{HDB_ERROR_MSGS:yr,HTTP_STATUS_CODES:At}=Pee,{streamAsJSON:vee}=(em(),ie(Cb)),{Upload:Bee}=require("@aws-sdk/lib-storage"),r0=["search_by_value","search_by_hash","sql","search_by_conditions"],n0=["json","csv"],i0="json",o0="csv",Hee="Successfully exported JSON locally.",xee="Successfully exported CSV locally.",Gee=1e3,qee=Bg.searchByHash,Fee=Bg.searchByValue,kee=s0(Cee.evaluateSQL),Vee=s0(al.finished);l0.exports={export_to_s3:Wee,export_local:$ee,toCsvStream:a0};async function $ee(e){mn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=c0(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 u0(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===i0){let n=vg.createWriteStream(e);return vee(r).pipe(n),await Vee(n),{message:Hee,path:e}}else if(t===o0){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=c0(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 u0(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===o0){i=e.s3.key+".csv";let u=a0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===i0){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 a0(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(a0,"toCsvStream");function c0(e){if(mn.trace("in exportCoreValidation"),zr.isEmpty(e.format))return"format missing";if(n0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${n0.join(", ")}`;let t=e.search_operation.operation;if(zr.isEmpty(t))return"search_operation.operation missing";if(r0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${r0.join(", ")}`}a(c0,"exportCoreValidation");async function u0(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(u0,"getRecords")});var S0={};qe(S0,{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=d0&&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>d0?(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||f0(e,n);return o=>jee(o).then(i)}return e&&Gt.get(e)?.deserialize||f0(e,n)}function f0(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,E0,Hg,xg,h0,m0,cl,Gg,ul,Gt,qg,_0,p0,zee,Jee,d0,Ia=Re(()=>{em();Ff=B(qf()),us=require("msgpackr"),Ao=require("cbor-x"),Hs=require("zlib"),kf=require("stream");ar();E0=require("../index"),Hg=B(Z()),xg=B(M()),h0=B(require("yaml")),m0=Hg.default.get(xg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,cl=m0?xi:JSON.stringify,Gg=m0?Zh:JSON.parse,ul={useRecords:!1,useToJSON:!0},Gt=new Map,qg=Gt;nt.contentTypes=qg;(0,E0._assignPackageExport)("contentTypes",qg);Gt.set("application/json",{serializeStream:Oc,serialize:cl,deserialize:Gg,q:.8});_0=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:_0.encode,deserialize:_0.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 h0.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
20
|
`),e.data){let r=e.data;typeof r=="object"&&(r=cl(r)),t+="data: "+r+`
|
|
21
21
|
`}return e.id&&(t+="id: "+e.id+`
|
|
22
22
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
@@ -25,8 +25,8 @@ Database backup has not been removed and can be found here: ${s}`;Fu.error(u),co
|
|
|
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()}});m0={type:"application/json",serializeStream:Oc,serialize:cl,deserialize:Qee,q:.5};Gt.set("*/*",m0);Gt.set("",m0);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");_0=Hg.default.get(xg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a($f,"serialize");a(So,"serializeMessage");a(jee,"streamToBuffer");a(Ao,"getDeserializer");a(d0,"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=S0}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]?S0: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"&&T0(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=g0(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"&&T0(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 S0(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 T0(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 g0(e){let t=R0(e[0]);return e.length>1&&(t.next=g0(e.slice(1))),t}function R0(e){if(Array.isArray(e)){let t=R0(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(S0,"typedDecoding");a(T0,"wildcardDecoding");a(g0,"toSortObject");a(R0,"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 y0(e){let t={openapi:cte,info:{title:"HarperDB HTTP REST interface",version:(0,N0.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 b0(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 b0(_);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 O0(l,r,"delete all the records that match the provided query",{204:new A0})),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 O0([f],r,"delete a record with the given primary key",{204:new A0})),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 A0(){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 O0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function b0(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 N0,cte,Wg,Ci,Xg,I0=Re(()=>{N0=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(y0,"generateJsonApi");a(ute,"Post");a(Qg,"Get");a(zg,"Response200");a(A0,"Response204");a(lte,"Put");a(O0,"Delete");a(b0,"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!==w0){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=Ao(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new Ha.ClientError(h,400)}if(e.authorize=!0,i===w0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return y0(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?Oo.warn(i):Oo.info(i):Oo.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,!C0&&(C0=!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;D0||(D0=!0,lu(u=>{dl>0&&u.push({metric:"ws-connections",connections:dl,byThread:!0})}));let i;t.on("error",u=>{i=!0,Oo.warn(u)});let o;t.on("message",a(function(_){o||(o=Ao(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=So(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 Oo,Ha,Kt,_te,Zg,w0,C0,zf,D0,dl,Ete,L0=Re(()=>{Ia();ws();Oo=B($()),Ha=B(ne());Qf();Rc();to();Wu();I0();Kt=new Uint8Array(8),_te=new Float64Array(Kt.buffer,0,1),Zg={},w0="openapi";a(dte,"http");dl=0;a(fte,"start");Ete={401:3e3,403:3003}});var eR=R((Qme,M0)=>{var{recordAction:jf,recordActionBinary:hte}=(ws(),ie(_u)),mte=require("fastify-plugin"),pte=200;M0.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,B0)=>{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(),U0=" 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"}},P0=tE(sR);P0.data.presence={message:U0};var v0=tE(sR);v0.file_path.presence={message:U0};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,P0);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,v0);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");B0.exports={dataObject:Cte,urlObject:Dte,fileObject:Lte,s3FileObject:Mte}});var aR=R((Zme,H0)=>{"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");H0.exports={callOperationFunctionAsAwait:Ute}});var G0=R((tpe,x0)=>{"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}};x0.exports={BulkLoadFileObject:cR,BulkLoadDataObject:uR}});var F0=R((npe,q0)=>{"use strict";var lR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};q0.exports=lR});var mR=R((upe,sB)=>{"use strict";var iE=Hr(),aE=oR(),Pte=require("needle"),xn=M(),ipe=ke(),Ga=Q(),{handleHDBError:ot,hdb_errors:J0}=ne(),{HTTP_STATUS_CODES:Wt,HDB_ERROR_MSGS:Ct,CHECK_LOGS_WRAPPER:No}=J0,qa=$(),_R=require("papaparse");Ga.promisifyPapaParse();var Gn=require("fs-extra"),vte=require("path"),{chain:k0}=require("stream-chain"),V0=require("stream-json/streamers/StreamArray"),$0=require("stream-json/utils/Batch"),Y0=require("stream-chain/utils/comp"),{finished:K0}=require("stream"),Bte=Z(),j0=aR(),Hte=Pg(),{BulkLoadFileObject:fR,BulkLoadDataObject:xte}=G0(),ER=bg(),{verifyBulkLoadAttributePerms:X0}=Hf(),ope=F0(),ape=it(),cpe=Rs(),{databases:Gte}=(Ae(),ie(Fe)),{coerceType:qte}=(cE(),ie(pR)),W0="No records parsed from csv file.",bo=`${Bte.get("HDB_ROOT")}/tmp`,{schema_regex:Fte}=zn(),Q0=1024*1024*2,z0=5e3,kte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};sB.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=tB(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&&X0(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 j0.callOperationFunctionAsAwait(rB,u,null),n.message===W0?W0:nB(n.records,n.number_written)}catch(s){throw yo(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=`${bo}/${r}`;try{await Wte(e,r)}catch(s){throw qa.error(Ct.DOWNLOAD_FILE_ERR(r)+" - "+s),ot(s,No(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),yo(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 yo(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=`${bo}/${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),yo(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=`${bo}/${e}`;await Gn.mkdirp(bo),await Gn.writeFile(`${bo}/${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,No(Ct.S3_DOWNLOAD_ERR))}}a(Qte,"downloadFileFromS3");async function zte(e,t){try{await Gn.mkdirp(bo),await Gn.writeFile(`${bo}/${e}`,t)}catch(r){throw qa.error(Ct.WRITE_TEMP_FILE_ERR),ot(r,No(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!==J0.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 nB(t.records,t.number_written)}catch(t){throw yo(t)}}a(hR,"fileLoad");async function Z0(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&&X0(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(Z0,"validateChunk");async function eB(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 j0.callOperationFunctionAsAwait(rB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=ot(c,No(Ct.INSERT_CSV_ERR),Wt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,Ct.INSERT_CSV_ERR+" - "+c);r(u)}}a(eB,"insertChunk");async function jte(e){let t={records:0,number_written:0},r=tB(e.schema,e.table);try{let n=new ER,s=Gn.createReadStream(e.file_path,{highWaterMark:Q0});s.setEncoding("utf8"),await _R.parsePromise(s,Z0.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:Q0}),s.setEncoding("utf8"),await _R.parsePromise(s,eB.bind(null,e,t),dR.bind(null,r)),s.destroy(),t}catch(n){throw ot(n,No(Ct.PAPA_PARSE_ERR),Wt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,Ct.PAPA_PARSE_ERR+n)}}a(jte,"callPapaParse");function tB(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(tB,"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=k0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),V0.withParser(),c=>c.value,new $0({batchSize:z0}),Y0(async c=>{await Z0(e,n,r,c)})]);await new Promise((c,u)=>{K0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw ot(new Error,i,Wt.BAD_REQUEST);let o=k0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),V0.withParser(),c=>c.value,new $0({batchSize:z0}),Y0(async c=>{await eB(e,t,r,c)})]);return await new Promise((c,u)=>{K0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw ot(n,No(Ct.INSERT_JSON_ERR),Wt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,Ct.INSERT_JSON_ERR+n)}}a(Xte,"insertJson");async function rB(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 yo(r)}return t}a(rB,"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 yo(o)}}a(ere,"bulkFileLoad");function nB(e,t){return`successfully loaded ${t} of ${e} records`}a(nB,"buildResponseMsg");function yo(e){return ot(e,No(Ct.DEFAULT_BULK_LOAD_ERR),Wt.INTERNAL_SERVER_ERROR,xn.LOG_LEVELS.ERROR,Ct.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(yo,"buildTopLevelErrMsg")});var oB=R((_pe,iB)=>{"use strict";var SR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};iB.exports=SR});var uB=R((fpe,cB)=>{"use strict";var tre=M(),aB=require("moment"),rre=require("uuid").v4,TR=class{static{a(this,"JobObject")}constructor(){this.id=rre(),this.type=void 0,this.start_datetime=aB().valueOf(),this.created_datetime=aB().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}};cB.exports=TR});var gR=R((hpe,hB)=>{"use strict";var nre=require("uuid").v4,dB=Hr(),fB=Br(),sre=es(),ire=sa(),ore=oB(),at=M(),are=uB(),cre=Bd(),pn=$(),ure=Hc(),Fa=Q(),{promisify:lre}=require("util"),Io=require("moment"),_re=Gf(),uE=oR(),lB=Ym(),{deleteTransactionLogsBeforeValidator:dre}=Tg(),{handleHDBError:fre,hdb_errors:Ere}=ne(),{HTTP_STATUS_CODES:hre}=Ere,_B=fB.searchByValue,mre=fB.searchByHash,pre=dB.insert,Sre=lre(_re.evaluateSQL),Tre=dB.update;hB.exports={addJob:Are,updateJob:bre,handleGetJob:gre,handleGetJobsByStartDate:Rre,getJobById:EB};async function gre(e){try{let t=await EB(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=Io(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Io(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=lB(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=lB(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 _B(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 _B(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=Io(e.from_date,Io.ISO_8601),r=Io(e.to_date,Io.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 EB(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(EB,"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=Io().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 RB=R((ppe,gB)=>{"use strict";var mB=Q(),wr=M(),Nre=require("moment"),lE=mR(),_E=$(),pB=gR(),SB=qf(),TB=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(mB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(mB.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,SB.export_local);break;case wr.JOB_TYPE_ENUM.export_to_s3:await qs(e,SB.export_to_s3);break;case wr.JOB_TYPE_ENUM.delete_files_before:case wr.JOB_TYPE_ENUM.delete_records_before:await qs(e,TB.deleteFilesBefore);break;case wr.JOB_TYPE_ENUM.delete_audit_logs_before:await qs(e,TB.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 pB.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 pB.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");gB.exports={parseMessage:wre,RunnerMessage:RR}});var OB=R((Tpe,AB)=>{"use strict";var AR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};AB.exports=AR});var qB=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(),bB=CT(),Ure=jd(),Pre=LT(),vre=MT(),Bre=vT(),Hre=HT(),OR=qT(),NB=qf(),xre=Hf(),yR=gR(),q=M(),{hdb_errors:pl,handleHDBError:ml}=ne(),{HTTP_STATUS_CODES:yB}=pl,bR=YT(),IB=Tf(),BB=require("util"),ka=Hr(),Gre=Os(),qre=Sa(),wB=RB(),CB=bu(),DB=(Of(),ie(Qu)),LB=dr(),MB=Uf(),UB=wf(),{setServerUtilities:Fre}=(cE(),ie(pR)),{CONTEXT:kre}=(Nn(),ie(Gp)),{_assignPackageExport:Vre}=require("../index"),{transformReq:$re}=Q(),{server:Yre}=(ar(),ie(Bi)),rr=hE.loggerWithTag("operation"),Kre=aR(),PB=mE.searchByHash,Wre=mE.searchByValue,Qre=BB.promisify(mE.search),zre=BB.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=OB();async function HB(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(HB,"processLocalTransaction");var vB=Xre();wR.exports={chooseOperation:xB,getOperationFunction:GB,operation:IR,processLocalTransaction:HB};Fre(wR.exports);Yre.operation=IR;function xB(e){let t;try{t=GB(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(`${yB.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(`${yB.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(xB,"chooseOperation");function GB(e){if(rr.trace(`getOperationFunction with operation: ${e.operation}`),vB.has(e.operation))return vB.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(GB,"getOperationFunction");Vre("operation",IR);function IR(e,t){e.hdb_user=this[kre]?.user,e.bypass_auth=!t;let r=xB(e);return HB({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 wB.RunnerMessage(t,e);return await wB.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(PB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(PB)),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(bB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(bB)),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(LB.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,NB.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,NB.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(IB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(IB.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(CB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(CB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(DB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(DB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(LB.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(MB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(_s,MB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(UB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(UB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(Xre,"initializeOperationFunctionMap")});var SE=R((Ope,VB)=>{"use strict";var CR=M(),Zre=Q(),Sl=$(),{handleHDBError:DR,hdb_errors:pE}=ne(),{isMainThread:ene}=require("worker_threads"),{Readable:tne}=require("stream"),FB=require("os"),rne=require("util"),nne=aT(),sne=rne.promisify(nne.authorize),kB=qB(),{createGzip:ine,constants:one}=require("zlib");function ane(e){let t=`Found an uncaught exception with message: ${e.message}. ${FB.EOL}Stack: ${e.stack} ${FB.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=kB.chooseOperation(e.body);let s=await kB.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");VB.exports={authHandler:lne,handlePostRequest:_ne,handleServerUncaughtException:ane,serverErrorHandler:cne,reqBodyValidationHandler:une}});var WB=R((Npe,KB)=>{"use strict";var dne=require("fastify-plugin"),{handlePostRequest:$B,authHandler:fne,reqBodyValidationHandler:Ene}=SE();async function hne(e){e.decorate("hdbCore",{preValidation:[Ene,fne],request:t=>YB($B(t,response)),requestWithoutAuthentication:(t,r)=>YB($B(t,r,!0))})}a(hne,"hdbCore");async function YB(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(YB,"convertAsyncIterators");KB.exports=dne(hne)});var JB=R((wpe,zB)=>{"use strict";var Ipe=require("fs"),LR=Z();LR.initSync();var{CONFIG_PARAMS:QB}=M(),mne=1024*1024*1024;function pne(e){let t=LR.get(QB.HTTP_TIMEOUT),r=LR.get(QB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:mne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(pne,"getServerOptions");zB.exports=pne});var ZB=R((Dpe,XB)=>{"use strict";var MR=Z();MR.initSync();var{CONFIG_PARAMS:jB}=M();function Sne(){let e=MR.get(jB.HTTP_CORSACCESSLIST),t=MR.get(jB.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");XB.exports=Sne});var rH=R((Mpe,tH)=>{"use strict";var eH=Z();eH.initSync();var Tne=M();function gne(){return eH.get(Tne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(gne,"getHeaderTimeoutConfig");tH.exports=gne});var PR={};qe(PR,{customFunctionsServer:()=>One,ready:()=>pH,start:()=>Ane});function Ane(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=mH(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)),!nH.has(c)){nH.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:pH}}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=uH.get(lH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await mH(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 _H.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,sH.existsSync)(e)&&r.register(cH.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 mH(e){$e.info("Custom Functions starting buildServer.");let t=(0,dH.default)(e),r=(0,iH.default)(t);r.server.headersTimeout=(0,EH.default)(),r.setErrorHandler(hH.serverErrorHandler);let n=(0,fH.default)();return n&&r.register(oH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(aH.default),await r.register(Rne),await r.after(),Fg(r),$e.info("Custom Functions completed buildServer."),r}function pH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var UR,sH,iH,oH,aH,cH,uH,lH,$e,Rne,_H,dH,fH,EH,hH,ks,nH,SH=Re(()=>{UR=require("path"),sH=require("fs"),iH=B(require("fastify")),oH=B(require("@fastify/cors")),aH=B(eR()),cH=B(require("@fastify/autoload")),uH=B(Z()),lH=B(M()),$e=B($()),Rne=B(WB()),_H=B(un()),dH=B(JB()),fH=B(ZB()),EH=B(rH()),hH=B(SE());Ia();ar();nH=new Set;a(Ane,"start");a(One,"customFunctionsServer");a(bne,"setUp");a(Nne,"buildRouteFolder");a(mH,"buildServer");a(pH,"ready")});var vR={};qe(vR,{start:()=>yne});function yne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,OH.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){gH||(gH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=TH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,RH.default)(s,(0,AH.realpathSync)(o))}}return i(s)},{runFirst:!0})),TH.set(r,n)}}}var RH,AH,OH,TH,gH,bH=Re(()=>{RH=B(require("send")),AH=require("fs"),OH=B(require("serve-static")),TH=new Map;a(yne,"start")});function Cne(e,t=1,r){if(BR++,(0,wo.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)wH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{HR?HR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,wo.shutdownWorkers)(),BR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function CH(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=wH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),HR=!0,r(o,(c,u)=>{if(!c){if(NH){let l=o._socket||new Ya.Socket({handle:o,writable:!0,readable:!0});NH.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 wo,Ya,RE,xR,AE,IH,Ine,Va,$a,wH,NH,BR,wne,HR,TE,yH,Ka,Mne,gE,Pne,DH=Re(()=>{wo=B(Je()),Ya=require("net"),RE=B(M()),xR=B($()),AE=require("fs");ws();IH=require("worker_threads"),Ine=B(zi()),Va=[],$a=[],wH=[],BR=0,wne=[];IH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Cne,"startHTTPWorker");a(CH,"startSocketServer");TE=0;a(GR,"findMostIdleWorker");yH=36e5,Ka=new Map;a(Dne,"findByRemoteAddressAffinity");a(Lne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ka)r.lastUsed+yH<e&&Ka.delete(t)},yH).unref();Mne=1e3;a(Une,"updateWorkerIdleness");(0,wo.setMonitorListener)(Une);gE=new Map,Pne=1;a(vne,"proxySocket")});var VR={};qe(VR,{Request:()=>qR,createReuseportFd:()=>OE});var LH,qR,FR,kR,OE,bE=Re(()=>{LH=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,LH.platform)()!="win32"&&(OE=require("node-unix-socket").createReuseportFd)});var vH=R((Wpe,PH)=>{"use strict";var Bne=require("cluster"),Co=Z();Co.initSync();var UH=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=zi(),{server:Qne}=(ar(),ie(Bi)),{node_request_key:Ype}=(bE(),ie(VR)),{authHandler:zne,handlePostRequest:Jne,serverErrorHandler:jne,reqBodyValidationHandler:Xne}=SE(),Kpe=require("net"),{registerContentHandlers:Zne}=(Ia(),ie(p0)),ese=6e4,tse=1024*1024*1024,rse="TRUE",{CONFIG_PARAMS:Tl}=UH,Wa;PH.exports={hdbServer:MH,start:MH};async function MH(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(MH,"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=Co.get(UH.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=Co.get(Tl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Co.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=Co.get(Tl.OPERATIONSAPI_NETWORK_CORS),t=Co.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 Co.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){qH=e}function lse(e,t){IE=e,QR=t}function dse(){if(qH||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&&kH(r)}),!BH&&(BH=!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){kH(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=FH;return i}a(n,"getNATSTransaction")}function kH(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 HH,KR,WR,xH,GH,gl,Rl,yE,qH,IE,QR,_se,FH,BH,NE,YR,VH=Re(()=>{Ae();Nn();HH=B(it()),KR=B(ke()),WR=B(Rs());Rc();xH=B(IS()),GH=B(Mr()),gl=B(Z()),Rl=B(M()),yE=B($());a(cse,"start");a(use,"disableNATS");IE=HH.publishToStream,QR=xH.setSubscription;a(lse,"setPublishToStream");_se=2;a(dse,"assignReplicationSource");a($R,"setNATSReplicator");a(kH,"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,GH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};FH=new YR});var ix=R(Do=>{"use strict";var{isMainThread:QH,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:$H,existsSync:Tse}=require("fs"),Dt=$(),xe=Z(),Et=M(),{server:ME}=(ar(),ie(Bi)),{WebSocketServer:gse}=require("ws"),{createSecureContext:Rse,createServer:Ase}=require("node:tls"),{getTicketKeys:zH,restartNumber:Ose,getWorkerIndex:DE}=Je(),{Headers:JH,appendHeader:bse}=(Wu(),ie(FP)),{recordAction:Al,recordActionBinary:Nse}=(ws(),ie(_u)),{Request:jH,createReuseportFd:YH}=(bE(),ie(VR)),{checkMemoryLimit:yse}=zi(),{X509Certificate:Ise}=require("crypto"),XH=require("tls"),wse=XH.createSecureContext,Qa;XH.createSecureContext=function(e){return Qa||wse(e)};var ZH=xe.get(Et.CONFIG_PARAMS.THREADS_DEBUG);if(ZH){let e;if(QH)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)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={};Do.registerServer=rA;Do.httpServer=nA;Do.deliverSocket=tA;Do.startServers=ex;Do.when_components_loaded=null;ME.http=nA;ME.request=Pse;ME.socket=vse;ME.ws=Bse;var jR={},CE={},Lse,$s={},LE={},Mse=[],ZR=[];function ex(){return Do.when_components_loaded=sA().loadRootComponents(!0).then(()=>{Ol?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)tA(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});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()}});p0={type:"application/json",serializeStream:Oc,serialize:cl,deserialize:Qee,q:.5};Gt.set("*/*",p0);Gt.set("",p0);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");d0=Hg.default.get(xg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a($f,"serialize");a(To,"serializeMessage");a(jee,"streamToBuffer");a(Oo,"getDeserializer");a(f0,"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=T0}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]?T0: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"&&g0(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=R0(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"&&g0(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 T0(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 g0(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 R0(e){let t=A0(e[0]);return e.length>1&&(t.next=R0(e.slice(1))),t}function A0(e){if(Array.isArray(e)){let t=A0(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(T0,"typedDecoding");a(g0,"wildcardDecoding");a(R0,"toSortObject");a(A0,"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 I0(e){let t={openapi:cte,info:{title:"HarperDB HTTP REST interface",version:(0,y0.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 N0(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 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 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 b0(l,r,"delete all the records that match the provided query",{204:new O0})),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 b0([f],r,"delete a record with the given primary key",{204:new O0})),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 O0(){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 b0(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 Jg(e,t){this.type=e,this.format=t}function jg(e,t,r){this.name=e,this.in=t,this.schema=r}var y0,cte,Wg,Ci,Xg,w0=Re(()=>{y0=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(I0,"generateJsonApi");a(ute,"Post");a(Qg,"Get");a(zg,"Response200");a(O0,"Response204");a(lte,"Put");a(b0,"Delete");a(N0,"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!==C0){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===C0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return I0(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,!D0&&(D0=!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;L0||(L0=!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,C0,D0,zf,L0,dl,Ete,M0=Re(()=>{Ia();ws();bo=B($()),Ha=B(ne());Qf();Rc();ro();Wu();w0();Kt=new Uint8Array(8),_te=new Float64Array(Kt.buffer,0,1),Zg={},C0="openapi";a(dte,"http");dl=0;a(fte,"start");Ete={401:3e3,403:3003}});var eR=R((Qme,U0)=>{var{recordAction:jf,recordActionBinary:hte}=(ws(),ie(_u)),mte=require("fastify-plugin"),pte=200;U0.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,H0)=>{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(),P0=" 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"}},v0=tE(sR);v0.data.presence={message:P0};var B0=tE(sR);B0.file_path.presence={message:P0};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,v0);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,B0);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");H0.exports={dataObject:Cte,urlObject:Dte,fileObject:Lte,s3FileObject:Mte}});var aR=R((Zme,x0)=>{"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");x0.exports={callOperationFunctionAsAwait:Ute}});var q0=R((tpe,G0)=>{"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}};G0.exports={BulkLoadFileObject:cR,BulkLoadDataObject:uR}});var k0=R((npe,F0)=>{"use strict";var lR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};F0.exports=lR});var mR=R((upe,iB)=>{"use strict";var iE=Hr(),aE=oR(),Pte=require("needle"),xn=M(),ipe=ke(),Ga=Q(),{handleHDBError:ot,hdb_errors:j0}=ne(),{HTTP_STATUS_CODES:Wt,HDB_ERROR_MSGS:Ct,CHECK_LOGS_WRAPPER:yo}=j0,qa=$(),_R=require("papaparse");Ga.promisifyPapaParse();var Gn=require("fs-extra"),vte=require("path"),{chain:V0}=require("stream-chain"),$0=require("stream-json/streamers/StreamArray"),Y0=require("stream-json/utils/Batch"),K0=require("stream-chain/utils/comp"),{finished:W0}=require("stream"),Bte=Z(),X0=aR(),Hte=Pg(),{BulkLoadFileObject:fR,BulkLoadDataObject:xte}=q0(),ER=bg(),{verifyBulkLoadAttributePerms:Z0}=Hf(),ope=k0(),ape=it(),cpe=Rs(),{databases:Gte}=(Ae(),ie(Fe)),{coerceType:qte}=(cE(),ie(pR)),Q0="No records parsed from csv file.",No=`${Bte.get("HDB_ROOT")}/tmp`,{schema_regex:Fte}=zn(),z0=1024*1024*2,J0=5e3,kte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};iB.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=rB(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&&Z0(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 X0.callOperationFunctionAsAwait(nB,u,null),n.message===Q0?Q0:sB(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!==j0.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 sB(t.records,t.number_written)}catch(t){throw Io(t)}}a(hR,"fileLoad");async function eB(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&&Z0(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(eB,"validateChunk");async function tB(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 X0.callOperationFunctionAsAwait(nB,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(tB,"insertChunk");async function jte(e){let t={records:0,number_written:0},r=rB(e.schema,e.table);try{let n=new ER,s=Gn.createReadStream(e.file_path,{highWaterMark:z0});s.setEncoding("utf8"),await _R.parsePromise(s,eB.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:z0}),s.setEncoding("utf8"),await _R.parsePromise(s,tB.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 rB(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(rB,"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=V0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),$0.withParser(),c=>c.value,new Y0({batchSize:J0}),K0(async c=>{await eB(e,n,r,c)})]);await new Promise((c,u)=>{W0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw ot(new Error,i,Wt.BAD_REQUEST);let o=V0([Gn.createReadStream(e.file_path,{encoding:"utf-8"}),$0.withParser(),c=>c.value,new Y0({batchSize:J0}),K0(async c=>{await tB(e,t,r,c)})]);return await new Promise((c,u)=>{W0(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 nB(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(nB,"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 sB(e,t){return`successfully loaded ${t} of ${e} records`}a(sB,"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 aB=R((_pe,oB)=>{"use strict";var SR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};oB.exports=SR});var lB=R((fpe,uB)=>{"use strict";var tre=M(),cB=require("moment"),rre=require("uuid").v4,TR=class{static{a(this,"JobObject")}constructor(){this.id=rre(),this.type=void 0,this.start_datetime=cB().valueOf(),this.created_datetime=cB().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}};uB.exports=TR});var gR=R((hpe,mB)=>{"use strict";var nre=require("uuid").v4,fB=Hr(),EB=Br(),sre=es(),ire=sa(),ore=aB(),at=M(),are=lB(),cre=Bd(),pn=$(),ure=Hc(),Fa=Q(),{promisify:lre}=require("util"),wo=require("moment"),_re=Gf(),uE=oR(),_B=Ym(),{deleteTransactionLogsBeforeValidator:dre}=Tg(),{handleHDBError:fre,hdb_errors:Ere}=ne(),{HTTP_STATUS_CODES:hre}=Ere,dB=EB.searchByValue,mre=EB.searchByHash,pre=fB.insert,Sre=lre(_re.evaluateSQL),Tre=fB.update;mB.exports={addJob:Are,updateJob:bre,handleGetJob:gre,handleGetJobsByStartDate:Rre,getJobById:hB};async function gre(e){try{let t=await hB(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=_B(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=_B(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 dB(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 dB(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 hB(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(hB,"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 AB=R((ppe,RB)=>{"use strict";var pB=Q(),wr=M(),Nre=require("moment"),lE=mR(),_E=$(),SB=gR(),TB=qf(),gB=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(pB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(pB.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,TB.export_local);break;case wr.JOB_TYPE_ENUM.export_to_s3:await qs(e,TB.export_to_s3);break;case wr.JOB_TYPE_ENUM.delete_files_before:case wr.JOB_TYPE_ENUM.delete_records_before:await qs(e,gB.deleteFilesBefore);break;case wr.JOB_TYPE_ENUM.delete_audit_logs_before:await qs(e,gB.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 SB.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 SB.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");RB.exports={parseMessage:wre,RunnerMessage:RR}});var bB=R((Tpe,OB)=>{"use strict";var AR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};OB.exports=AR});var FB=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(),NB=CT(),Ure=jd(),Pre=LT(),vre=MT(),Bre=vT(),Hre=HT(),OR=qT(),yB=qf(),xre=Hf(),yR=gR(),q=M(),{hdb_errors:pl,handleHDBError:ml}=ne(),{HTTP_STATUS_CODES:IB}=pl,bR=YT(),wB=Tf(),HB=require("util"),ka=Hr(),Gre=Os(),qre=Sa(),CB=AB(),DB=bu(),LB=(Of(),ie(Qu)),MB=dr(),UB=Uf(),PB=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(),vB=mE.searchByHash,Wre=mE.searchByValue,Qre=HB.promisify(mE.search),zre=HB.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=bB();async function xB(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(xB,"processLocalTransaction");var BB=Xre();wR.exports={chooseOperation:GB,getOperationFunction:qB,operation:IR,processLocalTransaction:xB};Fre(wR.exports);Yre.operation=IR;function GB(e){let t;try{t=qB(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(`${IB.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(`${IB.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(GB,"chooseOperation");function qB(e){if(rr.trace(`getOperationFunction with operation: ${e.operation}`),BB.has(e.operation))return BB.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(qB,"getOperationFunction");Vre("operation",IR);function IR(e,t){e.hdb_user=this[kre]?.user,e.bypass_auth=!t;let r=GB(e);return xB({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 CB.RunnerMessage(t,e);return await CB.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(vB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(vB)),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(NB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(NB)),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(MB.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,yB.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,yB.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(wB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(wB.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(DB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(DB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(LB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(LB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(MB.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(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(PB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(PB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(Xre,"initializeOperationFunctionMap")});var SE=R((Ope,$B)=>{"use strict";var CR=M(),Zre=Q(),Sl=$(),{handleHDBError:DR,hdb_errors:pE}=ne(),{isMainThread:ene}=require("worker_threads"),{Readable:tne}=require("stream"),kB=require("os"),rne=require("util"),nne=aT(),sne=rne.promisify(nne.authorize),VB=FB(),{createGzip:ine,constants:one}=require("zlib");function ane(e){let t=`Found an uncaught exception with message: ${e.message}. ${kB.EOL}Stack: ${e.stack} ${kB.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=VB.chooseOperation(e.body);let s=await VB.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");$B.exports={authHandler:lne,handlePostRequest:_ne,handleServerUncaughtException:ane,serverErrorHandler:cne,reqBodyValidationHandler:une}});var QB=R((Npe,WB)=>{"use strict";var dne=require("fastify-plugin"),{handlePostRequest:YB,authHandler:fne,reqBodyValidationHandler:Ene}=SE();async function hne(e){e.decorate("hdbCore",{preValidation:[Ene,fne],request:t=>KB(YB(t,response)),requestWithoutAuthentication:(t,r)=>KB(YB(t,r,!0))})}a(hne,"hdbCore");async function KB(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(KB,"convertAsyncIterators");WB.exports=dne(hne)});var jB=R((wpe,JB)=>{"use strict";var Ipe=require("fs"),LR=Z();LR.initSync();var{CONFIG_PARAMS:zB}=M(),mne=1024*1024*1024;function pne(e){let t=LR.get(zB.HTTP_TIMEOUT),r=LR.get(zB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:mne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(pne,"getServerOptions");JB.exports=pne});var eH=R((Dpe,ZB)=>{"use strict";var MR=Z();MR.initSync();var{CONFIG_PARAMS:XB}=M();function Sne(){let e=MR.get(XB.HTTP_CORSACCESSLIST),t=MR.get(XB.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");ZB.exports=Sne});var nH=R((Mpe,rH)=>{"use strict";var tH=Z();tH.initSync();var Tne=M();function gne(){return tH.get(Tne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(gne,"getHeaderTimeoutConfig");rH.exports=gne});var PR={};qe(PR,{customFunctionsServer:()=>One,ready:()=>SH,start:()=>Ane});function Ane(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=pH(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)),!sH.has(c)){sH.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:SH}}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=lH.get(_H.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await pH(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 dH.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,iH.existsSync)(e)&&r.register(uH.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 pH(e){$e.info("Custom Functions starting buildServer.");let t=(0,fH.default)(e),r=(0,oH.default)(t);r.server.headersTimeout=(0,hH.default)(),r.setErrorHandler(mH.serverErrorHandler);let n=(0,EH.default)();return n&&r.register(aH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(cH.default),await r.register(Rne),await r.after(),Fg(r),$e.info("Custom Functions completed buildServer."),r}function SH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var UR,iH,oH,aH,cH,uH,lH,_H,$e,Rne,dH,fH,EH,hH,mH,ks,sH,TH=Re(()=>{UR=require("path"),iH=require("fs"),oH=B(require("fastify")),aH=B(require("@fastify/cors")),cH=B(eR()),uH=B(require("@fastify/autoload")),lH=B(Z()),_H=B(M()),$e=B($()),Rne=B(QB()),dH=B(un()),fH=B(jB()),EH=B(eH()),hH=B(nH()),mH=B(SE());Ia();ar();sH=new Set;a(Ane,"start");a(One,"customFunctionsServer");a(bne,"setUp");a(Nne,"buildRouteFolder");a(pH,"buildServer");a(SH,"ready")});var vR={};qe(vR,{start:()=>yne});function yne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,bH.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){RH||(RH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=gH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,AH.default)(s,(0,OH.realpathSync)(o))}}return i(s)},{runFirst:!0})),gH.set(r,n)}}}var AH,OH,bH,gH,RH,NH=Re(()=>{AH=B(require("send")),OH=require("fs"),bH=B(require("serve-static")),gH=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)CH[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 DH(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=CH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),HR=!0,r(o,(c,u)=>{if(!c){if(yH){let l=o._socket||new Ya.Socket({handle:o,writable:!0,readable:!0});yH.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,wH,Ine,Va,$a,CH,yH,BR,wne,HR,TE,IH,Ka,Mne,gE,Pne,LH=Re(()=>{Co=B(Je()),Ya=require("net"),RE=B(M()),xR=B($()),AE=require("fs");ws();wH=require("worker_threads"),Ine=B(Ji()),Va=[],$a=[],CH=[],BR=0,wne=[];wH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Cne,"startHTTPWorker");a(DH,"startSocketServer");TE=0;a(GR,"findMostIdleWorker");IH=36e5,Ka=new Map;a(Dne,"findByRemoteAddressAffinity");a(Lne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ka)r.lastUsed+IH<e&&Ka.delete(t)},IH).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 MH,qR,FR,kR,OE,bE=Re(()=>{MH=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,MH.platform)()!="win32"&&(OE=require("node-unix-socket").createReuseportFd)});var BH=R((Wpe,vH)=>{"use strict";var Bne=require("cluster"),Do=Z();Do.initSync();var PH=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(S0)),ese=6e4,tse=1024*1024*1024,rse="TRUE",{CONFIG_PARAMS:Tl}=PH,Wa;vH.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=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(UH,"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(PH.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){FH=e}function lse(e,t){IE=e,QR=t}function dse(){if(FH||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&&VH(r)}),!HH&&(HH=!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){VH(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=kH;return i}a(n,"getNATSTransaction")}function VH(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 xH,KR,WR,GH,qH,gl,Rl,yE,FH,IE,QR,_se,kH,HH,NE,YR,$H=Re(()=>{Ae();Nn();xH=B(it()),KR=B(ke()),WR=B(Rs());Rc();GH=B(IS()),qH=B(Mr()),gl=B(Z()),Rl=B(M()),yE=B($());a(cse,"start");a(use,"disableNATS");IE=xH.publishToStream,QR=GH.setSubscription;a(lse,"setPublishToStream");_se=2;a(dse,"assignReplicationSource");a($R,"setNATSReplicator");a(VH,"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,qH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};kH=new YR});var ix=R(Di=>{"use strict";var{isMainThread:zH,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:YH,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(kP)),{recordAction:Al,recordActionBinary:Nse}=(ws(),ie(_u)),{Request:XH,createReuseportFd:KH}=(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(zH)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)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=rA;Di.httpServer=nA;Di.deliverSocket=tA;Di.startServers=tx;Di.when_components_loaded=null;Di.createSNICallback=sA;ME.http=nA;ME.request=Pse;ME.socket=vse;ME.ws=Bse;var jR={},CE={},Lse,$s={},LE={},Mse=[],ZR=[];function tx(){return Di.when_components_loaded=iA().loadRootComponents(!0).then(()=>{Ol?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)tA(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
|
|
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{
|
|
32
|
-
`)}a(WH,"defaultNotFound");function XR(e){return e.startsWith("-----BEGIN")?e:Sse(e)}a(XR,"readPEM");function sx(e){let t=[];for(let s=0;e[s];s++)t.push(e[s]);t.length||t.push(e);let r=new Map,n;for(let s of t){let i=XR(s.privateKey),o=XR(s.certificate),c=s.certificateAuthority&&XR(s.certificateAuthority);if(!i||!o)throw new Error("Missing private key or certificate for secure server");let u={ciphers:xe.get("tls_ciphers"),ca:c,ticketKeys:zH()},_=Rse(u);_.options=u,u.instantiatedContext=_,_.context.setCert(o),_.context.setKey(i,void 0),u.cert=o,u.key=i,_.certStart=o.subarray(0,100).toString(),n||(n=_);let l=new Ise(o),d=s.hostname??s.host??s.hostnames??s.hosts??(l.subjectAltName?l.subjectAltName.split(",").map(f=>{let E=f.indexOf(":");return f.slice(E+1)}):[l.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(d)||(d=[d]);for(let f of d)f?r.has(f)||r.set(f,_):Dt.error("No hostname found for certificate at",s.certificate)}return(s,i)=>{let o=r.get(s);o?(Dt.debug("Found certificate for",s,o.certStart),i(null,o)):(Dt.debug("No certificate found to match",s,"using the first certificate"),i(null,n))}}a(sx,"createSNICallback")});async function ux({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await iA.get(e,{returnNonexistent:!0});i=new cA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await iA.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 oA(){return UE++,UE>65500&&(UE=1),UE}function aA(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,Di,ax,cx,iA,bl,UE,PE,cA,lx=Re(()=>{Ae();Ku();ox=B(Mr()),Di=B($());to();ax=B(Je()),cx=B(ix());ar();iA=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{aA(r,t,r)}catch{(0,Di.warn)("Failed to publish will",t)}bl.delete(e.id,r)})}})();a(ux,"getSession");UE=1;a(oA,"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,Di.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=oA());let v=g.id;Array.isArray(v)&&(v=Na(v)),v==null&&(v=""),this.listener(h+"/"+v,g.value,L,t)}catch(L){(0,Di.warn)(L)}})(),A});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=oA();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 aA(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 aA(n,n.data,r)}}finally{await bl.delete(this.sessionId)}}).catch(n=>{(0,Di.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(aA,"publish");cA=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=oA(),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,Di.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,Di.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),iA.put(this.sessionRecord)}}});var lA={};qe(lA,{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=Ao(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=Ao(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 So(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var HE,fx,za,zt,uA,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()),uA=B($()),Ex=require("events"),BE=(0,uA.loggerWithTag)("auth-event"),nr=(0,uA.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&&(dA=t),e&&(fA=e);let r=[];if((0,qn.existsSync)(_A)){let s=(0,qn.readdirSync)(_A,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Ot.join)(_A,o);r.push(xE(c,dA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(xE(n,dA,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&&(fA=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=EA;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=hA.get(mA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);g&&Nl.default.warn("Session affinity is not recommended and may cause memory leaks"),(g||!OE)&&(px.push(A),CH(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),fA.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!==EA[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,hA,mA,gx,Xa,Nl,Rx,Ax,Gse,Ox,qse,_A,fA,bx,dA,ja,Fse,EA,px,Sx,yl,Il,Mf=Re(()=>{qn=require("fs"),Ot=require("path"),Ja=require("worker_threads"),Tx=require("yaml"),hA=B(Z()),mA=B(M());mb();gb();Rb();L0();SH();bH();gx=B(require("fast-glob")),Xa=B(Je()),Nl=B($());Wh();ar();Rx=B(ne());Nn();Ae();DH();Ax=B(Z()),Gse=B(vH());Of();VH();mx();Ox=B(dr());bE();({readFile:qse}=qn.promises),_A=hA.get(mA.CONFIG_PARAMS.COMPONENTSROOT),fA=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:lA},EA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(EA,"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 sA=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(qP)),Wse=hg(),Qse=dr(),{dirname:zse}=require("path"),{getConnection:Jse}=it(),jse=Z(),Xse=M(),pA=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,pA),await $se(pA,t);let r=[];for(let[n]of pA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Zse,"loadRootComponents");Ix.exports.loadRootComponents=Zse});var Je=R((wSe,Mi)=>{"use strict";var{Worker:eie,MessageChannel:tie,parentPort:Es,isMainThread:AA,threadId:rie,workerData:Ys}=require("worker_threads"),{PACKAGE_ROOT:nie}=M(),{join:Lx,isAbsolute:sie,extname:iie}=require("path"),{server:Mx}=(ar(),ie(Bi)),{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,Li=[],Sn=[],_ie=50,OA=1e4,die="restart",Px="request_thread_info",vx="resource_report",Bx="thread_info",Hx="added-port",fie="ack",SA;uie("threads",Sn);Mi.exports={startWorker:TA,restartWorkers:NA,shutdownWorkers:Sie,workers:Li,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 bA;function Eie(e){OA=e}a(Eie,"setTerminateTimeout");function xx(){return Ys?Ys.workerIndex:bA?0:void 0}a(xx,"getWorkerIndex");function Gx(){return Ys?Ys.workerCount:bA?1:void 0}a(Gx,"getWorkerCount");function hie(e){bA=e}a(hie,"setMainIsWorker");var qx=1,GE;function Fx(){return GE||(GE=AA?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 TA(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:Mi.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=()=>TA(e,t),c.on("error",u=>{Ks.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Li.splice(Li.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<_ie?(t.unexpectedRestarts=c.unexpectedRestarts+1,TA(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)}),Li.push(c),wie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(TA,"startWorker");var mie=[wl.THREAD_TYPES.HTTP];async function NA(e=null,t=Math.max(qx>3,1),r=!0){if(AA){if(r){let{loadRootComponents:o}=sA();await o()}Mi.exports.restartNumber++,t<1&&(t=t*Li.length);let n=[],s=[];for(let o of Li.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Mi.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(),OA*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(NA,"restartWorkers");function pie(e,t){kx[e]=t}a(pie,"setChildListenerByType");function Sie(e){return NA(e,1/0,!1)}a(Sie,"shutdownWorkers");var Vx=[];function Tie(e){Vx.push(e)}a(Tie,"onMessageFromWorkers");var gA=new Map;function $x(e,t){let r=gA.get(e);r||gA.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 Li.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 RA;function yie(e){RA=e}a(yie,"setMonitorListener");var Iie=1e3,Dx=!1;function wie(){Dx||(Dx=!0,setInterval(()=>{for(let e of Li){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}RA&&RA()},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(),SA=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 SA=Yx;Mi.exports.getThreadInfo=SA;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=gA.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(AA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await aie(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(Lx(n,i.name));try{for await(let{filename:i}of oie(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await NA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");Mi.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else Es.on("message",async e=>{let{type:t}=e;t===wl.ITC_EVENT_TYPES.SHUTDOWN&&(Mi.exports.restartNumber=e.restartNumber,Es.unref(),setTimeout(()=>{Ks.warn("Thread did not voluntarily terminate",rie),process.exit(0)},OA).unref())})});var wC={};qe(wC,{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()-yA})){if((_[0]&15)===CA){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,yA/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){yA=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?(LA.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 DA(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&IA||n&wA&&!E)return f.decoder.decode(e.subarray(t.position));if(n&wA&&h)return MA(f.getEntry(this.recordId),h,f)}}}catch(t){return LA.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,LA,Tn,Za,eG,Ef,yA,Die,kE,IA,wA,Kx,CA,Wx,Qx,zx,tG,DA,ti=Re(()=>{ec=require("ordered-binary"),VE=B(Z()),jx=B(ut()),Xx=B(M()),$E=B(Je()),Zx=B(Q());wc();LA=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},yA=(0,Zx.convertToMS)((0,VE.get)(Xx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Die=1e3,kE=1e4;a(YE,"openAuditStore");a(Lie,"setAuditRetention");IA=16,wA=32,Kx=1,CA=2,Wx=3,Qx=4,zx=5,tG={put:Kx|IA,[Kx]:"put",delete:CA,[CA]:"delete",message:Wx|IA,[Wx]:"message",invalidate:Qx,[Qx]:"invalidate",patch:zx|wA,[zx]:"patch"};a(E_,"createAuditEntry");a(Ut,"readAuditEntry");DA=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 UA={};qe(UA,{add:()=>WE,applyReverse:()=>rG,getRecordAtTime:()=>MA,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 MA(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(MA,"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=UA[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 vA;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 PA(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):PA(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(PA(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(PA(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,vA,Nn=Re(()=>{aG=require("crypto");Rc();cG=require("../index"),uG=B(ne());_d();to();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");vA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Xr,"transactional");a(Zr,"missingMethod");a(PA,"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 HA(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,BA.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,BA.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 BA,lG,_G,HA,EG=Re(()=>{BA=B($());Rc();Ku();ti();lG=Object.create(null),_G=Object.create(null);a(dG,"addSubscription");HA=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,sO=!1,Ah,Oh,Sq=i.getRange({start:!1,end:!1}).constructor,Tq=10,gq=6;h&&aO();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[xA]=!0,qA(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[xA]=!0,qA(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&&aO(),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||sO&&b){if(O||(O={}),b){let D=N?.length>0&&GA(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=GA(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=GA(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)=>iO(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=iO(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[xA]: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)"),sO=!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=oO(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 eo,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 iO(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(iO,"transformToEntries");async function oO(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(oO(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;qA(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⋘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(oO,"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 aO(){z=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(aO,"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 GA(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 qA(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,xA,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();to();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,xA=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(GA,"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(qA,"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 Ui)e.needsDeletion=!0;Er();for(let[e,t]of Ui)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Ui.delete(e));return st}function Gl(e,t,r=VA,n,s){let i=new FA.default(e,!1);try{let o=Ui.get(e);o?o.needsDeletion=!1:(o=(0,ah.open)(i),Ui.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 $A)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=VA),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=Ui.get(o);if(!c){let u=new FA.default(o,!1);c=(0,ah.open)(u),Ui.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;Ui.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=VA);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 $A)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){$A.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,FA,Lt,_h,kA,OG,ch,uh,ql,Rn,bG,VA,dh,NG,Ur,st,rc,$A,lh,Ui,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()),FA=B(Dc()),Lt=B(M()),_h=B(require("fs-extra")),kA=require("../index"),OG=B(Mr()),ch=B(bs()),uh=B(Ln()),ql=require("worker_threads"),Rn=B($()),bG=B(Je());ti();wc();VA="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,kA._assignPackageExport)("databases",st);(0,kA._assignPackageExport)("tables",Ur);rc=Symbol.for("next-table-id"),$A=[],Ui=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 Pi=require("path"),MG=require("fs-extra"),Cr=$(),wG=require("fs-extra"),fh=require("os"),jie=require("net"),Xie=require("recursive-iterator"),ct=M(),Zie=qO(),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:KA,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:WA,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(Pi.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 KA(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=KA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=KA(r);n!==r&&(e[t]=n)}return e}else return vG(e)}a(KA,"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=Pi.join(HG(),ct.HDB_HOME_DIR_NAME,ct.BOOT_PROPS_FILE_NAME);return MG.existsSync(e)||(e=Pi.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=Pi.basename(e,Pi.extname(e));return Pi.join(Pi.dirname(e),r+t)}a(Voe,"changeExtension");function WA(){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(WA,"getEnvCliRootPath");var YA;function $oe(){if(YA)return YA;let e=WA();if(WA()&&MG.pathExistsSync(Pi.join(e,ct.HDB_CONFIG_FILE)))return YA=!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 QA=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(),QA.accessSync(e,QA.constants.F_OK|QA.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 zA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};XG.exports=zA});var rq=R((CTe,tq)=>{"use strict";var oae=jG(),Qs=$(),JA=ke(),aae=M(),jA=_n(),xo=it(),ZG=Su(),cae=id(),{Node:uae,NodeSubscription:eq}=pi(),XA=$l(),ZA=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 XA(JA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=_ae(await jA.getNodeRecord(n)),c=!ZA.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(!ZA.doesSchemaExist(f)){Qs.trace(`updateRemoteSource creating schema: ${f}`);try{await ZG.createSchema({operation:"create_schema",schema:f})}catch(h){Qs.error(h)}}if(E&&!ZA.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 jA.upsertNodeRecord(u),dae({type:"nats_update"}),new XA(JA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${lae.get(aae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await jA.getSystemInfo())}catch(t){Qs.error(t);let r=t.message?t.message:t;return new XA(JA.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(),eO=M(),Sae=_n(),Tae=Q(),aq=it(),gae=Z(),gh=$l(),{NodeSubscription:Rae}=pi(),Aae=ia(),Oae=oi(),{broadcast:bae}=Je(),Nae=gae.get(eO.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(eO.SYSTEM_SCHEMA_NAME,eO.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(),tO=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(tO.get(Yl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),tO.get(Yl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??tO.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(),rO=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),nO=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=`${nO}.__request__`,r=e.subscribe(t,{queue:nO});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 '${nO}' reply service received unrecognized request operation`;Kl.error(s),n=new Bae(rO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Kl.trace(n),t.respond(Hae(n))}}a(Wae,"handleRequest");async function Qae(){try{return{status:rO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await qae.describeAll()}}catch(e){return Kl.error(e),{status:rO.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(xe.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&DE()==0)try{YH(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(KH&&!Dse)for(let t in ds){let r=ds[t];if(isNaN(t)&&DE()==0){Tse(t)&&YH(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=KH(+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");zH||tx();function tA(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(tA,"deliverSocket");var WH=new Map;function Use(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=WH.get(s),r){case"connection":i=tA(void 0,t),WH.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 rA(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",QH),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",QH)}a(rA,"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 nA(e,t){for(let{port:r,secure:n}of rx(t))nx(r,n,t?.isOperationsServer),typeof e=="function"?ZR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,rA(e,r,!1)),LE[r]=eA(ZR,r),Lse=eA(Mse,r)}a(nA,"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:sA(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}})),rA($s[e],e)}return $s[e]}a(nx,"getHTTPServer");function eA(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(eA,"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){nA(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:sA(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]=eA(ZR,n)}return r}a(Bse,"onWebSocket");function QH(e,t){t.writeHead(404),t.end(`Not found
|
|
32
|
+
`)}a(QH,"defaultNotFound");function XR(e){return e.startsWith("-----BEGIN")?e:Sse(e)}a(XR,"readPEM");function sA(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(sA,"createSNICallback")});async function ux({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await oA.get(e,{returnNonexistent:!0});i=new uA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await oA.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 aA(){return UE++,UE>65500&&(UE=1),UE}function cA(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,oA,bl,UE,PE,uA,lx=Re(()=>{Ae();Ku();ox=B(Mr()),Li=B($());ro();ax=B(Je()),cx=B(ix());ar();oA=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{cA(r,t,r)}catch{(0,Li.warn)("Failed to publish will",t)}bl.delete(e.id,r)})}})();a(ux,"getSession");UE=1;a(aA,"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=aA());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=aA();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 cA(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 cA(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(cA,"publish");uA=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=aA(),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}}),oA.put(this.sessionRecord)}}});var _A={};qe(_A,{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,lA,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()),lA=B($()),Ex=require("events"),BE=(0,lA.loggerWithTag)("auth-event"),nr=(0,lA.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&&(fA=t),e&&(EA=e);let r=[];if((0,qn.existsSync)(dA)){let s=(0,qn.readdirSync)(dA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Ot.join)(dA,o);r.push(xE(c,fA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(xE(n,fA,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&&(EA=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=hA;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=mA.get(pA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);g&&Nl.default.warn("Session affinity is not recommended and may cause memory leaks"),(g||!OE)&&(px.push(A),DH(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),EA.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!==hA[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,mA,pA,gx,Xa,Nl,Rx,Ax,Gse,Ox,qse,dA,EA,bx,fA,ja,Fse,hA,px,Sx,yl,Il,Mf=Re(()=>{qn=require("fs"),Ot=require("path"),Ja=require("worker_threads"),Tx=require("yaml"),mA=B(Z()),pA=B(M());pb();Rb();Ab();M0();TH();NH();gx=B(require("fast-glob")),Xa=B(Je()),Nl=B($());Wh();ar();Rx=B(ne());Nn();Ae();LH();Ax=B(Z()),Gse=B(BH());Of();$H();mx();Ox=B(dr());bE();({readFile:qse}=qn.promises),dA=mA.get(pA.CONFIG_PARAMS.COMPONENTSROOT),EA=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:_A},hA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(hA,"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 iA=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(FP)),Wse=hg(),Qse=dr(),{dirname:zse}=require("path"),{getConnection:Jse}=it(),jse=Z(),Xse=M(),SA=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,SA),await $se(SA,t);let r=[];for(let[n]of SA)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:OA,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,bA=1e4,die="restart",Px="request_thread_info",vx="resource_report",Bx="thread_info",Hx="added-port",fie="ack",TA;uie("threads",Sn);Ui.exports={startWorker:gA,restartWorkers:yA,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 NA;function Eie(e){bA=e}a(Eie,"setTerminateTimeout");function xx(){return Ys?Ys.workerIndex:NA?0:void 0}a(xx,"getWorkerIndex");function Gx(){return Ys?Ys.workerCount:NA?1:void 0}a(Gx,"getWorkerCount");function hie(e){NA=e}a(hie,"setMainIsWorker");var qx=1,GE;function Fx(){return GE||(GE=OA?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 gA(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=()=>gA(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,gA(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(gA,"startWorker");var mie=[wl.THREAD_TYPES.HTTP];async function yA(e=null,t=Math.max(qx>3,1),r=!0){if(OA){if(r){let{loadRootComponents:o}=iA();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(),bA*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(yA,"restartWorkers");function pie(e,t){kx[e]=t}a(pie,"setChildListenerByType");function Sie(e){return yA(e,1/0,!1)}a(Sie,"shutdownWorkers");var Vx=[];function Tie(e){Vx.push(e)}a(Tie,"onMessageFromWorkers");var RA=new Map;function $x(e,t){let r=RA.get(e);r||RA.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 AA;function yie(e){AA=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}AA&&AA()},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(),TA=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 TA=Yx;Ui.exports.getThreadInfo=TA;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=RA.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(OA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await aie(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(Lx(n,i.name));try{for await(let{filename:i}of oie(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await yA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");Ui.exports.watchDir=r,process.env.WATCH_DIR&&r(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)},bA).unref())})});var CC={};qe(CC,{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()-IA})){if((_[0]&15)===DA){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,IA/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){IA=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?(MA.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 LA(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&wA||n&CA&&!E)return f.decoder.decode(e.subarray(t.position));if(n&CA&&h)return UA(f.getEntry(this.recordId),h,f)}}}catch(t){return MA.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,MA,Tn,Za,eG,Ef,IA,Die,kE,wA,CA,Kx,DA,Wx,Qx,zx,tG,LA,ti=Re(()=>{ec=require("ordered-binary"),VE=B(Z()),jx=B(ut()),Xx=B(M()),$E=B(Je()),Zx=B(Q());wc();MA=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},IA=(0,Zx.convertToMS)((0,VE.get)(Xx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Die=1e3,kE=1e4;a(YE,"openAuditStore");a(Lie,"setAuditRetention");wA=16,CA=32,Kx=1,DA=2,Wx=3,Qx=4,zx=5,tG={put:Kx|wA,[Kx]:"put",delete:DA,[DA]:"delete",message:Wx|wA,[Wx]:"message",invalidate:Qx,[Qx]:"invalidate",patch:zx|CA,[zx]:"patch"};a(E_,"createAuditEntry");a(Ut,"readAuditEntry");LA=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 PA={};qe(PA,{add:()=>WE,applyReverse:()=>rG,getRecordAtTime:()=>UA,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 UA(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(UA,"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=PA[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 BA;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 vA(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):vA(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(vA(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(vA(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,BA,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");BA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Xr,"transactional");a(Zr,"missingMethod");a(vA,"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 xA(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,HA.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,HA.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 HA,lG,_G,xA,EG=Re(()=>{HA=B($());Rc();Ku();ti();lG=Object.create(null),_G=Object.create(null);a(dG,"addSubscription");xA=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,iO=!1,Ah,Oh,Sq=i.getRange({start:!1,end:!1}).constructor,Tq=10,gq=6;h&&cO();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[GA]=!0,FA(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[GA]=!0,FA(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&&cO(),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||iO&&b){if(O||(O={}),b){let D=N?.length>0&&qA(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=qA(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=qA(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)=>oO(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=oO(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[GA]: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)"),iO=!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=aO(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 oO(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(oO,"transformToEntries");async function aO(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(aO(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;FA(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⋘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(aO,"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 cO(){z=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(cO,"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 qA(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 FA(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,GA,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,GA=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(qA,"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(FA,"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=$A,n,s){let i=new kA.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 YA)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=$A),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 kA.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=$A);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 YA)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){YA.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,kA,Lt,_h,VA,OG,ch,uh,ql,Rn,bG,$A,dh,NG,Ur,st,rc,YA,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()),kA=B(Dc()),Lt=B(M()),_h=B(require("fs-extra")),VA=require("../index"),OG=B(Mr()),ch=B(bs()),uh=B(Ln()),ql=require("worker_threads"),Rn=B($()),bG=B(Je());ti();wc();$A="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,VA._assignPackageExport)("databases",st);(0,VA._assignPackageExport)("tables",Ur);rc=Symbol.for("next-table-id"),YA=[],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=FO(),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:WA,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:QA,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 WA(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=WA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=WA(r);n!==r&&(e[t]=n)}return e}else return vG(e)}a(WA,"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 QA(){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(QA,"getEnvCliRootPath");var KA;function $oe(){if(KA)return KA;let e=QA();if(QA()&&MG.pathExistsSync(vi.join(e,ct.HDB_CONFIG_FILE)))return KA=!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 zA=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(),zA.accessSync(e,zA.constants.F_OK|zA.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=$(),jA=ke(),aae=M(),XA=_n(),xo=it(),ZG=Su(),cae=id(),{Node:uae,NodeSubscription:eq}=pi(),ZA=$l(),eO=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 ZA(jA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=_ae(await XA.getNodeRecord(n)),c=!eO.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(!eO.doesSchemaExist(f)){Qs.trace(`updateRemoteSource creating schema: ${f}`);try{await ZG.createSchema({operation:"create_schema",schema:f})}catch(h){Qs.error(h)}}if(E&&!eO.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 XA.upsertNodeRecord(u),dae({type:"nats_update"}),new ZA(jA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${lae.get(aae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await XA.getSystemInfo())}catch(t){Qs.error(t);let r=t.message?t.message:t;return new ZA(jA.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(),tO=M(),Sae=_n(),Tae=Q(),aq=it(),gae=Z(),gh=$l(),{NodeSubscription:Rae}=pi(),Aae=ia(),Oae=oi(),{broadcast:bae}=Je(),Nae=gae.get(tO.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(tO.SYSTEM_SCHEMA_NAME,tO.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(),rO=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(rO.get(Yl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),rO.get(Yl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??rO.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(),nO=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),sO=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=`${sO}.__request__`,r=e.subscribe(t,{queue:sO});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 '${sO}' reply service received unrecognized request operation`;Kl.error(s),n=new Bae(nO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Kl.trace(n),t.respond(Hae(n))}}a(Wae,"handleRequest");async function Qae(){try{return{status:nO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await qae.describeAll()}}catch(e){return Kl.error(e),{status:nO.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)}})();
|