harperdb 4.3.0 → 4.3.2
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 +58 -57
- package/bin/lite.js +20 -20
- package/json/systemSchema.json +8 -2
- package/launchServiceScripts/launchInstallNATSServer.js +2 -2
- package/launchServiceScripts/launchNatsIngestService.js +19 -19
- package/launchServiceScripts/launchNatsReplyService.js +20 -20
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +20 -20
- package/npm-shrinkwrap.json +51 -51
- package/package.json +2 -2
- package/server/jobs/jobProcess.js +20 -20
- package/server/threads/threadServer.js +20 -20
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.6edd076f.js → main.a7ed3686.js} +2 -2
- package/utility/scripts/restartHdb.js +20 -20
- package/config/yaml/defaultCloneConfig.yaml +0 -26
- /package/studio/build-local/static/js/{main.6edd076f.js.LICENSE.txt → main.a7ed3686.js.LICENSE.txt} +0 -0
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
"use strict";var pq=Object.create;var oc=Object.defineProperty;var Sq=Object.getOwnPropertyDescriptor;var Tq=Object.getOwnPropertyNames;var gq=Object.getPrototypeOf,Rq=Object.prototype.hasOwnProperty;var a=(e,t)=>oc(e,"name",{value:t,configurable:!0});var ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qe=(e,t)=>{for(var r in t)oc(e,r,{get:t[r],enumerable:!0})},lO=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Tq(t))!Rq.call(e,n)&&n!==r&&oc(e,n,{get:()=>t[n],enumerable:!(s=Sq(t,n))||s.enumerable});return e};var v=(e,t,r)=>(r=e!=null?pq(gq(e)):{},lO(t||!e||!e.__esModule?oc(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>lO(oc({},"__esModule",{value:!0}),e);var fO=g((qae,dO)=>{var Aq=require("fast-glob"),{statSync:wh,existsSync:Ch,readFileSync:Oq,writeFileSync:bq}=require("fs"),{spawnSync:yq,spawn:Nq,execFileSync:Gae}=require("child_process"),{isMainThread:Iq}=require("worker_threads"),{join:Xn,relative:_O}=require("path"),{PACKAGE_ROOT:bs}=L(),{tmpdir:wq,platform:Cq}=require("os");require("source-map-support").install();var Dq=["resources","server","dataLayer","components"],ac="ts-build",Dh,Lq=__filename.endsWith("tsBuild.js");if(Lq){if(Iq){let r;try{wh(Xn(bs,ac)),r=!0}catch{}if(r)for(let s of Aq.sync(Dq.map(n=>n+"/**/*.ts"),{cwd:bs})){let n=0,i=0;try{n=wh(Xn(bs,s)).mtimeMs-5e3,i=wh(Xn(bs,ac,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Dh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Dh=!0;if(Dh){let s=Xn(bs,"node_modules/.bin/tsc");Cq()==="win32"&&(s+=".cmd");let n=yq(s,{cwd:bs});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=Xn(wq(),"harperdb-tsc.pid"),o;if(Ch(i))try{process.kill(+Oq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Nq(s,["--watch"],{cwd:bs,detached:!0,stdio:"ignore"});bq(i,c.pid.toString()),c.unref()}}}}let e=dO.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(bs)&&!s[0].includes("node_modules")){let i=_O(bs,s[0]),o;i.startsWith(ac)?o=Xn(bs,_O(ac,i)):o=Xn(bs,ac,i);let c=Xn(o,r),u=c+".js";if(Ch(u))return u;if(c.includes(".")&&Ch(c))return c}return t(r,s,n)}}});var L=g((Vae,IO)=>{"use strict";var ss=require("path"),Mq=require("fs"),{relative:Fae,join:kae}=ss,{existsSync:Uq}=Mq;function Pq(){let e=__dirname;for(;!Uq(ss.join(e,"package.json"));){let t=ss.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Pq,"getHDBPackageRoot");var jn=Pq(),EO="js",jl=EO,vq="harperdb-config.yaml",Bq="defaultConfig.yaml",Hq="hdb",hO=`harperdb.${jl}`,mO=`customFunctionsServer.${jl}`,xq=`restartHdb.${jl}`,Mh="HarperDB",Xl="Custom Functions",Zl="Clustering Hub",e_="Clustering Leaf",Gq="Clustering Ingest Service",qq="Clustering Reply Service",Fq="foreground.pid",kq="hdb.pid",Vq="data",$q={HDB:Mh,CLUSTERING_HUB:Zl,CLUSTERING_LEAF:e_,CLUSTERING_INGEST_SERVICE:Gq,CLUSTERING_REPLY_SERVICE:qq,CUSTOM_FUNCTIONS:Xl,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"},Yq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Kq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Wq={harperdb:Mh,"clustering hub":Zl,"clustering leaf":e_,"custom functions":Xl,custom_functions:Xl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},Qq={CLUSTERING_HUB_PROC_DESCRIPTOR:Zl,CLUSTERING_LEAF_PROC_DESCRIPTOR:e_},Lh={HDB:ss.join(jn,"server/harperdb"),CUSTOM_FUNCTIONS:ss.join(jn,"server/customFunctions"),CLUSTERING_HUB:ss.join(jn,"server/nats"),CLUSTERING_LEAF:ss.join(jn,"server/nats")},zq={HDB:ss.join(Lh.HDB,hO),CUSTOM_FUNCTIONS:ss.join(Lh.CUSTOM_FUNCTIONS,mO)},Jq={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:ss.join(jn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:ss.join(jn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:ss.join(jn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},Xq={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},pO="support@harperdb.io",jq="customer-success@harperdb.io",SO=1,Zq=4141,TO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",eF="https://www.harperdb.io/product",tF=`For support, please submit a request at ${TO} or contact ${pO}`,gO=`For license support, please contact ${jq}`,rF="None of the specified records were found.",sF="hash attribute not found",nF=`Your current license only supports ${SO} role. ${gO}`,iF="Your current license only supports 3 connections to a node.",oF="127.0.0.1",aF=1,cF=/^\.$/,uF=/^\.\.$/,lF="U+002E",_F=/\//g,dF="U+002F",fF=/U\+002F/g,EF=/^U\+002E$/,hF=/^U\+002EU\+002E$/,mF="d",pF=999999,SF="*",TF="--max-old-space-size=",gF="system",RF="__hdb_hash",AF=".harperdb",OF=".hdb",bF="keys",yF="hdb_boot_properties.file",NF=".updateConfig.json",IF="SIGTSTP",wF=24,CF=6e4,DF=448,LF="blob",MF="trash",UF="database",PF="schema",vF="transactions",BF=".count",HF="id",xF="PROCESS_NAME",RO={SETTINGS_PATH_KEY:"settings_path"},AO=require("lodash"),GF={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"},qF={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},FF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},kF={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"},VF={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"},wr="hdb_internal:",$F={CREATE_SCHEMA:wr+"create_schema",CREATE_TABLE:wr+"create_table",CREATE_ATTRIBUTE:wr+"create_attribute",ADD_USER:wr+"add_user",ALTER_USER:wr+"alter_user",DROP_USER:wr+"drop_user",HDB_NODES:wr+"hdb_nodes",HDB_USERS:wr+"hdb_users",HDB_WORKERS:wr+"hdb_workers",CATCHUP:wr+"catchup",SCHEMA_CATCHUP:wr+"schema_catchup",WORKER_ROOM:wr+"cluster_workers"},YF={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"},KF="060493.ks",WF=".license",QF={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},Z={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"},zF={CSV:".csv",JSON:".json"},JF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},XF={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},cc={};cc[Z.INSERT]=Z.INSERT;cc[Z.UPDATE]=Z.UPDATE;cc[Z.UPSERT]=Z.UPSERT;cc[Z.DELETE]=Z.DELETE;var xe=Object.create(null);xe[Z.DESCRIBE_ALL]=Z.DESCRIBE_ALL;xe[Z.DESCRIBE_TABLE]=Z.DESCRIBE_TABLE;xe[Z.DESCRIBE_SCHEMA]=Z.DESCRIBE_SCHEMA;xe[Z.READ_LOG]=Z.READ_LOG;xe[Z.ADD_NODE]=Z.ADD_NODE;xe[Z.LIST_USERS]=Z.LIST_USERS;xe[Z.LIST_ROLES]=Z.LIST_ROLES;xe[Z.USER_INFO]=Z.USER_INFO;xe[Z.SQL]=Z.SQL;xe[Z.GET_JOB]=Z.GET_JOB;xe[Z.SEARCH_JOBS_BY_START_DATE]=Z.SEARCH_JOBS_BY_START_DATE;xe[Z.DELETE_FILES_BEFORE]=Z.DELETE_FILES_BEFORE;xe[Z.EXPORT_LOCAL]=Z.EXPORT_LOCAL;xe[Z.EXPORT_TO_S3]=Z.EXPORT_TO_S3;xe[Z.CLUSTER_STATUS]=Z.CLUSTER_STATUS;xe[Z.REMOVE_NODE]=Z.REMOVE_NODE;xe[Z.RESTART]=Z.RESTART;xe[Z.CUSTOM_FUNCTIONS_STATUS]=Z.CUSTOM_FUNCTIONS_STATUS;xe[Z.GET_CUSTOM_FUNCTIONS]=Z.GET_CUSTOM_FUNCTIONS;xe[Z.GET_CUSTOM_FUNCTION]=Z.GET_CUSTOM_FUNCTION;xe[Z.SET_CUSTOM_FUNCTION]=Z.SET_CUSTOM_FUNCTION;xe[Z.DROP_CUSTOM_FUNCTION]=Z.DROP_CUSTOM_FUNCTION;xe[Z.ADD_CUSTOM_FUNCTION_PROJECT]=Z.ADD_CUSTOM_FUNCTION_PROJECT;xe[Z.DROP_CUSTOM_FUNCTION_PROJECT]=Z.DROP_CUSTOM_FUNCTION_PROJECT;xe[Z.PACKAGE_CUSTOM_FUNCTION_PROJECT]=Z.PACKAGE_CUSTOM_FUNCTION_PROJECT;xe[Z.DEPLOY_CUSTOM_FUNCTION_PROJECT]=Z.DEPLOY_CUSTOM_FUNCTION_PROJECT;var jF={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"},ZF={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},OO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},ek=AO.invert(OO),tk={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_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",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"},bO={settings_path:RO.SETTINGS_PATH_KEY,hdb_root_key:w.ROOTPATH,hdb_root:w.ROOTPATH,rootpath:w.ROOTPATH,server_port_key:w.OPERATIONSAPI_NETWORK_PORT,server_port:w.OPERATIONSAPI_NETWORK_PORT,cert_key:w.TLS_CERTIFICATE,certificate:w.TLS_CERTIFICATE,private_key_key:w.TLS_PRIVATEKEY,private_key:w.TLS_PRIVATEKEY,http_secure_enabled_key:w.OPERATIONSAPI_NETWORK_HTTPS,https_on:w.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:w.OPERATIONSAPI_NETWORK_CORS,cors_on:w.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:w.LOGGING_LEVEL,log_level:w.LOGGING_LEVEL,log_path_key:w.LOGGING_ROOT,log_path:w.LOGGING_ROOT,clustering_node_name_key:w.CLUSTERING_NODENAME,node_name:w.CLUSTERING_NODENAME,clustering_enabled_key:w.CLUSTERING_ENABLED,clustering:w.CLUSTERING_ENABLED,max_http_threads:w.THREADS_COUNT,max_hdb_processes:w.THREADS_COUNT,server_timeout_key:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:w.LOGGING_AUDITLOG,disable_transaction_log:w.LOGGING_AUDITLOG,operation_token_timeout_key:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:w.HTTP_PORT,custom_functions_port:w.HTTP_PORT,custom_functions_directory_key:w.COMPONENTSROOT,custom_functions_directory:w.COMPONENTSROOT,max_custom_function_processes:w.THREADS_COUNT,log_to_file:w.LOGGING_FILE,log_to_stdstreams:w.LOGGING_STDSTREAMS,local_studio_on:w.LOCALSTUDIO_ENABLED,clustering_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:w.CLUSTERING_USER,clustering_enabled:w.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:w.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:w.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:w.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:w.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:w.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:w.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:w.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:w.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:w.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:w.CLUSTERING_NODENAME,clustering_tls_certificate:w.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:w.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:w.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:w.CLUSTERING_TLS_INSECURE,clustering_tls_verify:w.CLUSTERING_TLS_VERIFY,clustering_loglevel:w.CLUSTERING_LOGLEVEL,clustering_republishmessages:w.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:w.CLUSTERING_DATABASELEVEL,customfunctions_network_port:w.HTTP_PORT,customfunctions_tls_certificate:w.TLS_CERTIFICATE,customfunctions_network_cors:w.HTTP_CORS,customfunctions_network_corsaccesslist:w.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:w.HTTP_HEADERSTIMEOUT,customfunctions_network_https:w.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:w.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:w.HTTP_TIMEOUT,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_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,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_certificate:w.TLS_CERTIFICATE,tls_privatekey:w.TLS_PRIVATEKEY,tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,tls_ciphers:w.TLS_CIPHERS};for(let e in w){let t=w[e];bO[t.toLowerCase()]=t}var rk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},sk={csv_file_load:"csv_file_load",csv_data_load:Z.CSV_DATA_LOAD,csv_url_load:Z.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"},nk={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"},ik={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},ok={VERSION_DEFAULT:"2.2.0"},ak={DEVELOPMENT:8192,DEFAULT:512},ck={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"},uk={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"},lk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},yO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},_k=Symbol("metadata"),dk="__clustering__",fk=Object.values(yO),Ek=15984864e5,NO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},hk=AO.invert(NO),mk={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"},pk=111,Sk=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
4
|
-
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,s])=>({pid:Number.parseInt(r,10),name:Xk.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(tV,"findPs")});var ut=g((Xae,$O)=>{"use strict";var rV="__dbis__",sV="__txns__",nV="__environment_name__",iV="__dbi_defintion__",oV={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"},aV=["__createdtime__","__updatedtime__"],cV="\uFFFF",VO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},uV=Object.values(VO);$O.exports={AUDIT_STORE_NAME:sV,INTERNAL_DBIS_NAME:rV,DBI_DEFINITION_NAME:iV,SEARCH_TYPES:oV,TIMESTAMP_NAMES:aV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:nV,TRANSACTIONS_DBI_NAMES_ENUM:VO,TRANSACTIONS_DBIS:uV,OVERFLOW_MARKER:cV}});var Cr=g((jae,ZO)=>{"use strict";var YO=L(),KO=ut(),WO={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},QO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),zO={500:QO("There was an error processing your request."),400:"Invalid request"},lV=zO[WO.INTERNAL_SERVER_ERROR],_V={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.`},dV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},fV={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"},EV={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${KO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${KO.INTERNAL_DBIS_NAME}`,START_VALUE_REQUIRED:"start_value is required",END_VALUE_REQUIRED:"end_value is required",CANNOT_COMPARE_STRING_TO_NUMERIC_KEYS:"cannot compare a string to numeric keys",END_VALUE_MUST_BE_GREATER_THAN_START_VALUE:"end_value must be greater than or equal to start_value",UNKNOWN_SEARCH_TYPE:"unknown search type",CANNOT_DROP_TABLE_HASH_ATTRIBUTE:"cannot drop a table's hash attribute"},hV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${YO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes.`,ATTR_NAME_NULLISH_ERR:"transaction aborted due to record(s) with an attribute name that is null, undefined or empty string",HASH_VAL_LENGTH_ERR:`transaction aborted due to record(s) with a hash value that exceeds ${YO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},JO={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},mV={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."},pV={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`},SV={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"},TV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},gV={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},XO={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},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}`},RV={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."},AV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},OV={...JO,...fV,..._V,...mV,...pV,...SV,...TV,...gV,...hV,...XO,...jO,...RV,...AV,...dV};ZO.exports={CHECK_LOGS_WRAPPER:QO,HDB_ERROR_MSGS:OV,DEFAULT_ERROR_MSGS:zO,DEFAULT_ERROR_RESP:lV,HTTP_STATUS_CODES:WO,LMDB_ERRORS_ENUM:EV,AUTHENTICATION_ERROR_MSGS:JO,VALIDATION_ERROR_MSGS:XO,ITC_ERRORS:jO}});var se=g((ece,rb)=>{"use strict";var ko=Cr(),bV=$(),yV=L(),i_=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,eb),this.statusCode=s||ko.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(ko.DEFAULT_ERROR_MSGS[s]?ko.DEFAULT_ERROR_MSGS[s]: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,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&bV[n](i)}},Fh=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},kh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function eb(e,t,r,s=yV.LOG_LEVELS.ERROR,n=null,i=!1){if(tb(e))return e;let o=new i_(e,t,r,s,n);return i&&delete o.stack,o}a(eb,"handleHDBError");function tb(e){return e.__proto__.constructor.name===i_.name}a(tb,"isHDBError");rb.exports={isHDBError:tb,handleHDBError:eb,ClientError:Fh,ServerError:kh,hdb_errors:ko}});var Je=g((rce,ub)=>{"use strict";var Sc=L(),NV=Q(),ir=ee(),Tc=require("path"),IV=require("minimist"),sb=require("fs-extra"),nb=require("lodash");ir.initSync();var{CONFIG_PARAMS:Zn,DATABASES_PARAM_CONFIG:Ec,SYSTEM_SCHEMA_NAME:o_}=Sc,hc,mc,pc;function ib(){if(hc!==void 0)return hc;if(ir.getHdbBasePath()!==void 0)return hc=ir.get(Zn.STORAGE_PATH)||Tc.join(ir.getHdbBasePath(),Sc.DATABASES_DIR_NAME),hc}a(ib,"getBaseSchemaPath");function ob(){if(mc!==void 0)return mc;if(ir.getHdbBasePath()!==void 0)return mc=cb(o_),mc}a(ob,"getSystemSchemaPath");function ab(){if(pc!==void 0)return pc;if(ir.getHdbBasePath()!==void 0)return pc=ir.get(Sc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Tc.join(ir.getHdbBasePath(),Sc.TRANSACTIONS_DIR_NAME),pc}a(ab,"getTransactionAuditStoreBasePath");function wV(e,t){let r=ir.get(Zn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Tc.join(ab(),e.toString())}a(wV,"getTransactionAuditStorePath");function cb(e,t){e=e.toString(),t=t&&t.toString();let r=ir.get(Sc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Tc.join(ib(),e)}a(cb,"getSchemaPath");function CV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,IV(process.argv));let s=r[Zn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!NV.isObject(s))throw o;i=s}for(let o of i){let c=o[o_];if(!c)continue;let u=ir.get(Zn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[Ec.PATH];if(_)return nb.set(u,[o_,Ec.TABLES,t,Ec.PATH],_),ir.setProperty(Zn.DATABASES,u),_;let l=c?.[Ec.PATH];if(l)return nb.set(u,[o_,Ec.PATH],l),ir.setProperty(Zn.DATABASES,u),l}}let n=r[Zn.STORAGE_PATH.toUpperCase()];if(n){if(!sb.pathExistsSync(n))throw new Error(n+" does not exist");let i=Tc.join(n,e);return sb.mkdirsSync(i),ir.setProperty(Zn.STORAGE_PATH,n),i}return ob()}a(CV,"initSystemSchemaPaths");function DV(){hc=void 0,mc=void 0,pc=void 0}a(DV,"resetPaths");ub.exports={getBaseSchemaPath:ib,getSystemSchemaPath:ob,getTransactionAuditStorePath:wV,getTransactionAuditStoreBasePath:ab,getSchemaPath:cb,initSystemSchemaPaths:CV,resetPaths:DV}});var Dr=g((oce,Eb)=>{"use strict";var LV=Cr().LMDB_ERRORS_ENUM,nce=require("lmdb"),MV=ut(),ice=require("buffer").Buffer,{OVERFLOW_MARKER:lb,MAX_SEARCH_KEY_LENGTH:a_}=MV,_b=["number","string","symbol","boolean","bigint"];function UV(e){if(e=e?.primaryStore||e,!e)throw new Error(LV.ENV_REQUIRED)}a(UV,"validateEnv");function PV(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(PV,"stringifyData");function vV(e){return e instanceof Date?e.valueOf():e}a(vV,"convertKeyValueToWrite");function BV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(_b.includes(typeof e))return e.length>a_?[e.slice(0,a_)+lb]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if(_b.includes(typeof i))i.length>a_?r.push(i.slice(0,a_)+lb):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(BV,"getIndexedValues");var c_=0,db=0;function fb(){db=Date.now()-performance.now()}a(fb,"adjustStartTime");fb();var HV=6e4;setInterval(fb,HV).unref();function xV(){let e=performance.now()+db;return e>c_?(c_=e,e):(c_+=488e-6,c_)}a(xV,"getNextMonotonicTime");Eb.exports={validateEnv:UV,stringifyData:PV,convertKeyValueToWrite:vV,getNextMonotonicTime:xV,getIndexedValues:BV}});var hb,ys,Vh,gc=ge(()=>{hb=require("events"),ys=class extends hb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Vh;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},Vh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var xi={};qe(xi,{server:()=>st});var mb,st,or=ge(()=>{mb=require("../index"),st={};(0,mb._assignPackageExport)("server",st)});var Kh={};qe(Kh,{loadGQLSchema:()=>FV,start:()=>Yh,startOnMainThread:()=>qV});function Yh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),n)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let x=function(P){if(P.kind==="NonNullType"){let X=x(P.type);return X.nullable=!1,X}if(P.kind==="ListType")return{type:"array",elements:x(P.type)};let B={type:P.name?.value};return Object.defineProperty(B,"location",{value:P.loc.startToken}),B};a(x,"getProperty");let T=S.name.value,A=[],R={table:null,database:null,properties:A};f.set(T,R);for(let P of S.directives){if(P.name.value==="table"){for(let k of P.arguments)R[k.name.value]=k.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=T),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,E.push(R)}if(P.name.value==="sealed"&&(R.sealed=!0),P.name.value==="export"){R.export=!0;for(let k of P.arguments)k.name.value==="name"&&(R.export={name:k.value.value})}}let M=!1;for(let P of S.fields){let k=x(P.type);k.name=P.name.value,A.push(k);for(let B of P.directives)if(B.name.value==="primaryKey")M?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,M=!0);else if(B.name.value==="indexed")k.indexed=!0;else if(B.name.value==="relationship"){let X={};for(let z of B.arguments)X[z.name.value]=z.value.value;k.relationship=X}else if(B.name.value==="createdTime")k.assignCreatedTime=!0;else if(B.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(B.name.value==="expiresAt")k.expiresAt=!0;else if(B.name.value==="allow"){let X=k.authorizedRoles=[];for(let z of B.arguments)z.name.value==="role"&&X.push(z.value.value)}}R.type=T,T==="Query"&&(h=R)}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):GV.includes(S.type)||(0,pb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${n}`)}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)(s),S.tableClass):i.set((0,$h.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass))}}var $h,pb,GV,qV,FV,Sb=ge(()=>{$h=require("path");Re();pb=v(Ke()),GV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Yh,"start");qV=Yh,FV=Yh({ensureTable:lt}).handleFile});async function u_(e){return kV?(Rc||(Rc=VV(YV)),(await(await Rc).import(e)).namespace):import(e)}async function VV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Rc=new Compartment({console,Math,Date,fetch:$V,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,gb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:Ft,tables:Lr,databases:nt})}};let s=await(0,Tb.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),Rc}function $V(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 YV(){return{Resource:Ft,tables:Lr}}var Tb,gb,kV,Rc,Wh=ge(()=>{Ns();Re();Tb=require("fs/promises"),gb=require("path"),kV=!1;a(u_,"secureImport");a(VV,"getCompartment");a($V,"secureOnlyFetch");a(YV,"getGlobalVars")});var zh={};qe(zh,{handleFile:()=>KV});async function KV(e,t,r,s){let n=new Map,i=(0,Rb.pathToFileURL)(r).toString(),o=await u_(i);u(o.default)&&s.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)?s.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),n}var Rb,Qh,Ab=ge(()=>{Rb=require("url");Wh();Qh=require("path");a(KV,"handleFile")});var Xh={};qe(Xh,{start:()=>WV});function WV({resources:e}){e.set("login",Jh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Jh,Ob=ge(()=>{Ns();a(WV,"start");Jh=class extends Ft{static{a(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:o}=r;return{data:await s.login(n,i)}}}});var Db={};qe(Db,{parse:()=>Zh,streamAsJSON:()=>Ac,stringify:()=>Gi});function Ac(e){return new jh({value:e})}function bb(e){return console.error(e),JSON.stringify(e.toString())}function yb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Gi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===wb)return Cb(e);if(t.resolution)return t.resolution.then(()=>Gi(e));throw t}}function Cb(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let s=0;s<e.length;s++)s>0&&(r+=","),r+=Cb(e[s]);return r+"]"}else{r="{";let s=!0;for(let n in e)s?s=!1:r+=",",r+=JSON.stringify(n)+":"+Gi(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Zh(e){return JV.test(e)?QV.parse(e):JSON.parse(e)}var Nb,Ib,QV,zV,wb,jh,JV,em=ge(()=>{Nb=require("stream"),Ib=v(require("json-bigint-fixes")),QV=(0,Ib.default)({useNativeBigInt:!0}),zV=1e4,wb={};BigInt.prototype.toJSON=function(){throw wb};a(Ac,"streamAsJSON");jh=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],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else n?n=!1:yield",",yield*this.serialize(o.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),bb)}catch(n){yield bb(n)}else yield Gi(t)}else yield Gi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);yb(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>zV?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 yb(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let s of this.activeIterators)t?s.throw(t):s.return();r()}};a(bb,"handleError");a(yb,"when");a(Gi,"stringify");a(Cb,"jsStringify");JV=/[[,:]\s*-?\d{16,}/;a(Zh,"parse")});var Vb=g((Ace,kb)=>{"use strict";var tm=require("recursive-iterator"),XV=require("alasql"),rm=require("clone"),Lb=Q(),{handleHDBError:Mb,hdb_errors:jV}=se(),{HDB_ERROR_MSGS:Ub,HTTP_STATUS_CODES:Pb}=jV,{getDatabases:ZV}=(Re(),ie(Fe)),e$=["DISTINCT_ARRAY"],vb=Symbol("validateTables"),sm=Symbol("validateTable"),Rce=Symbol("getAllColumns"),Bb=Symbol("validateAllColumns"),l_=Symbol("findColumn"),Hb=Symbol("validateOrderBy"),Oc=Symbol("validateSegment"),nm=Symbol("validateColumn"),xb=Symbol("setColumnsForTable"),Gb=Symbol("checkColumnsForAsterisk"),qb=Symbol("validateGroupBy"),Fb=Symbol("hasColumns"),im=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[vb](),this[Gb](),this[Bb]()}[vb](){if(this[Fb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[sm](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[sm](t.table)})}}[Fb](){let t=!1,r=new tm(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[sm](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=ZV();if(!r[t.databaseid])throw Mb(new Error,Ub.SCHEMA_NOT_FOUND(t.databaseid),Pb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Mb(new Error,Ub.TABLE_NOT_FOUND(t.databaseid,t.tableid),Pb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=rm(n);i.table=rm(t),this.attributes.push(i)})}[l_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[Gb](){let t=new tm(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[xb](r.tableid)}[xb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new XV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Bb](){this[Oc](this.statement.columns,!1),this[Oc](this.statement.joins,!1),this[Oc](this.statement.where,!1),this[qb](this.statement.group,!1),this[Oc](this.statement.order,!0)}[Oc](t,r){if(!t)return;let s=new tm(t),n=[];for(let{node:i,path:o}of s)!Lb.isEmpty(i)&&!Lb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Hb](i):n.push(this[nm](i)));return n}[qb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&e$.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=rm(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[l_](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[l_](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[Hb](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[nm](t)}[nm](t){let r=this[l_](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};kb.exports=im});var Yb=g((bce,$b)=>{"use strict";var om=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};$b.exports=om});var Wb=g((Nce,Kb)=>{"use strict";var am=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Kb.exports=am});var Xb={};qe(Xb,{HAS_EXPIRATION:()=>Em,LAST_TIMESTAMP_PLACEHOLDER:()=>Nc,LOCAL_TIMESTAMP:()=>t$,METADATA:()=>bc,NO_TIMESTAMP:()=>um,PENDING_LOCAL_TIME:()=>hm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>fm,RecordEncoder:()=>dm,TIMESTAMP_ASSIGN_LAST:()=>s$,TIMESTAMP_ASSIGN_NEW:()=>zb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Jb,TIMESTAMP_PLACEHOLDER:()=>__,TIMESTAMP_RECORD_PREVIOUS:()=>lm,getUpdateRecord:()=>mm,handleLocalTimeForGets:()=>h_});function i$(){return yc[0]=yc[0]^64,r$.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?.[bc];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?.[bc]>=0?c.value:c};let s=e.getRange;e.getRange=function(i){let o=s.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[bc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let n=e.useReadTransaction();if(n.done(),!n.done.isTracked){let i=n.constructor,o=n.use,c=n.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,qi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<qi.length;u++){let _=qi[u].deref();(!_||_.isDone||_.isCommitted)&&qi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function mm(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Vo=i?.localTime?lm|Jb:um:Vo=u?i?.localTime?lm|16384:zb|16384:um,l>0&&(c|=Em),f_=c,_m=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Vo>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(s,n,h);if(u){let T=_?.user?.username;if(E&&(d_=e.encoder.encode(E)),f&&i?.localTime){let A=i?.localTime,R=r.get(A);if(R){let M=Mt(R).previousLocalTime;return r.put(A,E_(o,t,s,M,T,d,d_),{ifVersion:p}),S}}r.put(Nc,E_(o,t,s,i?.localTime?1:0,T,d,d_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+s+" options: "+h,S}}}var Qb,cm,__,Nc,fm,t$,bc,yc,r$,um,zb,s$,Jb,lm,Em,hm,n$,d_,Vo,f_,_m,dm,qi,Ic=ge(()=>{Qb=require("msgpackr");ei();cm=v($()),__=new Uint8Array([1,1,1,1,4,64,0,0]),Nc=new Uint8Array([1,1,1,1,1,0,0,0]),fm=new Uint8Array([1,1,1,1,3,64,0,0]),t$=Symbol("local-timestamp"),bc=Symbol("metadata"),yc=new Uint8Array(8),r$=new DataView(yc.buffer,0,8),um=0,zb=0,s$=1,Jb=3,lm=4,Em=16,hm=1,Vo=0,f_=-1,_m=0,dm=class extends Qb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,n){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 _=n$=r.call(this,s,n|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,s,n)}}decode(t,r){let s=r?.start||0,n=r>-1?r:r?.end||t.length,i=t[s],o=0;try{if(i<32&&n>2){let c=s,u;if(i===2){if(t.copy)t.copy(yc,0,c),c+=8;else for(let d=0;d<8;d++)yc[d]=t[c++];u=i$(),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,n),n-c);return{localTime:u,value:l,[bc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(i$,"getTimestamp");a(h_,"handleLocalTimeForGets");qi=[];setInterval(()=>{for(let e=0;e<qi.length;e++){let t=qi[e].deref();!t||t.isDone||t.isCommitted?qi.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 wc=g((Lce,Zb)=>{"use strict";var jb=ee(),o$=L(),{RecordEncoder:a$}=(Ic(),ie(Xb)),Dce=require("fs");jb.initSync();var c$=jb.get(o$.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=c$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:a$})}};Zb.exports=pm});var Cc=g((Uce,ey)=>{"use strict";var Mr=ee(),ns=L();Mr.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=Mr.get(ns.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Mr.get(ns.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Mr.get(ns.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Mr.get(ns.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Mr.get(ns.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Mr.get(ns.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Mr.get(ns.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Mr.get(ns.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Mr.get(ns.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Mr.get(ns.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Mr.get(ns.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Mr.get(ns.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ey.exports=m_;m_.MAX_DBS=1e4});var We=g((vce,ly)=>{"use strict";var Tm=require("lmdb"),Is=require("fs-extra"),Ur=require("path"),p_=Dr(),sy=$(),ar=Cr().LMDB_ERRORS_ENUM,S_=Wb(),gm=wc(),ny=Cc(),ti=ut(),ty=L(),{table:u$,resetDatabases:l$}=(Re(),ie(Fe)),ry=ee(),ws=ti.INTERNAL_DBIS_NAME,iy=ti.DBI_DEFINITION_NAME,_$="data.mdb",d$="lock.mdb",Dc=".mdb",f$="-lock",Sm=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=is(t,r),this.key_type=this.dbi[ti.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ti.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!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(ar.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(ar.ENV_NAME_REQUIRED)}a(T_,"pathEnvNameValidation");async function Rm(e,t,r=!0){try{await Is.access(e)}catch(s){throw s.code==="ENOENT"?new Error(ar.INVALID_BASE_PATH):s}try{let s=Ur.join(e,t+Dc);return await Is.access(s,Is.constants.R_OK|Is.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Is.access(Ur.join(e,t,_$),Is.constants.R_OK|Is.constants.F_OK),Ur.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(ar.INVALID_ENVIRONMENT)}else throw new Error(ar.INVALID_ENVIRONMENT);throw s}}a(Rm,"validateEnvironmentPath");function g_(e,t){if(p_.validateEnv(e),t===void 0)throw new Error(ar.DBI_NAME_REQUIRED)}a(g_,"validateEnvDBIName");async function E$(e,t,r=!1,s=!1){T_(e,t);let n=Ur.basename(e);t=t.toString();let i=ry.get(ty.CONFIG_PARAMS.DATABASES);i||ry.setProperty(ty.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await Rm(e,t,s),oy(e,t,r)}catch(o){if(o.message===ar.INVALID_ENVIRONMENT){let c=Ur.join(e,t);await Is.mkdirp(s?c:e);let u=new ny(s?c:c+Dc,!1),_=Tm.open(u);_.dbis=Object.create(null);let l=new gm(!1);_.openDB(ws,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=Am(e,t,r);return _[ti.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(E$,"createEnvironment");async function h$(e,t,r,s=!0){T_(e,t),t=t.toString();let n=Ur.join(e,t);return u$({table:t,database:Ur.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(h$,"copyEnvironment");async function oy(e,t,r=!1){T_(e,t),t=t.toString();let s=Am(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await Rm(e,t),i=Ur.join(e,t+Dc),o=n!=i,c=new ny(n,o),u=Tm.open(c);u.dbis=Object.create(null);let _=cy(u);for(let l=0;l<_.length;l++)is(u,_[l]);return u[ti.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(oy,"openEnvironment");async function m$(e,t,r=!1){T_(e,t),t=t.toString();let s=Ur.join(e,t+Dc),n=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 ay(o),delete global.lmdb_map[i]}}await Is.remove(n),await Is.remove(n===s?n+f$:Ur.join(Ur.dirname(n),d$))}a(m$,"deleteEnvironment");async function ay(e){p_.validateEnv(e);let t=e[ti.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(ay,"closeEnvironment");function Am(e,t,r=!1){let n=`${Ur.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(Am,"getCachedEnvironmentName");function p$(e){p_.validateEnv(e);let t=Object.create(null),r=is(e,ws);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==ws)try{t[s]=Object.assign(new S_,n)}catch{sy.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(p$,"listDBIDefinitions");function cy(e){p_.validateEnv(e);let t=[],r=is(e,ws);for(let{key:s}of r.getRange({start:!1}))s!==ws&&t.push(s);return t}a(cy,"listDBIs");function S$(e,t){let s=is(e,ws).getEntry(t),n=new S_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{sy.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(S$,"getDBIDefinition");function uy(e,t,r,s=!r){if(g_(e,t),t=t.toString(),t===ws)throw new Error(ar.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return is(e,t)}catch(n){if(n.message===ar.DBI_DOES_NOT_EXIST){let i=new gm(r,s===!0),o=e.openDB(t,i),c=new S_(r===!0,s);return o[iy]=c,is(e,ws).putSync(t,c),e.dbis[t]=o,o}throw n}}a(uy,"createDBI");function is(e,t){if(g_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==ws?r=S$(e,t):r=new S_,r===void 0)throw new Error(ar.DBI_DOES_NOT_EXIST);let s;try{let n=new gm(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(ar.DBI_DOES_NOT_EXIST):n}return s[iy]=r,e.dbis[t]=s,s}a(is,"openDBI");function T$(e,t){g_(e,t),t=t.toString();let r=is(e,t),s=r.getStats();return r[ti.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(T$,"statDBI");async function g$(e,t){try{let r=Ur.join(e,t+Dc);return(await Is.stat(r)).size}catch{throw new Error(ar.INVALID_ENVIRONMENT)}}a(g$,"environmentDataSize");function R$(e,t){if(g_(e,t),t=t.toString(),t===ws)throw new Error(ar.CANNOT_DROP_INTERNAL_DBIS_NAME);is(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],is(e,ws).removeSync(t)}a(R$,"dropDBI");function A$(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{is(e,i)}catch(o){if(o.message===ar.DBI_DOES_NOT_EXIST)uy(e,i,i!==t,i===t),s=!0;else throw o}}s&&l$()}a(A$,"initializeDBIs");ly.exports={openDBI:is,openEnvironment:oy,createEnvironment:E$,listDBIs:cy,listDBIDefinitions:p$,createDBI:uy,dropDBI:R$,statDBI:T$,deleteEnvironment:m$,initializeDBIs:A$,TransactionCursor:Sm,environmentDataSize:g$,copyEnvironment:h$,closeEnvironment:ay}});var dy=g((Hce,_y)=>{"use strict";var Om=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};_y.exports=Om});var Ey=g((Gce,fy)=>{"use strict";var bm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};fy.exports=bm});var my=g((Fce,hy)=>{"use strict";var ym=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};hy.exports=ym});var $o=g((Kce,Ty)=>{"use strict";var O$=We(),b$=dy(),y$=Ey(),N$=my(),Qs=Dr(),Lc=Cr().LMDB_ERRORS_ENUM,I$=ut(),Tn=L(),w$=Q(),C$=require("uuid"),Vce=require("lmdb"),{handleHDBError:D$,hdb_errors:L$}=se(),{OVERFLOW_MARKER:$ce,MAX_SEARCH_KEY_LENGTH:Yce}=I$,py=ee();py.initSync();var R_=py.get(Tn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Nm=Tn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Fi=Tn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function M$(e,t,r,s,n=Qs.getNextMonotonicTime()){Dm(e,t,r,s),Im(e,t,r);let i=new b$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];Sy(_,!0,n);let l=U$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return wm(o,c,s,i,n)}a(M$,"insertRecords");function U$(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Tn.FUNC_VAL],s[o]=c)}let u=Qs.getIndexedValues(c),_=e.dbis[o];if(u){R_&&_.prefetch(u.map(l=>({key:l,value:n})),A_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],n)}}R_&&e.dbis[t].prefetch([n],A_),e.dbis[t].put(n,s,s[Fi])})}a(U$,"insertRecord");function P$(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(P$,"removeSkippedRecords");function Sy(e,t,r){let s=r>0;(s||!Number.isInteger(e[Fi]))&&(e[Fi]=r||(r=Qs.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[Nm]))&&(e[Nm]=r||Qs.getNextMonotonicTime()):delete e[Nm]}a(Sy,"setTimestamps");function Im(e,t,r){r.indexOf(Tn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Tn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Tn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Tn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),O$.initializeDBIs(e,t,r)}a(Im,"initializeTransaction");async function v$(e,t,r,s,n=Qs.getNextMonotonicTime()){Dm(e,t,r,s),Im(e,t,r);let i=new y$,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=Cm(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return wm(c,u,s,i,n,o)}a(v$,"updateRecords");async function B$(e,t,r,s,n=Qs.getNextMonotonicTime()){try{Dm(e,t,r,s)}catch(u){throw D$(u,u.message,L$.HTTP_STATUS_CODES.BAD_REQUEST)}Im(e,t,r);let i=new N$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;w$.isEmpty(_[t])?(l=C$.v4(),_[t]=l):l=_[t];let d=Cm(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return wm(o,c,s,i,n)}a(B$,"upsertRecords");async function wm(e,t,r,s,n,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||Qs.getNextMonotonicTime(),P$(r,i),s}a(wm,"finalizeWrite");function Cm(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Sy(r,!l,o),Number.isInteger(r[Fi])&&_[Fi]>r[Fi])return!1;l&&n.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let T=_[h];if(typeof p=="function"){let R=p([[_]]);Array.isArray(R)&&(p=R[0][Tn.FUNC_VAL],r[h]=p)}if(p===T)continue;let A=Qs.getIndexedValues(T);if(A){R_&&S.prefetch(A.map(R=>({key:R,value:s})),A_);for(let R=0,M=A.length;R<M;R++)S.remove(A[R],s)}if(A=Qs.getIndexedValues(p),A){R_&&S.prefetch(A.map(R=>({key:R,value:s})),A_);for(let R=0,M=A.length;R<M;R++)S.put(A[R],s)}}let E=Object.assign({},_,r);c.put(s,E,E[Fi])},"do_put");return u?d=c.ifVersion(s,u.version,f):d=c.ifNoExists(s,f),d.then(E=>E?!0:Cm(e,t,r,s,n,i,o))}a(Cm,"updateUpsertRecord");function H$(e,t,r){if(Qs.validateEnv(e),t===void 0)throw new Error(Lc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Lc.WRITE_ATTRIBUTES_REQUIRED):new Error(Lc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(H$,"validateBasic");function Dm(e,t,r,s){if(H$(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Lc.RECORDS_REQUIRED):new Error(Lc.RECORDS_MUST_BE_ARRAY)}a(Dm,"validateWrite");function A_(){}a(A_,"noop");Ty.exports={insertRecords:M$,updateRecords:v$,upsertRecords:B$}});var ki=g((Qce,x$)=>{x$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},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 Js=g((zce,Ay)=>{"use strict";var Ry=Q(),gy=L(),Yo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,zs=require("joi"),ri={schema_format:{pattern:Yo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},G$=zs.alternatives(zs.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),zs.number(),zs.array()).required(),q$=zs.alternatives(zs.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),zs.number()),F$=zs.alternatives(zs.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),zs.number()).required();function k$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ri.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(k$,"checkValidTable");function V$(e,t){return Ry.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(V$,"validateSchemaExists");function $$(e,t){let r=t.state.ancestors[0].schema;return Ry.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a($$,"validateTableExists");function Y$(e,t){return e.toLowerCase()===gy.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${gy.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(Y$,"validateSchemaName");Ay.exports={common_validators:ri,schema_regex:Yo,hdb_schema_table:G$,validateSchemaExists:V$,validateTableExists:$$,validateSchemaName:Y$,checkValidTable:k$,hdb_database:q$,hdb_table:F$}});var Xe=g((Xce,Oy)=>{"use strict";var cr=require("validate.js");cr.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||cr.validators.type.checks[t](e)?null:` must be a '${t}' value`};cr.validators.type.checks={Object:function(e){return cr.isObject(e)&&!cr.isArray(e)},Array:cr.isArray,Integer:cr.isInteger,Number:cr.isNumber,String:cr.isString,Date:cr.isDate,Boolean:function(e){return typeof e=="boolean"}};cr.validators.hasValidFileExt=function(e,t){return cr.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};Oy.exports={validateObject:K$,validateObjectAsync:W$,validateBySchema:Q$};function K$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=cr(e,t,{format:"flat"});return r?new Error(r):null}a(K$,"validateObject");async function W$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await cr.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(W$,"validateObjectAsync");function Q$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(Q$,"validateBySchema")});var O_=g((Zce,by)=>{var{common_validators:Xs}=Js(),Uc=Xe(),Mc="is required",mt={database:{presence:!1,format:Xs.schema_format,length:Xs.schema_length},schema:{presence:!1,format:Xs.schema_format,length:Xs.schema_length},table:{presence:!0,format:Xs.schema_format,length:Xs.schema_length},attribute:{presence:!0,format:Xs.schema_format,length:Xs.schema_length},hash_attribute:{presence:!0,format:Xs.schema_format,length:Xs.schema_length}};function Pc(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(Pc,"makeAttributesStrings");function z$(e){return e=Pc(e),mt.table.presence=!1,mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(z$,"schema_object");function J$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(J$,"table_object");function X$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence=!1,Uc.validateObject(e,mt)}a(X$,"create_table_object");function j$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence={message:Mc},mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(j$,"attribute_object");function Z$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(Z$,"describe_table");function e1(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(e1,"validateTableResidence");by.exports={schema_object:z$,create_table_object:X$,table_object:J$,attribute_object:j$,describe_table:Z$,validateTableResidence:e1}});var Ny=g((tue,yy)=>{"use strict";var t1=require("uuid"),Lm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||t1.v4(),this.schema_table=`${this.schema}.${this.table}`}};yy.exports=Lm});var b_=g((sue,Iy)=>{"use strict";var r1=Ny(),Mm=class extends r1{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};Iy.exports=Mm});var Cy=g((iue,wy)=>{"use strict";wy.exports=n1;var s1="inserted";function n1(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===s1?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(n1,"returnObject")});var y_=g((aue,Py)=>{"use strict";var i1=L(),Um=We(),o1=$o(),{getSystemSchemaPath:a1,getSchemaPath:c1}=Je(),u1=ki(),l1=O_(),_1=b_(),d1=Cy(),{handleHDBError:Dy,hdb_errors:My}=se(),Ly=Q(),{HTTP_STATUS_CODES:f1}=My,Pm=u1.hdb_attribute,Uy=[];for(let e=0;e<Pm.attributes.length;e++)Uy.push(Pm.attributes[e].attribute);var E1="inserted";Py.exports=h1;async function h1(e){let t=l1.attribute_object(e);if(t)throw Dy(new Error,t.message,My.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&Ly.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Dy(new Error,r,f1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Ly.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new _1(e.schema,e.table,e.attribute,e.id);try{let i=await Um.openEnvironment(c1(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(a1(),i1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await o1.insertRecords(o,Pm.hash_attribute,Uy,[n]);return d1(E1,c,{records:[n]},u)}catch(i){throw i}}a(h1,"lmdbCreateAttribute")});var Bm=g((uue,By)=>{var{hdb_table:m1,hdb_database:vy}=Js(),p1=Xe(),vm=require("joi"),S1={undefined:"undefined",null:"null"},T1=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||S1[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),g1=vm.object({database:vy,schema:vy,table:m1,records:vm.array().items(vm.object().custom(T1)).required()});By.exports=function(e){return p1.validateBySchema(e,g1)}});var vc=g((due,xy)=>{"use strict";var gn=Q(),Hy=$(),_ue=Bm(),{getDatabases:R1}=(Re(),ie(Fe)),{ClientError:Vi}=se();xy.exports=A1;function A1(e){if(gn.isEmpty(e))throw new Vi("invalid update parameters defined.");if(gn.isEmptyOrZeroLength(e.schema))throw new Vi("invalid schema specified.");if(gn.isEmptyOrZeroLength(e.table))throw new Vi("invalid table specified.");if(!Array.isArray(e.records))throw new Vi("records must be an array");let t=R1()[e.schema]?.[e.table];if(gn.isEmpty(t))throw new Vi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&gn.isEmptyOrZeroLength(o[r]))throw Hy.error("a valid hash attribute must be provided with update record:",o),new Vi("a valid hash attribute must be provided with update record, check log for more info");if(!gn.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw Hy.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Vi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gn.isEmpty(o[r])&&o[r]!==""&&s.has(gn.autoCast(o[r]))&&(o.skip=!0),s.add(gn.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(A1,"insertUpdateValidate")});var Bc=g((Eue,Gy)=>{"use strict";var O1=L().OPERATIONS_ENUM,Hm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=O1.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};Gy.exports=Hm});var Hc=g((pue,Fy)=>{"use strict";var mue=Bc(),N_=L(),xm=Q(),qy=$(),b1=require("uuid"),{handleHDBError:I_,hdb_errors:y1}=se(),{HDB_ERROR_MSGS:w_,HTTP_STATUS_CODES:C_}=y1;Fy.exports=N1;function N1(e,t,r){for(let n=0;n<t.length;n++)I1(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];w1(i,r,e.operation)}}a(N1,"processRows");function I1(e){if(Buffer.byteLength(String(e))>N_.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(I1,"validateAttribute");function w1(e,t,r){if(!e.hasOwnProperty(t)||xm.isEmptyOrZeroLength(e[t])){if(r===N_.OPERATIONS_ENUM.INSERT||r===N_.OPERATIONS_ENUM.UPSERT){e[t]=b1.v4();return}throw qy.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]))>N_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw qy.error(e),I_(new Error,w_.HASH_VAL_LENGTH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}a(w1,"validateHash")});var Vy=g((Tue,ky)=>{"use strict";var Gm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};ky.exports=Gm});var Ky=g((Rue,Yy)=>{"use strict";var qm=We(),C1=$(),$y=Cr().LMDB_ERRORS_ENUM;Yy.exports=D1;async function D1(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!==$y.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await qm.closeEnvironment(global.lmdb_map[s]),await qm.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==$y.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){C1.error(t)}}a(D1,"cleanLMDBMap")});var Rn=g((Oue,Jy)=>{"use strict";var xc=require("crypto"),L1=ee(),{CONFIG_PARAMS:M1}=L(),Qy="aes-256-cbc",U1=32,P1=16,Fm=64,zy=32,v1=Fm+zy,Wy=new Map;Jy.exports={encrypt:B1,decrypt:H1,createNatsTableStreamName:x1};function B1(e){let t=xc.randomBytes(U1),r=xc.randomBytes(P1),s=xc.createCipheriv(Qy,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(B1,"encrypt");function H1(e){let t=e.substr(0,Fm),r=e.substr(Fm,zy),s=e.substr(v1,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=xc.createDecipheriv(Qy,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(H1,"decrypt");function x1(e,t){let r=L1.get(M1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=Wy.get(r);return s||(s=xc.createHash("md5").update(r).digest("hex"),Wy.set(r,s)),s}a(x1,"createNatsTableStreamName")});var An=g((Nue,jy)=>{"use strict";var yue=Pr(),D_=$(),Xy=O_(),G1=Rn(),L_=Q(),{handleHDBError:M_,hdb_errors:q1}=se(),{HDB_ERROR_MSGS:U_,HTTP_STATUS_CODES:km}=q1,F1=ee();F1.initSync();var{getDatabases:Vm}=(Re(),ie(Fe));jy.exports={describeAll:k1,describeTable:P_,describeSchema:V1};async function k1(e){try{let t=L_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=Vm(),i={},o={},c=[],u=e?.exact_count;for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let d=n[l];for(let f in d)try{let E;if(t||s)E=await 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||s?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return D_.error("Got an error in describeAll"),D_.error(t),M_(new Error,U_.DESCRIBE_ALL_ERR)}}a(k1,"describeAll");async function P_(e,t){L_.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=Xy.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[s];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(n){let f={};n.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=G1.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 V1(e){L_.transformReq(e);let t=Xy.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=Vm()[s];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(V1,"describeSchema")});var On=g((Due,sN)=>{var $1=ki(),{callbackify:eN,promisify:Y1}=require("util"),{getDatabases:tN}=(Re(),ie(Fe));sN.exports={setSchemaDataToGlobal:Zy,getTableSchema:K1,getSystemSchema:W1,setSchemaDataToGlobalAsync:Y1(Zy)};var rN=An(),wue=eN(rN.describeAll),Cue=eN(rN.describeTable);function Zy(e){global.hdb_schema=tN(),e&&e()}a(Zy,"setSchemaDataToGlobal");function K1(e,t,r){let s=tN()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}a(K1,"getTableSchema");function W1(){return $1}a(W1,"getSystemSchema")});var vr=g((Mue,aN)=>{"use strict";var B_=Bm(),kt=Q(),Q1=require("util"),H_=Cs(),z1=On(),nN=$(),{handleHDBError:$i,hdb_errors:J1}=se(),{HTTP_STATUS_CODES:Yi}=J1,X1=Q1.promisify(z1.getTableSchema),j1="updated",iN="inserted",oN="upserted";aN.exports={insert:eY,update:tY,upsert:rY,validation:Z1,flush:sY};async function Z1(e){if(kt.isEmpty(e))throw new Error("invalid update parameters defined.");if(kt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(kt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await X1(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 s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&kt.isEmptyOrZeroLength(c[s]))throw nN.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(!kt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw nN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!kt.isEmpty(c[s])&&c[s]!==""&&n.has(kt.autoCast(c[s]))&&(c.skip=!0),n.add(kt.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(Z1,"validation");async function eY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=B_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let s=await H_.createRecords(e);return v_(iN,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(eY,"insertData");async function tY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=B_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let s=await H_.updateRecords(e);return kt.isEmpty(s.existing_rows)?v_(j1,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):v_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(tY,"updateData");async function rY(e){if(e.operation!=="upsert")throw $i(new Error,"invalid operation, must be upsert",Yi.INTERNAL_SERVER_ERROR);let t=B_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let s=await H_.upsertRecords(e);return v_(oN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(rY,"upsertData");function v_(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===iN?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===oN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(v_,"returnObject");function sY(e){return kt.transformReq(e),H_.flush(e.schema,e.table)}a(sY,"flush")});var Ym=g((Pue,lN)=>{var nY=Xe(),$m=require("joi"),{hdb_table:iY,hdb_database:cN}=Js(),uN={schema:cN,database:cN,table:iY},oY={date:$m.date().iso().required()},aY={timestamp:$m.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};lN.exports=function(e,t){let r=t==="timestamp"?{...uN,...aY}:{...uN,...oY},s=$m.object(r);return nY.validateBySchema(e,s)}});var fN=g((vue,dN)=>{var cY=Xe(),Km=require("joi"),{hdb_table:uY,hdb_database:_N}=Js(),lY=Km.object({schema:_N,database:_N,table:uY,hash_values:Km.array().required(),ids:Km.array()});dN.exports=function(e){return cY.validateBySchema(e,lY)}});var hN=g((Bue,EN)=>{"use strict";var Wm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},Qm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}},zm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};EN.exports={InsertObject:Wm,NoSQLSeachObject:Qm,DeleteResponseObject:zm}});var ii=g((xue,gN)=>{"use strict";var pN=Ym(),_Y=fN(),Ki=Q(),mN=require("moment"),SN=$(),{promisify:dY,callbackify:fY}=require("util"),Wi=L(),EY=On(),Jm=dY(EY.getTableSchema),Xm=Cs(),{DeleteResponseObject:hY}=hN(),{handleHDBError:si,hdb_errors:mY}=se(),{HDB_ERROR_MSGS:x_,HTTP_STATUS_CODES:ni}=mY,pY="records successfully deleted",SY=fY(TN);gN.exports={delete:SY,deleteRecord:TN,deleteFilesBefore:TY,deleteAuditLogsBefore:gY};async function TY(e){let t=pN(e,"date");if(t)throw si(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),!mN(e.date,mN.ISO_8601).isValid())throw si(new Error,x_.INVALID_DATE,ni.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,x_.INVALID_DATE,!0);let s=Ki.checkSchemaTableExist(e.schema,e.table);if(s)throw si(new Error,s,ni.NOT_FOUND,Wi.LOG_LEVELS.ERROR,s,!0);let n=await Xm.deleteRecordsBefore(e);if(await Jm(e.schema,e.table),SN.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(TY,"deleteFilesBefore");async function gY(e){let t=pN(e,"timestamp");if(t)throw si(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),isNaN(e.timestamp))throw si(new Error,x_.INVALID_VALUE("Timestamp"),ni.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,x_.INVALID_VALUE("Timestamp"),!0);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ni.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);let s=await Xm.deleteAuditLogsBefore(e);return await Jm(e.schema,e.table),SN.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(gY,"deleteAuditLogsBefore");async function TN(e){e.ids&&(e.hash_values=e.ids);let t=_Y(e);if(t)throw si(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);Ki.transformReq(e);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ni.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);try{await Jm(e.schema,e.table);let s=await Xm.deleteRecords(e);return Ki.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${pY}`),s}catch(s){if(s.message===Wi.SEARCH_NOT_FOUND_MESSAGE){let n=new hY;return n.message=Wi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(TN,"deleteRecord")});var G_=g((que,ON)=>{var RY=require("crypto"),RN=9;function AY(e){let t=bY(RN),r=AN(e+t);return t+r}a(AY,"createHash");function OY(e,t){let r=e?.substr(0,RN),s=r+AN(t+r);return e===s}a(OY,"validateHash");function bY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(bY,"generateSalt");function AN(e){return RY.createHash("md5").update(e).digest("hex")}a(AN,"md5");ON.exports={hash:AY,validate:OY}});var yN=g((kue,bN)=>{var jm=Xe(),Qt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function yY(e){return Qt.password.presence=!0,Qt.username.presence=!0,Qt.role.presence=!0,Qt.active.presence=!0,jm.validateObject(e,Qt)}a(yY,"addUserValidation");function NY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,jm.validateObject(e,Qt)}a(NY,"alterUserValidation");function IY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,jm.validateObject(e,Qt)}a(IY,"dropUserValidation");bN.exports={addUserValidation:yY,alterUserValidation:NY,dropUserValidation:IY}});var ke=g((Yue,IN)=>{"use strict";var{platform:$ue}=require("os"),wY="nats-server.zip",Zm="nats-server",CY=process.platform==="win32"?`${Zm}.exe`:Zm,DY=/^[^\s.,*>]+$/,NN="__request__",LY=a(e=>`${e}.${NN}`,"REQUEST_SUBJECT"),MY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},UY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},PY={HUB:"hub.pid",LEAF:"leaf.pid"},vY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},BY={SUCCESS:"success",ERROR:"error"},HY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},xY={TXN:"txn",MSGID:"msgid"},Ko={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},GY={[Ko.ERR]:1,[Ko.WRN]:2,[Ko.INF]:3,[Ko.DBG]:4,[Ko.TRC]:5},qY={debug:"-D",trace:"-DVV"};IN.exports={NATS_SERVER_ZIP:wY,NATS_SERVER_NAME:Zm,NATS_BINARY_NAME:CY,PID_FILES:PY,NATS_CONFIG_FILES:UY,SERVER_SUFFIX:vY,NATS_TERM_CONSTRAINTS_RX:DY,REQUEST_SUFFIX:NN,UPDATE_REMOTE_RESPONSE_STATUSES:BY,CLUSTER_STATUS_STATUSES:HY,REQUEST_SUBJECT:LY,SUBJECT_PREFIXES:xY,MSG_HEADERS:MY,LOG_LEVELS:Ko,LOG_LEVEL_FLAGS:qY,LOG_LEVEL_HIERARCHY:GY}});var CN=g((Wue,wN)=>{"use strict";var FY={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 Sq=Object.create;var ac=Object.defineProperty;var Tq=Object.getOwnPropertyDescriptor;var gq=Object.getOwnPropertyNames;var Rq=Object.getPrototypeOf,Aq=Object.prototype.hasOwnProperty;var a=(e,t)=>ac(e,"name",{value:t,configurable:!0});var ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qe=(e,t)=>{for(var r in t)ac(e,r,{get:t[r],enumerable:!0})},lO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of gq(t))!Aq.call(e,s)&&s!==r&&ac(e,s,{get:()=>t[s],enumerable:!(n=Tq(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Sq(Rq(e)):{},lO(t||!e||!e.__esModule?ac(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>lO(ac({},"__esModule",{value:!0}),e);var fO=g((Vae,dO)=>{var Oq=require("fast-glob"),{statSync:wh,existsSync:Ch,readFileSync:bq,writeFileSync:yq}=require("fs"),{spawnSync:Nq,spawn:Iq,execFileSync:kae}=require("child_process"),{isMainThread:wq}=require("worker_threads"),{join:js,relative:_O}=require("path"),{PACKAGE_ROOT:bn}=L(),{tmpdir:Cq,platform:Dq}=require("os");require("source-map-support").install();var Lq=["resources","server","dataLayer","components"],cc="ts-build",Dh,Mq=__filename.endsWith("tsBuild.js");if(Mq){if(wq){let r;try{wh(js(bn,cc)),r=!0}catch{}if(r)for(let n of Oq.sync(Lq.map(s=>s+"/**/*.ts"),{cwd:bn})){let s=0,i=0;try{s=wh(js(bn,n)).mtimeMs-5e3,i=wh(js(bn,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=js(bn,"node_modules/.bin/tsc");Dq()==="win32"&&(n+=".cmd");let s=Nq(n,{cwd:bn});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=js(Cq(),"harperdb-tsc.pid"),o;if(Ch(i))try{process.kill(+bq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Iq(n,["--watch"],{cwd:bn,detached:!0,stdio:"ignore"});yq(i,c.pid.toString()),c.unref()}}}}let e=dO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(bn)&&!n[0].includes("node_modules")){let i=_O(bn,n[0]),o;i.startsWith(cc)?o=js(bn,_O(cc,i)):o=js(bn,cc,i);let c=js(o,r),u=c+".js";if(Ch(u))return u;if(c.includes(".")&&Ch(c))return c}return t(r,n,s)}}});var L=g((Kae,IO)=>{"use strict";var nn=require("path"),Uq=require("fs"),{relative:$ae,join:Yae}=nn,{existsSync:Pq}=Uq;function vq(){let e=__dirname;for(;!Pq(nn.join(e,"package.json"));){let t=nn.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(vq,"getHDBPackageRoot");var Xs=vq(),EO="js",e_=EO,Bq="harperdb-config.yaml",Hq="defaultConfig.yaml",xq="hdb",hO=`harperdb.${e_}`,mO=`customFunctionsServer.${e_}`,Gq=`restartHdb.${e_}`,Mh="HarperDB",Zl="Custom Functions",t_="Clustering Hub",r_="Clustering Leaf",qq="Clustering Ingest Service",Fq="Clustering Reply Service",kq="foreground.pid",Vq="hdb.pid",$q="data",Yq={HDB:Mh,CLUSTERING_HUB:t_,CLUSTERING_LEAF:r_,CLUSTERING_INGEST_SERVICE:qq,CLUSTERING_REPLY_SERVICE:Fq,CUSTOM_FUNCTIONS:Zl,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},Kq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Wq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Qq={harperdb:Mh,"clustering hub":t_,"clustering leaf":r_,"custom functions":Zl,custom_functions:Zl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},zq={CLUSTERING_HUB_PROC_DESCRIPTOR:t_,CLUSTERING_LEAF_PROC_DESCRIPTOR:r_},Lh={HDB:nn.join(Xs,"server/harperdb"),CUSTOM_FUNCTIONS:nn.join(Xs,"server/customFunctions"),CLUSTERING_HUB:nn.join(Xs,"server/nats"),CLUSTERING_LEAF:nn.join(Xs,"server/nats")},Jq={HDB:nn.join(Lh.HDB,hO),CUSTOM_FUNCTIONS:nn.join(Lh.CUSTOM_FUNCTIONS,mO)},jq={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:nn.join(Xs,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:nn.join(Xs,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:nn.join(Xs,"launchServiceScripts/launchUpdateNodes4-0-0.js")},Xq={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},pO="support@harperdb.io",Zq="customer-success@harperdb.io",SO=1,eF=4141,TO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",tF="https://www.harperdb.io/product",rF=`For support, please submit a request at ${TO} or contact ${pO}`,gO=`For license support, please contact ${Zq}`,nF="None of the specified records were found.",sF="hash attribute not found",iF=`Your current license only supports ${SO} role. ${gO}`,oF="Your current license only supports 3 connections to a node.",aF="127.0.0.1",cF=1,uF=/^\.$/,lF=/^\.\.$/,_F="U+002E",dF=/\//g,fF="U+002F",EF=/U\+002F/g,hF=/^U\+002E$/,mF=/^U\+002EU\+002E$/,pF="d",SF=999999,TF="*",gF="--max-old-space-size=",RF="system",AF="__hdb_hash",OF=".harperdb",bF=".hdb",yF="keys",NF="hdb_boot_properties.file",IF=".updateConfig.json",wF="SIGTSTP",CF=24,DF=6e4,LF=448,MF="blob",UF="trash",PF="database",vF="schema",BF="transactions",HF=".count",xF="id",GF="PROCESS_NAME",RO={SETTINGS_PATH_KEY:"settings_path"},AO=require("lodash"),qF={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"},FF={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},kF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},VF={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"},$F={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"},wr="hdb_internal:",YF={CREATE_SCHEMA:wr+"create_schema",CREATE_TABLE:wr+"create_table",CREATE_ATTRIBUTE:wr+"create_attribute",ADD_USER:wr+"add_user",ALTER_USER:wr+"alter_user",DROP_USER:wr+"drop_user",HDB_NODES:wr+"hdb_nodes",HDB_USERS:wr+"hdb_users",HDB_WORKERS:wr+"hdb_workers",CATCHUP:wr+"catchup",SCHEMA_CATCHUP:wr+"schema_catchup",WORKER_ROOM:wr+"cluster_workers"},KF={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"},WF="060493.ks",QF=".license",zF={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},Z={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},JF={CSV:".csv",JSON:".json"},jF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},XF={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},uc={};uc[Z.INSERT]=Z.INSERT;uc[Z.UPDATE]=Z.UPDATE;uc[Z.UPSERT]=Z.UPSERT;uc[Z.DELETE]=Z.DELETE;var xe=Object.create(null);xe[Z.DESCRIBE_ALL]=Z.DESCRIBE_ALL;xe[Z.DESCRIBE_TABLE]=Z.DESCRIBE_TABLE;xe[Z.DESCRIBE_SCHEMA]=Z.DESCRIBE_SCHEMA;xe[Z.READ_LOG]=Z.READ_LOG;xe[Z.ADD_NODE]=Z.ADD_NODE;xe[Z.LIST_USERS]=Z.LIST_USERS;xe[Z.LIST_ROLES]=Z.LIST_ROLES;xe[Z.USER_INFO]=Z.USER_INFO;xe[Z.SQL]=Z.SQL;xe[Z.GET_JOB]=Z.GET_JOB;xe[Z.SEARCH_JOBS_BY_START_DATE]=Z.SEARCH_JOBS_BY_START_DATE;xe[Z.DELETE_FILES_BEFORE]=Z.DELETE_FILES_BEFORE;xe[Z.EXPORT_LOCAL]=Z.EXPORT_LOCAL;xe[Z.EXPORT_TO_S3]=Z.EXPORT_TO_S3;xe[Z.CLUSTER_STATUS]=Z.CLUSTER_STATUS;xe[Z.REMOVE_NODE]=Z.REMOVE_NODE;xe[Z.RESTART]=Z.RESTART;xe[Z.CUSTOM_FUNCTIONS_STATUS]=Z.CUSTOM_FUNCTIONS_STATUS;xe[Z.GET_CUSTOM_FUNCTIONS]=Z.GET_CUSTOM_FUNCTIONS;xe[Z.GET_CUSTOM_FUNCTION]=Z.GET_CUSTOM_FUNCTION;xe[Z.SET_CUSTOM_FUNCTION]=Z.SET_CUSTOM_FUNCTION;xe[Z.DROP_CUSTOM_FUNCTION]=Z.DROP_CUSTOM_FUNCTION;xe[Z.ADD_CUSTOM_FUNCTION_PROJECT]=Z.ADD_CUSTOM_FUNCTION_PROJECT;xe[Z.DROP_CUSTOM_FUNCTION_PROJECT]=Z.DROP_CUSTOM_FUNCTION_PROJECT;xe[Z.PACKAGE_CUSTOM_FUNCTION_PROJECT]=Z.PACKAGE_CUSTOM_FUNCTION_PROJECT;xe[Z.DEPLOY_CUSTOM_FUNCTION_PROJECT]=Z.DEPLOY_CUSTOM_FUNCTION_PROJECT;var ZF={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"},ek={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},OO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},tk=AO.invert(OO),rk={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_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",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",CLONED:"cloned"},bO={settings_path:RO.SETTINGS_PATH_KEY,hdb_root_key:w.ROOTPATH,hdb_root:w.ROOTPATH,rootpath:w.ROOTPATH,server_port_key:w.OPERATIONSAPI_NETWORK_PORT,server_port:w.OPERATIONSAPI_NETWORK_PORT,cert_key:w.TLS_CERTIFICATE,certificate:w.TLS_CERTIFICATE,private_key_key:w.TLS_PRIVATEKEY,private_key:w.TLS_PRIVATEKEY,http_secure_enabled_key:w.OPERATIONSAPI_NETWORK_HTTPS,https_on:w.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:w.OPERATIONSAPI_NETWORK_CORS,cors_on:w.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:w.LOGGING_LEVEL,log_level:w.LOGGING_LEVEL,log_path_key:w.LOGGING_ROOT,log_path:w.LOGGING_ROOT,clustering_node_name_key:w.CLUSTERING_NODENAME,node_name:w.CLUSTERING_NODENAME,clustering_enabled_key:w.CLUSTERING_ENABLED,clustering:w.CLUSTERING_ENABLED,max_http_threads:w.THREADS_COUNT,max_hdb_processes:w.THREADS_COUNT,server_timeout_key:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:w.LOGGING_AUDITLOG,disable_transaction_log:w.LOGGING_AUDITLOG,operation_token_timeout_key:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:w.HTTP_PORT,custom_functions_port:w.HTTP_PORT,custom_functions_directory_key:w.COMPONENTSROOT,custom_functions_directory:w.COMPONENTSROOT,max_custom_function_processes:w.THREADS_COUNT,log_to_file:w.LOGGING_FILE,log_to_stdstreams:w.LOGGING_STDSTREAMS,local_studio_on:w.LOCALSTUDIO_ENABLED,clustering_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:w.CLUSTERING_USER,clustering_enabled:w.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:w.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:w.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:w.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:w.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:w.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:w.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:w.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:w.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:w.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:w.CLUSTERING_NODENAME,clustering_tls_certificate:w.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:w.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:w.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:w.CLUSTERING_TLS_INSECURE,clustering_tls_verify:w.CLUSTERING_TLS_VERIFY,clustering_loglevel:w.CLUSTERING_LOGLEVEL,clustering_republishmessages:w.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:w.CLUSTERING_DATABASELEVEL,customfunctions_network_port:w.HTTP_PORT,customfunctions_tls_certificate:w.TLS_CERTIFICATE,customfunctions_network_cors:w.HTTP_CORS,customfunctions_network_corsaccesslist:w.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:w.HTTP_HEADERSTIMEOUT,customfunctions_network_https:w.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:w.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:w.HTTP_TIMEOUT,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_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,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_certificate:w.TLS_CERTIFICATE,tls_privatekey:w.TLS_PRIVATEKEY,tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,tls_ciphers:w.TLS_CIPHERS};for(let e in w){let t=w[e];bO[t.toLowerCase()]=t}var nk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},sk={csv_file_load:"csv_file_load",csv_data_load:Z.CSV_DATA_LOAD,csv_url_load:Z.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"},ik={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"},ok={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},ak={VERSION_DEFAULT:"2.2.0"},ck={DEVELOPMENT:8192,DEFAULT:512},uk={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"},lk={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"},_k={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},yO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},dk=Symbol("metadata"),fk="__clustering__",Ek=Object.values(yO),hk=15984864e5,NO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},mk=AO.invert(NO),pk={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"},Sk=111,Tk=`\r
|
|
2
|
+
`,gk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Rk=["*","%"],Ak="unauthorized_access",Ok="func_val",bk={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},yk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Nk={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"},Ik={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},wk={HTTP:"http"},Ck={STOPPED:"stopped",ONLINE:"online"},Dk="3.x.x",Lk={SUCCESS:"success",FAILURE:"failure"},Mk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};IO.exports={LOCAL_HARPERDB_OPERATIONS:xe,HDB_SUPPORT_ADDRESS:pO,HDB_SUPPORT_URL:TO,HDB_PRICING_URL:tF,SUPPORT_HELP_MSG:rF,LICENSE_HELP_MSG:gO,HDB_PROC_NAME:hO,HDB_PROC_DESCRIPTOR:Mh,CLUSTERING_LEAF_PROC_DESCRIPTOR:r_,CLUSTERING_HUB_PROC_DESCRIPTOR:t_,SYSTEM_SCHEMA_NAME:RF,HASH_FOLDER_NAME:AF,HDB_HOME_DIR_NAME:OF,UPDATE_FILE_NAME:IF,LICENSE_KEY_DIR_NAME:yF,BOOT_PROPS_FILE_NAME:NF,JOB_TYPE_ENUM:sk,JOB_STATUS_ENUM:zF,SYSTEM_TABLE_NAMES:VF,SYSTEM_TABLE_HASH_ATTRIBUTES:$F,OPERATIONS_ENUM:Z,VALID_S3_FILE_TYPES:JF,S3_BUCKET_AUTH_KEYS:jF,VALID_SQL_OPS_ENUM:XF,GEO_CONVERSION_ENUM:ek,HDB_SETTINGS_NAMES:OO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:tk,SERVICE_ACTIONS_ENUM:ZF,CLUSTER_MESSAGE_TYPE_ENUM:ik,CLUSTER_CONNECTION_DIRECTION_ENUM:ok,CLUSTER_EVENTS_DEFS_ENUM:uk,PERIOD_REGEX:uF,DOUBLE_PERIOD_REGEX:lF,UNICODE_PERIOD:_F,FORWARD_SLASH_REGEX:dF,UNICODE_FORWARD_SLASH:fF,ESCAPED_FORWARD_SLASH_REGEX:EF,ESCAPED_PERIOD_REGEX:hF,ESCAPED_DOUBLE_PERIOD_REGEX:mF,REG_KEY_FILE_NAME:WF,RESTART_TIMEOUT_MS:DF,HDB_FILE_PERMISSIONS:LF,DATABASES_DIR_NAME:PF,LEGACY_DATABASES_DIR_NAME:vF,TRANSACTIONS_DIR_NAME:BF,LIMIT_COUNT_NAME:HF,ID_ATTRIBUTE_STRING:xF,INSERT_MODULE_ENUM:FF,UPGRADE_JSON_FIELD_NAMES_ENUM:kF,RESTART_CODE:wF,RESTART_CODE_NUM:CF,CLUSTER_OPERATIONS:uc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:KF,HDB_INTERNAL_SC_CHANNEL_PREFIX:wr,INTERNAL_SC_CHANNELS:YF,CLUSTERING_MESSAGE_TYPES:pk,HDB_FILE_SUFFIX:bF,BLOB_FOLDER_NAME:MF,HDB_TRASH_DIR:UF,ORIGINATOR_SET_VALUE:Sk,LICENSE_VALUES:ak,RAM_ALLOCATION_ENUM:ck,TIME_STAMP_NAMES_ENUM:yO,TIME_STAMP_NAMES:Ek,PERMS_UPDATE_RELEASE_TIMESTAMP:hk,SEARCH_NOT_FOUND_MESSAGE:nF,SEARCH_ATTRIBUTE_NOT_FOUND:sF,LICENSE_ROLE_DENIED_RESPONSE:iF,LICENSE_MAX_CONNS_REACHED:oF,BASIC_LICENSE_MAX_NON_CU_ROLES:SO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:eF,VALUE_SEARCH_COMPARATORS:NO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:mk,LICENSE_FILE_NAME:QF,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:lk,NEW_LINE:Tk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:cF,MOMENT_DAYS_TAG:pF,API_TURNOVER_SEC:SF,LOOPBACK:aF,CODE_EXTENSION:e_,WILDCARD_SEARCH_VALUE:TF,NODE_ERROR_CODES:_k,JAVASCRIPT_EXTENSION:EO,PERMS_CRUD_ENUM:gk,UNAUTHORIZED_PERMISSION_NAME:Ak,SEARCH_WILDCARDS:Rk,FUNC_VAL:Ok,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:bk,JWT_ENUM:yk,CLUSTERING_FLAG:fk,ITC_EVENT_TYPES:Nk,CUSTOM_FUNCTION_PROC_NAME:mO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Zl,SERVICES:Ik,THREAD_TYPES:wk,MEM_SETTING_KEY:gF,HDB_RESTART_SCRIPT:Gq,PROCESS_DESCRIPTORS:Yq,SERVICE_SERVERS:Jq,SERVICE_SERVERS_CWD:Lh,PROCESS_DESCRIPTORS_VALIDATE:Qq,LAUNCH_SERVICE_SCRIPTS:jq,LOG_LEVELS:Wq,PROCESS_NAME_ENV_PROP:GF,LOG_NAMES:Kq,PM2_PROCESS_STATUSES:Ck,CONFIG_PARAM_MAP:bO,CONFIG_PARAMS:w,HDB_CONFIG_FILE:Bq,HDB_DEFAULT_CONFIG_FILE:Hq,ROLE_TYPES_ENUM:Xq,BOOT_PROP_PARAMS:RO,INSTALL_PROMPTS:qF,HDB_ROOT_DIR_NAME:xq,CLUSTERING_PROCESSES:zq,FOREGROUND_PID_FILE:kq,PACKAGE_ROOT:Xs,PRE_4_0_0_VERSION:Dk,DATABASES_PARAM_CONFIG:nk,METADATA_PROPERTY:dk,AUTH_AUDIT_STATUS:Lk,AUTH_AUDIT_TYPES:Mk,HDB_PID_FILE:Vq,DEFAULT_DATABASE_NAME:$q,LEGACY_CONFIG_PARAMS:rk};fO()});var Uh=g((Qae,DO)=>{"use strict";var wO=require("minimist");DO.exports=Uk;function Uk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=CO(process.env),n=CO(wO(process.argv))):(r=process.env,n=wO(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(Uk,"assignCMDENVVariables");function CO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(CO,"objKeysToLowerCase")});var $=g((Jae,qh)=>{"use strict";var Bi=require("fs-extra"),{workerData:Pk,threadId:vk}=require("worker_threads"),ps=require("path"),UO=require("yaml"),PO=require("properties-reader"),mt=L(),LO=Uh(),Bk=require("os"),{PACKAGE_ROOT:vh}=L(),{_assignPackageExport:Hk}=require("../index"),_c={};for(let e in console)_c[e]||(_c[e]=console[e]);var sr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},vO={STDOUT:"stdOut",STDERR:"stdErr"},xk=ps.join(vh,"logs"),Gk=ps.join(vh,"config/yaml/",mt.HDB_DEFAULT_CONFIG_FILE),qk=1e4,ms,Kn,nr,n_,s_,dc,Fo,lc;lc===void 0&&BO();qh.exports={notify:GO,fatal:qO,error:fc,warn:Gh,info:i_,debug:xh,trace:Hh,setLogLevel:Wk,log_level:nr,loggerWithTag:Fk,suppressLogging:kk,initLogSettings:BO,setupConsoleLogging:HO,logCustomLevel:Yk,closeLogFile:Bh,getLogFilePath:()=>dc,OUTPUTS:vO,AuthAuditLog:Jk};Hk("logger",qh.exports);function BO(e=!1){try{if(lc===void 0||e){Bh();let t=Kk(),r=LO(["ROOTPATH"]);try{lc=PO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Bi.pathExistsSync(ps.join(r.ROOTPATH,mt.HDB_CONFIG_FILE)))throw n}({level:nr,config_log_path:s_,to_file:ms,to_stream:Kn}=Qk(r.ROOTPATH?ps.join(r.ROOTPATH,mt.HDB_CONFIG_FILE):lc.get("settings_path"))),n_=mt.LOG_NAMES.HDB,dc=ps.join(s_,n_)}}catch(t){if(lc=void 0,t.code===mt.NODE_ERROR_CODES.ENOENT||t.code===mt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=LO(Object.keys(mt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=mt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===mt.CONFIG_PARAMS.LOGGING_LEVEL){nr=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}=zk();ms=ms===void 0?s:ms,ms=MO(ms),Kn=Kn===void 0?i:Kn,Kn=MO(Kn),nr=nr===void 0?n:nr,s_=xk,n_=mt.LOG_NAMES.INSTALL,dc=ps.join(s_,n_);return}throw fc("Error initializing log settings"),fc(t),t}process.env.DEV_MODE&&(Kn=!0),HO()}a(BO,"initLogSettings");var Ph=!0;function HO(){qo("error",fc),qo("warn",Gh),qo("log",i_),qo("info",i_),qo("debug",xh),qo("trace",Hh)}a(HO,"setupConsoleLogging");function qo(e,t){console[e]=function(...r){if(Ph&&t(...r),!/PM2 log:|App \[/.test(r[0]))return _c[e](...r)}}a(qo,"logConsole");function Fk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(GO),fatal:r(qO),error:r(fc),warn:r(Gh),info:r(i_),debug:r(xh),trace:r(Hh)};function r(n){return function(...s){return n(t,...s)}}}a(Fk,"loggerWithTag");function kk(e){try{Ph=!1,e()}finally{Ph=!0}}a(kk,"suppressLogging");var Vk=Pk?.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||Vk+"/"+vk);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
3
|
+
`}a(Ss,"createLogRecord");function Ec(e){ms&&xO(e),Kn&&process.stdout.write(e)}a(Ec,"logStdOut");function o_(e){ms&&xO(e),Kn&&process.stderr.write(e)}a(o_,"logStdErr");function xO(e){$k(),Fo?Bi.appendFileSync(Fo,e):_c.log(e)}a(xO,"logToFile");function Bh(){try{Bi.closeSync(Fo)}catch{}Fo=null}a(Bh,"closeLogFile");function $k(){if(!Fo){try{if(!dc)debugger;Fo=Bi.openSync(dc,"a")}catch(e){_c.error(e)}setTimeout(()=>{Bh()},qk).unref()}}a($k,"openLogFile");function i_(...e){sr[nr]<=sr.info&&Ec(Ss("info",e))}a(i_,"info");function Hh(...e){sr[nr]<=sr.trace&&Ec(Ss("trace",e))}a(Hh,"trace");function fc(...e){sr[nr]<=sr.error&&o_(Ss("error",e))}a(fc,"error");function xh(...e){sr[nr]<=sr.debug&&Ec(Ss("debug",e))}a(xh,"debug");function GO(...e){sr[nr]<=sr.notify&&Ec(Ss("notify",e))}a(GO,"notify");function qO(...e){sr[nr]<=sr.fatal&&o_(Ss("fatal",e))}a(qO,"fatal");function Gh(...e){sr[nr]<=sr.warn&&o_(Ss("warn",e))}a(Gh,"warn");function Yk(e,t,...r){t===vO.STDERR?o_(Ss(e,r)):Ec(Ss(e,r))}a(Yk,"logCustomLevel");function Kk(){let e;try{e=Bk.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(Kk,"getPropsFilePath");function Wk(e){nr=e}a(Wk,"setLogLevel");function MO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(MO,"autoCastBoolean");function Qk(e){try{if(e.includes("config/settings.js")){let o=PO(e);return{level:o.get(mt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ps.dirname(o.get(mt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(mt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(mt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=UO.parseDocument(Bi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===mt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Qk,"getLogConfig");function zk(){try{let e=UO.parseDocument(Bi.readFileSync(Gk,"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(zk,"getDefaultConfig");function Jk(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(Jk,"AuthAuditLog")});var kO=g((Xae,FO)=>{"use strict";var jk=require("util"),Xk=require("path"),Zk=require("child_process"),eV=jk.promisify(Zk.execFile),tV=1e3*1e3*10;FO.exports={findPs:rV};async function rV(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await eV("ps",["wwxo",`pid,${r}`],{maxBuffer:tV});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:Xk.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(rV,"findPs")});var ut=g((ece,$O)=>{"use strict";var nV="__dbis__",sV="__txns__",iV="__environment_name__",oV="__dbi_defintion__",aV={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"},cV=["__createdtime__","__updatedtime__"],uV="\uFFFF",VO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},lV=Object.values(VO);$O.exports={AUDIT_STORE_NAME:sV,INTERNAL_DBIS_NAME:nV,DBI_DEFINITION_NAME:oV,SEARCH_TYPES:aV,TIMESTAMP_NAMES:cV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:iV,TRANSACTIONS_DBI_NAMES_ENUM:VO,TRANSACTIONS_DBIS:lV,OVERFLOW_MARKER:uV}});var Cr=g((tce,ZO)=>{"use strict";var YO=L(),KO=ut(),WO={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},QO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),zO={500:QO("There was an error processing your request."),400:"Invalid request"},_V=zO[WO.INTERNAL_SERVER_ERROR],dV={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.`},fV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},EV={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"},hV={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${KO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${KO.INTERNAL_DBIS_NAME}`,START_VALUE_REQUIRED:"start_value is required",END_VALUE_REQUIRED:"end_value is required",CANNOT_COMPARE_STRING_TO_NUMERIC_KEYS:"cannot compare a string to numeric keys",END_VALUE_MUST_BE_GREATER_THAN_START_VALUE:"end_value must be greater than or equal to start_value",UNKNOWN_SEARCH_TYPE:"unknown search type",CANNOT_DROP_TABLE_HASH_ATTRIBUTE:"cannot drop a table's hash attribute"},mV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${YO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes.`,ATTR_NAME_NULLISH_ERR:"transaction aborted due to record(s) with an attribute name that is null, undefined or empty string",HASH_VAL_LENGTH_ERR:`transaction aborted due to record(s) with a hash value that exceeds ${YO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},JO={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},pV={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."},SV={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`},TV={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"},gV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},RV={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},jO={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},XO={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},AV={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."},OV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},bV={...JO,...EV,...dV,...pV,...SV,...TV,...gV,...RV,...mV,...jO,...XO,...AV,...OV,...fV};ZO.exports={CHECK_LOGS_WRAPPER:QO,HDB_ERROR_MSGS:bV,DEFAULT_ERROR_MSGS:zO,DEFAULT_ERROR_RESP:_V,HTTP_STATUS_CODES:WO,LMDB_ERRORS_ENUM:hV,AUTHENTICATION_ERROR_MSGS:JO,VALIDATION_ERROR_MSGS:jO,ITC_ERRORS:XO}});var ne=g((nce,rb)=>{"use strict";var ko=Cr(),yV=$(),NV=L(),a_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,eb),this.statusCode=n||ko.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(ko.DEFAULT_ERROR_MSGS[n]?ko.DEFAULT_ERROR_MSGS[n]:ko.DEFAULT_ERROR_MSGS[ko.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&yV[s](i)}},Fh=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},kh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function eb(e,t,r,n=NV.LOG_LEVELS.ERROR,s=null,i=!1){if(tb(e))return e;let o=new a_(e,t,r,n,s);return i&&delete o.stack,o}a(eb,"handleHDBError");function tb(e){return e.__proto__.constructor.name===a_.name}a(tb,"isHDBError");rb.exports={isHDBError:tb,handleHDBError:eb,ClientError:Fh,ServerError:kh,hdb_errors:ko}});var Je=g((ice,ub)=>{"use strict";var Tc=L(),IV=Q(),ir=ee(),gc=require("path"),wV=require("minimist"),nb=require("fs-extra"),sb=require("lodash");ir.initSync();var{CONFIG_PARAMS:Zs,DATABASES_PARAM_CONFIG:hc,SYSTEM_SCHEMA_NAME:c_}=Tc,mc,pc,Sc;function ib(){if(mc!==void 0)return mc;if(ir.getHdbBasePath()!==void 0)return mc=ir.get(Zs.STORAGE_PATH)||gc.join(ir.getHdbBasePath(),Tc.DATABASES_DIR_NAME),mc}a(ib,"getBaseSchemaPath");function ob(){if(pc!==void 0)return pc;if(ir.getHdbBasePath()!==void 0)return pc=cb(c_),pc}a(ob,"getSystemSchemaPath");function ab(){if(Sc!==void 0)return Sc;if(ir.getHdbBasePath()!==void 0)return Sc=ir.get(Tc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||gc.join(ir.getHdbBasePath(),Tc.TRANSACTIONS_DIR_NAME),Sc}a(ab,"getTransactionAuditStoreBasePath");function CV(e,t){let r=ir.get(Zs.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||gc.join(ab(),e.toString())}a(CV,"getTransactionAuditStorePath");function cb(e,t){e=e.toString(),t=t&&t.toString();let r=ir.get(Tc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||gc.join(ib(),e)}a(cb,"getSchemaPath");function DV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,wV(process.argv));let n=r[Zs.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!IV.isObject(n))throw o;i=n}for(let o of i){let c=o[c_];if(!c)continue;let u=ir.get(Zs.DATABASES);u=u??{};let _=c?.tables?.[t]?.[hc.PATH];if(_)return sb.set(u,[c_,hc.TABLES,t,hc.PATH],_),ir.setProperty(Zs.DATABASES,u),_;let l=c?.[hc.PATH];if(l)return sb.set(u,[c_,hc.PATH],l),ir.setProperty(Zs.DATABASES,u),l}}let s=r[Zs.STORAGE_PATH.toUpperCase()];if(s){if(!nb.pathExistsSync(s))throw new Error(s+" does not exist");let i=gc.join(s,e);return nb.mkdirsSync(i),ir.setProperty(Zs.STORAGE_PATH,s),i}return ob()}a(DV,"initSystemSchemaPaths");function LV(){mc=void 0,pc=void 0,Sc=void 0}a(LV,"resetPaths");ub.exports={getBaseSchemaPath:ib,getSystemSchemaPath:ob,getTransactionAuditStorePath:CV,getTransactionAuditStoreBasePath:ab,getSchemaPath:cb,initSystemSchemaPaths:DV,resetPaths:LV}});var Dr=g((uce,Eb)=>{"use strict";var MV=Cr().LMDB_ERRORS_ENUM,ace=require("lmdb"),UV=ut(),cce=require("buffer").Buffer,{OVERFLOW_MARKER:lb,MAX_SEARCH_KEY_LENGTH:u_}=UV,_b=["number","string","symbol","boolean","bigint"];function PV(e){if(e=e?.primaryStore||e,!e)throw new Error(MV.ENV_REQUIRED)}a(PV,"validateEnv");function vV(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(vV,"stringifyData");function BV(e){return e instanceof Date?e.valueOf():e}a(BV,"convertKeyValueToWrite");function HV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(_b.includes(typeof e))return e.length>u_?[e.slice(0,u_)+lb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(_b.includes(typeof i))i.length>u_?r.push(i.slice(0,u_)+lb):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(HV,"getIndexedValues");var l_=0,db=0;function fb(){db=Date.now()-performance.now()}a(fb,"adjustStartTime");fb();var xV=6e4;setInterval(fb,xV).unref();function GV(){let e=performance.now()+db;return e>l_?(l_=e,e):(l_+=488e-6,l_)}a(GV,"getNextMonotonicTime");Eb.exports={validateEnv:PV,stringifyData:vV,convertKeyValueToWrite:BV,getNextMonotonicTime:GV,getIndexedValues:HV}});var hb,yn,Vh,Rc=ge(()=>{hb=require("events"),yn=class extends hb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Vh;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},Vh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var Hi={};qe(Hi,{server:()=>nt});var mb,nt,or=ge(()=>{mb=require("../index"),nt={};(0,mb._assignPackageExport)("server",nt)});var Kh={};qe(Kh,{loadGQLSchema:()=>kV,start:()=>Yh,startOnMainThread:()=>FV});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,b=[],R={table:null,database:null,properties:b};f.set(T,R);for(let P of S.directives){if(P.name.value==="table"){for(let k of P.arguments)R[k.name.value]=k.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=T),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,E.push(R)}if(P.name.value==="sealed"&&(R.sealed=!0),P.name.value==="export"){R.export=!0;for(let k of P.arguments)k.name.value==="name"&&(R.export={name:k.value.value})}}let M=!1;for(let P of S.fields){let k=v(P.type);k.name=P.name.value,b.push(k);for(let H of P.directives)if(H.name.value==="primaryKey")M?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,M=!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)}}R.type=T,T==="Query"&&(h=R)}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):qV.includes(S.type)||(0,pb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of f.values())for(let T of S.properties)p(T);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,$h.dirname)(n),S.tableClass):i.set((0,$h.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var $h,pb,qV,FV,kV,Sb=ge(()=>{$h=require("path");Re();pb=B(Ke()),qV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Yh,"start");FV=Yh,kV=Yh({ensureTable:lt}).handleFile});async function __(e){return VV?(Ac||(Ac=$V(KV)),(await(await Ac).import(e)).namespace):import(e)}async function $V(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:YV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,gb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:Ft,tables:Lr,databases:st})}};let n=await(0,Tb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Ac}function YV(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 KV(){return{Resource:Ft,tables:Lr}}var Tb,gb,VV,Ac,Wh=ge(()=>{Nn();Re();Tb=require("fs/promises"),gb=require("path"),VV=!1;a(__,"secureImport");a($V,"getCompartment");a(YV,"secureOnlyFetch");a(KV,"getGlobalVars")});var zh={};qe(zh,{handleFile:()=>WV});async function WV(e,t,r,n){let s=new Map,i=(0,Rb.pathToFileURL)(r).toString(),o=await __(i);u(o.default)&&n.set((0,Qh.dirname)(t),o.default),c(o,(0,Qh.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var Rb,Qh,Ab=ge(()=>{Rb=require("url");Wh();Qh=require("path");a(WV,"handleFile")});var jh={};qe(jh,{start:()=>QV});function QV({resources:e}){e.set("login",Jh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Jh,Ob=ge(()=>{Nn();a(QV,"start");Jh=class extends Ft{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var Db={};qe(Db,{parse:()=>Zh,streamAsJSON:()=>Oc,stringify:()=>xi});function Oc(e){return new Xh({value:e})}function bb(e){return console.error(e),JSON.stringify(e.toString())}function yb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function xi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===wb)return Cb(e);if(t.resolution)return t.resolution.then(()=>xi(e));throw t}}function Cb(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=Cb(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+xi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Zh(e){return jV.test(e)?zV.parse(e):JSON.parse(e)}var Nb,Ib,zV,JV,wb,Xh,jV,em=ge(()=>{Nb=require("stream"),Ib=B(require("json-bigint-fixes")),zV=(0,Ib.default)({useNativeBigInt:!0}),JV=1e4,wb={};BigInt.prototype.toJSON=function(){throw wb};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),bb)}catch(s){yield bb(s)}else yield xi(t)}else yield xi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);yb(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>JV?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 yb(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(bb,"handleError");a(yb,"when");a(xi,"stringify");a(Cb,"jsStringify");jV=/[[,:]\s*-?\d{16,}/;a(Zh,"parse")});var Vb=g((yce,kb)=>{"use strict";var tm=require("recursive-iterator"),XV=require("alasql"),rm=require("clone"),Lb=Q(),{handleHDBError:Mb,hdb_errors:ZV}=ne(),{HDB_ERROR_MSGS:Ub,HTTP_STATUS_CODES:Pb}=ZV,{getDatabases:e$}=(Re(),ie(Fe)),t$=["DISTINCT_ARRAY"],vb=Symbol("validateTables"),nm=Symbol("validateTable"),bce=Symbol("getAllColumns"),Bb=Symbol("validateAllColumns"),d_=Symbol("findColumn"),Hb=Symbol("validateOrderBy"),bc=Symbol("validateSegment"),sm=Symbol("validateColumn"),xb=Symbol("setColumnsForTable"),Gb=Symbol("checkColumnsForAsterisk"),qb=Symbol("validateGroupBy"),Fb=Symbol("hasColumns"),im=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[vb](),this[Gb](),this[Bb]()}[vb](){if(this[Fb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[nm](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[nm](t.table)})}}[Fb](){let t=!1,r=new tm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[nm](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=e$();if(!r[t.databaseid])throw Mb(new Error,Ub.SCHEMA_NOT_FOUND(t.databaseid),Pb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Mb(new Error,Ub.TABLE_NOT_FOUND(t.databaseid,t.tableid),Pb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=rm(s);i.table=rm(t),this.attributes.push(i)})}[d_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[Gb](){let t=new tm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[xb](r.tableid)}[xb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new XV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Bb](){this[bc](this.statement.columns,!1),this[bc](this.statement.joins,!1),this[bc](this.statement.where,!1),this[qb](this.statement.group,!1),this[bc](this.statement.order,!0)}[bc](t,r){if(!t)return;let n=new tm(t),s=[];for(let{node:i,path:o}of n)!Lb.isEmpty(i)&&!Lb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Hb](i):s.push(this[sm](i)));return s}[qb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&t$.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[d_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[d_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[Hb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[sm](t)}[sm](t){let r=this[d_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};kb.exports=im});var Yb=g((Ice,$b)=>{"use strict";var om=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};$b.exports=om});var Wb=g((Cce,Kb)=>{"use strict";var am=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Kb.exports=am});var jb={};qe(jb,{HAS_EXPIRATION:()=>Em,LAST_TIMESTAMP_PLACEHOLDER:()=>Ic,LOCAL_TIMESTAMP:()=>r$,METADATA:()=>yc,NO_TIMESTAMP:()=>um,PENDING_LOCAL_TIME:()=>hm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>fm,RecordEncoder:()=>dm,TIMESTAMP_ASSIGN_LAST:()=>s$,TIMESTAMP_ASSIGN_NEW:()=>zb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Jb,TIMESTAMP_PLACEHOLDER:()=>f_,TIMESTAMP_RECORD_PREVIOUS:()=>lm,getUpdateRecord:()=>mm,handleLocalTimeForGets:()=>p_});function o$(){return Nc[0]=Nc[0]^64,n$.getFloat64(0)}function p_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[yc];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?.[yc]>=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[yc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Gi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Gi.length;u++){let _=Gi[u].deref();(!_||_.isDone||_.isCommitted)&&Gi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function mm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Vo=i?.localTime?lm|Jb:um:Vo=u?i?.localTime?lm|16384:zb|16384:um,l>0&&(c|=Em),h_=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&&(E_=e.encoder.encode(E)),f&&i?.localTime){let b=i?.localTime,R=r.get(b);if(R){let M=Mt(R).previousLocalTime;return r.put(b,m_(o,t,n,M,T,d,E_),{ifVersion:p}),S}}r.put(Ic,m_(o,t,n,i?.localTime?1:0,T,d,E_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Qb,cm,f_,Ic,fm,r$,yc,Nc,n$,um,zb,s$,Jb,lm,Em,hm,i$,E_,Vo,h_,_m,dm,Gi,wc=ge(()=>{Qb=require("msgpackr");ei();cm=B($()),f_=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]),r$=Symbol("local-timestamp"),yc=Symbol("metadata"),Nc=new Uint8Array(8),n$=new DataView(Nc.buffer,0,8),um=0,zb=0,s$=1,Jb=3,lm=4,Em=16,hm=1,Vo=0,h_=-1,_m=0,dm=class extends Qb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(Vo||h_>=0){let i=0,o=Vo;o&&(i+=8,Vo=0);let c=h_,u=_m;c>=0&&(i+=2,h_=-1,u&&(i+=8,_m=0));let _=i$=r.call(this,n,s|2048|i);E_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(f_[4]=o,f_[5]=o>>8,_.set(f_,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(Nc,0,c),c+=8;else for(let d=0;d<8;d++)Nc[d]=t[c++];u=o$(),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,[yc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(o$,"getTimestamp");a(p_,"handleLocalTimeForGets");Gi=[];setInterval(()=>{for(let e=0;e<Gi.length;e++){let t=Gi[e].deref();!t||t.isDone||t.isCommitted?Gi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(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=g((Pce,Zb)=>{"use strict";var Xb=ee(),a$=L(),{RecordEncoder:c$}=(wc(),ie(jb)),Uce=require("fs");Xb.initSync();var u$=Xb.get(a$.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=u$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:c$})}};Zb.exports=pm});var Dc=g((Bce,ey)=>{"use strict";var Mr=ee(),sn=L();Mr.initSync();var S_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=Mr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Mr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Mr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Mr.get(sn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Mr.get(sn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Mr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Mr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Mr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Mr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Mr.get(sn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Mr.get(sn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Mr.get(sn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ey.exports=S_;S_.MAX_DBS=1e4});var We=g((xce,ly)=>{"use strict";var Tm=require("lmdb"),In=require("fs-extra"),Ur=require("path"),T_=Dr(),ny=$(),ar=Cr().LMDB_ERRORS_ENUM,g_=Wb(),gm=Cc(),sy=Dc(),ti=ut(),ty=L(),{table:l$,resetDatabases:_$}=(Re(),ie(Fe)),ry=ee(),wn=ti.INTERNAL_DBIS_NAME,iy=ti.DBI_DEFINITION_NAME,d$="data.mdb",f$="lock.mdb",Lc=".mdb",E$="-lock",Sm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=on(t,r),this.key_type=this.dbi[ti.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ti.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 R_(e,t){if(e===void 0)throw new Error(ar.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(ar.ENV_NAME_REQUIRED)}a(R_,"pathEnvNameValidation");async function Rm(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(ar.INVALID_BASE_PATH):n}try{let n=Ur.join(e,t+Lc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(Ur.join(e,t,d$),In.constants.R_OK|In.constants.F_OK),Ur.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(ar.INVALID_ENVIRONMENT)}else throw new Error(ar.INVALID_ENVIRONMENT);throw n}}a(Rm,"validateEnvironmentPath");function A_(e,t){if(T_.validateEnv(e),t===void 0)throw new Error(ar.DBI_NAME_REQUIRED)}a(A_,"validateEnvDBIName");async function h$(e,t,r=!1,n=!1){R_(e,t);let s=Ur.basename(e);t=t.toString();let i=ry.get(ty.CONFIG_PARAMS.DATABASES);i||ry.setProperty(ty.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Rm(e,t,n),oy(e,t,r)}catch(o){if(o.message===ar.INVALID_ENVIRONMENT){let c=Ur.join(e,t);await In.mkdirp(n?c:e);let u=new sy(n?c:c+Lc,!1),_=Tm.open(u);_.dbis=Object.create(null);let l=new gm(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=Am(e,t,r);return _[ti.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(h$,"createEnvironment");async function m$(e,t,r,n=!0){R_(e,t),t=t.toString();let s=Ur.join(e,t);return l$({table:t,database:Ur.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(m$,"copyEnvironment");async function oy(e,t,r=!1){R_(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=Ur.join(e,t+Lc),o=s!=i,c=new sy(s,o),u=Tm.open(c);u.dbis=Object.create(null);let _=cy(u);for(let l=0;l<_.length;l++)on(u,_[l]);return u[ti.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(oy,"openEnvironment");async function p$(e,t,r=!1){R_(e,t),t=t.toString();let n=Ur.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 ay(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+E$:Ur.join(Ur.dirname(s),f$))}a(p$,"deleteEnvironment");async function ay(e){T_.validateEnv(e);let t=e[ti.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(ay,"closeEnvironment");function Am(e,t,r=!1){let s=`${Ur.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(Am,"getCachedEnvironmentName");function S$(e){T_.validateEnv(e);let t=Object.create(null),r=on(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new g_,s)}catch{ny.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(S$,"listDBIDefinitions");function cy(e){T_.validateEnv(e);let t=[],r=on(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(cy,"listDBIs");function T$(e,t){let n=on(e,wn).getEntry(t),s=new g_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{ny.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(T$,"getDBIDefinition");function uy(e,t,r,n=!r){if(A_(e,t),t=t.toString(),t===wn)throw new Error(ar.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return on(e,t)}catch(s){if(s.message===ar.DBI_DOES_NOT_EXIST){let i=new gm(r,n===!0),o=e.openDB(t,i),c=new g_(r===!0,n);return o[iy]=c,on(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(uy,"createDBI");function on(e,t){if(A_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=T$(e,t):r=new g_,r===void 0)throw new Error(ar.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(ar.DBI_DOES_NOT_EXIST):s}return n[iy]=r,e.dbis[t]=n,n}a(on,"openDBI");function g$(e,t){A_(e,t),t=t.toString();let r=on(e,t),n=r.getStats();return r[ti.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(g$,"statDBI");async function R$(e,t){try{let r=Ur.join(e,t+Lc);return(await In.stat(r)).size}catch{throw new Error(ar.INVALID_ENVIRONMENT)}}a(R$,"environmentDataSize");function A$(e,t){if(A_(e,t),t=t.toString(),t===wn)throw new Error(ar.CANNOT_DROP_INTERNAL_DBIS_NAME);on(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],on(e,wn).removeSync(t)}a(A$,"dropDBI");function O$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{on(e,i)}catch(o){if(o.message===ar.DBI_DOES_NOT_EXIST)uy(e,i,i!==t,i===t),n=!0;else throw o}}n&&_$()}a(O$,"initializeDBIs");ly.exports={openDBI:on,openEnvironment:oy,createEnvironment:h$,listDBIs:cy,listDBIDefinitions:S$,createDBI:uy,dropDBI:A$,statDBI:g$,deleteEnvironment:p$,initializeDBIs:O$,TransactionCursor:Sm,environmentDataSize:R$,copyEnvironment:m$,closeEnvironment:ay}});var dy=g((qce,_y)=>{"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}};_y.exports=Om});var Ey=g((kce,fy)=>{"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}};fy.exports=bm});var my=g(($ce,hy)=>{"use strict";var ym=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};hy.exports=ym});var $o=g((zce,Ty)=>{"use strict";var b$=We(),y$=dy(),N$=Ey(),I$=my(),Wn=Dr(),Mc=Cr().LMDB_ERRORS_ENUM,w$=ut(),Ts=L(),C$=Q(),D$=require("uuid"),Kce=require("lmdb"),{handleHDBError:L$,hdb_errors:M$}=ne(),{OVERFLOW_MARKER:Wce,MAX_SEARCH_KEY_LENGTH:Qce}=w$,py=ee();py.initSync();var O_=py.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Nm=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function U$(e,t,r,n,s=Wn.getNextMonotonicTime()){Dm(e,t,r,n),Im(e,t,r);let i=new y$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Sy(_,!0,s);let l=P$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return wm(o,c,n,i,s)}a(U$,"insertRecords");function P$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Ts.FUNC_VAL],n[o]=c)}let u=Wn.getIndexedValues(c),_=e.dbis[o];if(u){O_&&_.prefetch(u.map(l=>({key:l,value:s})),b_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}O_&&e.dbis[t].prefetch([s],b_),e.dbis[t].put(s,n,n[qi])})}a(P$,"insertRecord");function v$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(v$,"removeSkippedRecords");function Sy(e,t,r){let n=r>0;(n||!Number.isInteger(e[qi]))&&(e[qi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[Nm]))&&(e[Nm]=r||Wn.getNextMonotonicTime()):delete e[Nm]}a(Sy,"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),b$.initializeDBIs(e,t,r)}a(Im,"initializeTransaction");async function B$(e,t,r,n,s=Wn.getNextMonotonicTime()){Dm(e,t,r,n),Im(e,t,r);let i=new N$,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(B$,"updateRecords");async function H$(e,t,r,n,s=Wn.getNextMonotonicTime()){try{Dm(e,t,r,n)}catch(u){throw L$(u,u.message,M$.HTTP_STATUS_CODES.BAD_REQUEST)}Im(e,t,r);let i=new I$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;C$.isEmpty(_[t])?(l=D$.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(H$,"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(),v$(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(Sy(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 R=p([[_]]);Array.isArray(R)&&(p=R[0][Ts.FUNC_VAL],r[h]=p)}if(p===T)continue;let b=Wn.getIndexedValues(T);if(b){O_&&S.prefetch(b.map(R=>({key:R,value:n})),b_);for(let R=0,M=b.length;R<M;R++)S.remove(b[R],n)}if(b=Wn.getIndexedValues(p),b){O_&&S.prefetch(b.map(R=>({key:R,value:n})),b_);for(let R=0,M=b.length;R<M;R++)S.put(b[R],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 x$(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(x$,"validateBasic");function Dm(e,t,r,n){if(x$(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 b_(){}a(b_,"noop");Ty.exports={insertRecords:U$,updateRecords:B$,upsertRecords:H$}});var Fi=g((jce,G$)=>{G$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var zn=g((Xce,Ay)=>{"use strict";var Ry=Q(),gy=L(),Yo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Qn=require("joi"),ri={schema_format:{pattern:Yo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},q$=Qn.alternatives(Qn.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),Qn.number(),Qn.array()).required(),F$=Qn.alternatives(Qn.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),Qn.number()),k$=Qn.alternatives(Qn.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),Qn.number()).required();function V$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ri.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(V$,"checkValidTable");function $$(e,t){return Ry.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a($$,"validateSchemaExists");function Y$(e,t){let r=t.state.ancestors[0].schema;return Ry.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(Y$,"validateTableExists");function K$(e,t){return e.toLowerCase()===gy.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${gy.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(K$,"validateSchemaName");Ay.exports={common_validators:ri,schema_regex:Yo,hdb_schema_table:q$,validateSchemaExists:$$,validateTableExists:Y$,validateSchemaName:K$,checkValidTable:V$,hdb_database:F$,hdb_table:k$}});var je=g((eue,Oy)=>{"use strict";var cr=require("validate.js");cr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||cr.validators.type.checks[t](e)?null:` must be a '${t}' value`};cr.validators.type.checks={Object:function(e){return cr.isObject(e)&&!cr.isArray(e)},Array:cr.isArray,Integer:cr.isInteger,Number:cr.isNumber,String:cr.isString,Date:cr.isDate,Boolean:function(e){return typeof e=="boolean"}};cr.validators.hasValidFileExt=function(e,t){return cr.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};Oy.exports={validateObject:W$,validateObjectAsync:Q$,validateBySchema:z$};function W$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=cr(e,t,{format:"flat"});return r?new Error(r):null}a(W$,"validateObject");async function Q$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await cr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(Q$,"validateObjectAsync");function z$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(z$,"validateBySchema")});var y_=g((rue,by)=>{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 J$(e){return e=vc(e),pt.table.presence=!1,pt.attribute.presence=!1,pt.hash_attribute.presence=!1,Pc.validateObject(e,pt)}a(J$,"schema_object");function j$(e){return e=vc(e),pt.table.presence={message:Uc},pt.attribute.presence=!1,pt.hash_attribute.presence=!1,Pc.validateObject(e,pt)}a(j$,"table_object");function X$(e){return e=vc(e),pt.table.presence={message:Uc},pt.attribute.presence=!1,Pc.validateObject(e,pt)}a(X$,"create_table_object");function Z$(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(Z$,"attribute_object");function e1(e){return e=vc(e),pt.table.presence={message:Uc},pt.attribute.presence=!1,pt.hash_attribute.presence=!1,Pc.validateObject(e,pt)}a(e1,"describe_table");function t1(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(t1,"validateTableResidence");by.exports={schema_object:J$,create_table_object:X$,table_object:j$,attribute_object:Z$,describe_table:e1,validateTableResidence:t1}});var Ny=g((sue,yy)=>{"use strict";var r1=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||r1.v4(),this.schema_table=`${this.schema}.${this.table}`}};yy.exports=Lm});var N_=g((oue,Iy)=>{"use strict";var n1=Ny(),Mm=class extends n1{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}};Iy.exports=Mm});var Cy=g((cue,wy)=>{"use strict";wy.exports=i1;var s1="inserted";function i1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===s1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(i1,"returnObject")});var I_=g((lue,Py)=>{"use strict";var o1=L(),Um=We(),a1=$o(),{getSystemSchemaPath:c1,getSchemaPath:u1}=Je(),l1=Fi(),_1=y_(),d1=N_(),f1=Cy(),{handleHDBError:Dy,hdb_errors:My}=ne(),Ly=Q(),{HTTP_STATUS_CODES:E1}=My,Pm=l1.hdb_attribute,Uy=[];for(let e=0;e<Pm.attributes.length;e++)Uy.push(Pm.attributes[e].attribute);var h1="inserted";Py.exports=m1;async function m1(e){let t=_1.attribute_object(e);if(t)throw Dy(new Error,t.message,My.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&Ly.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Dy(new Error,r,E1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Ly.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 d1(e.schema,e.table,e.attribute,e.id);try{let i=await Um.openEnvironment(u1(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(c1(),o1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await a1.insertRecords(o,Pm.hash_attribute,Uy,[s]);return f1(h1,c,{records:[s]},u)}catch(i){throw i}}a(m1,"lmdbCreateAttribute")});var Bm=g((due,By)=>{var{hdb_table:p1,hdb_database:vy}=zn(),S1=je(),vm=require("joi"),T1={undefined:"undefined",null:"null"},g1=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||T1[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"),R1=vm.object({database:vy,schema:vy,table:p1,records:vm.array().items(vm.object().custom(g1)).required()});By.exports=function(e){return S1.validateBySchema(e,R1)}});var Bc=g((hue,xy)=>{"use strict";var gs=Q(),Hy=$(),Eue=Bm(),{getDatabases:A1}=(Re(),ie(Fe)),{ClientError:ki}=ne();xy.exports=O1;function O1(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=A1()[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 Hy.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 Hy.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(O1,"insertUpdateValidate")});var Hc=g((pue,Gy)=>{"use strict";var b1=L().OPERATIONS_ENUM,Hm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=b1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};Gy.exports=Hm});var xc=g((gue,Fy)=>{"use strict";var Tue=Hc(),w_=L(),xm=Q(),qy=$(),y1=require("uuid"),{handleHDBError:C_,hdb_errors:N1}=ne(),{HDB_ERROR_MSGS:D_,HTTP_STATUS_CODES:L_}=N1;Fy.exports=I1;function I1(e,t,r){for(let s=0;s<t.length;s++)w1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];C1(i,r,e.operation)}}a(I1,"processRows");function w1(e){if(Buffer.byteLength(String(e))>w_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw C_(new Error,D_.ATTR_NAME_LENGTH_ERR(e),L_.BAD_REQUEST,void 0,void 0,!0);if(xm.isEmptyOrZeroLength(e)||xm.isEmpty(e.trim()))throw C_(new Error,D_.ATTR_NAME_NULLISH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}a(w1,"validateAttribute");function C1(e,t,r){if(!e.hasOwnProperty(t)||xm.isEmptyOrZeroLength(e[t])){if(r===w_.OPERATIONS_ENUM.INSERT||r===w_.OPERATIONS_ENUM.UPSERT){e[t]=y1.v4();return}throw qy.error("Update transaction aborted due to record with no hash value:",e),C_(new Error,D_.RECORD_MISSING_HASH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>w_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw qy.error(e),C_(new Error,D_.HASH_VAL_LENGTH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}a(C1,"validateHash")});var Vy=g((Aue,ky)=>{"use strict";var Gm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};ky.exports=Gm});var Ky=g((bue,Yy)=>{"use strict";var qm=We(),D1=$(),$y=Cr().LMDB_ERRORS_ENUM;Yy.exports=L1;async function L1(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!==$y.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!==$y.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){D1.error(t)}}a(L1,"cleanLMDBMap")});var Rs=g((Nue,Jy)=>{"use strict";var Gc=require("crypto"),M1=ee(),{CONFIG_PARAMS:U1}=L(),Qy="aes-256-cbc",P1=32,v1=16,Fm=64,zy=32,B1=Fm+zy,Wy=new Map;Jy.exports={encrypt:H1,decrypt:x1,createNatsTableStreamName:G1};function H1(e){let t=Gc.randomBytes(P1),r=Gc.randomBytes(v1),n=Gc.createCipheriv(Qy,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(H1,"encrypt");function x1(e){let t=e.substr(0,Fm),r=e.substr(Fm,zy),n=e.substr(B1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Gc.createDecipheriv(Qy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(x1,"decrypt");function G1(e,t){let r=M1.get(U1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Wy.get(r);return n||(n=Gc.createHash("md5").update(r).digest("hex"),Wy.set(r,n)),n}a(G1,"createNatsTableStreamName")});var As=g((Cue,Xy)=>{"use strict";var wue=Pr(),M_=$(),jy=y_(),q1=Rs(),U_=Q(),{handleHDBError:P_,hdb_errors:F1}=ne(),{HDB_ERROR_MSGS:v_,HTTP_STATUS_CODES:km}=F1,k1=ee();k1.initSync();var{getDatabases:Vm}=(Re(),ie(Fe));Xy.exports={describeAll:V1,describeTable:B_,describeSchema:$1};async function V1(e){try{let t=U_.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 B_({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 B_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){M_.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 M_.error("Got an error in describeAll"),M_.error(t),P_(new Error,v_.DESCRIBE_ALL_ERR)}}a(V1,"describeAll");async function B_(e,t){U_.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=jy.describe_table(e);if(i)throw i;let c=Vm()[r];if(!c)throw P_(new Error,v_.SCHEMA_NOT_FOUND(e.schema),km.NOT_FOUND);let u=c[n];if(!u)throw P_(new Error,v_.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=q1.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){M_.warn(`unable to stat table dbi due to ${f}`)}return d}a(B_,"descTable");async function $1(e){U_.transformReq(e);let t=jy.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 P_(new Error,v_.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]),U_.isEmpty(u)||u.describe){let _=await B_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a($1,"describeSchema")});var Os=g((Uue,nN)=>{var Y1=Fi(),{callbackify:eN,promisify:K1}=require("util"),{getDatabases:tN}=(Re(),ie(Fe));nN.exports={setSchemaDataToGlobal:Zy,getTableSchema:W1,getSystemSchema:Q1,setSchemaDataToGlobalAsync:K1(Zy)};var rN=As(),Lue=eN(rN.describeAll),Mue=eN(rN.describeTable);function Zy(e){global.hdb_schema=tN(),e&&e()}a(Zy,"setSchemaDataToGlobal");function W1(e,t,r){let n=tN()[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(W1,"getTableSchema");function Q1(){return Y1}a(Q1,"getSystemSchema")});var vr=g((vue,aN)=>{"use strict";var x_=Bm(),kt=Q(),z1=require("util"),G_=Cn(),J1=Os(),sN=$(),{handleHDBError:Vi,hdb_errors:j1}=ne(),{HTTP_STATUS_CODES:$i}=j1,X1=z1.promisify(J1.getTableSchema),Z1="updated",iN="inserted",oN="upserted";aN.exports={insert:tY,update:rY,upsert:nY,validation:eY,flush:sY};async function eY(e){if(kt.isEmpty(e))throw new Error("invalid update parameters defined.");if(kt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(kt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await X1(e.schema,e.table),r=x_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&kt.isEmptyOrZeroLength(c[n]))throw sN.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(!kt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw sN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!kt.isEmpty(c[n])&&c[n]!==""&&s.has(kt.autoCast(c[n]))&&(c.skip=!0),s.add(kt.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(eY,"validation");async function tY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.createRecords(e);return H_(iN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(tY,"insertData");async function rY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.updateRecords(e);return kt.isEmpty(n.existing_rows)?H_(Z1,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):H_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(rY,"updateData");async function nY(e){if(e.operation!=="upsert")throw Vi(new Error,"invalid operation, must be upsert",$i.INTERNAL_SERVER_ERROR);let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.upsertRecords(e);return H_(oN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(nY,"upsertData");function H_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===iN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===oN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(H_,"returnObject");function sY(e){return kt.transformReq(e),G_.flush(e.schema,e.table)}a(sY,"flush")});var Ym=g((Hue,lN)=>{var iY=je(),$m=require("joi"),{hdb_table:oY,hdb_database:cN}=zn(),uN={schema:cN,database:cN,table:oY},aY={date:$m.date().iso().required()},cY={timestamp:$m.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};lN.exports=function(e,t){let r=t==="timestamp"?{...uN,...cY}:{...uN,...aY},n=$m.object(r);return iY.validateBySchema(e,n)}});var fN=g((xue,dN)=>{var uY=je(),Km=require("joi"),{hdb_table:lY,hdb_database:_N}=zn(),_Y=Km.object({schema:_N,database:_N,table:lY,hash_values:Km.array().required(),ids:Km.array()});dN.exports=function(e){return uY.validateBySchema(e,_Y)}});var hN=g((Gue,EN)=>{"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=[]}};EN.exports={InsertObject:Wm,NoSQLSeachObject:Qm,DeleteResponseObject:zm}});var ii=g((Fue,gN)=>{"use strict";var pN=Ym(),dY=fN(),Yi=Q(),mN=require("moment"),SN=$(),{promisify:fY,callbackify:EY}=require("util"),Ki=L(),hY=Os(),Jm=fY(hY.getTableSchema),jm=Cn(),{DeleteResponseObject:mY}=hN(),{handleHDBError:ni,hdb_errors:pY}=ne(),{HDB_ERROR_MSGS:q_,HTTP_STATUS_CODES:si}=pY,SY="records successfully deleted",TY=EY(TN);gN.exports={delete:TY,deleteRecord:TN,deleteFilesBefore:gY,deleteAuditLogsBefore:RY};async function gY(e){let t=pN(e,"date");if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!mN(e.date,mN.ISO_8601).isValid())throw ni(new Error,q_.INVALID_DATE,si.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,q_.INVALID_DATE,!0);let n=Yi.checkSchemaTableExist(e.schema,e.table);if(n)throw ni(new Error,n,si.NOT_FOUND,Ki.LOG_LEVELS.ERROR,n,!0);let s=await jm.deleteRecordsBefore(e);if(await Jm(e.schema,e.table),SN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(gY,"deleteFilesBefore");async function RY(e){let t=pN(e,"timestamp");if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),isNaN(e.timestamp))throw ni(new Error,q_.INVALID_VALUE("Timestamp"),si.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,q_.INVALID_VALUE("Timestamp"),!0);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw ni(new Error,r,si.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);let n=await jm.deleteAuditLogsBefore(e);return await Jm(e.schema,e.table),SN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(RY,"deleteAuditLogsBefore");async function TN(e){e.ids&&(e.hash_values=e.ids);let t=dY(e);if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);Yi.transformReq(e);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw ni(new Error,r,si.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} ${SY}`),n}catch(n){if(n.message===Ki.SEARCH_NOT_FOUND_MESSAGE){let s=new mY;return s.message=Ki.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(TN,"deleteRecord")});var F_=g((Vue,ON)=>{var AY=require("crypto"),RN=9;function OY(e){let t=yY(RN),r=AN(e+t);return t+r}a(OY,"createHash");function bY(e,t){let r=e?.substr(0,RN),n=r+AN(t+r);return e===n}a(bY,"validateHash");function yY(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(yY,"generateSalt");function AN(e){return AY.createHash("md5").update(e).digest("hex")}a(AN,"md5");ON.exports={hash:OY,validate:bY}});var yN=g((Yue,bN)=>{var Xm=je(),Qt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function NY(e){return Qt.password.presence=!0,Qt.username.presence=!0,Qt.role.presence=!0,Qt.active.presence=!0,Xm.validateObject(e,Qt)}a(NY,"addUserValidation");function IY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Xm.validateObject(e,Qt)}a(IY,"alterUserValidation");function wY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Xm.validateObject(e,Qt)}a(wY,"dropUserValidation");bN.exports={addUserValidation:NY,alterUserValidation:IY,dropUserValidation:wY}});var ke=g((Que,IN)=>{"use strict";var{platform:Wue}=require("os"),CY="nats-server.zip",Zm="nats-server",DY=process.platform==="win32"?`${Zm}.exe`:Zm,LY=/^[^\s.,*>]+$/,NN="__request__",MY=a(e=>`${e}.${NN}`,"REQUEST_SUBJECT"),UY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},PY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},vY={HUB:"hub.pid",LEAF:"leaf.pid"},BY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},HY={SUCCESS:"success",ERROR:"error"},xY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},GY={TXN:"txn",MSGID:"msgid"},Ko={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},qY={[Ko.ERR]:1,[Ko.WRN]:2,[Ko.INF]:3,[Ko.DBG]:4,[Ko.TRC]:5},FY={debug:"-D",trace:"-DVV"};IN.exports={NATS_SERVER_ZIP:CY,NATS_SERVER_NAME:Zm,NATS_BINARY_NAME:DY,PID_FILES:vY,NATS_CONFIG_FILES:PY,SERVER_SUFFIX:BY,NATS_TERM_CONSTRAINTS_RX:LY,REQUEST_SUFFIX:NN,UPDATE_REMOTE_RESPONSE_STATUSES:HY,CLUSTER_STATUS_STATUSES:xY,REQUEST_SUBJECT:MY,SUBJECT_PREFIXES:GY,MSG_HEADERS:UY,LOG_LEVELS:Ko,LOG_LEVEL_FLAGS:FY,LOG_LEVEL_HIERARCHY:qY}});var CN=g((Jue,wN)=>{"use strict";var kY={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
|
-
`)},kY="certificate.pem",VY="privateKey.pem",$Y="ca.pem";wN.exports={CERTIFICATE_VALUES:FY,CERTIFICATE_PEM_NAME:kY,PRIVATEKEY_PEM_NAME:VY,CA_PEM_NAME:$Y}});var tp=g((zue,PN)=>{"use strict";var UN=require("fs-extra"),oe=require("joi"),YY=require("os"),{boolean:be,string:zt,number:Ze,array:ep}=oe.types(),{totalmem:DN}=require("os"),Qi=require("path"),KY=$(),q_=Q(),Que=CN(),LN=L(),WY=Xe(),MN="log",QY="components",zY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",JY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",XY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",jY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",ZY="rootPath config parameter is undefined",eK="clustering.enabled config parameter is undefined",zi=Ze.min(0).required(),F_=ep.items({host:zt.required(),port:zi}).empty(null),js;PN.exports={configValidator:tK,routesValidator:aK,route_constraints:F_};function tK(e){if(js=e.rootPath,q_.isEmpty(js))throw ZY;let t=be.required(),r=Ze.min(0).max(1e3).empty(null).default(oK),s=zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Gc),n=zt.optional().empty(null),i=zt.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=oe.string().empty(null).default(Gc),c=oe.custom(sK).empty(null).default(Gc),u=e.clustering?.enabled;if(q_.isEmpty(u))throw eK;let _;return u===!0?_=oe.object({enabled:t,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:zi,routes:F_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:zi}).required()}).required(),network:oe.object({port:zi}).required()}).required(),leafServer:oe.object({network:oe.object({port:zi,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:o}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:be.required(),verify:be.optional()}),user:zt.optional().empty(null)}).required():_=oe.object({enabled:t,tls:oe.object({certificate:n,certificateAuthority:n,privateKey:n,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:_,localStudio:oe.object({enabled:t}).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:zt.custom(iK).optional().empty(null),maxSize:zt.custom(nK).optional().empty(null),path:zt.optional().empty(null).default(Gc)}).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(Gc),securePort:Ze.optional().empty(null),timeout:Ze.min(1).optional()}).optional(),tls:oe.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:zi,securePort:zi,mtls:oe.alternatives([be.optional(),oe.object({user:zt.optional(),certificateAuthority:n,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:zt.optional(),certificateAuthority:n,required:be.optional()})])}).required(),threads:oe.alternatives(r.optional(),oe.object({count:r.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:Ze.min(1).optional(),host:zt.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:zt.optional(),threshold:Ze.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:c,prefetchWrites:be.optional(),maxFreeSpaceToLoad:Ze.optional(),maxFreeSpaceToRetain:Ze.optional()}).required(),ignoreScripts:be.optional(),tls:oe.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:zt.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(tK,"configValidator");function rK(e){return UN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(rK,"doesPathExist");function sK(e,t){oe.assert(e,zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=rK(e);if(r)return t.message(r)}a(sK,"validatePath");function nK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(zY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(XY):e}a(nK,"validateRotationMaxSize");function iK(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(JY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(jY):e}a(iK,"validateRotationInterval");function oK(e,t){let r=t.state.path.join("."),s=YY.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||DN();return i=Math.round(Math.min(i,DN())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),KY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(oK,"setDefaultThreads");function Gc(e,t){let r=t.state.path.join(".");if(!q_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(q_.isEmpty(js))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Qi.join(js,QY);case"logging.root":return Qi.join(js,MN);case"clustering.leafServer.streams.path":return Qi.join(js,"clustering","leaf");case"storage.path":let s=Qi.join(js,LN.LEGACY_DATABASES_DIR_NAME);return UN.existsSync(s)?s:Qi.join(js,LN.DATABASES_DIR_NAME);case"logging.rotation.path":return Qi.join(js,MN);case"operationsApi.network.domainSocket":return r==null?null:Qi.join(js,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Gc,"setDefaultRoot");function aK(e){let t=oe.object({routes:F_});return WY.validateBySchema({routes:e},t)}a(aK,"routesValidator")});var lr=g((jue,VN)=>{"use strict";var Hr=L(),Ut=Q(),bt=$(),{configValidator:cK,routesValidator:vN}=tp(),ur=require("fs-extra"),uK=require("yaml"),Ds=require("path"),lK=require("is-number"),HN=require("properties-reader"),_K=require("lodash"),{handleHDBError:dK}=se(),{HTTP_STATUS_CODES:fK,HDB_ERROR_MSGS:k_}=Cr(),Xue=require("minimist"),{server:EK}=(or(),ie(xi)),{DATABASES_PARAM_CONFIG:qc,CONFIG_PARAMS:Br,CONFIG_PARAM_MAP:Ls}=Hr,hK="Unable to get config value because config is uninitialized",mK="Config successfully initialized",pK="Error backing up config file",SK="Empty parameter sent to getConfigValue",xN=Ds.join(Hr.PACKAGE_ROOT,"config","yaml",Hr.HDB_DEFAULT_CONFIG_FILE),TK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",BN={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,$_;VN.exports={createConfigFile:gK,getDefaultConfig:RK,getConfigValue:qN,initConfig:sp,flattenConfig:Wo,updateConfigValue:FN,updateConfigObject:OK,getConfiguration:NK,setConfiguration:IK,readConfigFile:ip,getClusteringRoutes:wK,initOldConfig:kN,getConfigFromFile:CK,getConfigFilePath:Ji,addConfig:DK,deleteConfigFromFile:LK,getConfigObj:MK};function gK(e){let t=oi(xN);V_=Wo(t.toJSON());let r;for(let o in e){let c=Ls[o.toLowerCase()];if(c===Br.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=rp(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){bt.error(l)}}}r&&GN(t,r),np(t);let s=t.toJSON();yt=Wo(s);let n=t.getIn(["rootPath"]),i=Ds.join(n,Hr.HDB_CONFIG_FILE);ur.createFileSync(i),ur.writeFileSync(i,String(t)),bt.trace(`Config file written to ${i}`)}a(gK,"createConfigFile");function GN(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!Ut.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(qc.TABLES))for(let i in s[n][qc.TABLES])for(let o in s[n][qc.TABLES][i]){let c=s[n][qc.TABLES][i][o],u=[Br.DATABASES,n,qc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[Br.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){bt.error("Error parsing schemas CLI/env config arguments",s)}}a(GN,"setSchemasConfig");function RK(e){if(V_===void 0){let r=oi(xN);V_=Wo(r.toJSON())}let t=Ls[e.toLowerCase()];if(t!==void 0)return V_[t.toLowerCase()]}a(RK,"getDefaultConfig");function qN(e){if(e==null){bt.error(SK);return}if(yt===void 0){bt.trace(hK);return}let t=Ls[e.toLowerCase()];if(t!==void 0)return yt[t.toLowerCase()]}a(qN,"getConfigValue");function Ji(e=Ut.getPropsFilePath()){let t=Ut.getEnvCliRootPath();return t?Ds.join(t,Hr.HDB_CONFIG_FILE):HN(e).get(Hr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ji,"getConfigFilePath");function sp(e=!1){if(yt===void 0||e){let t;if(!Ut.noBootFile()){t=Ut.getPropsFilePath();try{ur.accessSync(t,ur.constants.F_OK|ur.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ji(t),s;if(r.includes("config/settings.js"))try{kN(r);return}catch(i){if(i.code!==Hr.NODE_ERROR_CODES.ENOENT)throw i}try{s=oi(r)}catch(i){if(i.code===Hr.NODE_ERROR_CODES.ENOENT){bt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}AK(s,r),np(s);let n=s.toJSON();if(EK.config=n,yt=Wo(n),yt.logging_rotation_rotate)for(let i in BN)yt[i]&&bt.error(`Config ${BN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(mK)}}a(sp,"initConfig");function AK(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Ds.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Ds.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Ds.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!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"}),s=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),s=!0),s&&(bt.trace("Updating config file with missing config params"),ur.writeFileSync(t,String(e)))}a(AK,"checkForUpdatedConfig");function np(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t?.http?.threads&&(t.threads=t?.http?.threads);let r=cK(t);if(r.error)throw k_.CONFIG_VALIDATION(r.error.message);typeof r.value.threads=="object"?e.setIn(["threads","count"],r.value.threads.count):e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(np,"validateConfig");function OK(e,t){yt===void 0&&(yt={});let r=Ls[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}yt[r.toLowerCase()]=t}a(OK,"updateConfigObject");function FN(e,t,r=void 0,s=!1,n=!1,i=!1){yt===void 0&&sp();let o=qN(Ls.hdb_root),c=Ds.join(o,Hr.HDB_CONFIG_FILE),u=oi(c),_;if(r===void 0&&e.toLowerCase()===Br.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Ls[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=Ls[f.toLowerCase()];if(E===Br.HTTP_SECUREPORT&&r[f]===yt[Br.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Br.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===yt[Br.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Br.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")&&(E=f),E!==void 0){let h=E.split("_"),p=Hr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=rp(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){bt.error(T)}}}_&&GN(u,_),np(u);let l=u.getIn(["rootPath"]),d=Ds.join(l,Hr.HDB_CONFIG_FILE);s===!0&&bK(c,l),ur.writeFileSync(d,String(u)),n&&(yt=Wo(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(FN,"updateConfigValue");function bK(e,t){try{let r=Ds.join(t,"backup",`${Hr.HDB_CONFIG_FILE}.bak`);ur.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(pK),bt.error(r)}}a(bK,"backupConfigFile");var yK=["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(s){let n={};for(let i in s)if(s.hasOwnProperty(i)){if(typeof s[i]=="object"&&s[i]!==null&&!Array.isArray(s[i])&&!yK.includes(i)){let o=r(s[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Br[u.toUpperCase()]&&Ls[u]&&(n[Ls[u].toLowerCase()]=o[c]),n[u]=o[c]}}s[i]!==void 0&&(n[i.toLowerCase()]=s[i])}return n}a(r,"squashObj")}a(Wo,"flattenConfig");function rp(e,t){if(e===Br.CLUSTERING_NODENAME||e===Br.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(lK(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Ut.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 Ut.autoCast(t)}a(rp,"castConfigValue");function NK(){let e=Ut.getPropsFilePath(),t=Ji(e);return oi(t).toJSON()}a(NK,"getConfiguration");async function IK(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return FN(void 0,void 0,n,!0),TK}catch(i){throw typeof i=="string"||i instanceof String?dK(i,i,fK.BAD_REQUEST,void 0,void 0,!0):i}}a(IK,"setConfiguration");function ip(){let e=Ut.getPropsFilePath();try{ur.accessSync(e,ur.constants.F_OK|ur.constants.R_OK)}catch(s){if(!Ut.noBootFile())throw bt.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ji(e);return oi(t).toJSON()}a(ip,"readConfigFile");function oi(e){return uK.parseDocument(ur.readFileSync(e,"utf8"),{simpleKeys:!0})}a(oi,"parseYamlDoc");function wK(){let e=ip(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Ut.isEmptyOrZeroLength(t)?[]:t;let r=vN(t);if(r)throw k_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=Ut.isEmptyOrZeroLength(s)?[]:s;let n=vN(s);if(n)throw k_.CONFIG_VALIDATION(n.message);if(!Ut.isEmptyOrZeroLength(s)&&!Ut.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!Ut.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw k_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(wK,"getClusteringRoutes");function kN(e){let t=HN(e);yt={};for(let r in Ls){let s=t.get(r.toUpperCase());if(Ut.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=Ls[r].toLowerCase();n===Br.LOGGING_ROOT?yt[n]=Ds.dirname(s):yt[n]=s}return yt}a(kN,"initOldConfig");function CK(e){let t=ip();return _K.get(t,e.replaceAll("_","."))}a(CK,"getConfigFromFile");async function DK(e,t){let r=oi(Ji());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await ur.writeFile(Ji(),String(r))}a(DK,"addConfig");function LK(e){let t=Ji(Ut.getPropsFilePath()),r=oi(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Ds.join(s,Hr.HDB_CONFIG_FILE);ur.writeFileSync(n,String(r))}a(LK,"deleteConfigFromFile");function MK(){return $_||(sp(),$_)}a(MK,"getConfigObj")});var YN=g((ele,$N)=>{"use strict";var Y_=L(),K_=class{static{a(this,"BaseLicense")}constructor(t=0,r=Y_.RAM_ALLOCATION_ENUM.DEFAULT,s=Y_.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},op=class extends K_{static{a(this,"ExtendedLicense")}constructor(t=0,r=Y_.RAM_ALLOCATION_ENUM.DEFAULT,s=Y_.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};$N.exports={BaseLicense:K_,ExtendedLicense:op}});var Xi=g((rle,XN)=>{"use strict";var zo=require("fs-extra"),WN=G_(),QN=require("crypto"),UK=require("moment"),PK=require("uuid").v4,Jt=$(),cp=require("path"),vK=Q(),ai=L(),{totalmem:KN}=require("os"),BK=YN().ExtendedLicense,Qo="invalid license key format",HK="061183",xK="mofi25",GK="aes-256-cbc",qK=16,FK=32,zN=ee();zN.initSync();var ap;XN.exports={validateLicense:JN,generateFingerPrint:VK,licenseSearch:_p,getLicense:KK,checkMemoryLimit:WK};function up(){return cp.join(zN.getHdbBasePath(),ai.LICENSE_KEY_DIR_NAME,ai.LICENSE_FILE_NAME)}a(up,"getLicenseDirPath");function kK(){let e=up();return cp.join(e,ai.LICENSE_FILE_NAME)}a(kK,"getLicenseFilePath");function lp(){let e=up();return cp.join(e,ai.REG_KEY_FILE_NAME)}a(lp,"getFingerPrintFilePath");async function VK(){let e=lp();try{return await zo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await $K();throw Jt.error(`Error writing fingerprint file to ${e}`),Jt.error(t),new Error("There was an error generating the fingerprint")}}a(VK,"generateFingerPrint");async function $K(){let e=PK(),t=WN.hash(e),r=lp();try{await zo.mkdirp(up()),await zo.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Jt.error(`Error writing fingerprint file to ${r}`),Jt.error(s),new Error("There was an error generating the fingerprint")}return t}a($K,"writeFingerprint");function JN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ai.RAM_ALLOCATION_ENUM.DEFAULT,version:ai.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Jt.error("empty license key passed to validate."),r;let s=lp(),n=!1;try{n=zo.statSync(s)}catch(i){Jt.error(i)}if(n){let i;try{i=zo.readFileSync(s,"utf8")}catch{Jt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(xK),c=o[1];c=Buffer.concat([Buffer.from(c)],qK);let u=Buffer.concat([Buffer.from(i)],FK),_=QN.createDecipheriv(GK,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=YK(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<UK().valueOf()&&(r.valid_date=!1),WN.validate(o[1],`${HK}${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(JN,"validateLicense");function YK(e,t){try{let r=QN.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Jt.warn("Check old license failed")}}a(YK,"checkOldLicense");function _p(){let e=new BK,t=[];try{t=zo.readFileSync(kK(),"utf-8").split(ai.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 s=t[r];try{if(vK.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=JN(n.license_key,n.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(n){Jt.error("There was an error parsing the license string."),Jt.error(n),e.ram_allocation=ai.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return ap=e,e}a(_p,"licenseSearch");async function KK(){return ap||await _p(),ap}a(KK,"getLicense");function WK(){let e=_p().ram_allocation,t=process.constrainedMemory?.()||KN();if(t=Math.round(Math.min(t,KN())/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(WK,"checkMemoryLimit")});var os=g((ale,fI)=>{"use strict";var tI="username is required",rI="nothing to update, must supply active, role or password to update",sI="password cannot be an empty string",nI="If role is specified, it cannot be empty.",iI="active must be true or false";fI.exports={addUser:rW,alterUser:sW,dropUser:iW,getSuperUser:uW,userInfo:oW,listUsers:Q_,listUsersExternal:aW,setUsersToGlobal:Xo,findAndValidateUser:_I,getClusterUser:lW,USERNAME_REQUIRED:tI,ALTERUSER_NOTHING_TO_UPDATE:rI,EMPTY_PASSWORD:sI,EMPTY_ROLE:nI,ACTIVE_BOOLEAN:iI};var oI=vr(),QK=ii(),Ep=G_(),aI=yN(),cI=Pr(),hp=bn(),xr=Q(),uI=require("validate.js"),Ae=$(),{promisify:zK}=require("util"),mp=Rn(),jN=L(),ZN=ke(),JK=lr(),nle=ee(),ile=Xi(),XK=ki(),{table:ole}=(Re(),ie(Fe)),{handleHDBError:Zs,hdb_errors:jK}=se(),{HTTP_STATUS_CODES:en,AUTHENTICATION_ERROR_MSGS:dp,HDB_ERROR_MSGS:Jo}=jK,{UserEventMsg:pp}=Ms(),fp=require("lodash"),{server:Sp}=(or(),ie(xi)),ZK=$();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,eW=cI.searchByHash,tW=zK(QK.delete);async function rW(e){let t=uI.cleanAttributes(e,lI),r=aI.addUserValidation(t);if(r)throw Zs(new Error,r.message,en.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await W_(s),n=n&&Array.from(n)}catch(u){throw Ae.error("There was an error searching for a role in add user"),Ae.error(u),u}if(!n||n.length<1)throw Zs(new Error,Jo.ROLE_NAME_NOT_FOUND(t.role),en.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw Zs(new Error,Jo.DUP_ROLES_FOUND(t.role),en.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=mp.encrypt(t.password)),t.password=Ep.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await oI.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await Xo()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.error(u),u}if(o.skipped_hashes.length===1)throw Zs(new Error,Jo.USER_ALREADY_EXISTS(t.username),en.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],hp.signalUserChange(new pp(process.pid)),`${c.username} successfully added`}a(rW,"addUser");async function sW(e){let t=uI.cleanAttributes(e,lI);if(xr.isEmptyOrZeroLength(t.username))throw new Error(tI);if(xr.isEmptyOrZeroLength(t.password)&&xr.isEmptyOrZeroLength(t.role)&&xr.isEmptyOrZeroLength(t.active))throw new Error(rI);if(!xr.isEmpty(t.password)&&xr.isEmptyOrZeroLength(t.password.trim()))throw new Error(sI);if(!xr.isEmpty(t.active)&&!xr.isBoolean(t.active))throw new Error(iI);let r=nW(t.username);if(!xr.isEmpty(t.password)&&!xr.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 Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=Jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.error(c),Zs(new Error,c,en.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Jo.ALTER_USER_DUP_ROLES(t.role);throw Ae.error(c),Zs(new Error,c,en.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await oI.update(s)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await Xo()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return hp.signalUserChange(new pp(process.pid)),n}a(sW,"alterUser");function nW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(nW,"isClusterUser");async function iW(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(xr.isEmpty(global.hdb_users.get(e.username)))throw Zs(new Error,Jo.USER_NOT_EXIST(e.username),en.NOT_FOUND,void 0,void 0,!0);let s;try{s=await tW(r)}catch(n){throw Ae.error("Got an error deleting a user."),Ae.error(n),n}Ae.debug(s);try{await Xo()}catch(n){throw Ae.error("Got an error setting users to global."),Ae.error(n),n}return hp.signalUserChange(new pp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(iW,"dropUser");async function oW(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:["*"]},s;try{s=await eW(r)}catch(n){throw Ae.error("Got an error searching for a role."),Ae.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ae.error(r),r}return t}a(oW,"userInfo");async function aW(){let e;try{e=await Q_()}catch(t){throw Ae.error("Got an error listing users."),Ae.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(aW,"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 Ae.error("Got an error searching for roles."),Ae.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 s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await W_(s)}catch(o){throw Ae.error("Got an error searching for users."),Ae.error(o),o}let i=new Map;for(let o of n)o=fp.cloneDeep(o),o.role=r[o.role],cW(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),xr.errorizeMessage(e)}return null}a(Q_,"listUsers");function cW(e){try{if(!e){Ae.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(XK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Ae.error("Got an error trying to set system permissions."),Ae.error(t)}}a(cW,"appendSystemTablesToRole");async function Xo(){try{let e=await Q_();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(Xo,"setUsersToGlobal");async function _I(e,t,r=!0){global.hdb_users||await Xo();let s=global.hdb_users.get(e);if(!s){if(!r)return{username:e};throw Zs(new Error,dp.GENERIC_AUTH_FAIL,en.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw Zs(new Error,dp.USER_INACTIVE,en.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(eI.get(t)===s.password)return n;if(Ep.validate(s.password,t))eI.set(t,s.password);else throw Zs(new Error,dp.GENERIC_AUTH_FAIL,en.UNAUTHORIZED,void 0,void 0,!0)}return n}a(_I,"findAndValidateUser");async function uW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(uW,"getSuperUser");async function lW(){let e=await Q_(),t=JK.getConfigFromFile(jN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!xr.isEmpty(r)&&r?.role?.role===jN.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+ZN.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+ZN.SERVER_SUFFIX.ADMIN,r}a(lW,"getClusterUser");var dI=[];Sp.invalidateUser=function(e){for(let t of dI)try{t(e)}catch(r){ZK.error("Error invalidating user",r)}};Sp.onInvalidatedUser=function(e){dI.push(e)}});var kc=g((_le,pI)=>{"use strict";var ji=$(),Gr=L(),_W=Ky(),ule=On(),lle=An(),dW=os(),{validateEvent:EI}=Ms(),Fc=Cs(),fW=require("process"),{resetDatabases:EW}=(Re(),ie(Fe)),hW={[Gr.ITC_EVENT_TYPES.SCHEMA]:mW,[Gr.ITC_EVENT_TYPES.USER]:mI};async function mW(e){let t=EI(e);if(t){ji.error(t);return}ji.trace("ITC schemaHandler received schema event:",e),await _W(e.message),await pW(e.message)}a(mW,"schemaHandler");async function pW(e){try{Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=EW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ji.error(t)}}a(pW,"syncSchemaMetadata");var hI=[];async function mI(e){try{try{Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.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 ${Gr.HDB_ITC_CLIENT_PREFIX}${fW.pid} received user event:`,e),await dW.setUsersToGlobal();for(let r of hI)r()}catch(t){ji.error(t)}}a(mI,"userHandler");mI.addListener=function(e){hI.push(e)};pI.exports=hW});var Ms=g((ple,TI)=>{"use strict";var fle=$(),Tp=Q(),SW=L(),{ITC_ERRORS:Vc}=Cr(),{parentPort:Ele,threadId:TW,isMainThread:gW,workerData:hle}=require("worker_threads"),{onMessageFromWorkers:RW,broadcast:mle,broadcastWithAcknowledgement:AW}=Ke();TI.exports={sendItcEvent:OW,validateEvent:SI,SchemaEventMsg:bW,UserEventMsg:yW};var z_;RW(async(e,t)=>{z_=z_||kc(),SI(e),z_[e.type]&&await z_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function OW(e){return!gW&&e.message&&(e.message.originator=TW),AW(e)}a(OW,"sendItcEvent");function SI(e){if(typeof e!="object")return Vc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Tp.isEmpty(e.type))return Vc.MISSING_TYPE;if(!e.hasOwnProperty("message")||Tp.isEmpty(e.message))return Vc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Tp.isEmpty(e.message.originator))return Vc.MISSING_ORIGIN;if(SW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Vc.INVALID_EVENT(e.type)}a(SI,"validateEvent");function bW(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(bW,"SchemaEventMsg");function yW(e){this.originator=e}a(yW,"UserEventMsg")});var bn=g((gle,OI)=>{"use strict";var gI=L(),Tle=Q(),J_=$(),RI=Vy(),jo,{sendItcEvent:AI}=Ms();function NW(e){try{J_.trace("signalSchemaChange called with message:",e),jo=jo||kc();let t=new RI(gI.ITC_EVENT_TYPES.SCHEMA,e);return jo.schema(t),AI(t)}catch(t){J_.error(t)}}a(NW,"signalSchemaChange");function IW(e){try{J_.trace("signalUserChange called with message:",e),jo=jo||kc();let t=new RI(gI.ITC_EVENT_TYPES.USER,e);return jo.user(t),AI(t)}catch(t){J_.error(t)}}a(IW,"signalUserChange");OI.exports={signalSchemaChange:NW,signalUserChange:IW}});var X_=g((Ale,yI)=>{"use strict";var bI=Q(),wW=L(),CW=$(),DW=y_(),LW=b_(),MW=bn(),{SchemaEventMsg:UW}=Ms(),PW="already exists in";yI.exports=vW;async function vW(e,t,r){if(bI.isEmptyOrZeroLength(r))return r;let s=[];bI.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await BW(e,t.schema,t.name,i)})),n}a(vW,"lmdbCheckForNewAttributes");async function BW(e,t,r,s){let n=new LW(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await HW(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(PW))CW.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(BW,"createNewAttribute");async function HW(e){let t;return t=await DW(e),MW.signalSchemaChange(new UW(process.pid,wW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(HW,"createAttribute")});var Zo=g((ble,NI)=>{"use strict";var gp=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};NI.exports=gp});var wI=g((Nle,II)=>{"use strict";var xW=Zo(),GW=L().OPERATIONS_ENUM,Rp=class extends xW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(GW.INSERT,r,s,n,i),this.records=t}};II.exports=Rp});var DI=g((wle,CI)=>{"use strict";var qW=Zo(),FW=L().OPERATIONS_ENUM,Ap=class extends qW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(FW.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};CI.exports=Ap});var MI=g((Dle,LI)=>{"use strict";var kW=Zo(),VW=L().OPERATIONS_ENUM,Op=class extends kW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(VW.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};LI.exports=Op});var PI=g((Mle,UI)=>{"use strict";var $W=Zo(),YW=L().OPERATIONS_ENUM,bp=class extends $W{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(YW.DELETE,s,n,t,i),this.original_records=r}};UI.exports=bp});var $c=g((vle,xI)=>{"use strict";var Ple=require("path"),vI=We(),KW=wI(),WW=DI(),QW=MI(),zW=PI(),ea=ut(),BI=Q(),{CONFIG_PARAMS:JW}=L(),HI=ee();HI.initSync();var j_=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:XW}=Je();xI.exports=jW;async function jW(e,t){if(HI.get(JW.LOGGING_AUDITLOG)===!1)return;let r=XW(e.schema,e.table),s=await vI.openEnvironment(r,e.table,!0),n=ZW(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){vI.initializeDBIs(s,ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ea.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),BI.isEmpty(n.user_name)||s.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(jW,"writeTransaction");function ZW(e,t){let r=BI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===j_.INSERT)return new KW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.UPDATE)return new WW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.UPSERT)return new QW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.DELETE)return new zW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(ZW,"createTransactionObject")});var yp=g((xle,GI)=>{"use strict";var eQ=vc(),Hle=Bc(),Yc=L(),tQ=Hc(),rQ=$o().insertRecords,sQ=We(),nQ=$(),iQ=X_(),{getSchemaPath:oQ}=Je(),aQ=$c();GI.exports=cQ;async function cQ(e){try{let{schema_table:t,attributes:r}=eQ(e);tQ(e,r,t.hash_attribute),e.schema!==Yc.SYSTEM_SCHEMA_NAME&&(r.includes(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await iQ(e.hdb_auth_header,t,r),n=oQ(e.schema,e.table),i=await sQ.openEnvironment(n,e.table),o=await rQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await aQ(e,o)}catch(c){nQ.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(cQ,"lmdbCreateRecords")});var kI=g((qle,FI)=>{"use strict";var qI=L(),uQ=yp(),lQ=Bc(),_Q=require("fs-extra"),{getSchemaPath:dQ}=Je();FI.exports=fQ;async function fQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new lQ(qI.SYSTEM_SCHEMA_NAME,qI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await uQ(r),await _Q.mkdirp(dQ(e.schema))}a(fQ,"lmdbCreateSchema")});var $I=g((kle,VI)=>{"use strict";var Np=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};VI.exports=Np});var QI=g((Wle,WI)=>{"use strict";var YI=We(),Ip=Dr(),wp=Cr().LMDB_ERRORS_ENUM,EQ=ut(),KI=$(),$le=Q(),hQ=require("lmdb"),mQ=$I(),pQ=L(),{OVERFLOW_MARKER:Yle,MAX_SEARCH_KEY_LENGTH:Kle}=EQ,SQ=pQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function TQ(e,t,r,s){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 n=YI.listDBIs(e);YI.initializeDBIs(e,t,n);let i=new mQ,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||s&&h[SQ]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,hQ.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let T=n[S];if(!h.hasOwnProperty(T)||T===t)continue;let A=e.dbis[T],R=h[T];if(R!=null)try{let M=Ip.getIndexedValues(R);if(M)for(let x=0,P=M.length;x<P;x++)A.remove(M[x],o)}catch{KI.warn(`cannot delete from attribute: ${T}, ${R}:${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(n){throw n}}a(TQ,"deleteRecords");WI.exports={deleteRecords:TQ}});var Kc=g((zle,JI)=>{"use strict";var ta=Q(),gQ=QI(),RQ=We(),{getSchemaPath:AQ}=Je(),OQ=$c(),bQ=$();JI.exports=yQ;async function yQ(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(ta.isEmpty(s))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][s];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]={[s]:e.hash_values[c]}}let n=AQ(e.schema,e.table),i=await RQ.openEnvironment(n,e.table),o=await gQ.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await OQ(e,o)}catch(c){bQ.error(`unable to write transaction due to ${c.message}`)}return zI(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(yQ,"lmdbDeleteRecords");function zI(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(zI,"createDeleteResponse")});var Dp=g((jle,XI)=>{"use strict";var NQ=L(),Xle=Dr();function Cp(e,t){let r=Object.create(null);if(t.length===1&&NQ.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a(Cp,"parseRow");function IQ(e,t,r,s){let n=Cp(r,e);s.push(n)}a(IQ,"searchAll");function wQ(e,t,r,s){let n=Cp(r,e);s[t]=n}a(wQ,"searchAllToMap");function CQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(CQ,"iterateDBI");function Zi(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(Zi,"pushResults");function DQ(e,t,r,s,n,i){t.toString().endsWith(e)&&Zi(t,r,s,n,i)}a(DQ,"endsWith");function LQ(e,t,r,s,n,i){t.toString().includes(e)&&Zi(t,r,s,n,i)}a(LQ,"contains");function MQ(e,t,r,s,n,i){t>e&&Zi(t,r,s,n,i)}a(MQ,"greaterThanCompare");function UQ(e,t,r,s,n,i){t>=e&&Zi(t,r,s,n,i)}a(UQ,"greaterThanEqualCompare");function PQ(e,t,r,s,n,i){t<e&&Zi(t,r,s,n,i)}a(PQ,"lessThanCompare");function vQ(e,t,r,s,n,i){t<=e&&Zi(t,r,s,n,i)}a(vQ,"lessThanEqualCompare");XI.exports={parseRow:Cp,searchAll:IQ,searchAllToMap:wQ,iterateDBI:CQ,endsWith:DQ,contains:LQ,greaterThanCompare:MQ,greaterThanEqualCompare:UQ,lessThanCompare:PQ,lessThanEqualCompare:vQ,pushResults:Zi}});var ra=g((s_e,nw)=>{"use strict";var ci=We(),e_e=$(),qr=Dr(),Z_=ut(),_t=Cr().LMDB_ERRORS_ENUM,t_e=Q(),BQ=L(),ed=Dp(),{parseRow:HQ}=ed,r_e=require("lmdb"),{OVERFLOW_MARKER:jI,MAX_SEARCH_KEY_LENGTH:xQ}=Z_;function ZI(e,t,r,s=!1,n=void 0,i=void 0){return eo(e,t,r,(o,c)=>c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}a(ZI,"iterateFullIndex");function Wc(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,_=!1){return eo(e,t,r,(l,d,f,E)=>{let A={transaction:l,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(A.values=!1,d.getRange(A).map(R=>({value:R}))):d.getRange(A)})}a(Wc,"iterateRangeBetween");function eo(e,t,r,s){let n=e.database||e,i=ci.openDBI(n,r);i[Z_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ci.openDBI(n,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=s(o,i,n,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(eo,"setupTransaction");function ew(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(jI)){if(!n)if(r)n=ci.openDBI(e,r);else{let u=ci.listDBIs(e);for(let _=0,l=u.length;_<l&&(n=ci.openDBI(e,u[_]),!n[Z_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(ew,"getOverflowCheck");function GQ(e,t,r,s=!1,n=void 0,i=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return eo(e,t,t,(o,c,u)=>(td(r),r=Qc(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(_=>HQ(_.value,r))))}a(GQ,"searchAll");function qQ(e,t,r,s=!1,n=void 0,i=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);td(r),r=Qc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of ZI(e,t,t,s,n,i))o.set(c,ed.parseRow(u,r));return o}a(qQ,"searchAllToMap");function FQ(e,t,r=!1,s=void 0,n=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=ZI(e,void 0,t,r,s,n),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(FQ,"iterateDBI");function kQ(e,t){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return ci.statDBI(e,t).entryCount}a(kQ,"countAll");function VQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ui(e,r,s),eo(e,t,r,(c,u,_,l)=>(s=qr.convertKeyValueToWrite(s),l===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(VQ,"equals");function $Q(e,t,r){return ui(e,t,r),ci.openDBI(e,t).getValuesCount(r)}a($Q,"count");function YQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ui(e,r,s),eo(e,null,r,(c,u)=>{s=qr.convertKeyValueToWrite(s);let _=!0;typeof s=="number"&&(_=!1);let l;if(n===!0){let d;for(let f of u.getKeys({transaction:c,start:s}))if(!f.startsWith(s)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(s))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(YQ,"startsWith");function KQ(e,t,r,s,n=!1,i=void 0,o=void 0){return tw(e,t,r,s,n,i,o,!0)}a(KQ,"endsWith");function tw(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return ui(e,r,s),eo(e,null,r,(u,_,l,d)=>{let f=ew(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(E=>{let h=E.toString();return h.endsWith(jI)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(s):S.includes(s))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(s):h.includes(s))?_[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 WQ(e,t,r,s,n=!1,i=void 0,o=void 0){ui(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Wc(e,t,r,s,u,n,i,o,!0,!1)}a(WQ,"greaterThan");function QQ(e,t,r,s,n=!1,i=void 0,o=void 0){ui(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Wc(e,t,r,s,u,n,i,o,!1,!1)}a(QQ,"greaterThanEqual");function zQ(e,t,r,s,n=!1,i=void 0,o=void 0){ui(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Wc(e,t,r,u,s,n,i,o,!1,!0)}a(zQ,"lessThan");function JQ(e,t,r,s,n=!1,i=void 0,o=void 0){ui(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Wc(e,t,r,u,s,n,i,o,!1,!1)}a(JQ,"lessThanEqual");function XQ(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(qr.validateEnv(e),r===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(_t.START_VALUE_REQUIRED);if(n===void 0)throw new Error(_t.END_VALUE_REQUIRED);if(s=qr.convertKeyValueToWrite(s),n=qr.convertKeyValueToWrite(n),s>n)throw new Error(_t.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Wc(e,t,r,s,n,i,o,c)}a(XQ,"between");function jQ(e,t,r,s){qr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(td(r),r=Qc(n,r),s===void 0)throw new Error(_t.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=ed.parseRow(c,r)),o}a(jQ,"searchByHash");function ZQ(e,t,r){qr.validateEnv(e);let s=e.database||e,n=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 s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(ZQ,"checkHashExists");function ez(e,t,r,s,n=[]){return sw(e,t,r,s,n),rw(e,t,r,s,n).map(i=>i[1])}a(ez,"batchSearchByHash");function tz(e,t,r,s,n=[]){sw(e,t,r,s,n);let i=new Map;for(let[o,c]of rw(e,t,r,s,n))i.set(o,c);return i}a(tz,"batchSearchByHashToMap");function rw(e,t,r,s,n=[]){return eo(e,t,t,(i,o,c)=>{r=Qc(c,r);let u=r.length<3;return s.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,ed.parseRow(l,r)];n.push(_)}).filter(_=>_)})}a(rw,"batchHashSearch");function sw(e,t,r,s,n){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(td(r),s==null)throw new Error(_t.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(_t.IDS_MUST_BE_ITERABLE)}a(sw,"initializeBatchSearchByHash");function td(e){if(!Array.isArray(e))throw e===void 0?new Error(_t.FETCH_ATTRIBUTES_REQUIRED):new Error(_t.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(td,"validateFetchAttributes");function ui(e,t,r){if(qr.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>xQ)throw new Error(_t.SEARCH_VALUE_TOO_LARGE)}a(ui,"validateComparisonFunctions");function Qc(e,t){return t.length===1&&BQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ci.listDBIs(e)),t}a(Qc,"setGetWholeRowAttributes");nw.exports={searchAll:GQ,searchAllToMap:qQ,count:$Q,countAll:kQ,equals:VQ,startsWith:YQ,endsWith:KQ,contains:tw,searchByHash:jQ,setGetWholeRowAttributes:Qc,batchSearchByHash:ez,batchSearchByHashToMap:tz,checkHashExists:ZQ,iterateDBI:FQ,greaterThan:WQ,greaterThanEqual:QQ,lessThan:zQ,lessThanEqual:JQ,between:XQ}});var sa=g((i_e,uw)=>{var iw=require("lodash"),ow=Xe(),fe=require("joi"),rz=Q(),{hdb_schema_table:zc,checkValidTable:aw,hdb_table:cw,hdb_database:rd}=Js(),{handleHDBError:sz,hdb_errors:nz}=se(),{getDatabases:iz}=(Re(),ie(Fe)),{HTTP_STATUS_CODES:oz}=nz,az=fe.object({database:rd,schema:rd,table:cw,search_attribute:zc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(zc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),cz=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(zc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(zc,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(zc,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,az);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;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"),n&&(r=new Error(n.trim()));break;case"conditions":r=ow.validateBySchema(e,cz);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=rz.checkGlobalSchemaTable(e.schema,e.table);if(n)return sz(new Error,n,oz.NOT_FOUND);let o=iz()[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=g((a_e,lw)=>{"use strict";var uz=We(),lz=sa(),{getSchemaPath:_z}=Je();lw.exports=dz;function dz(e){let t=lz(e,"hashes");if(t)throw t;let r=_z(e.schema,e.table);return uz.openEnvironment(r,e.table)}a(dz,"initialize")});var Mp=g((u_e,_w)=>{"use strict";var fz=ra(),Ez=Lp();_w.exports=hz;async function hz(e){let t=await Ez(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return fz.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(hz,"lmdbGetDataByHash")});var na=g((__e,dw)=>{"use strict";var Up=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};dw.exports=Up});var Ew=g((E_e,fw)=>{"use strict";var f_e=na(),mz=ra(),pz=Lp();fw.exports=Sz;async function Sz(e){let t=await pz(e),r=global.hdb_schema[e.schema][e.table];return mz.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(Sz,"lmdbSearchByHash")});var tn=g((m_e,hw)=>{"use strict";var Pp=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};hw.exports=Pp});var sd=g((S_e,Rw)=>{"use strict";var Xt=ra(),Tz=We(),gz=Q(),Ee=ut(),to=L(),Rz=ki(),mw=Cr().LMDB_ERRORS_ENUM,{getSchemaPath:Az}=Je(),yn=to.SEARCH_WILDCARDS;async function Oz(e,t,r){let s;e.schema===to.SYSTEM_SCHEMA_NAME?s=Rz[e.table]:s=global.hdb_schema[e.schema][e.table];let n=gw(e,s.hash_attribute,r,t);return Sw(e,n,s.hash_attribute,r)}a(Oz,"prepSearch");async function Sw(e,t,r,s){let n=Az(e.schema,e.table),i=await Tz.openEnvironment(n,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(bz(e,r)===!1){let l=e.search_attribute;if(l===r)return s?pw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?pw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?Xt.batchSearchByHashToMap(c,r,e.get_attributes,_):Xt.batchSearchByHash(c,r,e.get_attributes,_)}a(Sw,"executeSearch");function Tw(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:n=Xt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:n=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:n=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:n=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,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Xt.searchAllToMap(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:n=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:n=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:n=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:n=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:n=Xt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(Tw,"searchByType");function pw(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(pw,"createMapFromIterable");function bz(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(bz,"checkToFetchMore");function gw(e,t,r,s){if(gz.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),yn.indexOf(n)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(yn[0])<0&&n.indexOf(yn[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(yn.indexOf(i)>=0&&yn.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(yn.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(yn.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(n.includes(yn[0])||n.includes(yn[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(mw.UNKNOWN_SEARCH_TYPE)}else switch(s){case to.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case to.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case to.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case to.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case to.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:Oz,searchByType:Tw}});var Ow=g((R_e,Aw)=>{"use strict";var g_e=tn(),yz=sa(),Nz=Q(),Iz=L(),wz=sd();Aw.exports=Cz;function Cz(e,t){if(!Nz.isEmpty(t)&&Iz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=yz(e,"value");if(s)throw s;return wz.prepSearch(e,t,!0)}a(Cz,"lmdbGetDataByValue")});var Jc=g((b_e,bw)=>{"use strict";var O_e=tn(),Dz=sa(),Lz=Q(),Mz=L(),Uz=sd();bw.exports=Pz;async function Pz(e,t){if(!Lz.isEmpty(t)&&Mz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=Dz(e,"value");if(s)throw s;return Uz.prepSearch(e,t,!1)}a(Pz,"lmdbSearchByValue")});var Nw=g((I_e,yw)=>{"use strict";var N_e=ut(),vp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}},Bp=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Hp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};yw.exports={SearchByConditionsObject:vp,SearchCondition:Bp,SortAttribute:Hp}});var Lw=g((L_e,Dw)=>{"use strict";var C_e=Nw().SearchByConditionsObject,vz=tn(),Bz=sa(),xp=ra(),nd=ut(),{Resource:D_e}=(Ns(),ie(Gp)),Cw=sd(),Hz=Dp(),xz=require("lodash"),{getSchemaPath:Gz}=Je(),Iw=We(),{handleHDBError:qz,hdb_errors:Fz}=se(),{HTTP_STATUS_CODES:kz}=Fz,Vz=1e8;Dw.exports=$z;async function $z(e){let t=Bz(e,"conditions");if(t)throw qz(t,t.message,kz.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=Gz(e.schema,e.table),s=await Iw.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Iw.openDBI(s,_.search_attribute);let i=xz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===nd.SEARCH_TYPES.EQUALS?_.estimated_count=xp.count(s,_.search_attribute,_.search_value):l===nd.SEARCH_TYPES.CONTAINS||l===nd.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=Vz}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await ww(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=s.dbis[n.hash_attribute],l=i.slice(1).map(Cw.filterByType),d=l.length,f=xp.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>Hz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await ww(o,e,f,n.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=xp.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a($z,"lmdbSearchByConditions");async function ww(e,t,r,s){let n=new vz(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===nd.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,Cw.searchByType(e,n,i,s).map(o=>o.value)}a(ww,"executeConditionSearch")});var ia=g((U_e,Mw)=>{"use strict";var Yz=L().OPERATIONS_ENUM,qp=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=Yz.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};Mw.exports=qp});var Fp=g((v_e,qw)=>{"use strict";var Bw=tn(),Hw=ia(),xw=Jc(),Gw=Kc(),_r=L(),Uw=Q(),Pw=We(),{getTransactionAuditStorePath:Kz,getSchemaPath:Wz}=Je(),vw=$();qw.exports=Qz;async function Qz(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 zz(e),await Jz(e);let t=Wz(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=Kz(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(Qz,"lmdbDropTable");async function zz(e){let t=new Bw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await xw(t)),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new Hw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await Gw(n)}a(zz,"deleteAttributesFromSystem");async function Jz(e){let t=new Bw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;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&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new Hw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await Gw(n)}catch(i){throw i}}a(Jz,"dropTableFromSystem")});var kw=g((H_e,Fw)=>{"use strict";var Xz=require("fs-extra"),jz=tn(),Zz=na(),e2=ia(),t2=Fp(),r2=Kc(),s2=Mp(),n2=Jc(),Nn=L(),{getSchemaPath:i2}=Je(),{handleHDBError:o2,hdb_errors:a2}=se(),{HDB_ERROR_MSGS:c2,HTTP_STATUS_CODES:u2}=a2;Fw.exports=l2;async function l2(e){let t;try{t=await _2(e.schema);let r=new jz(Nn.SYSTEM_SCHEMA_NAME,Nn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Nn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Nn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await n2(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await t2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new e2(Nn.SYSTEM_SCHEMA_NAME,Nn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await r2(n);let i=i2(t);await Xz.remove(i)}catch(r){throw r}}a(l2,"lmdbDropSchema");async function _2(e){let t=new Zz(Nn.SYSTEM_SCHEMA_NAME,Nn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Nn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await s2(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw o2(new Error,c2.SCHEMA_NOT_FOUND(e),u2.NOT_FOUND,void 0,void 0,!0);return s}a(_2,"validateDropSchema")});var id=g((G_e,Vw)=>{"use strict";var kp=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};Vw.exports=kp});var Yw=g((k_e,$w)=>{"use strict";var d2=require("fs-extra"),od=We(),{getTransactionAuditStorePath:f2}=Je(),Vp=ut(),F_e=id();$w.exports=E2;async function E2(e){let t;try{let r=f2(e.schema,e.table);await d2.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(E2,"createTransactionsAuditEnvironment")});var zw=g(($_e,Qw)=>{"use strict";var $p=L(),Kw=We(),h2=$o(),{getSystemSchemaPath:m2,getSchemaPath:p2}=Je(),S2=ki(),T2=y_(),Yp=b_(),g2=$(),R2=Yw(),Wp=S2.hdb_table,Ww=[];for(let e=0;e<Wp.attributes.length;e++)Ww.push(Wp.attributes[e].attribute);Qw.exports=A2;async function A2(e,t){let r=p2(t.schema,t.table),s=new Yp(t.schema,t.table,$p.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=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(m2(),$p.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await h2.insertRecords(o,Wp.hash_attribute,Ww,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Kp(s),await Kp(n),await Kp(i)}await R2(t)}catch(o){throw o}}a(A2,"lmdbCreateTable");async function Kp(e){try{await T2(e)}catch(t){g2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Kp,"createAttribute")});var Xw=g((K_e,Jw)=>{"use strict";var O2=vc(),b2=Hc(),y2=X_(),Xc=L(),N2=$o().updateRecords,I2=We(),{getSchemaPath:w2}=Je(),C2=$c(),D2=$();Jw.exports=L2;async function L2(e){try{let{schema_table:t,attributes:r}=O2(e);b2(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 s=await y2(e.hdb_auth_header,t,r),n=w2(e.schema,e.table),i=await I2.openEnvironment(n,e.table),o=await N2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await C2(e,o)}catch(c){D2.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(L2,"lmdbUpdateRecords")});var Zw=g((Q_e,jw)=>{"use strict";var M2=L().OPERATIONS_ENUM,Qp=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=M2.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};jw.exports=Qp});var tC=g((X_e,eC)=>{"use strict";var J_e=Zw(),U2=vc(),P2=Hc(),v2=X_(),jc=L(),B2=$o().upsertRecords,H2=We(),{getSchemaPath:x2}=Je(),G2=$c(),q2=$(),{handleHDBError:F2,hdb_errors:k2}=se();eC.exports=V2;async function V2(e){let t;try{t=U2(e)}catch(u){throw F2(u,u.message,k2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;P2(e,s,r.hash_attribute),e.schema!==jc.SYSTEM_SCHEMA_NAME&&(s.includes(jc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(jc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(jc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(jc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await v2(e.hdb_auth_header,r,s),i=x2(e.schema,e.table),o=await H2.openEnvironment(i,e.table),c=await B2(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await G2(e,c)}catch(u){q2.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(V2,"lmdbUpsertRecords")});var sC=g((Z_e,rC)=>{"use strict";var zp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};rC.exports=zp});var iC=g((tde,nC)=>{"use strict";var Jp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};nC.exports=Jp});var cC=g((nde,aC)=>{"use strict";var Xp=We(),{getTransactionAuditStorePath:$2}=Je(),sde=sC(),Zc=ut(),Y2=Q(),oC=iC(),K2=require("util").promisify,W2=K2(setTimeout),Q2=1e4,z2=100;aC.exports=J2;async function J2(e){let t=$2(e.schema,e.table),r=await Xp.openEnvironment(t,e.table,!0),s=Xp.listDBIs(r);Xp.initializeDBIs(r,Zc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new oC;do n=await X2(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await W2(z2);while(n.transactions_deleted>0);return i}a(J2,"deleteAuditLogsBefore");async function X2(e,t){let r=new oC;try{let s=e.dbis[Zc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[Zc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];Y2.isEmpty(c)||(n=e.dbis[Zc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Zc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>Q2)break}return await n,r}catch(s){throw s}}a(X2,"deleteTransactions")});var lC=g((ode,uC)=>{"use strict";var jp=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};uC.exports=jp});var dC=g((ude,_C)=>{"use strict";var j2=tn(),Z2=ia(),cde=lC(),rn=L(),eJ=Q(),Zp=We(),tJ=ki(),rJ=Jc(),sJ=Kc(),{getSchemaPath:nJ}=Je();_C.exports=iJ;async function iJ(e,t=!0){let r;e.schema===rn.SYSTEM_SCHEMA_NAME?r=tJ[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await aJ(e),n=nJ(e.schema,e.table),i=await Zp.openEnvironment(n,e.table);return t===!0&&await oJ(e,i,r.hash_attribute),Zp.dropDBI(i,e.attribute),s}a(iJ,"lmdbDropAttribute");async function oJ(e,t,r){let s=Zp.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);n=t.dbis[r].put(o,_,u)}await n}a(oJ,"removeAttributeFromAllObjects");async function aJ(e){let t=new j2(rn.SYSTEM_SCHEMA_NAME,rn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await rJ(t)).filter(o=>o[rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(eJ.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new Z2(rn.SYSTEM_SCHEMA_NAME,rn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return sJ(i)}a(aJ,"dropAttributeFromSystem")});var SC=g((dde,pC)=>{"use strict";var eS=We(),oa=ut(),_de=Dr(),tS=L(),fC=Q(),{getTransactionAuditStorePath:cJ}=Je(),uJ=ra(),ad=Zo(),lJ=$();pC.exports=_J;async function _J(e){let t=cJ(e.schema,e.table),r=await eS.openEnvironment(t,e.table,!0),s=eS.listDBIs(r);eS.initializeDBIs(r,oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;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 n=global.hdb_schema[e.schema][e.table].hash_attribute,fJ(r,e.search_values,n);case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return dJ(r,e.search_values);default:return EC(r)}}a(_J,"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],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new ad,n))}a(EC,"searchTransactionsByTimestamp");function dJ(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[oa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,mC(e,i))}return Object.fromEntries(r)}a(dJ,"searchTransactionsByUsername");function fJ(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=uJ.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);s.has(f)?s.get(f).push(_.toString()):s.set(f,[_.toString()])}}let n=Array.from(s.keys()),i=mC(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);hC(u,"records",r,l,o),hC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(fJ,"searchTransactionsByHashValues");function hC(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let _=n.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new 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],n.set(u,[_])}}}a(hC,"loopRecords");function mC(e,t){let r=[];try{let s=e.dbis[oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new ad,i);r.push(o)}}catch(i){lJ.warn(i)}return r}catch(s){throw s}}a(mC,"batchSearchTransactions")});var gC=g((mde,TC)=>{"use strict";var{getSchemaPath:Ede}=Je(),hde=We(),{database:EJ}=(Re(),ie(Fe));TC.exports={writeTransaction:hJ};async function hJ(e,t,r){return EJ({database:e,table:t}).transaction(r)}a(hJ,"writeTransaction")});var bC=g((Sde,OC)=>{"use strict";var{getSchemaPath:RC}=Je(),AC=We();OC.exports={flush:mJ,resetReadTxn:pJ};async function mJ(e,t){return(await AC.openEnvironment(RC(e,t),t.toString())).flushed}a(mJ,"flush");async function pJ(e,t){try{(await AC.openEnvironment(RC(e,t),t.toString())).resetReadTxn()}catch{}}a(pJ,"resetReadTxn")});var wC=g((gde,IC)=>{"use strict";var{Readable:SJ}=require("stream"),{getDatabases:TJ}=(Re(),ie(Fe)),{readSync:gJ,openSync:RJ,createReadStream:yC}=require("fs"),{open:AJ}=require("lmdb"),NC=wc(),OJ=Cc(),{AUDIT_STORE_OPTIONS:bJ}=(ei(),ie(CC)),{INTERNAL_DBIS_NAME:yJ,AUDIT_STORE_NAME:NJ}=ut();IC.exports=wJ;var rS=32768,IJ=100;async function wJ(e){let t=e.database||e.schema||"data",r=TJ()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let _=r[n[0]];if(!_)throw new Error(`Can not find table ${n[0]}`);let l=_.dbisDB,d=AJ({noSync:!0,maxDbs:OJ.MAX_DBS}),f,E=d.openDB(yJ,new NC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(A,R){R.encoding="binary",R.encoder=void 0;let M=d.openDB(A,R),x=l.openDB(A,R);for(let{key:P,version:k,value:B}of x.getRange({start:null,transaction:h,versions:x.useVersions}))f=M.put(P,B,k),p++%IJ===0&&(await new Promise(X=>setTimeout(X,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:R}of l.getRange({transaction:h,start:!1}))if(n.some(M=>A.startsWith?.(M+"/"))){E.put(A,R);let[,M]=A.split("/"),x=!M,P=new NC(!x,x);await S(A,P)}e.include_audit&&await S(NJ,Object.assign({},bJ)),await f;let T=yC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=RJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(rS);gJ(c,_,0,rS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=yC(null,{fd:c,start:rS}),f=new SJ.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",s),_}}a(wJ,"getBackup")});var MC=g((Ade,LC)=>{"use strict";var CJ=$(),{handleHDBError:DJ}=se(),LJ=Yb(),MJ=y_(),UJ=yp(),PJ=kI(),vJ=Kc(),BJ=Mp(),HJ=Ew(),xJ=Ow(),GJ=Jc(),qJ=Lw(),FJ=kw(),kJ=zw(),VJ=Xw(),$J=tC(),YJ=cC(),KJ=Fp(),WJ=dC(),QJ=SC(),zJ=gC(),DC=bC(),JJ=wC(),sS=class extends LJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return qJ(t)}async getDataByHash(t){return await BJ(t)}async searchByHash(t){return await HJ(t)}async getDataByValue(t,r){return await xJ(t,r)}async searchByValue(t){return await GJ(t)}async createSchema(t){return await PJ(t)}async dropSchema(t){return await FJ(t)}async createTable(t,r){return await kJ(t,r)}async dropTable(t){return await KJ(t)}async createAttribute(t){return await MJ(t)}async createRecords(t){return await UJ(t)}async updateRecords(t){return await VJ(t)}async upsertRecords(t){try{return await $J(t)}catch(r){throw DJ(r,null,null,CJ.ERR,r)}}async deleteRecords(t){return await vJ(t)}async dropAttribute(t){return await WJ(t)}async deleteAuditLogsBefore(t){return await YJ(t)}async readAuditLog(t){return await QJ(t)}writeTransaction(t,r,s){return zJ.writeTransaction(t,r,s)}flush(t,r){return DC.flush(t,r)}resetReadTxn(t,r){return DC.resetReadTxn(t,r)}getBackup(t){return JJ(t)}};LC.exports=sS});function t4(){e4=setInterval(function(){for(let e of nS)if(e.stale){let t=e[ye]?.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},ZJ).unref()}var iS,PC,vC,XJ,nS,jJ,eu,UC,ro,cd,ZJ,e4,oS=ge(()=>{iS=v(Dr()),PC=v(se()),vC=v($());Ns();XJ=100,nS=new Set,jJ=25e3,ro=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;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),nS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(nS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(eu&&performance.now()-UC>jJ)throw new PC.ServerError("Outstanding write transactions have too long of queue, please try again later",503)}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 s=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let T=S();E?E.push?E.push(T):E=[E,T]:E=T}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}s||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let n,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,s)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){s>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);n=n||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<XJ>>s?u():n=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),n)return eu||(eu=n,UC=performance.now(),eu.then(()=>{eu=null})),n.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=s+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},cd=class extends ro{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,iS.getNextMonotonicTime)())}getReadTxn(){}},ZJ=3e4;a(t4,"startMonitoringTxns");t4()});function je(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 s=e.transaction=new ro;e.timestamp&&(s.timestamp=e.timestamp),s[ye]=e,e.resourceCache||(e.resourceCache=[]);let n;try{if(n=t(s),n?.then)return n.then(i,o)}catch(c){o(c)}return i(n);function i(c){let u=s.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw s.abort({}),c}}var BC,so=ge(()=>{BC=require("../index");Ns();oS();a(je,"transaction");(0,BC._assignPackageExport)("transaction",je);je.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};je.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var YC={};qe(YC,{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 xC(e,t){let r=sn(e),s=lS(e,r);if(!r)throw new Us.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user},o;je(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:n,select:s},i);return l=l&&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 sn(e){let t=e.database||e.schema||s4,r=dr()[t];if(!r)throw(0,Us.handleHDBError)(new Error,r4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function GC(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*qC(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(o),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[o],records:[u]})}s&&(yield s)}var FC,ud,Us,kC,VC,Ps,aS,cS,$C,r4,s4,n4,i4,HC,uS,KC=ge(()=>{"use strict";FC=v(MC()),ud=v(sa()),Us=v(se());Re();kC=v(vc()),VC=v(Hc()),Ps=v(L()),aS=v(bn()),cS=v(Ms()),$C=v(Q());so();_d();({HDB_ERROR_MSGS:r4}=Us.hdb_errors),s4="data",n4=1e4,i4=10,uS=class extends FC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),HC=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,Us.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=sn(t);if(!s)throw new Us.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:lS(t,s),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let o of s)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Us.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}lt({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await sn(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=sn(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=a((o,c,u)=>(c=Object.assign({},c),delete c[s],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))n=i(o,c,u),await new Promise(_=>setImmediate(_));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){sn(t).dropTable()}createSchema(t){return tu({database:t.schema,table:null}),aS.signalSchemaChange(new cS.SchemaEventMsg(process.pid,Ps.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await _S(t.schema),aS.signalSchemaChange(new cS.SchemaEventMsg(process.pid,Ps.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,HC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,kC.default)(t);(0,VC.default)(t,s,r.primaryKey);let n,i=dr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return je(o,async c=>{if(!i.schemaDefined){n=[];for(let l of s)i.attributes.find(f=>f.name==l)||n.push(l);n.length>0&&await i.addAttributes(n.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=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:n,skipped_hashes:_}})}async deleteRecords(t){let r=dr()[t.schema][t.table],s={user:t.hdb_user};return je(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,s)?o.push(u):c.push(u);return GC(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=dr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Us.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Ps.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,$C.async_set_timeout)(i4),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%n4===0&&await _();return u.length>0&&await _(),n?GC(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 xC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of xC(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&Ps.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let s=(0,ud.default)(t,"value");if(s)throw s;let n=sn(t);if(!n)throw new Us.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===Ps.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:lS(t,n)})}async getDataByValue(t,r){let s=new Map,n=sn(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){sn({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return sn(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=sn(t),s={};switch(t.search_type){case Ps.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case Ps.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of qC(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return qC(r,t.search_values?.[0],t.search_values?.[1])}}};a(lS,"getSelect");a(xC,"getRecords");a(sn,"getTable");a(GC,"createDeleteResponse");a(qC,"groupRecordsInHistory")});var Cs=g((Hde,WC)=>{"use strict";var{ResourceBridge:o4}=(KC(),ie(YC)),a4=ee();a4.initSync();var dd;function c4(){return dd||(dd=new o4,dd)}a(c4,"getBridge");WC.exports=c4()});var XC=g((Gde,JC)=>{"use strict";var QC=require("lodash"),ru=require("mathjs"),u4=require("jsonata"),zC=Q();JC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?QC.uniqWith(e,QC.isEqual):e,searchJSON:l4,mad:su.bind(null,ru.mad),mean:su.bind(null,ru.mean),mode:su.bind(null,ru.mode),prod:su.bind(null,ru.prod),median:su.bind(null,ru.median)};function su(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(su,"aggregateFunction");function l4(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 s=u4(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(l4,"searchJSON")});var ZC=g((Fde,jC)=>{"use strict";var pt=require("moment"),dS="YYYY-MM-DDTHH:mm:ss.SSSZZ";pt.suppressDeprecationWarnings=!0;jC.exports={current_date:()=>pt().utc().format("YYYY-MM-DD"),current_time:()=>pt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return pt(e).utc().format("YYYY");case"month":return pt(e).utc().format("MM");case"day":return pt(e).utc().format("DD");case"hour":return pt(e).utc().format("HH");case"minute":return pt(e).utc().format("mm");case"second":return pt(e).utc().format("ss");case"millisecond":return pt(e).utc().format("SSS");default:break}},date:e=>pt(e).utc().format(dS),date_format:(e,t)=>pt(e).utc().format(t),date_add:(e,t,r)=>pt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>pt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=pt(e).utc(),n=pt(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>pt().utc().valueOf(),get_server_time:()=>pt().format(dS),offset_utc:(e,t)=>pt(e).utc().utcOffset(t).format(dS)}});var sD=g((kde,rD)=>{"use strict";var _4=require("@turf/area"),d4=require("@turf/length"),f4=require("@turf/circle"),E4=require("@turf/difference"),h4=require("@turf/distance"),m4=require("@turf/boolean-contains"),p4=require("@turf/boolean-equal"),S4=require("@turf/boolean-disjoint"),T4=require("@turf/helpers"),eD=L(),Se=Q(),In=$();rD.exports={geoArea:g4,geoLength:R4,geoCircle:A4,geoDifference:O4,geoDistance:tD,geoNear:b4,geoContains:y4,geoEqual:N4,geoCrosses:I4,geoConvert:w4};function g4(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return _4.default(e)}catch(t){return In.trace(t,e),NaN}}a(g4,"geoArea");function R4(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return d4.default(e,{units:t||"kilometers"})}catch(r){return In.trace(r,e),NaN}}a(R4,"geoLength");function A4(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return f4.default(e,t,{units:r||"kilometers"})}catch(s){return In.trace(s,e,t),NaN}}a(A4,"geoCircle");function O4(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return E4(e,t)}catch(r){return In.trace(r,e,t),NaN}}a(O4,"geoDifference");function tD(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return h4.default(e,t,{units:r||"kilometers"})}catch(s){return In.trace(s,e,t),NaN}}a(tD,"geoDistance");function b4(e,t,r,s){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return tD(e,t,s)<=r}catch(n){return In.trace(n,e,t),!1}}a(b4,"geoNear");function y4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return m4.default(e,t)}catch(r){return In.trace(r,e,t),!1}}a(y4,"geoContains");function N4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return p4.default(e,t)}catch(r){return In.trace(r,e,t),!1}}a(N4,"geoEqual");function I4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return!S4.default(e,t)}catch(r){return In.trace(r,e,t),!1}}a(I4,"geoCrosses");function w4(e,t,r){if(Se.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Se.isEmpty(t))throw new Error("geo_type is required");if(Se.isEmpty(eD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(eD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),T4[t](e,r)}a(w4,"geoConvert")});var fd=g(($de,nD)=>{var no=XC(),Fr=ZC(),nn=sD();nD.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=Fr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Fr.current_time,e.fn.extract=e.fn.EXTRACT=Fr.extract,e.fn.date=e.fn.DATE=Fr.date,e.fn.date_format=e.fn.DATE_FORMAT=Fr.date_format,e.fn.date_add=e.fn.DATE_ADD=Fr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Fr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Fr.date_diff,e.fn.now=e.fn.NOW=Fr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Fr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Fr.get_server_time,e.fn.getdate=e.fn.GETDATE=Fr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Fr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=nn.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=nn.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=nn.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=nn.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=nn.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=nn.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=nn.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=nn.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=nn.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=nn.geoNear}});var cD=g((Yde,aD)=>{"use strict";var nu=require("lodash"),fr=require("alasql");fr.options.cache=!1;var C4=fd(),iD=require("clone"),Ed=require("recursive-iterator"),le=$(),Ce=Q(),aa=Cs(),D4=L(),{hdb_errors:L4}=se(),{getDatabases:oD}=(Re(),ie(Fe)),M4="IS NULL",vs="There was a problem performing this search. Please check the logs and try again.";C4(fr);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 s=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(s))return le.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw le.error("Error thrown from checkEmptySQL in SQLSearch class method search."),le.error(s),new Error(vs)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw le.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),le.error(s),new Error(vs)}if(Object.keys(this.data).length===0)return le.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw le.error("Error thrown from processJoins in SQLSearch class method search."),le.error(s),new Error(vs)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw le.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),le.error(s),new Error(vs)}try{return t=await this._finalSQL(),t}catch(s){throw le.error("Error thrown from finalSQL in SQLSearch class method search."),le.error(s),new Error(vs)}}_getColumns(){let t=new Ed(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(iD(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=nu.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=oD()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__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 s=Ce.autoCast(r.right.value);[!0,!1].indexOf(s)>=0&&(r.right=new fr.yy.LogicValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=Ce.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new fr.yy.LogicValue({value:i}):s instanceof fr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new fr.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 s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ce.isEmpty(D4.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)?s.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)s.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&nu.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(Ce.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);Ce.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(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 fr.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 s=this._findColumn(r);s&&this.fetch_attributes.push(iD(s))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(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(M4)>-1&&this.tables.forEach(n=>{let i={columnid:oD()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=nu.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,_=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!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]=[...s[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(vs)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await aa.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(vs)}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]=[...s[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]):(this.data[i].__merged_data[p]=[...s[i]],this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),le.error(l),new Error(vs)}else try{c.search_attribute=n.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]=[...s[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),le.error(l),new Error(vs)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof fr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new fr.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new fr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let n=t.is_func?new fr.yy.FuncValue:new fr.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,n);f=await fr.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=nu.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 s=[],n=new Ed(this.columns);for(let{node:i}of n)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&s.push(o)}}s=nu.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw le.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),le.error(i),new Error(vs)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await aa.getDataByHash(c),_=n.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=n.columns[h],S=E[p]===void 0?null:E[p];this.data[s].__merged_data[f].push(S)}}}}catch(r){throw 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(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let s;try{let n=this._buildSQL();le.trace(`Final SQL: ${n}`),s=await fr.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),le.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw le.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),le.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return le.error(L4.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(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=n[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;s=s.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;s=s.replace(u,_)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await aa.getDataByValue(i);for(let[c,u]of o)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(o){throw le.error("There was an error when processing this SQL operation. Check your logs"),le.error(o),new Error(vs)}}return Object.values(Object.values(this.data)[0].__merged_data)}};aD.exports=fS});var Pr=g((Wde,uD)=>{"use strict";var U4=Vb();uD.exports={searchByConditions:v4,searchByHash:B4,searchByValue:H4,search:x4};var ES=Cs(),{transformReq:hS}=Q(),P4=cD();async function v4(e){return hS(e),ES.searchByConditions(e)}a(v4,"searchByConditions");async function B4(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(B4,"searchByHash");async function H4(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(H4,"searchByValue");function x4(e,t){try{let r=new U4(e);r.validate(),new P4(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(x4,"search")});var hd=g((zde,lD)=>{"use strict";var G4=Cs();lD.exports={writeTransaction:q4};function q4(e,t,r){return G4.writeTransaction(e,t,r)}a(q4,"writeTransaction")});var ED=g((jde,fD)=>{"use strict";var F4=Pr(),k4=On(),_D=$(),V4=vr(),Xde=hd(),$4=require("clone"),pS=require("alasql"),Y4=fd(),dD=require("util"),K4=dD.promisify(k4.getTableSchema),W4=dD.promisify(F4.search),Q4=L(),mS=Q();Y4(pS);fD.exports={update:J4};var z4="There was a problem performing this update. Please check the logs and try again.";async function J4({statement:e,hdb_user:t}){let r=await K4(e.table.databaseid,e.table.tableid),s=X4(e.columns);mS.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=$4(n),c=mS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=pS.parse(u).statements[0],l=await W4(_),d=j4(s,l);return Z4(o,d,t)}a(J4,"update");function X4(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 [${Q4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw _D.error(t),new Error(z4)}}a(X4,"createUpdateRecord");function j4(e,t){return mS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(j4,"buildUpdateRecords");async function Z4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await V4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){_D.error(`Error delete new_attributes from update response: ${i}`)}return n}a(Z4,"updateRecords")});var mD=g((rfe,hD)=>{var e3=require("alasql"),t3=Pr(),r3=$(),s3=Cs(),TS=require("util"),SS=Q(),n3=L(),i3=On(),efe=hd(),tfe=vr(),o3="record",a3="successfully deleted",c3=TS.callbackify(d3),u3=TS.promisify(t3.search),l3=TS.promisify(i3.getTableSchema);hD.exports={convertDelete:c3};function _3(e){return`${e.deleted_hashes.length} ${o3}${e.deleted_hashes.length===1?"":"s"} ${a3}`}a(_3,"generateReturnMessage");async function d3({statement:e,hdb_user:t}){let r=await l3(e.table.databaseid,e.table.tableid);SS.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=SS.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=e3.parse(o).statements[0],u={operation:n3.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await u3(c);let _=await s3.deleteRecords(u);return SS.isEmptyOrZeroLength(_.message)&&(_.message=_3(_)),delete _.txn_time,_}catch(_){throw r3.error(_),_.hdb_code?_.message:_}}a(d3,"convertDelete")});var RD=g((nfe,gD)=>{"use strict";var f3=An(),{hdb_errors:pD}=se(),{getDatabases:SD}=(Re(),ie(Fe));gD.exports={checkSchemaExists:TD,checkSchemaTableExists:E3,schema_describe:f3};async function TD(e){if(!SD()[e])return pD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(TD,"checkSchemaExists");async function E3(e,t){let r=await TD(e);if(r)return r;if(!SD()[e][t])return pD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(E3,"checkSchemaTableExists")});var iu=g((ofe,h3)=>{h3.exports={name:"harperdb",version:"4.3.0",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.0",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.3","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 lu={};qe(lu,{addAnalyticsListener:()=>uu,recordAction:()=>kr,recordActionBinary:()=>as,setAnalyticsEnabled:()=>m3});function m3(e){DD=e}function kr(e,t,r,s,n){if(!DD)return;let i=t+(r?"-"+r:"");s!==void 0&&(i+="-"+s),n!==void 0&&(i+="-"+n);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:s,type:n},Sd.set(i,o)}md||p3()}function as(e,t,r,s,n){kr(!!e,t,r,s,n)}function uu(e){UD.push(e)}function p3(){md=performance.now(),setTimeout(async()=>{let e=performance.now()-md;md=0;let t=[],r={time:Date.now(),period:e,threadId:io.threadId,metrics:t};for(let[n,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 PD){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 vD()}let s=process.memoryUsage();t.push({metric:"memory",threadId:io.threadId,byThread:!0,...s});for(let n of UD)n(t);Sd=new Map,io.parentPort?io.parentPort.postMessage({type:MD,report:r}):xD({report:r})},LD).unref()}async function S3(e,t=6e4){let r=AS(),s=BD(),n=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,ou.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-S)+"ms"),S=performance.now()}),s.primaryStore.prefetch([1],()=>{let T=performance.now();T-S>5e3&&(0,ou.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of s.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:A}=S;for(let R of T||[]){let{path:M,method:x,type:P,metric:k,count:B,total:X,distribution:z,threads:J,...me}=R;B||(B=1);let ce=k+(M?"-"+M:"");x!==void 0&&(ce+="-"+x),P!==void 0&&(ce+="-"+P);let de=c.get(ce);if(de){if(de.threads){let Be=de.threads[A];if(Be)de=Be;else{de.threads[A]=Object.assign({},me);continue}}de.count||(de.count=1);let Le=de.count;for(let Be in me){let Lt=me[Be];typeof Lt=="number"&&(de[Be]=(de[Be]*Le+Lt*B)/(Le+B))}de.count+=B,X>=0&&(de.total+=X,de.ratio=de.total/de.count)}else de=Object.assign({period:t},R),delete de.distribution,c.set(ce,de),de.byThread&&(de.threads=[],de.threads[A]=Object.assign({},me),_.push(de));if(z){z=z.map(Be=>typeof Be=="number"?{value:Be,count:1}:Be);let Le=u.get(ce);Le?Le.push(...z):u.set(ce,z)}}await vD()}for(let p of _){let{path:S,method:T,type:A,metric:R,count:M,total:x,distribution:P,threads:k,...B}=p;k=k.filter(X=>X);for(let X in B){if(typeof p[X]!="number")continue;let z=0;for(let J of k){let me=J[X];typeof me=="number"&&(z+=me)}p[X]=z}p.count=k.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Be,Lt)=>Be.value>Lt.value?1:-1);let A=T.count-1,R=[],M=0,x=0,P;for(let Be of PD){let Lt=A*Be;for(;M<Lt;)P=S[x++],M+=P.count,x===1&&M--;let Wl=S[x>1?x-2:0];P||(P=S[0]),R.push(P.value-(P.value-Wl.value)*(M-Lt)/P.count)}let[k,B,X,z,J,me,ce,de,Le]=R;Object.assign(T,{p1:k,p10:B,p25:X,median:z,p75:J,p90:me,p95:ce,p99:de,p999:Le})}let d;for(let[p,S]of c)S.id=(0,pd.getNextMonotonicTime)(),S.time=l,s.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||s.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-AD,active:h-OD,taskQueueLatency:await n,time:f,...process.memoryUsage()};s.primaryStore.put(p,S,{append:!0}).then(T=>{T||s.primaryStore.put(p,S)})}AD=E,OD=h}async function bD(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function AS(){return yD||(yD=lt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function BD(){return ND||(ND=lt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function R3(){HD=!0;let e=(0,cu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await S3(LD,e),await bD(AS(),T3),await bD(BD(),g3)},Math.min(e/2,2147483647)).unref()}function xD(e,t){let r=e.report;r.threadId=t?.threadId||io.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(ID+=s.mean*s.count);r.totalBytesProcessed=ID,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(wD.get(t))}),wD.set(t,t.performance.eventLoopUtilization())),r.id=(0,pd.getNextMonotonicTime)(),AS().primaryStore.put(r.id,r),HD||R3(),A3&&(GD=b3(r))}async function b3(e){if(await GD,!li){let r=(0,au.dirname)((0,ou.getLogFilePath)());try{li=await(0,gS.open)((0,au.join)(r,"analytics.log"),"r+")}catch{li=await(0,gS.open)((0,au.join)(r,"analytics.log"),"w+")}}let t=(await li.stat()).size;if(t>O3){let r=Buffer.alloc(t);await li.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await li.write(r,{position:0}),await li.truncate(r.length),t=r.length}await li.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var
|
|
6
|
+
`)},VY="certificate.pem",$Y="privateKey.pem",YY="ca.pem";wN.exports={CERTIFICATE_VALUES:kY,CERTIFICATE_PEM_NAME:VY,PRIVATEKEY_PEM_NAME:$Y,CA_PEM_NAME:YY}});var tp=g((Xue,vN)=>{"use strict";var UN=require("fs-extra"),oe=require("joi"),KY=require("os"),{boolean:be,string:zt,number:Ze,array:ep}=oe.types(),{totalmem:DN}=require("os"),Wi=require("path"),WY=$(),k_=Q(),jue=CN(),LN=L(),QY=je(),MN="log",zY="components",JY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",jY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",XY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",ZY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",eK="rootPath config parameter is undefined",tK="clustering.enabled config parameter is undefined",Qi=Ze.min(0).required(),V_=ep.items({host:zt.required(),port:Qi}).empty(null),jn,PN=!1;vN.exports={configValidator:rK,routesValidator:cK,route_constraints:V_};function rK(e,t=!1){if(PN=t,jn=e.rootPath,k_.isEmpty(jn))throw eK;let r=be.required(),n=Ze.min(0).max(1e3).empty(null).default(aK),s=zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(qc),i=zt.optional().empty(null),o=zt.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(sK).empty(null).default(qc),_=e.clustering?.enabled;if(k_.isEmpty(_))throw tK;let l;return _===!0?l=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:Qi,routes:V_}).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:V_}).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:zt.optional().empty(null)}).required():l=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:l,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:zt.custom(oK).optional().empty(null),maxSize:zt.custom(iK).optional().empty(null),path:zt.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.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:zt.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:zt.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:zt.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:zt.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:zt.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.object({certificate:i.optional(),certificateAuthority:i.optional(),privateKey:i.optional(),ciphers:zt.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(rK,"configValidator");function nK(e){return PN||UN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(nK,"doesPathExist");function sK(e,t){oe.assert(e,zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=nK(e);if(r)return t.message(r)}a(sK,"validatePath");function iK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(JY);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(XY):e}a(iK,"validateRotationMaxSize");function oK(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(jY);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(ZY):e}a(oK,"validateRotationInterval");function aK(e,t){let r=t.state.path.join("."),n=KY.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||DN();return i=Math.round(Math.min(i,DN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),WY.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(aK,"setDefaultThreads");function qc(e,t){let r=t.state.path.join(".");if(!k_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(k_.isEmpty(jn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(jn,zY);case"logging.root":return Wi.join(jn,MN);case"clustering.leafServer.streams.path":return Wi.join(jn,"clustering","leaf");case"storage.path":let n=Wi.join(jn,LN.LEGACY_DATABASES_DIR_NAME);return UN.existsSync(n)?n:Wi.join(jn,LN.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(jn,MN);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 cK(e){let t=oe.object({routes:V_});return QY.validateBySchema({routes:e},t)}a(cK,"routesValidator")});var lr=g((tle,$N)=>{"use strict";var Hr=L(),Ut=Q(),bt=$(),{configValidator:uK,routesValidator:BN}=tp(),ur=require("fs-extra"),lK=require("yaml"),Dn=require("path"),_K=require("is-number"),xN=require("properties-reader"),dK=require("lodash"),{handleHDBError:fK}=ne(),{HTTP_STATUS_CODES:EK,HDB_ERROR_MSGS:$_}=Cr(),ele=require("minimist"),{server:hK}=(or(),ie(Hi)),{DATABASES_PARAM_CONFIG:Fc,CONFIG_PARAMS:Br,CONFIG_PARAM_MAP:Ln}=Hr,mK="Unable to get config value because config is uninitialized",pK="Config successfully initialized",SK="Error backing up config file",TK="Empty parameter sent to getConfigValue",GN=Dn.join(Hr.PACKAGE_ROOT,"config","yaml",Hr.HDB_DEFAULT_CONFIG_FILE),gK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",HN={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"},Y_,yt,K_;$N.exports={createConfigFile:RK,getDefaultConfig:AK,getConfigValue:FN,initConfig:np,flattenConfig:Wo,updateConfigValue:kN,updateConfigObject:bK,getConfiguration:IK,setConfiguration:wK,readConfigFile:ip,getClusteringRoutes:CK,initOldConfig:VN,getConfigFromFile:DK,getConfigFilePath:zi,addConfig:LK,deleteConfigFromFile:MK,getConfigObj:UK};function RK(e,t=!1){let r=oi(GN);Y_=Wo(r.toJSON());let n;for(let c in e){let u=Ln[c.toLowerCase()];if(u===Br.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){bt.error(d)}}}n&&qN(r,n),sp(r,t);let s=r.toJSON();yt=Wo(s);let i=r.getIn(["rootPath"]),o=Dn.join(i,Hr.HDB_CONFIG_FILE);ur.createFileSync(o),ur.writeFileSync(o,String(r)),bt.trace(`Config file written to ${o}`)}a(RK,"createConfigFile");function qN(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Ut.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=[Br.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=[Br.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){bt.error("Error parsing schemas CLI/env config arguments",n)}}a(qN,"setSchemasConfig");function AK(e){if(Y_===void 0){let r=oi(GN);Y_=Wo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return Y_[t.toLowerCase()]}a(AK,"getDefaultConfig");function FN(e){if(e==null){bt.error(TK);return}if(yt===void 0){bt.trace(mK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return yt[t.toLowerCase()]}a(FN,"getConfigValue");function zi(e=Ut.getPropsFilePath()){let t=Ut.getEnvCliRootPath();return t?Dn.join(t,Hr.HDB_CONFIG_FILE):xN(e).get(Hr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function np(e=!1){if(yt===void 0||e){let t;if(!Ut.noBootFile()){t=Ut.getPropsFilePath();try{ur.accessSync(t,ur.constants.F_OK|ur.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=zi(t),n;if(r.includes("config/settings.js"))try{VN(r);return}catch(i){if(i.code!==Hr.NODE_ERROR_CODES.ENOENT)throw i}try{n=oi(r)}catch(i){if(i.code===Hr.NODE_ERROR_CODES.ENOENT){bt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}OK(n,r),sp(n);let s=n.toJSON();if(hK.config=s,yt=Wo(s),yt.logging_rotation_rotate)for(let i in HN)yt[i]&&bt.error(`Config ${HN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(pK)}}a(np,"initConfig");function OK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(bt.trace("Updating config file with missing config params"),ur.writeFileSync(t,String(e)))}a(OK,"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=uK(r,t);if(n.error)throw $_.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 bK(e,t){yt===void 0&&(yt={});let r=Ln[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}yt[r.toLowerCase()]=t}a(bK,"updateConfigObject");function kN(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&np();let o=FN(Ln.hdb_root),c=Dn.join(o,Hr.HDB_CONFIG_FILE),u=oi(c),_;if(r===void 0&&e.toLowerCase()===Br.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Ln[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=Ln[f.toLowerCase()];if(E===Br.HTTP_SECUREPORT&&r[f]===yt[Br.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Br.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===yt[Br.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Br.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=Hr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=rp(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){bt.error(T)}}}_&&qN(u,_),sp(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,Hr.HDB_CONFIG_FILE);n===!0&&yK(c,l),ur.writeFileSync(d,String(u)),s&&(yt=Wo(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(kN,"updateConfigValue");function yK(e,t){try{let r=Dn.join(t,"backup",`${Hr.HDB_CONFIG_FILE}.bak`);ur.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(SK),bt.error(r)}}a(yK,"backupConfigFile");var NK=["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)),K_=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])&&!NK.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Br[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Wo,"flattenConfig");function rp(e,t){if(e===Br.CLUSTERING_NODENAME||e===Br.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(_K(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Ut.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 Ut.autoCast(t)}a(rp,"castConfigValue");function IK(){let e=Ut.getPropsFilePath(),t=zi(e);return oi(t).toJSON()}a(IK,"getConfiguration");async function wK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return kN(void 0,void 0,s,!0),gK}catch(i){throw typeof i=="string"||i instanceof String?fK(i,i,EK.BAD_REQUEST,void 0,void 0,!0):i}}a(wK,"setConfiguration");function ip(){let e=Ut.getPropsFilePath();try{ur.accessSync(e,ur.constants.F_OK|ur.constants.R_OK)}catch(n){if(!Ut.noBootFile())throw bt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return oi(t).toJSON()}a(ip,"readConfigFile");function oi(e){return lK.parseDocument(ur.readFileSync(e,"utf8"),{simpleKeys:!0})}a(oi,"parseYamlDoc");function CK(){let e=ip(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Ut.isEmptyOrZeroLength(t)?[]:t;let r=BN(t);if(r)throw $_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Ut.isEmptyOrZeroLength(n)?[]:n;let s=BN(n);if(s)throw $_.CONFIG_VALIDATION(s.message);if(!Ut.isEmptyOrZeroLength(n)&&!Ut.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Ut.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw $_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(CK,"getClusteringRoutes");function VN(e){let t=xN(e);yt={};for(let r in Ln){let n=t.get(r.toUpperCase());if(Ut.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Br.LOGGING_ROOT?yt[s]=Dn.dirname(n):yt[s]=n}return yt}a(VN,"initOldConfig");function DK(e){let t=ip();return dK.get(t,e.replaceAll("_","."))}a(DK,"getConfigFromFile");async function LK(e,t){let r=oi(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await ur.writeFile(zi(),String(r))}a(LK,"addConfig");function MK(e){let t=zi(Ut.getPropsFilePath()),r=oi(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,Hr.HDB_CONFIG_FILE);ur.writeFileSync(s,String(r))}a(MK,"deleteConfigFromFile");function UK(){return K_||(np(),K_)}a(UK,"getConfigObj")});var KN=g((nle,YN)=>{"use strict";var W_=L(),Q_=class{static{a(this,"BaseLicense")}constructor(t=0,r=W_.RAM_ALLOCATION_ENUM.DEFAULT,n=W_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},op=class extends Q_{static{a(this,"ExtendedLicense")}constructor(t=0,r=W_.RAM_ALLOCATION_ENUM.DEFAULT,n=W_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};YN.exports={BaseLicense:Q_,ExtendedLicense:op}});var Ji=g((ile,XN)=>{"use strict";var zo=require("fs-extra"),QN=F_(),zN=require("crypto"),PK=require("moment"),vK=require("uuid").v4,Jt=$(),cp=require("path"),BK=Q(),ai=L(),{totalmem:WN}=require("os"),HK=KN().ExtendedLicense,Qo="invalid license key format",xK="061183",GK="mofi25",qK="aes-256-cbc",FK=16,kK=32,JN=ee();JN.initSync();var ap;XN.exports={validateLicense:jN,generateFingerPrint:$K,licenseSearch:_p,getLicense:WK,checkMemoryLimit:QK};function up(){return cp.join(JN.getHdbBasePath(),ai.LICENSE_KEY_DIR_NAME,ai.LICENSE_FILE_NAME)}a(up,"getLicenseDirPath");function VK(){let e=up();return cp.join(e,ai.LICENSE_FILE_NAME)}a(VK,"getLicenseFilePath");function lp(){let e=up();return cp.join(e,ai.REG_KEY_FILE_NAME)}a(lp,"getFingerPrintFilePath");async function $K(){let e=lp();try{return await zo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await YK();throw Jt.error(`Error writing fingerprint file to ${e}`),Jt.error(t),new Error("There was an error generating the fingerprint")}}a($K,"generateFingerPrint");async function YK(){let e=vK(),t=QN.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(YK,"writeFingerprint");function jN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ai.RAM_ALLOCATION_ENUM.DEFAULT,version:ai.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(GK),c=o[1];c=Buffer.concat([Buffer.from(c)],FK);let u=Buffer.concat([Buffer.from(i)],kK),_=zN.createDecipheriv(qK,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=KK(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<PK().valueOf()&&(r.valid_date=!1),QN.validate(o[1],`${xK}${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(jN,"validateLicense");function KK(e,t){try{let r=zN.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(KK,"checkOldLicense");function _p(){let e=new HK,t=[];try{t=zo.readFileSync(VK(),"utf-8").split(ai.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(BK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=jN(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=ai.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return ap=e,e}a(_p,"licenseSearch");async function WK(){return ap||await _p(),ap}a(WK,"getLicense");function QK(){let e=_p().ram_allocation,t=process.constrainedMemory?.()||WN();if(t=Math.round(Math.min(t,WN())/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(QK,"checkMemoryLimit")});var an=g((lle,EI)=>{"use strict";var rI="username is required",nI="nothing to update, must supply active, role or password to update",sI="password cannot be an empty string",iI="If role is specified, it cannot be empty.",oI="active must be true or false";EI.exports={addUser:nW,alterUser:sW,dropUser:oW,getSuperUser:lW,userInfo:aW,listUsers:J_,listUsersExternal:cW,setUsersToGlobal:jo,findAndValidateUser:dI,getClusterUser:_W,USERNAME_REQUIRED:rI,ALTERUSER_NOTHING_TO_UPDATE:nI,EMPTY_PASSWORD:sI,EMPTY_ROLE:iI,ACTIVE_BOOLEAN:oI};var aI=vr(),zK=ii(),Ep=F_(),cI=yN(),uI=Pr(),hp=bs(),xr=Q(),lI=require("validate.js"),Ae=$(),{promisify:JK}=require("util"),mp=Rs(),ZN=L(),eI=ke(),jK=lr(),ale=ee(),cle=Ji(),XK=Fi(),{table:ule}=(Re(),ie(Fe)),{handleHDBError:Xn,hdb_errors:ZK}=ne(),{HTTP_STATUS_CODES:Zn,AUTHENTICATION_ERROR_MSGS:dp,HDB_ERROR_MSGS:Jo}=ZK,{UserEventMsg:pp}=Mn(),fp=require("lodash"),{server:Sp}=(or(),ie(Hi)),eW=$();Sp.getUser=(e,t)=>dI(e,t,t!=null);var _I={username:!0,active:!0,role:!0,password:!0},tI=new Map,z_=uI.searchByValue,tW=uI.searchByHash,rW=JK(zK.delete);async function nW(e){let t=lI.cleanAttributes(e,_I),r=cI.addUserValidation(t);if(r)throw Xn(new Error,r.message,Zn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await z_(n),s=s&&Array.from(s)}catch(u){throw Ae.error("There was an error searching for a role in add user"),Ae.error(u),u}if(!s||s.length<1)throw Xn(new Error,Jo.ROLE_NAME_NOT_FOUND(t.role),Zn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Xn(new Error,Jo.DUP_ROLES_FOUND(t.role),Zn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=mp.encrypt(t.password)),t.password=Ep.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await aI.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await jo()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.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(nW,"addUser");async function sW(e){let t=lI.cleanAttributes(e,_I);if(xr.isEmptyOrZeroLength(t.username))throw new Error(rI);if(xr.isEmptyOrZeroLength(t.password)&&xr.isEmptyOrZeroLength(t.role)&&xr.isEmptyOrZeroLength(t.active))throw new Error(nI);if(!xr.isEmpty(t.password)&&xr.isEmptyOrZeroLength(t.password.trim()))throw new Error(sI);if(!xr.isEmpty(t.active)&&!xr.isBoolean(t.active))throw new Error(oI);let r=iW(t.username);if(!xr.isEmpty(t.password)&&!xr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=mp.encrypt(t.password)),t.password=Ep.hash(t.password)),t.role==="")throw new Error(iI);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await z_(i)||[])}catch(c){throw Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=Jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.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 Ae.error(c),Xn(new Error,c,Zn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await aI.update(n)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await jo()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return hp.signalUserChange(new pp(process.pid)),s}a(sW,"alterUser");function iW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(iW,"isClusterUser");async function oW(e){try{let t=cI.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(xr.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 rW(r)}catch(s){throw Ae.error("Got an error deleting a user."),Ae.error(s),s}Ae.debug(n);try{await jo()}catch(s){throw Ae.error("Got an error setting users to global."),Ae.error(s),s}return hp.signalUserChange(new pp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(oW,"dropUser");async function aW(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 tW(r)}catch(s){throw Ae.error("Got an error searching for a role."),Ae.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ae.error(r),r}return t}a(aW,"userInfo");async function cW(){let e;try{e=await J_()}catch(t){throw Ae.error("Got an error listing users."),Ae.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(cW,"listUsersExternal");async function J_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await z_(e)}catch(o){throw Ae.error("Got an error searching for roles."),Ae.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 z_(n)}catch(o){throw Ae.error("Got an error searching for users."),Ae.error(o),o}let i=new Map;for(let o of s)o=fp.cloneDeep(o),o.role=r[o.role],uW(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),xr.errorizeMessage(e)}return null}a(J_,"listUsers");function uW(e){try{if(!e){Ae.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(XK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Ae.error("Got an error trying to set system permissions."),Ae.error(t)}}a(uW,"appendSystemTablesToRole");async function jo(){try{let e=await J_();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(jo,"setUsersToGlobal");async function dI(e,t,r=!0){global.hdb_users||await jo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Xn(new Error,dp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Xn(new Error,dp.USER_INACTIVE,Zn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(tI.get(t)===n.password)return s;if(Ep.validate(n.password,t))tI.set(t,n.password);else throw Xn(new Error,dp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(dI,"findAndValidateUser");async function lW(){global.hdb_users||await jo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(lW,"getSuperUser");async function _W(){let e=await J_(),t=jK.getConfigFromFile(ZN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!xr.isEmpty(r)&&r?.role?.role===ZN.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=mp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+eI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+eI.SERVER_SUFFIX.ADMIN,r}a(_W,"getClusterUser");var fI=[];Sp.invalidateUser=function(e){for(let t of fI)try{t(e)}catch(r){eW.error("Error invalidating user",r)}};Sp.onInvalidatedUser=function(e){fI.push(e)}});var Vc=g((Ele,SI)=>{"use strict";var ji=$(),Gr=L(),dW=Ky(),dle=Os(),fle=As(),fW=an(),{validateEvent:hI}=Mn(),kc=Cn(),EW=require("process"),{resetDatabases:hW}=(Re(),ie(Fe)),mW={[Gr.ITC_EVENT_TYPES.SCHEMA]:pW,[Gr.ITC_EVENT_TYPES.USER]:pI};async function pW(e){let t=hI(e);if(t){ji.error(t);return}ji.trace("ITC schemaHandler received schema event:",e),await dW(e.message),await SW(e.message)}a(pW,"schemaHandler");async function SW(e){try{kc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),kc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),kc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=hW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ji.error(t)}}a(SW,"syncSchemaMetadata");var mI=[];async function pI(e){try{try{kc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),kc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ji.warn(r)}let t=hI(e);if(t){ji.error(t);return}ji.trace(`ITC userHandler ${Gr.HDB_ITC_CLIENT_PREFIX}${EW.pid} received user event:`,e),await fW.setUsersToGlobal();for(let r of mI)r()}catch(t){ji.error(t)}}a(pI,"userHandler");pI.addListener=function(e){mI.push(e)};SI.exports=mW});var Mn=g((gle,gI)=>{"use strict";var mle=$(),Tp=Q(),TW=L(),{ITC_ERRORS:$c}=Cr(),{parentPort:ple,threadId:gW,isMainThread:RW,workerData:Sle}=require("worker_threads"),{onMessageFromWorkers:AW,broadcast:Tle,broadcastWithAcknowledgement:OW}=Ke();gI.exports={sendItcEvent:bW,validateEvent:TI,SchemaEventMsg:yW,UserEventMsg:NW};var j_;AW(async(e,t)=>{j_=j_||Vc(),TI(e),j_[e.type]&&await j_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function bW(e){return!RW&&e.message&&(e.message.originator=gW),OW(e)}a(bW,"sendItcEvent");function TI(e){if(typeof e!="object")return $c.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Tp.isEmpty(e.type))return $c.MISSING_TYPE;if(!e.hasOwnProperty("message")||Tp.isEmpty(e.message))return $c.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Tp.isEmpty(e.message.originator))return $c.MISSING_ORIGIN;if(TW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return $c.INVALID_EVENT(e.type)}a(TI,"validateEvent");function yW(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(yW,"SchemaEventMsg");function NW(e){this.originator=e}a(NW,"UserEventMsg")});var bs=g((Ole,bI)=>{"use strict";var RI=L(),Ale=Q(),X_=$(),AI=Vy(),Xo,{sendItcEvent:OI}=Mn();function IW(e){try{X_.trace("signalSchemaChange called with message:",e),Xo=Xo||Vc();let t=new AI(RI.ITC_EVENT_TYPES.SCHEMA,e);return Xo.schema(t),OI(t)}catch(t){X_.error(t)}}a(IW,"signalSchemaChange");function wW(e){try{X_.trace("signalUserChange called with message:",e),Xo=Xo||Vc();let t=new AI(RI.ITC_EVENT_TYPES.USER,e);return Xo.user(t),OI(t)}catch(t){X_.error(t)}}a(wW,"signalUserChange");bI.exports={signalSchemaChange:IW,signalUserChange:wW}});var Z_=g((yle,NI)=>{"use strict";var yI=Q(),CW=L(),DW=$(),LW=I_(),MW=N_(),UW=bs(),{SchemaEventMsg:PW}=Mn(),vW="already exists in";NI.exports=BW;async function BW(e,t,r){if(yI.isEmptyOrZeroLength(r))return r;let n=[];yI.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 HW(e,t.schema,t.name,i)})),s}a(BW,"lmdbCheckForNewAttributes");async function HW(e,t,r,n){let s=new MW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await xW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(vW))DW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(HW,"createNewAttribute");async function xW(e){let t;return t=await LW(e),UW.signalSchemaChange(new PW(process.pid,CW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(xW,"createAttribute")});var Zo=g((Ile,II)=>{"use strict";var gp=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};II.exports=gp});var CI=g((Cle,wI)=>{"use strict";var GW=Zo(),qW=L().OPERATIONS_ENUM,Rp=class extends GW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(qW.INSERT,r,n,s,i),this.records=t}};wI.exports=Rp});var LI=g((Lle,DI)=>{"use strict";var FW=Zo(),kW=L().OPERATIONS_ENUM,Ap=class extends FW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(kW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};DI.exports=Ap});var UI=g((Ule,MI)=>{"use strict";var VW=Zo(),$W=L().OPERATIONS_ENUM,Op=class extends VW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super($W.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};MI.exports=Op});var vI=g((vle,PI)=>{"use strict";var YW=Zo(),KW=L().OPERATIONS_ENUM,bp=class extends YW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(KW.DELETE,n,s,t,i),this.original_records=r}};PI.exports=bp});var Yc=g((xle,GI)=>{"use strict";var Hle=require("path"),BI=We(),WW=CI(),QW=LI(),zW=UI(),JW=vI(),ea=ut(),HI=Q(),{CONFIG_PARAMS:jW}=L(),xI=ee();xI.initSync();var ed=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:XW}=Je();GI.exports=ZW;async function ZW(e,t){if(xI.get(jW.LOGGING_AUDITLOG)===!1)return;let r=XW(e.schema,e.table),n=await BI.openEnvironment(r,e.table,!0),s=eQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){BI.initializeDBIs(n,ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ea.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),HI.isEmpty(s.user_name)||n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(ZW,"writeTransaction");function eQ(e,t){let r=HI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===ed.INSERT)return new WW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===ed.UPDATE)return new QW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===ed.UPSERT)return new zW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===ed.DELETE)return new JW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(eQ,"createTransactionObject")});var yp=g((Fle,qI)=>{"use strict";var tQ=Bc(),qle=Hc(),Kc=L(),rQ=xc(),nQ=$o().insertRecords,sQ=We(),iQ=$(),oQ=Z_(),{getSchemaPath:aQ}=Je(),cQ=Yc();qI.exports=uQ;async function uQ(e){try{let{schema_table:t,attributes:r}=tQ(e);rQ(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 oQ(e.hdb_auth_header,t,r),s=aQ(e.schema,e.table),i=await sQ.openEnvironment(s,e.table),o=await nQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await cQ(e,o)}catch(c){iQ.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(uQ,"lmdbCreateRecords")});var VI=g((Vle,kI)=>{"use strict";var FI=L(),lQ=yp(),_Q=Hc(),dQ=require("fs-extra"),{getSchemaPath:fQ}=Je();kI.exports=EQ;async function EQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new _Q(FI.SYSTEM_SCHEMA_NAME,FI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await lQ(r),await dQ.mkdirp(fQ(e.schema))}a(EQ,"lmdbCreateSchema")});var YI=g((Yle,$I)=>{"use strict";var Np=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};$I.exports=Np});var zI=g((Jle,QI)=>{"use strict";var KI=We(),Ip=Dr(),wp=Cr().LMDB_ERRORS_ENUM,hQ=ut(),WI=$(),Wle=Q(),mQ=require("lmdb"),pQ=YI(),SQ=L(),{OVERFLOW_MARKER:Qle,MAX_SEARCH_KEY_LENGTH:zle}=hQ,TQ=SQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function gQ(e,t,r,n){if(Ip.validateEnv(e),t===void 0)throw new Error(wp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(wp.IDS_REQUIRED):new Error(wp.IDS_MUST_BE_ITERABLE);try{let s=KI.listDBIs(e);KI.initializeDBIs(e,t,s);let i=new pQ,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[TQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,mQ.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 b=e.dbis[T],R=h[T];if(R!=null)try{let M=Ip.getIndexedValues(R);if(M)for(let v=0,P=M.length;v<P;v++)b.remove(M[v],o)}catch{WI.warn(`cannot delete from attribute: ${T}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){WI.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=Ip.getNextMonotonicTime(),i}catch(s){throw s}}a(gQ,"deleteRecords");QI.exports={deleteRecords:gQ}});var Wc=g((Xle,jI)=>{"use strict";var ta=Q(),RQ=zI(),AQ=We(),{getSchemaPath:OQ}=Je(),bQ=Yc(),yQ=$();jI.exports=NQ;async function NQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ta.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ta.isEmptyOrZeroLength(e.hash_values)&&!ta.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ta.isEmpty(u)||e.hash_values.push(u)}}if(ta.isEmptyOrZeroLength(e.hash_values))return JI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ta.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=OQ(e.schema,e.table),i=await AQ.openEnvironment(s,e.table),o=await RQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await bQ(e,o)}catch(c){yQ.error(`unable to write transaction due to ${c.message}`)}return JI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(NQ,"lmdbDeleteRecords");function JI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(JI,"createDeleteResponse")});var Dp=g((t_e,XI)=>{"use strict";var IQ=L(),e_e=Dr();function Cp(e,t){let r=Object.create(null);if(t.length===1&&IQ.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 wQ(e,t,r,n){let s=Cp(r,e);n.push(s)}a(wQ,"searchAll");function CQ(e,t,r,n){let s=Cp(r,e);n[t]=s}a(CQ,"searchAllToMap");function DQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(DQ,"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 LQ(e,t,r,n,s,i){t.toString().endsWith(e)&&Xi(t,r,n,s,i)}a(LQ,"endsWith");function MQ(e,t,r,n,s,i){t.toString().includes(e)&&Xi(t,r,n,s,i)}a(MQ,"contains");function UQ(e,t,r,n,s,i){t>e&&Xi(t,r,n,s,i)}a(UQ,"greaterThanCompare");function PQ(e,t,r,n,s,i){t>=e&&Xi(t,r,n,s,i)}a(PQ,"greaterThanEqualCompare");function vQ(e,t,r,n,s,i){t<e&&Xi(t,r,n,s,i)}a(vQ,"lessThanCompare");function BQ(e,t,r,n,s,i){t<=e&&Xi(t,r,n,s,i)}a(BQ,"lessThanEqualCompare");XI.exports={parseRow:Cp,searchAll:wQ,searchAllToMap:CQ,iterateDBI:DQ,endsWith:LQ,contains:MQ,greaterThanCompare:UQ,greaterThanEqualCompare:PQ,lessThanCompare:vQ,lessThanEqualCompare:BQ,pushResults:Xi}});var ra=g((o_e,iw)=>{"use strict";var ci=We(),n_e=$(),qr=Dr(),td=ut(),_t=Cr().LMDB_ERRORS_ENUM,s_e=Q(),HQ=L(),rd=Dp(),{parseRow:xQ}=rd,i_e=require("lmdb"),{OVERFLOW_MARKER:ZI,MAX_SEARCH_KEY_LENGTH:GQ}=td;function ew(e,t,r,n=!1,s=void 0,i=void 0){return Zi(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(ew,"iterateFullIndex");function Qc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Zi(e,t,r,(l,d,f,E)=>{let b={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?(b.values=!1,d.getRange(b).map(R=>({value:R}))):d.getRange(b)})}a(Qc,"iterateRangeBetween");function Zi(e,t,r,n){let s=e.database||e,i=ci.openDBI(s,r);i[td.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ci.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Zi,"setupTransaction");function tw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(ZI)){if(!s)if(r)s=ci.openDBI(e,r);else{let u=ci.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ci.openDBI(e,u[_]),!s[td.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(tw,"getOverflowCheck");function qQ(e,t,r,n=!1,s=void 0,i=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return Zi(e,t,t,(o,c,u)=>(nd(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(_=>xQ(_.value,r))))}a(qQ,"searchAll");function FQ(e,t,r,n=!1,s=void 0,i=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);nd(r),r=zc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of ew(e,t,t,n,s,i))o.set(c,rd.parseRow(u,r));return o}a(FQ,"searchAllToMap");function kQ(e,t,r=!1,n=void 0,s=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=ew(e,void 0,t,r,n,s),c=o.transaction,u=tw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(kQ,"iterateDBI");function VQ(e,t){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return ci.statDBI(e,t).entryCount}a(VQ,"countAll");function $Q(e,t,r,n,s=!1,i=void 0,o=void 0){return ui(e,r,n),Zi(e,t,r,(c,u,_,l)=>(n=qr.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($Q,"equals");function YQ(e,t,r){return ui(e,t,r),ci.openDBI(e,t).getValuesCount(r)}a(YQ,"count");function KQ(e,t,r,n,s=!1,i=void 0,o=void 0){return ui(e,r,n),Zi(e,null,r,(c,u)=>{n=qr.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(KQ,"startsWith");function WQ(e,t,r,n,s=!1,i=void 0,o=void 0){return rw(e,t,r,n,s,i,o,!0)}a(WQ,"endsWith");function rw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ui(e,r,n),Zi(e,null,r,(u,_,l,d)=>{let f=tw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(ZI)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[td.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(p=>({key:E,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(rw,"contains");function QQ(e,t,r,n,s=!1,i=void 0,o=void 0){ui(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(QQ,"greaterThan");function zQ(e,t,r,n,s=!1,i=void 0,o=void 0){ui(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(zQ,"greaterThanEqual");function JQ(e,t,r,n,s=!1,i=void 0,o=void 0){ui(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(JQ,"lessThan");function jQ(e,t,r,n,s=!1,i=void 0,o=void 0){ui(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(jQ,"lessThanEqual");function XQ(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(qr.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=qr.convertKeyValueToWrite(n),s=qr.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(XQ,"between");function ZQ(e,t,r,n){qr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(nd(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=rd.parseRow(c,r)),o}a(ZQ,"searchByHash");function ez(e,t,r){qr.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(ez,"checkHashExists");function tz(e,t,r,n,s=[]){return sw(e,t,r,n,s),nw(e,t,r,n,s).map(i=>i[1])}a(tz,"batchSearchByHash");function rz(e,t,r,n,s=[]){sw(e,t,r,n,s);let i=new Map;for(let[o,c]of nw(e,t,r,n,s))i.set(o,c);return i}a(rz,"batchSearchByHashToMap");function nw(e,t,r,n,s=[]){return Zi(e,t,t,(i,o,c)=>{r=zc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,rd.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(nw,"batchHashSearch");function sw(e,t,r,n,s){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(nd(r),n==null)throw new Error(_t.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(_t.IDS_MUST_BE_ITERABLE)}a(sw,"initializeBatchSearchByHash");function nd(e){if(!Array.isArray(e))throw e===void 0?new Error(_t.FETCH_ATTRIBUTES_REQUIRED):new Error(_t.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(nd,"validateFetchAttributes");function ui(e,t,r){if(qr.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>GQ)throw new Error(_t.SEARCH_VALUE_TOO_LARGE)}a(ui,"validateComparisonFunctions");function zc(e,t){return t.length===1&&HQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ci.listDBIs(e)),t}a(zc,"setGetWholeRowAttributes");iw.exports={searchAll:qQ,searchAllToMap:FQ,count:YQ,countAll:VQ,equals:$Q,startsWith:KQ,endsWith:WQ,contains:rw,searchByHash:ZQ,setGetWholeRowAttributes:zc,batchSearchByHash:tz,batchSearchByHashToMap:rz,checkHashExists:ez,iterateDBI:kQ,greaterThan:QQ,greaterThanEqual:zQ,lessThan:JQ,lessThanEqual:jQ,between:XQ}});var na=g((c_e,lw)=>{var ow=require("lodash"),aw=je(),fe=require("joi"),nz=Q(),{hdb_schema_table:Jc,checkValidTable:cw,hdb_table:uw,hdb_database:sd}=zn(),{handleHDBError:sz,hdb_errors:iz}=ne(),{getDatabases:oz}=(Re(),ie(Fe)),{HTTP_STATUS_CODES:az}=iz,cz=fe.object({database:sd,schema:sd,table:uw,search_attribute:Jc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(Jc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),uz=fe.object({database:sd,schema:sd,table:uw,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives(Jc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(Jc,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives(Jc,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});lw.exports=function(e,t){let r=null;switch(t){case"value":r=aw.validateBySchema(e,cz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(cw("database",e.schema)),i(cw("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=aw.validateBySchema(e,uz);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=nz.checkGlobalSchemaTable(e.schema,e.table);if(s)return sz(new Error,s,az.NOT_FOUND);let o=oz()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=ow.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!ow.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Lp=g((l_e,_w)=>{"use strict";var lz=We(),_z=na(),{getSchemaPath:dz}=Je();_w.exports=fz;function fz(e){let t=_z(e,"hashes");if(t)throw t;let r=dz(e.schema,e.table);return lz.openEnvironment(r,e.table)}a(fz,"initialize")});var Mp=g((d_e,dw)=>{"use strict";var Ez=ra(),hz=Lp();dw.exports=mz;async function mz(e){let t=await hz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Ez.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(mz,"lmdbGetDataByHash")});var sa=g((E_e,fw)=>{"use strict";var Up=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};fw.exports=Up});var hw=g((p_e,Ew)=>{"use strict";var m_e=sa(),pz=ra(),Sz=Lp();Ew.exports=Tz;async function Tz(e){let t=await Sz(e),r=global.hdb_schema[e.schema][e.table];return pz.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(Tz,"lmdbSearchByHash")});var es=g((T_e,mw)=>{"use strict";var Pp=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};mw.exports=Pp});var id=g((R_e,Aw)=>{"use strict";var jt=ra(),gz=We(),Rz=Q(),Ee=ut(),eo=L(),Az=Fi(),pw=Cr().LMDB_ERRORS_ENUM,{getSchemaPath:Oz}=Je(),ys=eo.SEARCH_WILDCARDS;async function bz(e,t,r){let n;e.schema===eo.SYSTEM_SCHEMA_NAME?n=Az[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Rw(e,n.hash_attribute,r,t);return Tw(e,s,n.hash_attribute,r)}a(bz,"prepSearch");async function Tw(e,t,r,n){let s=Oz(e.schema,e.table),i=await gz.openEnvironment(s,e.table),o=gw(i,e,t,r),c=o.transaction||i;if([Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Ee.SEARCH_TYPES.SEARCH_ALL,Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(yz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Sw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?Sw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?jt.batchSearchByHashToMap(c,r,e.get_attributes,_):jt.batchSearchByHash(c,r,e.get_attributes,_)}a(Tw,"executeSearch");function gw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=jt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=jt.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=jt.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=jt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return jt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return jt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return jt.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return jt.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=jt.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=jt.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=jt.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=jt.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=jt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(gw,"searchByType");function Sw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Sw,"createMapFromIterable");function yz(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(yz,"checkToFetchMore");function Rw(e,t,r,n){if(Rz.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),ys.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(ys[0])<0&&s.indexOf(ys[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(ys.indexOf(i)>=0&&ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(ys.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(ys[0])||s.includes(ys[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(pw.UNKNOWN_SEARCH_TYPE)}else switch(n){case eo.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case eo.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case eo.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case eo.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case eo.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(pw.UNKNOWN_SEARCH_TYPE)}}a(Rw,"createSearchTypeFromSearchObject");Aw.exports={executeSearch:Tw,createSearchTypeFromSearchObject:Rw,prepSearch:bz,searchByType:gw}});var bw=g((b_e,Ow)=>{"use strict";var O_e=es(),Nz=na(),Iz=Q(),wz=L(),Cz=id();Ow.exports=Dz;function Dz(e,t){if(!Iz.isEmpty(t)&&wz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Nz(e,"value");if(n)throw n;return Cz.prepSearch(e,t,!0)}a(Dz,"lmdbGetDataByValue")});var jc=g((I_e,yw)=>{"use strict";var N_e=es(),Lz=na(),Mz=Q(),Uz=L(),Pz=id();yw.exports=vz;async 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,!1)}a(vz,"lmdbSearchByValue")});var Iw=g((D_e,Nw)=>{"use strict";var C_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 Mw=g((P_e,Lw)=>{"use strict";var M_e=Iw().SearchByConditionsObject,Bz=es(),Hz=na(),xp=ra(),od=ut(),{Resource:U_e}=(Nn(),ie(Gp)),Dw=id(),xz=Dp(),Gz=require("lodash"),{getSchemaPath:qz}=Je(),ww=We(),{handleHDBError:Fz,hdb_errors:kz}=ne(),{HTTP_STATUS_CODES:Vz}=kz,$z=1e8;Lw.exports=Yz;async function Yz(e){let t=Hz(e,"conditions");if(t)throw Fz(t,t.message,Vz.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=qz(e.schema,e.table),n=await ww.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)ww.openDBI(n,_.search_attribute);let i=Gz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===od.SEARCH_TYPES.EQUALS?_.estimated_count=xp.count(n,_.search_attribute,_.search_value):l===od.SEARCH_TYPES.CONTAINS||l===od.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=$z}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Cw(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(Dw.filterByType),d=l.length,f=xp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>xz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await Cw(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=xp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Yz,"lmdbSearchByConditions");async function Cw(e,t,r,n){let s=new Bz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===od.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Dw.searchByType(e,s,i,n).map(o=>o.value)}a(Cw,"executeConditionSearch")});var ia=g((B_e,Uw)=>{"use strict";var Kz=L().OPERATIONS_ENUM,qp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=Kz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Uw.exports=qp});var Fp=g((x_e,Fw)=>{"use strict";var Hw=es(),xw=ia(),Gw=jc(),qw=Wc(),_r=L(),Pw=Q(),vw=We(),{getTransactionAuditStorePath:Wz,getSchemaPath:Qz}=Je(),Bw=$();Fw.exports=zz;async function zz(e){try{if(Pw.isEmpty(global.hdb_schema[e.schema])||Pw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await Jz(e),await jz(e);let t=Qz(e.schema,e.table);try{await vw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Bw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Wz(e.schema,e.table);await vw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Bw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(zz,"lmdbDropTable");async function Jz(e){let t=new Hw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Gw(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new xw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await qw(s)}a(Jz,"deleteAttributesFromSystem");async function jz(e){let t=new Hw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Gw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new xw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await qw(s)}catch(i){throw i}}a(jz,"dropTableFromSystem")});var Vw=g((q_e,kw)=>{"use strict";var Xz=require("fs-extra"),Zz=es(),e2=sa(),t2=ia(),r2=Fp(),n2=Wc(),s2=Mp(),i2=jc(),Ns=L(),{getSchemaPath:o2}=Je(),{handleHDBError:a2,hdb_errors:c2}=ne(),{HDB_ERROR_MSGS:u2,HTTP_STATUS_CODES:l2}=c2;kw.exports=_2;async function _2(e){let t;try{t=await d2(e.schema);let r=new Zz(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await i2(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await r2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new t2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await n2(s);let i=o2(t);await Xz.remove(i)}catch(r){throw r}}a(_2,"lmdbDropSchema");async function d2(e){let t=new e2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await s2(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw a2(new Error,u2.SCHEMA_NOT_FOUND(e),l2.NOT_FOUND,void 0,void 0,!0);return n}a(d2,"validateDropSchema")});var ad=g((k_e,$w)=>{"use strict";var kp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};$w.exports=kp});var Kw=g((Y_e,Yw)=>{"use strict";var f2=require("fs-extra"),cd=We(),{getTransactionAuditStorePath:E2}=Je(),Vp=ut(),$_e=ad();Yw.exports=h2;async function h2(e){let t;try{let r=E2(e.schema,e.table);await f2.mkdirp(r),t=await cd.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{cd.createDBI(t,Vp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),cd.createDBI(t,Vp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),cd.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(h2,"createTransactionsAuditEnvironment")});var Jw=g((W_e,zw)=>{"use strict";var $p=L(),Ww=We(),m2=$o(),{getSystemSchemaPath:p2,getSchemaPath:S2}=Je(),T2=Fi(),g2=I_(),Yp=N_(),R2=$(),A2=Kw(),Wp=T2.hdb_table,Qw=[];for(let e=0;e<Wp.attributes.length;e++)Qw.push(Wp.attributes[e].attribute);zw.exports=O2;async function O2(e,t){let r=S2(t.schema,t.table),n=new Yp(t.schema,t.table,$p.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Yp(t.schema,t.table,$p.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Yp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Ww.createEnvironment(r,t.table),e!==void 0){let o=await Ww.openEnvironment(p2(),$p.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await m2.insertRecords(o,Wp.hash_attribute,Qw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Kp(n),await Kp(s),await Kp(i)}await A2(t)}catch(o){throw o}}a(O2,"lmdbCreateTable");async function Kp(e){try{await g2(e)}catch(t){R2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Kp,"createAttribute")});var Xw=g((z_e,jw)=>{"use strict";var b2=Bc(),y2=xc(),N2=Z_(),Xc=L(),I2=$o().updateRecords,w2=We(),{getSchemaPath:C2}=Je(),D2=Yc(),L2=$();jw.exports=M2;async function M2(e){try{let{schema_table:t,attributes:r}=b2(e);y2(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 N2(e.hdb_auth_header,t,r),s=C2(e.schema,e.table),i=await w2.openEnvironment(s,e.table),o=await I2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await D2(e,o)}catch(c){L2.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(M2,"lmdbUpdateRecords")});var eC=g((j_e,Zw)=>{"use strict";var U2=L().OPERATIONS_ENUM,Qp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=U2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Zw.exports=Qp});var rC=g((ede,tC)=>{"use strict";var Z_e=eC(),P2=Bc(),v2=xc(),B2=Z_(),Zc=L(),H2=$o().upsertRecords,x2=We(),{getSchemaPath:G2}=Je(),q2=Yc(),F2=$(),{handleHDBError:k2,hdb_errors:V2}=ne();tC.exports=$2;async function $2(e){let t;try{t=P2(e)}catch(u){throw k2(u,u.message,V2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;v2(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 B2(e.hdb_auth_header,r,n),i=G2(e.schema,e.table),o=await x2.openEnvironment(i,e.table),c=await H2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await q2(e,c)}catch(u){F2.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($2,"lmdbUpsertRecords")});var sC=g((rde,nC)=>{"use strict";var zp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};nC.exports=zp});var oC=g((sde,iC)=>{"use strict";var Jp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};iC.exports=Jp});var uC=g((ade,cC)=>{"use strict";var jp=We(),{getTransactionAuditStorePath:Y2}=Je(),ode=sC(),eu=ut(),K2=Q(),aC=oC(),W2=require("util").promisify,Q2=W2(setTimeout),z2=1e4,J2=100;cC.exports=j2;async function j2(e){let t=Y2(e.schema,e.table),r=await jp.openEnvironment(t,e.table,!0),n=jp.listDBIs(r);jp.initializeDBIs(r,eu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new aC;do s=await X2(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 Q2(J2);while(s.transactions_deleted>0);return i}a(j2,"deleteAuditLogsBefore");async function X2(e,t){let r=new aC;try{let n=e.dbis[eu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[eu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];K2.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>z2)break}return await s,r}catch(n){throw n}}a(X2,"deleteTransactions")});var _C=g((ude,lC)=>{"use strict";var Xp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};lC.exports=Xp});var fC=g((dde,dC)=>{"use strict";var Z2=es(),eJ=ia(),_de=_C(),ts=L(),tJ=Q(),Zp=We(),rJ=Fi(),nJ=jc(),sJ=Wc(),{getSchemaPath:iJ}=Je();dC.exports=oJ;async function oJ(e,t=!0){let r;e.schema===ts.SYSTEM_SCHEMA_NAME?r=rJ[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await cJ(e),s=iJ(e.schema,e.table),i=await Zp.openEnvironment(s,e.table);return t===!0&&await aJ(e,i,r.hash_attribute),Zp.dropDBI(i,e.attribute),n}a(oJ,"lmdbDropAttribute");async function aJ(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(aJ,"removeAttributeFromAllObjects");async function cJ(e){let t=new Z2(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 nJ(t)).filter(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(tJ.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 eJ(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return sJ(i)}a(cJ,"dropAttributeFromSystem")});var TC=g((hde,SC)=>{"use strict";var eS=We(),oa=ut(),Ede=Dr(),tS=L(),EC=Q(),{getTransactionAuditStorePath:uJ}=Je(),lJ=ra(),ud=Zo(),_J=$();SC.exports=dJ;async function dJ(e){let t=uJ(e.schema,e.table),r=await eS.openEnvironment(t,e.table,!0),n=eS.listDBIs(r);eS.initializeDBIs(r,oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return hC(r,e.search_values);case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,EJ(r,e.search_values,s);case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return fJ(r,e.search_values);default:return hC(r)}}a(dJ,"readAuditLog");function hC(e,t=[0,Date.now()]){EC.isEmpty(t[0])&&(t[0]=0),EC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new ud,s))}a(hC,"searchTransactionsByTimestamp");function fJ(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[oa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,pC(e,i))}return Object.fromEntries(r)}a(fJ,"searchTransactionsByUsername");function EJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=lJ.equals(e,oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,oa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=pC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);mC(u,"records",r,l,o),mC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(EJ,"searchTransactionsByHashValues");function mC(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new ud(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new ud(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(mC,"loopRecords");function pC(e,t){let r=[];try{let n=e.dbis[oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new ud,i);r.push(o)}}catch(i){_J.warn(i)}return r}catch(n){throw n}}a(pC,"batchSearchTransactions")});var RC=g((Tde,gC)=>{"use strict";var{getSchemaPath:pde}=Je(),Sde=We(),{database:hJ}=(Re(),ie(Fe));gC.exports={writeTransaction:mJ};async function mJ(e,t,r){return hJ({database:e,table:t}).transaction(r)}a(mJ,"writeTransaction")});var yC=g((Rde,bC)=>{"use strict";var{getSchemaPath:AC}=Je(),OC=We();bC.exports={flush:pJ,resetReadTxn:SJ};async function pJ(e,t){return(await OC.openEnvironment(AC(e,t),t.toString())).flushed}a(pJ,"flush");async function SJ(e,t){try{(await OC.openEnvironment(AC(e,t),t.toString())).resetReadTxn()}catch{}}a(SJ,"resetReadTxn")});var CC=g((Ode,wC)=>{"use strict";var{Readable:TJ}=require("stream"),{getDatabases:gJ}=(Re(),ie(Fe)),{readSync:RJ,openSync:AJ,createReadStream:NC}=require("fs"),{open:OJ}=require("lmdb"),IC=Cc(),bJ=Dc(),{AUDIT_STORE_OPTIONS:yJ}=(ei(),ie(DC)),{INTERNAL_DBIS_NAME:NJ,AUDIT_STORE_NAME:IJ}=ut();wC.exports=CJ;var rS=32768,wJ=100;async function CJ(e){let t=e.database||e.schema||"data",r=gJ()[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=OJ({noSync:!0,maxDbs:bJ.MAX_DBS}),f,E=d.openDB(NJ,new IC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(b,R){R.encoding="binary",R.encoder=void 0;let M=d.openDB(b,R),v=l.openDB(b,R);for(let{key:P,version:k,value:H}of v.getRange({start:null,transaction:h,versions:v.useVersions}))f=M.put(P,H,k),p++%wJ===0&&(await new Promise(j=>setTimeout(j,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:b,value:R}of l.getRange({transaction:h,start:!1}))if(s.some(M=>b.startsWith?.(M+"/"))){E.put(b,R);let[,M]=b.split("/"),v=!M,P=new IC(!v,v);await S(b,P)}e.include_audit&&await S(IJ,Object.assign({},yJ)),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=AJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(rS);RJ(c,_,0,rS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=NC(null,{fd:c,start:rS}),f=new TJ.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(CJ,"getBackup")});var UC=g((yde,MC)=>{"use strict";var DJ=$(),{handleHDBError:LJ}=ne(),MJ=Yb(),UJ=I_(),PJ=yp(),vJ=VI(),BJ=Wc(),HJ=Mp(),xJ=hw(),GJ=bw(),qJ=jc(),FJ=Mw(),kJ=Vw(),VJ=Jw(),$J=Xw(),YJ=rC(),KJ=uC(),WJ=Fp(),QJ=fC(),zJ=TC(),JJ=RC(),LC=yC(),jJ=CC(),nS=class extends MJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return FJ(t)}async getDataByHash(t){return await HJ(t)}async searchByHash(t){return await xJ(t)}async getDataByValue(t,r){return await GJ(t,r)}async searchByValue(t){return await qJ(t)}async createSchema(t){return await vJ(t)}async dropSchema(t){return await kJ(t)}async createTable(t,r){return await VJ(t,r)}async dropTable(t){return await WJ(t)}async createAttribute(t){return await UJ(t)}async createRecords(t){return await PJ(t)}async updateRecords(t){return await $J(t)}async upsertRecords(t){try{return await YJ(t)}catch(r){throw LJ(r,null,null,DJ.ERR,r)}}async deleteRecords(t){return await BJ(t)}async dropAttribute(t){return await QJ(t)}async deleteAuditLogsBefore(t){return await KJ(t)}async readAuditLog(t){return await zJ(t)}writeTransaction(t,r,n){return JJ.writeTransaction(t,r,n)}flush(t,r){return LC.flush(t,r)}resetReadTxn(t,r){return LC.resetReadTxn(t,r)}getBackup(t){return jJ(t)}};MC.exports=nS});function r4(){t4=setInterval(function(){for(let e of sS)if(e.stale){let t=e[ye]?.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},e4).unref()}var iS,vC,BC,XJ,sS,ZJ,tu,PC,to,ld,e4,t4,oS=ge(()=>{iS=B(Dr()),vC=B(ne()),BC=B($());Nn();XJ=100,sS=new Set,ZJ=25e3,to=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;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&&performance.now()-PC>ZJ)throw new vC.ServerError("Outstanding write transactions have too long of queue, please try again later",503)}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 l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let T=S();E?E.push?E.push(T):E=[E,T]:E=T}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<XJ>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return tu||(tu=s,PC=performance.now(),tu.then(()=>{tu=null})),s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},ld=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(){}},e4=3e4;a(r4,"startMonitoringTxns");r4()});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[ye]=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 HC,ro=ge(()=>{HC=require("../index");Nn();oS();a(Xe,"transaction");(0,HC._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var KC={};qe(KC,{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 GC(e,t){let r=rs(e),n=lS(e,r);if(!r)throw new Un.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&&dd(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||s4,r=dr()[t];if(!r)throw(0,Un.handleHDBError)(new Error,n4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function qC(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*FC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var kC,_d,Un,VC,$C,Pn,aS,cS,YC,n4,s4,i4,o4,xC,uS,WC=ge(()=>{"use strict";kC=B(UC()),_d=B(na()),Un=B(ne());Re();VC=B(Bc()),$C=B(xc()),Pn=B(L()),aS=B(bs()),cS=B(Mn()),YC=B(Q());ro();fd();({HDB_ERROR_MSGS:n4}=Un.hdb_errors),s4="data",i4=1e4,o4=10,uS=class extends kC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),xC=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,_d.default)(t,"conditions");if(r)throw(0,Un.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=rs(t);if(!n)throw new Un.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 Un.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,Pn.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await _S(t.schema),aS.signalSchemaChange(new cS.SchemaEventMsg(process.pid,Pn.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,xC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,VC.default)(t);(0,$C.default)(t,n,r.primaryKey);let s,i=dr()[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=dd(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=dr()[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 qC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=dr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Un.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:Pn.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,YC.async_set_timeout)(o4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%i4===0&&await _();return u.length>0&&await _(),s?qC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,_d.default)(t,"hashes");if(r)throw r;return GC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of GC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Pn.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,_d.default)(t,"value");if(n)throw n;let s=rs(t);if(!s)throw new Un.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===Pn.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 Pn.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 Pn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of FC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return FC(r,t.search_values?.[0],t.search_values?.[1])}}};a(lS,"getSelect");a(GC,"getRecords");a(rs,"getTable");a(qC,"createDeleteResponse");a(FC,"groupRecordsInHistory")});var Cn=g((qde,QC)=>{"use strict";var{ResourceBridge:a4}=(WC(),ie(KC)),c4=ee();c4.initSync();var Ed;function u4(){return Ed||(Ed=new a4,Ed)}a(u4,"getBridge");QC.exports=u4()});var XC=g((kde,jC)=>{"use strict";var zC=require("lodash"),nu=require("mathjs"),l4=require("jsonata"),JC=Q();jC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?zC.uniqWith(e,zC.isEqual):e,searchJSON:_4,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 _4(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(JC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),JC.isEmpty(this.__ala__.res[r])){let n=l4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(_4,"searchJSON")});var eD=g(($de,ZC)=>{"use strict";var St=require("moment"),dS="YYYY-MM-DDTHH:mm:ss.SSSZZ";St.suppressDeprecationWarnings=!0;ZC.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 sD=g((Yde,nD)=>{"use strict";var d4=require("@turf/area"),f4=require("@turf/length"),E4=require("@turf/circle"),h4=require("@turf/difference"),m4=require("@turf/distance"),p4=require("@turf/boolean-contains"),S4=require("@turf/boolean-equal"),T4=require("@turf/boolean-disjoint"),g4=require("@turf/helpers"),tD=L(),Se=Q(),Is=$();nD.exports={geoArea:R4,geoLength:A4,geoCircle:O4,geoDifference:b4,geoDistance:rD,geoNear:y4,geoContains:N4,geoEqual:I4,geoCrosses:w4,geoConvert:C4};function R4(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return d4.default(e)}catch(t){return Is.trace(t,e),NaN}}a(R4,"geoArea");function A4(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return f4.default(e,{units:t||"kilometers"})}catch(r){return Is.trace(r,e),NaN}}a(A4,"geoLength");function O4(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return E4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(O4,"geoCircle");function b4(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return h4(e,t)}catch(r){return Is.trace(r,e,t),NaN}}a(b4,"geoDifference");function rD(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return m4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(rD,"geoDistance");function y4(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return rD(e,t,n)<=r}catch(s){return Is.trace(s,e,t),!1}}a(y4,"geoNear");function N4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return p4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(N4,"geoContains");function I4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return S4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(I4,"geoEqual");function w4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return!T4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(w4,"geoCrosses");function C4(e,t,r){if(Se.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Se.isEmpty(t))throw new Error("geo_type is required");if(Se.isEmpty(tD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(tD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),g4[t](e,r)}a(C4,"geoConvert")});var hd=g((Wde,iD)=>{var no=XC(),Fr=eD(),ns=sD();iD.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=Fr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Fr.current_time,e.fn.extract=e.fn.EXTRACT=Fr.extract,e.fn.date=e.fn.DATE=Fr.date,e.fn.date_format=e.fn.DATE_FORMAT=Fr.date_format,e.fn.date_add=e.fn.DATE_ADD=Fr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Fr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Fr.date_diff,e.fn.now=e.fn.NOW=Fr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Fr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Fr.get_server_time,e.fn.getdate=e.fn.GETDATE=Fr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Fr.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 uD=g((Qde,cD)=>{"use strict";var iu=require("lodash"),fr=require("alasql");fr.options.cache=!1;var D4=hd(),oD=require("clone"),md=require("recursive-iterator"),le=$(),De=Q(),aa=Cn(),L4=L(),{hdb_errors:M4}=ne(),{getDatabases:aD}=(Re(),ie(Fe)),U4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";D4(fr);var fS=class{static{a(this,"SQLSearch")}constructor(t,r){if(De.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(),De.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!De.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(vn)}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(vn)}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(vn)}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(vn)}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(vn)}}_getColumns(){let t=new md(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(oD(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=aD()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(De.isEmpty(this.statement.where)){le.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new md(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!De.isEmpty(r)&&r.right)if(De.isNotEmptyAndHasValue(r.right.value)){let n=De.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new fr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=De.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new fr.yy.LogicValue({value:i}):n instanceof fr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new fr.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 md(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!De.isEmpty(L4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(De.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(De.isEmptyOrZeroLength(r.left.columnid)||De.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(De.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!De.isEmpty(r.right.value)||!De.isEmpty(r.left.value)?n.add(De.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from)&&De.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&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(De.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);De.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(De.isEmptyOrZeroLength(this.all_table_attributes)&&!De.isEmptyOrZeroLength(this.columns.columns))return t;if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await fr.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(oD(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(De.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(U4)>-1&&this.tables.forEach(s=>{let i={columnid:aD()[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),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await 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(vn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let 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(vn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,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(vn)}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(vn)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof fr.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 fr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new fr.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 fr.yy.FuncValue:new fr.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 fr.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 b=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[b]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new md(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(vn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await 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 fr.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(M4.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(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};cD.exports=fS});var Pr=g((Jde,lD)=>{"use strict";var P4=Vb();lD.exports={searchByConditions:B4,searchByHash:H4,searchByValue:x4,search:G4};var ES=Cn(),{transformReq:hS}=Q(),v4=uD();async function B4(e){return hS(e),ES.searchByConditions(e)}a(B4,"searchByConditions");async function H4(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(H4,"searchByHash");async function x4(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(x4,"searchByValue");function G4(e,t){try{let r=new P4(e);r.validate(),new v4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(G4,"search")});var pd=g((Xde,_D)=>{"use strict";var q4=Cn();_D.exports={writeTransaction:F4};function F4(e,t,r){return q4.writeTransaction(e,t,r)}a(F4,"writeTransaction")});var hD=g((tfe,ED)=>{"use strict";var k4=Pr(),V4=Os(),dD=$(),$4=vr(),efe=pd(),Y4=require("clone"),pS=require("alasql"),K4=hd(),fD=require("util"),W4=fD.promisify(V4.getTableSchema),Q4=fD.promisify(k4.search),z4=L(),mS=Q();K4(pS);ED.exports={update:j4};var J4="There was a problem performing this update. Please check the logs and try again.";async function j4({statement:e,hdb_user:t}){let r=await W4(e.table.databaseid,e.table.tableid),n=X4(e.columns);mS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=Y4(s),c=mS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=pS.parse(u).statements[0],l=await Q4(_),d=Z4(n,l);return e3(o,d,t)}a(j4,"update");function X4(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 dD.error(t),new Error(J4)}}a(X4,"createUpdateRecord");function Z4(e,t){return mS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(Z4,"buildUpdateRecords");async function e3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await $4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){dD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(e3,"updateRecords")});var pD=g((ife,mD)=>{var t3=require("alasql"),r3=Pr(),n3=$(),s3=Cn(),TS=require("util"),SS=Q(),i3=L(),o3=Os(),nfe=pd(),sfe=vr(),a3="record",c3="successfully deleted",u3=TS.callbackify(f3),l3=TS.promisify(r3.search),_3=TS.promisify(o3.getTableSchema);mD.exports={convertDelete:u3};function d3(e){return`${e.deleted_hashes.length} ${a3}${e.deleted_hashes.length===1?"":"s"} ${c3}`}a(d3,"generateReturnMessage");async function f3({statement:e,hdb_user:t}){let r=await _3(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=t3.parse(o).statements[0],u={operation:i3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await l3(c);let _=await s3.deleteRecords(u);return SS.isEmptyOrZeroLength(_.message)&&(_.message=d3(_)),delete _.txn_time,_}catch(_){throw n3.error(_),_.hdb_code?_.message:_}}a(f3,"convertDelete")});var AD=g((afe,RD)=>{"use strict";var E3=As(),{hdb_errors:SD}=ne(),{getDatabases:TD}=(Re(),ie(Fe));RD.exports={checkSchemaExists:gD,checkSchemaTableExists:h3,schema_describe:E3};async function gD(e){if(!TD()[e])return SD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(gD,"checkSchemaExists");async function h3(e,t){let r=await gD(e);if(r)return r;if(!TD()[e][t])return SD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(h3,"checkSchemaTableExists")});var ou=g((ufe,m3)=>{m3.exports={name:"harperdb",version:"4.3.2",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.3",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.3","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:()=>kr,recordActionBinary:()=>cn,setAnalyticsEnabled:()=>p3});function p3(e){LD=e}function kr(e,t,r,n,s){if(!LD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=gd.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},gd.set(i,o)}Sd||S3()}function cn(e,t,r,n,s){kr(!!e,t,r,n,s)}function lu(e){PD.push(e)}function S3(){Sd=performance.now(),setTimeout(async()=>{let e=performance.now()-Sd;Sd=0;let t=[],r={time:Date.now(),period:e,threadId:so.threadId,metrics:t};for(let[s,i]of gd){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 vD){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 BD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:so.threadId,byThread:!0,...n});for(let s of PD)s(t);gd=new Map,so.parentPort?so.parentPort.postMessage({type:UD,report:r}):GD({report:r})},MD).unref()}async function T3(e,t=6e4){let r=AS(),n=HD(),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:b}=S;for(let R of T||[]){let{path:M,method:v,type:P,metric:k,count:H,total:j,distribution:z,threads:J,...me}=R;H||(H=1);let ce=k+(M?"-"+M:"");v!==void 0&&(ce+="-"+v),P!==void 0&&(ce+="-"+P);let de=c.get(ce);if(de){if(de.threads){let Be=de.threads[b];if(Be)de=Be;else{de.threads[b]=Object.assign({},me);continue}}de.count||(de.count=1);let Le=de.count;for(let Be in me){let Lt=me[Be];typeof Lt=="number"&&(de[Be]=(de[Be]*Le+Lt*H)/(Le+H))}de.count+=H,j>=0&&(de.total+=j,de.ratio=de.total/de.count)}else de=Object.assign({period:t},R),delete de.distribution,c.set(ce,de),de.byThread&&(de.threads=[],de.threads[b]=Object.assign({},me),_.push(de));if(z){z=z.map(Be=>typeof Be=="number"?{value:Be,count:1}:Be);let Le=u.get(ce);Le?Le.push(...z):u.set(ce,z)}}await BD()}for(let p of _){let{path:S,method:T,type:b,metric:R,count:M,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((Be,Lt)=>Be.value>Lt.value?1:-1);let b=T.count-1,R=[],M=0,v=0,P;for(let Be of vD){let Lt=b*Be;for(;M<Lt;)P=S[v++],M+=P.count,v===1&&M--;let zl=S[v>1?v-2:0];P||(P=S[0]),R.push(P.value-(P.value-zl.value)*(M-Lt)/P.count)}let[k,H,j,z,J,me,ce,de,Le]=R;Object.assign(T,{p1:k,p10:H,p25:j,median:z,p75:J,p90:me,p95:ce,p99:de,p999:Le})}let d;for(let[p,S]of c)S.id=(0,Td.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,Td.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:E-OD,active:h-bD,taskQueueLatency:await s,time:f,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}OD=E,bD=h}async function yD(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 ND||(ND=lt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function HD(){return ID||(ID=lt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function A3(){xD=!0;let e=(0,uu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await T3(MD,e),await yD(AS(),g3),await yD(HD(),R3)},Math.min(e/2,2147483647)).unref()}function GD(e,t){let r=e.report;r.threadId=t?.threadId||so.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(wD+=n.mean*n.count);r.totalBytesProcessed=wD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(CD.get(t))}),CD.set(t,t.performance.eventLoopUtilization())),r.id=(0,Td.getNextMonotonicTime)(),AS().primaryStore.put(r.id,r),xD||A3(),O3&&(qD=y3(r))}async function y3(e){if(await qD,!li){let r=(0,cu.dirname)((0,au.getLogFilePath)());try{li=await(0,gS.open)((0,cu.join)(r,"analytics.log"),"r+")}catch{li=await(0,gS.open)((0,cu.join)(r,"analytics.log"),"w+")}}let t=(await li.stat()).size;if(t>b3){let r=Buffer.alloc(t);await li.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await li.write(r,{position:0}),await li.truncate(r.length),t=r.length}await li.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var so,DD,au,cu,gS,Td,uu,RS,gd,LD,Sd,MD,UD,PD,vD,OD,bD,BD,g3,R3,ND,ID,xD,wD,CD,O3,qD,li,b3,ws=ge(()=>{so=require("worker_threads"),DD=B(Ke());Re();au=B($()),cu=require("path"),gS=require("fs/promises"),Td=B(Dr()),uu=B(ee()),RS=B(L());or();(0,uu.initSync)();gd=new Map,LD=(0,uu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(p3,"setAnalyticsEnabled");a(kr,"recordAction");nt.recordAnalytics=kr;a(cn,"recordActionBinary");Sd=0,MD=1e3,UD="analytics-report",PD=[];a(lu,"addAnalyticsListener");vD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(S3,"sendAnalytics");a(T3,"aggregation");OD=0,bD=0,BD=a(()=>new Promise(setImmediate),"rest");a(yD,"cleanup");g3=36e5,R3=31536e6;a(AS,"getRawAnalyticsTable");a(HD,"getAnalyticsTable");(0,DD.setChildListenerByType)(UD,GD);a(A3,"startScheduledTasks");wD=0,CD=new Map,O3=!1;a(GD,"recordAnalytics");b3=1e6;a(y3,"logAnalytics")});var wS=g((Afe,JD)=>{"use strict";var{decode:N3}=require("msgpackr"),{isMainThread:Tfe,parentPort:gfe,threadId:Rfe}=require("worker_threads"),du=it(),ca=ke(),yS=L(),Xt=$(),bS=ee(),I3=L(),{onMessageByType:w3}=Ke(),VD=Rs(),{recordAction:C3,recordActionBinary:D3}=(ws(),ie(_u)),{publishToStream:L3}=du,{ConsumerEvents:FD}=require("nats"),M3=Pr(),{promisify:U3}=require("util"),$D=U3(setTimeout),Od=1e4,bd,Ad,P3,v3,YD,fu=new Map,ua=new Map;JD.exports={initialize:NS,ingestConsumer:IS,setSubscription:B3,setIgnoreOrigin:G3,getDatabaseSubscriptions:x3,updateConsumer:KD};async function NS(){w3(yS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await KD(n)}),YD=!0,Xt.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await du.getNATSReferences();bd=e,Ad=e.info.server_name,P3=t,v3=r}a(NS,"initialize");async function KD(e){if(e.status==="start"){let{js:t,jsm:r}=await WD(e.node_domain_name);IS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=fu.get(e.stream_name+e.node_domain_name);t&&(Xt.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),fu.set(e.stream_name+e.node_domain_name,"close")),ua.get(e.node_domain_name)==="failed"&&ua.set(e.node_domain_name,"close")}}a(KD,"updateConsumer");var yd=new Map;function B3(e,t,r){let n=yd.get(e);n||yd.set(e,n=new Map),n.set(t,r),YD||NS().then(H3)}a(B3,"setSubscription");async function H3(){let e=await M3.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 WD(r),!n))break;let{schema:o,table:c}=i,u=VD.createNatsTableStreamName(o,c);IS(u,n,s,r)}}}a(H3,"accessConsumers");async function WD(e){let t,r,n=1;for(;!r;)try{t=await bd.jetstream({domain:e}),r=await bd.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(ua.get(e)==="close")break;ua.set(e,"failed"),n%10===1&&Xt.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<Od?n++*100:Od;await $D(i)}return{js:t,jsm:r}}a(WD,"connectToRemoteJS");function x3(){return yd}a(x3,"getDatabaseSubscriptions");var QD;function G3(e){QD=e}a(G3,"setIgnoreOrigin");var zD=100,kD=new Array(zD),Rd=0;async function IS(e,t,r,n){let{connection:s}=await du.getNATSReferences();bd=s,Ad=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,Ad),Xt.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(ua.get(n)==="close")break;o%10===1&&Xt.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(Xt.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await du.createConsumer(r,e,Ad,new Date(Date.now()).toISOString()));let l=o++*100<Od?o++*100:Od;await $D(l)}let c=!1,u;for(;!c;){if(fu.get(e+n)==="close"||ua.get(n)==="close"){fu.delete(e+n),c=!0;continue}u=await i.consume({max_messages:bS.get(yS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100}),fu.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===FD.ConsumerDeleted&&(await u.close(),c=!0),l.type===FD.HeartbeatsMissed){let d=l.data;Xt.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===2&&(Xt.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await kD[Rd],kD[Rd]=q3(l).catch(d=>{Xt.error(d)}),++Rd>=zD&&(Rd=0)}catch(l){l.message==="consumer deleted"?(Xt.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):Xt.error("Error consuming clustering ingest, restarting consumer",l)}du.clearClientCache(),!c&&_&&await NS()}}a(IS,"ingestConsumer");async function q3(e){let t=N3(e.data);C3(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),Xt.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=bS.get(yS.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&&!QD),D3(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;Xt.trace("processing message:",o,c,_,(l?"records: "+l.map(M=>M?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Xt.trace(`messageProcessor nats msg id: ${e.headers.get(ca.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let p=new Promise(M=>h=M),{timestamp:S,user:T,node_name:b}=f||{},R=yd.get(c)?.get(_);if(!R)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,R.send(t);else if(l.length===1&&!u)R.send({type:OS(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:S,table:_,onCommit:h,user:T,nodeName:b});else{let M=l.map((v,P)=>({type:OS(o),value:v,expiresAt:E,id:d?.[P],table:_}));for(;u;)M.push({type:OS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;R.send({type:"transaction",writes:M,table:_,timestamp:S,onCommit:h,user:T,nodeName:b})}bS.get(I3.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&L3(e.subject.split(".").slice(0,-1).join("."),VD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){Xt.error(o)}e.ack()}a(q3,"messageProcessor");function OS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(OS,"convertOperation")});var it=g((Cfe,fL)=>{"use strict";var Pt=ee();Pt.initSync();var F3=require("fs-extra"),k3=require("semver"),mu=require("path"),{monotonicFactory:V3}=require("ulidx"),XD=V3(),$3=require("util"),ZD=require("child_process"),Y3=$3.promisify(ZD.exec),K3=ZD.spawn,Vt=ke(),Ne=L(),Nd=Q(),Bn=$(),Id=Rs(),W3=pd(),Eu=lr(),{broadcast:Q3,onMessageByType:z3,getWorkerIndex:J3}=Ke(),{isMainThread:eL}=require("worker_threads"),{Encoder:j3,decode:MS}=require("msgpackr"),tL=new j3,{isEmpty:co}=Nd,rL=an(),bfe=48*36e11;eL&&z3(Ne.ITC_EVENT_TYPES.RESTART,()=>{Er=void 0,ao=void 0});var{connect:X3,StorageType:Z3,RetentionPolicy:ej,AckPolicy:US,DeliverPolicy:PS,DiscardPolicy:tj,NatsConnection:yfe,JetStreamManager:Nfe,JetStreamClient:Ife,StringCodec:wfe,JSONCodec:rj,createInbox:vS,headers:nj,ErrorCode:jD}=require("nats"),{PACKAGE_ROOT:sj}=L(),ij=ou(),{recordAction:oj}=(ws(),ie(_u)),nL=rj(),aj="clustering",cj=ij.engines[Vt.NATS_SERVER_NAME],uj=mu.join(sj,"dependencies"),LS=mu.join(uj,`${process.platform}-${process.arch}`,Vt.NATS_BINARY_NAME),CS,DS,hu,io,oo;fL.exports={runCommand:sL,checkNATSServerInstalled:lj,createConnection:BS,getConnection:pu,getJetStreamManager:Su,getJetStream:oL,getNATSReferences:ss,getServerList:dj,createLocalStream:HS,listStreams:aL,deleteLocalStream:fj,getServerConfig:la,listRemoteStreams:Ej,viewStream:hj,viewStreamIterator:mj,publishToStream:pj,request:gj,reloadNATS:xS,reloadNATSHub:Rj,reloadNATSLeaf:Aj,extractServerName:Tj,requestErrorHandler:Oj,createLocalTableStream:_L,createTableStreams:Nj,purgeTableStream:dL,purgeSchemaTableStreams:Ij,getStreamInfo:wj,updateLocalStreams:Dj,closeConnection:_j,getJsmServerName:wd,addNatsMsgHeader:cL,clearClientCache:iL,updateRemoteConsumer:bj,createConsumer:uL,updateConsumerIterator:yj};async function sL(e,t=void 0){let{stdout:r,stderr:n}=await Y3(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(sL,"runCommand");async function uX(){try{await q3.access(LS)}catch{return!1}let e=await sL(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return F3.eq(t,aX)}a(uX,"checkNATSServerInstalled");async function BS(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await tL.getClusterUser();if(uo(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bs.trace("create nats connection called");let i=await X3({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:2e5,tls:{keyFile:Pt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Pt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Pt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bs.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bs.error("Error with Nats client connection, connection closed",o),nL()}),i}a(BS,"createConnection");function nL(){Er=void 0,oo=void 0,ao=void 0,co=void 0}a(nL,"clearClientCache");async function lX(){Er&&(await Er.drain(),Er=void 0,oo=void 0,ao=void 0,co=void 0)}a(lX,"closeConnection");var Er,co;async function Nd(){return co||(co=BS(Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Er=await co),Er||co}a(Nd,"getConnection");async function mu(){if(oo)return oo;uo(Er)&&await Nd();let{domain:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=await Er.jetstreamManager({domain:e,timeout:6e4}),oo}a(mu,"getJetStreamManager");async function iL(){if(ao)return ao;uo(Er)&&await Nd();let{domain:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ao=Er.jetstream({domain:e,timeout:6e4}),ao}a(iL,"getJetStream");async function Hs(){let e=Er||await Nd(),t=oo||await mu(),r=ao||await iL();return{connection:e,jsm:t,js:r}}a(Hs,"getNATSReferences");async function _X(e){let t=Pt.get(De.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await tL.getClusterUser(),n=await BS(t,r,s),i=vS(),o=n.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=rL.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await n.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await n.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await n.flush(),await bd.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(_X,"getServerList");async function HS(e,t){let{jsm:r}=await Hs(),s=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:j3.File,retention:Z3.Limits,subjects:t,discard:eX.Old,max_msgs:n,max_bytes:i,max_age:s})}a(HS,"createLocalStream");async function oL(){let{jsm:e}=await Hs(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(oL,"listStreams");async function dX(e){let{jsm:t}=await Hs();await t.streams.delete(e)}a(dX,"deleteLocalStream");async function fX(e){let{connection:t}=await Hs(),r=[],s=vS(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(rL.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(fX,"listRemoteStreams");async function EX(e,t=void 0,r=void 0){let{jsm:s,js:n}=await Hs(),i=XD(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=PS.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=MS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Vt.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(EX,"viewStream");async function*hX(e,t=void 0,r=void 0){let{jsm:s,js:n}=await Hs(),i=XD(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=PS.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=MS(_.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(Vt.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(hX,"viewStreamIterator");async function mX(e,t,r,s){Bs.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=aL(s,r);let{js:n}=await Hs(),i=await Id(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:eL.encode(s);try{Bs.trace(`publishToStream publishing to subject: ${o}`),iX(c.length,"bytes-sent",e,s.operation,"replication"),await n.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return uL(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bs.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await HS(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(mX,"publishToStream");function aL(e,t){t===void 0&&(t=rX());let r=Pt.get(De.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Vt.MSG_HEADERS.ORIGIN)&&r&&t.append(Vt.MSG_HEADERS.ORIGIN,r),t}a(aL,"addNatsMsgHeader");function pu(e){e=e.toLowerCase();let t=hu.join(Pt.get(De.CONFIG_PARAMS.ROOTPATH),oX);if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return uo(DS)&&(DS={port:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.HUB,config_file:Vt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:hu.join(t,Vt.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return uo(CS)&&(CS={port:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,config_file:Vt.NATS_CONFIG_FILES.LEAF_SERVER,domain:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,pid_file_path:hu.join(t,Vt.PID_FILES.LEAF),hdb_nats_path:t}),CS;Bs.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(pu,"getServerConfig");async function cL(e,t,r,s){try{await e.consumers.add(t,{ack_policy:US.Explicit,durable_name:r,deliver_policy:PS.StartTime,opt_start_time:s})}catch(n){if(n.message!=="consumer already exists")throw n}}a(cL,"createConsumer");async function pX(e,t,r){await e.consumers.delete(t,r)}a(pX,"removeConsumer");function SX(e){return e.split(".")[1]}a(SX,"extractServerName");async function TX(e,t,r=6e4,s=vS()){if(!bd.isObject(t))throw new Error("data param must be an object");let n=eL.encode(t),{connection:i}=await Hs(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return MS(c.data)}a(TX,"request");function xS(e){return new Promise(async(t,r)=>{let s=Y3(LS,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(xS,"reloadNATS");async function gX(){let{pid_file_path:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await xS(e)}a(gX,"reloadNATSHub");async function RX(){let{pid_file_path:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await xS(e)}a(RX,"reloadNATSLeaf");function AX(e,t,r){let s;switch(e.code){case JD.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case JD.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(AX,"requestErrorHandler");async function OX(e,t){let r=t+Vt.SERVER_SUFFIX.LEAF,{connection:s}=await Hs(),{jsm:n}=await LX(r),{schema:i,table:o}=e,c=yd.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await uL(async()=>{if(e.subscribe===!0)await cL(n,c,s.info.server_name,u);else try{await pX(n,c,s.info.server_name)}catch(_){Bs.trace(_)}})}a(OX,"updateRemoteConsumer");async function bX(e,t,r,s){let n=yd.createNatsTableStreamName(e,t),i=r+Vt.SERVER_SUFFIX.LEAF,o={type:De.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:s,stream_name:n,node_domain_name:i};if(!ZD&&z3()<Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=wS();await c(o)}await W3(o),s==="stop"&&await bd.async_set_timeout(1e3)}a(bX,"updateConsumerIterator");function uL(e){return K3.writeTransaction(De.SYSTEM_SCHEMA_NAME,De.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(uL,"exclusiveLock");async function lL(e,t){let r=yd.createNatsTableStreamName(e,t),s=await Id(),n=wX(e,t,s);await HS(r,[n])}a(lL,"createLocalTableStream");async function yX(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await lL(s,n)}}a(yX,"createTableStreams");async function _L(e,t,r=void 0){if(Pt.get(De.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let s=yd.createNatsTableStreamName(e,t),{jsm:n}=await Hs();await n.streams.purge(s,r)}catch(s){if(s.message==="stream not found")Bs.warn(s);else throw s}}a(_L,"purgeTableStream");async function NX(e,t){if(Pt.get(De.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await _L(e,t[r])}a(NX,"purgeSchemaTableStreams");async function IX(e){return(await mu()).streams.info(e)}a(IX,"getStreamInfo");function wX(e,t,r){return`${Vt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(wX,"createSubjectName");async function Id(){if(Eu)return Eu;if(Eu=(await mu())?.nc?.info?.server_name,Eu===void 0)throw new Error("Unable to get jetstream manager server name");return Eu}a(Id,"getJsmServerName");async function CX(){let e=await mu(),t=await Id(),r=await oL();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=DX(s),c=i.split(".");if(c[c.length-1]===t&&!o||n.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bs.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l,await e.streams.update(n.name,n)}}a(CX,"updateLocalStreams");function DX(e){let{config:t}=e,r=!1,s=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(DX,"updateStreamLimits");async function LX(e){let t,r;try{t=await Er.jetstream({domain:e}),r=await Er.jetstreamManager({domain:e,checkAPI:!1})}catch(s){throw Bs.error("Unable to connect to:",e),s}return{js:t,jsm:r}}a(LX,"connectToRemoteJS")});var Su=g((Cfe,mL)=>{"use strict";var la=O_(),_a=RD(),MX=$(),UX=require("uuid").v4,wfe=require("clone"),Cd=bn(),da=L(),PX=require("util"),_i=Cs(),{handleHDBError:hr,hdb_errors:vX}=se(),{HDB_ERROR_MSGS:wd,HTTP_STATUS_CODES:mr}=vX,{SchemaEventMsg:Dd}=Ms(),fL=it(),{getDatabases:BX}=(Re(),ie(Fe)),{transformReq:fa}=Q();mL.exports={createSchema:HX,createSchemaStructure:EL,createTable:xX,createTableStructure:hL,createAttribute:VX,dropSchema:GX,dropTable:qX,dropAttribute:FX,getBackup:$X};async function HX(e){let t=await EL(e);return Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),t}a(HX,"createSchema");async function EL(e){let t=la.schema_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);if(fa(e),!await _a.checkSchemaExists(e.schema))throw hr(new Error,wd.SCHEMA_EXISTS_ERR(e.schema),mr.BAD_REQUEST,da.LOG_LEVELS.ERROR,wd.SCHEMA_EXISTS_ERR(e.schema),!0);return await _i.createSchema(e),`database '${e.schema}' successfully created`}a(EL,"createSchemaStructure");async function xX(e){return fa(e),e.hash_attribute=e.primary_key??e.hash_attribute,await hL(e)}a(xX,"createTable");async function hL(e){let t=la.create_table_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);if(la.validateTableResidence(e.residence),!await _a.checkSchemaTableExists(e.schema,e.table))throw hr(new Error,wd.TABLE_EXISTS_ERR(e.schema,e.table),mr.BAD_REQUEST,da.LOG_LEVELS.ERROR,wd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:UX(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await _i.createTable(s,e);else throw hr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",mr.BAD_REQUEST);else await _i.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(hL,"createTableStructure");async function GX(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=la.schema_object(e),s=t??r;if(s)throw hr(s,s.message,mr.BAD_REQUEST,void 0,void 0,!0);fa(e);let n=await _a.checkSchemaExists(e.schema);if(n)throw hr(new Error,n,mr.NOT_FOUND,da.LOG_LEVELS.ERROR,n,!0);let i=await _a.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await _i.dropSchema(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),await fL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(GX,"dropSchema");async function qX(e){let t=la.table_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);fa(e);let r=await _a.checkSchemaTableExists(e.schema,e.table);if(r)throw hr(new Error,r,mr.NOT_FOUND,da.LOG_LEVELS.ERROR,r,!0);return await _i.dropTable(e),await fL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(qX,"dropTable");async function FX(e){let t=la.attribute_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);fa(e);let r=await _a.checkSchemaTableExists(e.schema,e.table);if(r)throw hr(new Error,r,mr.NOT_FOUND,da.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw hr(new Error,"You cannot drop a hash attribute",mr.BAD_REQUEST,void 0,void 0,!0);if(da.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw hr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,mr.BAD_REQUEST,void 0,void 0,!0);try{return await _i.dropAttribute(e),kX(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw MX.error(`Got an error deleting attribute ${PX.inspect(e)}.`),s}}a(FX,"dropAttribute");function kX(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(kX,"dropAttributeFromGlobal");async function VX(e){fa(e);let t=BX()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw hr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,mr.BAD_REQUEST,void 0,void 0,!0);return await _i.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(VX,"createAttribute");function $X(e){return _i.getBackup(e)}a($X,"getBackup")});var SL=g((Lfe,pL)=>{"use strict";var{OPERATIONS_ENUM:YX}=L(),GS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=YX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};pL.exports=GS});var qS=g((Pfe,OL)=>{"use strict";var KX=Cs(),Ufe=SL(),Ld=Q(),Md=L(),WX=ee(),{handleHDBError:TL,hdb_errors:QX}=se(),{HDB_ERROR_MSGS:gL,HTTP_STATUS_CODES:RL}=QX,zX=Object.values(Md.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),AL="To use this operation audit log must be enabled in harperdb-config.yaml";OL.exports=JX;async function JX(e){if(Ld.isEmpty(e.schema))throw new Error(gL.SCHEMA_REQUIRED_ERR);if(Ld.isEmpty(e.table))throw new Error(gL.TABLE_REQUIRED_ERR);if(!WX.get(Md.CONFIG_PARAMS.LOGGING_AUDITLOG))throw TL(new Error,AL,RL.BAD_REQUEST,Md.LOG_LEVELS.ERROR,AL,!0);let t=Ld.checkSchemaTableExist(e.schema,e.table);if(t)throw TL(new Error,t,RL.NOT_FOUND,Md.LOG_LEVELS.ERROR,t,!0);if(!Ld.isEmpty(e.search_type)&&zX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await KX.readAuditLog(e)}a(JX,"readAuditLog")});var yL=g((Bfe,bL)=>{"use strict";var{OPERATIONS_ENUM:XX}=L(),FS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=XX.GET_BACKUP,this.schema=t,this.table=r}};bL.exports=FS});var wL=g((qfe,IL)=>{"use strict";var jX=Cs(),xfe=yL(),kS=Q(),ZX=L(),Gfe=ee(),{handleHDBError:ej,hdb_errors:tj}=se(),{HDB_ERROR_MSGS:NL,HTTP_STATUS_CODES:rj}=tj;IL.exports=sj;async function sj(e){if(kS.isEmpty(e.schema))throw new Error(NL.SCHEMA_REQUIRED_ERR);if(kS.isEmpty(e.table))throw new Error(NL.TABLE_REQUIRED_ERR);let t=kS.checkSchemaTableExist(e.schema,e.table);if(t)throw ej(new Error,t,rj.NOT_FOUND,ZX.LOG_LEVELS.ERROR,t,!0);return await jX.getBackup(read_audit_log_object)}a(sj,"getBackup")});var PL=g((kfe,UL)=>{var di=require("validate.js"),DL=Xe(),Ea=L(),{handleHDBError:nj,hdb_errors:ij}=se(),{HDB_ERROR_MSGS:dt,HTTP_STATUS_CODES:oj}=ij,VS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),aj={STRUCTURE_USER:"structure_user"},CL=Object.values(Ea.ROLE_TYPES_ENUM),cj="attribute_permissions",uj="attribute_name",{PERMS_CRUD_ENUM:ha}=Ea,lj=[cj,...Object.values(ha)],LL=[ha.READ,ha.INSERT,ha.UPDATE],_j=[uj,...LL];function dj(e){let t=VS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,ML(e,t)}a(dj,"addRoleValidation");function fj(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,ML(e,t)}a(fj,"alterRoleValidation");function Ej(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,DL.validateObject(e,t)}a(Ej,"dropRoleValidation");var hj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function ML(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)hj.includes(s[o])||n.push(s[o]);n.length>0&&St(dt.INVALID_ROLE_JSON_KEYS(n),r);let i=DL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{St(o,r)}),e.permission){let o=mj(e);o&&St(o,r),CL.forEach(c=>{e.permission[c]&&!di.isBoolean(e.permission[c])&&St(dt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(CL.indexOf(o)<0){if(o===aj.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]||St(dt.SCHEMA_NOT_FOUND(d),r)}continue}St(dt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){St(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]){St(dt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{lj.includes(l)||St(dt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ha).forEach(l=>{di.isDefined(_[l])?di.isBoolean(_[l])||St(dt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):St(dt.TABLE_PERM_MISSING(l),r,o,u)}),di.isDefined(_.attribute_permissions)){if(!di.isArray(_.attribute_permissions)){St(dt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{St(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=>{!_j.includes(p)&&p!==ha.DELETE&&St(dt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!di.isDefined(E.attribute_name)){St(dt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){St(dt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}LL.forEach(p=>{di.isDefined(E[p])?di.isBoolean(E[p])||St(dt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):St(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}`;St(dt.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return pj(r)}a(ML,"customValidate");UL.exports={addRoleValidation:dj,alterRoleValidation:fj,dropRoleValidation:Ej};function mj(e){let{operation:t,permission:r}=e;if(t===Ea.OPERATIONS_ENUM.ADD_ROLE||t===Ea.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return dt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Ea.ROLE_TYPES_ENUM.SUPER_USER:Ea.ROLE_TYPES_ENUM.CLUSTER_USER;return dt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(mj,"validateNoSUPerms");function pj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:dt.ROLE_PERMS_ERROR,...e};return nj(new Error,s,oj.BAD_REQUEST)}else return null}a(pj,"generateRolePermResponse");function St(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(St,"addPermError")});var zS=g(($fe,xL)=>{"use strict";var vL=vr(),BL=Pr(),Sj=ii(),YS=PL(),KS=bn(),Tj=require("uuid").v4,gj=require("util"),Ud=L(),Rj=Q(),WS=BL.searchByValue,Aj=BL.searchByHash,Oj=gj.promisify(Sj.delete),bj=tn(),yj=na(),{hdb_errors:Nj,handleHDBError:lo}=se(),{HDB_ERROR_MSGS:HL,HTTP_STATUS_CODES:Tu}=Nj,{UserEventMsg:QS}=Ms();xL.exports={addRole:Ij,alterRole:wj,dropRole:Cj,listRoles:Dj};function $S(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a($S,"scrubRoleDetails");async function Ij(e){let t=YS.addRoleValidation(e);if(t)throw t;e=$S(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},s;try{s=Array.from(await WS(r)||[])}catch(i){throw lo(i)}if(s&&s.length>0)throw lo(new Error,HL.ROLE_ALREADY_EXISTS(e.role),Tu.CONFLICT,void 0,void 0,!0);e.id||(e.id=Tj());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await vL.insert(n),KS.signalUserChange(new QS(process.pid)),e=$S(e),e}a(Ij,"addRole");async function wj(e){let t=YS.alterRoleValidation(e);if(t)throw t;e=$S(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await vL.update(r)}catch(n){throw lo(n)}if(s&&s?.message==="updated 0 of 1 records")throw lo(new Error,"Invalid role id",Tu.BAD_REQUEST,void 0,void 0,!0);return await KS.signalUserChange(new QS(process.pid)),e}a(wj,"alterRole");async function Cj(e){let t=YS.dropRoleValidation(e);if(t)throw lo(new Error,t,Tu.BAD_REQUEST,void 0,void 0,!0);let r=new yj(Ud.SYSTEM_SCHEMA_NAME,Ud.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await Aj(r));if(s.length===0)throw lo(new Error,HL.ROLE_NOT_FOUND,Tu.NOT_FOUND,void 0,void 0,!0);let n=new bj(Ud.SYSTEM_SCHEMA_NAME,Ud.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await WS(n)),o=!1;if(Rj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw lo(new Error,`Cannot drop role ${s[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 Oj(c),KS.signalUserChange(new QS(process.pid)),`${s[0].role} successfully deleted`}a(Cj,"dropRole");async function Dj(){return WS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Dj,"listRoles")});var kL=g((Kfe,FL)=>{"use strict";var Lj=ee(),fi=require("joi"),Mj=Xe(),GL=require("moment"),Uj=require("fs-extra"),JS=require("path"),Pj=require("lodash"),gu=L(),{LOG_LEVELS:_o}=L(),vj="YYYY-MM-DD hh:mm:ss",Bj=JS.resolve(__dirname,"../logs");FL.exports=function(e){return Mj.validateBySchema(e,Hj)};var Hj=fi.object({from:fi.custom(qL),until:fi.custom(qL),level:fi.valid(_o.NOTIFY,_o.FATAL,_o.ERROR,_o.WARN,_o.INFO,_o.DEBUG,_o.TRACE),order:fi.valid("asc","desc"),limit:fi.number().min(1),start:fi.number().min(0),log_name:fi.custom(xj)});function qL(e,t){if(GL(e,GL.ISO_8601).format(vj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(qL,"validateDatetime");function xj(e,t){if(Pj.invert(gu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=Lj.get(gu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?gu.LOG_NAMES.HDB:e,i=n===gu.LOG_NAMES.INSTALL?JS.join(Bj,gu.LOG_NAMES.INSTALL):JS.join(s,n);return Uj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(xj,"validateReadLogPath")});var jS=g((Qfe,$L)=>{"use strict";var Pd=L(),Gj=$(),qj=ee(),Fj=kL(),XS=require("path"),VL=require("fs-extra"),{once:kj}=require("events"),{handleHDBError:Vj,hdb_errors:$j}=se(),{PACKAGE_ROOT:Yj}=L(),Kj=XS.join(Yj,"logs"),Wj=1e3,Qj=200;$L.exports=zj;async function zj(e){let t=Fj(e);if(t)throw Vj(t,t.message,$j.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=qj.get(Pd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?Pd.LOG_NAMES.HDB:e.log_name,n=s===Pd.LOG_NAMES.INSTALL?XS.join(Kj,Pd.LOG_NAMES.INSTALL):XS.join(r,s),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?Wj: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(VL.statSync(n).size-(h+5)*Qj,0));let S=VL.createReadStream(n,{start:p});S.on("error",P=>{Gj.error(P)});let T=0,A=[],R="",M;S.on("data",P=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;P=R+P;let B=0,X;for(;(X=k.exec(P))&&!S.destroyed;){M&&(M.message=P.slice(B,X.index),x(M));let[z,J,me]=X,ce=me.split("] ["),de=ce[0],Le=ce[1];ce.splice(0,2),M={timestamp:J,thread:de,level:Le,tags:ce,message:""},B=X.index+z.length}R=P.slice(B)}),S.on("end",P=>{S.destroyed||M&&(M.message=R.trim(),x(M))}),S.resume();function x(P){let k,B,X;switch(!0){case(i&&c&&_):k=new Date(P.timestamp),B=new Date(u),X=new Date(l),P.level===o&&k>=B&&k<=X&&T<E?T++:P.level===o&&k>=B&&k<=X&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case(i&&c):k=new Date(P.timestamp),B=new Date(u),P.level===o&&k>=B&&T<E?T++:P.level===o&&k>=B&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case(i&&_):k=new Date(P.timestamp),X=new Date(l),P.level===o&&k<=X&&T<E?T++:P.level===o&&k<=X&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case(c&&_):k=new Date(P.timestamp),B=new Date(u),X=new Date(l),k>=B&&k<=X&&T<E?T++:k>=B&&k<=X&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case i:P.level===o&&T<E?T++:P.level===o&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case c:k=new Date(P.timestamp),B=new Date(u),k>=B&&T<E?T++:k>=B&&T>=E&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case _:k=new Date(P.timestamp),X=new Date(l),k<=X&&T<E?T++:k<=X&&T>=E&&(Ei(P,f,A),T++,T===h&&S.destroy());break;default:T<E?T++:(Ei(P,f,A),T++,T===h&&S.destroy())}}return a(x,"onLogMessage"),await kj(S,"close"),A}a(zj,"readLog");function Ei(e,t,r){t==="desc"?Jj(e,r):t==="asc"?Xj(e,r):r.push(e)}a(Ei,"pushLineToResult");function Jj(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(Jj,"insertDescending");function Xj(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(Xj,"insertAscending")});var vd=g((Zfe,QL)=>{"use strict";var ZS=require("joi"),{string:Ru,boolean:YL,date:jj}=ZS.types(),Zj=Xe(),{validateSchemaExists:Jfe,validateTableExists:Xfe,validateSchemaName:jfe}=Js(),eZ=L(),tZ=ke(),KL=ee();KL.initSync();var rZ=Ru.invalid(KL.get(eZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(tZ.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(),WL={operation:Ru.valid("add_node","update_node","set_node_replication"),node_name:rZ,subscriptions:ZS.array().items({table:Ru.optional(),schema:Ru.optional(),database:Ru.optional(),subscribe:YL.required(),publish:YL.required().custom(nZ),start_time:jj.iso()}).min(1).required()};function sZ(e){return Zj.validateBySchema(e,ZS.object(WL))}a(sZ,"addUpdateNodeValidator");function nZ(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(nZ,"checkForFalsy");QL.exports={addUpdateNodeValidator:sZ,validation_schema:WL}});var JL=g((tEe,zL)=>{var iZ=Xe(),oZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};zL.exports=function(e){return iZ.validateObject(e,oZ)}});var Bd=g((rEe,XL)=>{"use strict";var aZ=L().OPERATIONS_ENUM,eT=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=aZ.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};XL.exports=eT});var ZL=g((nEe,jL)=>{"use strict";var cZ={OPERATION:"operation",REFRESH:"refresh"},tT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},rT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};jL.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:cZ,JWTRSAKeys:rT}});var bu=g((oEe,sM)=>{"use strict";var Ou=require("jsonwebtoken"),sT=require("fs-extra"),nT=Q(),cs=L(),{handleHDBError:pr,hdb_errors:uZ}=se(),{HTTP_STATUS_CODES:Sr,AUTHENTICATION_ERROR_MSGS:Tr}=uZ,Au=$(),eM=G_(),aT=os(),lZ=vr().update,_Z=Bd(),dZ=bn(),{UserEventMsg:fZ}=Ms(),hi=ee();hi.initSync();var iT=require("path"),{JWTTokens:EZ,JWTRSAKeys:hZ,TOKEN_TYPE_ENUM:Hd}=ZL(),mZ=hi.get(cs.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?hi.get(cs.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",pZ=hi.get(cs.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?hi.get(cs.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",xd="RS256",oT;sM.exports={createTokens:SZ,validateOperationToken:gZ,refreshOperationToken:TZ,validateRefreshToken:rM};async function SZ(e){if(nT.isEmpty(e)||typeof e!="object")throw pr(new Error,Tr.INVALID_AUTH_OBJECT,Sr.BAD_REQUEST,void 0,void 0,!0);if(nT.isEmpty(e.username))throw pr(new Error,Tr.USERNAME_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);if(nT.isEmpty(e.password))throw pr(new Error,Tr.PASSWORD_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw pr(new Error,Tr.INVALID_CREDENTIALS,Sr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Au.error(f),pr(new Error,Tr.INVALID_CREDENTIALS,Sr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Gd(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await tM(i,r.private_key,r.passphrase),c=await Ou.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:pZ,algorithm:xd,subject:Hd.REFRESH}),u=eM.hash(c),_=new _Z(cs.SYSTEM_SCHEMA_NAME,cs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await lZ(_)}catch(f){Au.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw pr(new Error,Tr.REFRESH_TOKEN_SAVE_FAILED,Sr.INTERNAL_SERVER_ERROR);return dZ.signalUserChange(new fZ(process.pid)),new EZ(o,c)}a(SZ,"createTokens");async function tM(e,t,r){return await Ou.sign(e,{key:t,passphrase:r},{expiresIn:mZ,algorithm:xd,subject:Hd.OPERATION})}a(tM,"signOperationToken");async function Gd(){if(oT===void 0)try{let e=iT.join(hi.getHdbBasePath(),cs.LICENSE_KEY_DIR_NAME,cs.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(hi.getHdbBasePath(),cs.LICENSE_KEY_DIR_NAME,cs.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(hi.getHdbBasePath(),cs.LICENSE_KEY_DIR_NAME,cs.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await sT.readFile(e)).toString(),n=(await sT.readFile(t)).toString(),i=(await sT.readFile(r)).toString();oT=new hZ(i,n,s)}catch(e){throw Au.error(e),pr(new Error,Tr.NO_ENCRYPTION_KEYS,Sr.INTERNAL_SERVER_ERROR)}return oT}a(Gd,"getJWTRSAKeys");async function TZ(e){if(!e)throw pr(new Error,Tr.INVALID_BODY,Sr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw pr(new Error,Tr.REFRESH_TOKEN_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);await rM(e.refresh_token);let t=await Gd(),r=await Ou.decode(e.refresh_token);return{operation_token:await tM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(TZ,"refreshOperationToken");async function gZ(e){try{let t=await Gd(),r=await Ou.verify(e,t.public_key,{algorithms:xd,subject:Hd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Au.warn(t),t.name&&t.name==="TokenExpiredError"?pr(new Error,Tr.TOKEN_EXPIRED,Sr.FORBIDDEN):pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED)}}a(gZ,"validateOperationToken");async function rM(e){let t;try{let r=await Gd(),s=await Ou.verify(e,r.public_key,{algorithms:xd,subject:Hd.REFRESH});t=await aT.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Au.warn(r),r.name&&r.name==="TokenExpiredError"?pr(new Error,Tr.TOKEN_EXPIRED,Sr.FORBIDDEN):pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED)}if(!eM.validate(t.refresh_token,e))throw pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED);return t}a(rM,"validateRefreshToken")});var cT=g((uEe,oM)=>{"use strict";var RZ=JL(),ma=require("passport"),AZ=require("passport-local").Strategy,OZ=require("passport-http").BasicStrategy,bZ=require("util"),yZ=os(),iM=bZ.callbackify(yZ.findAndValidateUser),cEe=Cr(),NZ=L(),nM=bu();ma.use(new AZ(function(e,t,r){iM(e,t,r)}));ma.use(new OZ(function(e,t,r){iM(e,t,r)}));ma.serializeUser(function(e,t){t(null,e)});ma.deserializeUser(function(e,t){t(null,e)});function IZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let s,n;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),s){case"Basic":ma.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===NZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?nM.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):nM.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:ma.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(IZ,"authorize");function wZ(e,t){let r=RZ(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n?.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(wZ,"checkPermissions");oM.exports={authorize:IZ,checkPermissions:wZ}});var mi=g((_Ee,aM)=>{"use strict";var uT=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},lT=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};aM.exports={Node:uT,NodeSubscription:lT}});var uM=g((fEe,cM)=>{"use strict";var CZ=L().OPERATIONS_ENUM,_T=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=CZ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};cM.exports=_T});var yu=g((hEe,lM)=>{"use strict";var dT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},fT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,s,n,i,o,c){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};lM.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var dM=g((pEe,_M)=>{"use strict";var ET=class{static{a(this,"TableSizeObject")}constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};_M.exports=ET});var hM=g((AEe,EM)=>{"use strict";var DZ=dM(),TEe=ut(),fM=We(),LZ=$(),{getSchemaPath:gEe,getTransactionAuditStorePath:REe}=Je(),{getDatabases:MZ}=(Re(),ie(Fe));EM.exports=UZ;async function UZ(e){let t=new DZ;try{let r=MZ()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await fM.environmentDataSize(schema_path,e.name),o=await fM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=s.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=n.entryCount}catch(r){LZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(UZ,"lmdbGetTableSize")});var pM=g((bEe,mM)=>{"use strict";var hT=class{static{a(this,"SystemInformationObject")}constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};mM.exports=hT});var pa=g((CEe,AM)=>{"use strict";var PZ=require("fs-extra"),vZ=require("path"),Zt=require("systeminformation"),pi=$(),SM=it(),NEe=ke(),Fd=L(),BZ=hM(),HZ=An(),{getThreadInfo:TM}=Ke(),yT=ee();yT.initSync();var xZ=pM(),{openEnvironment:IEe}=We(),{getSchemaPath:wEe}=Je(),{database:GZ,databases:gM}=(Re(),ie(Fe)),qd;AM.exports={getHDBProcessInfo:TT,getNetworkInfo:RT,getDiskInfo:gT,getMemoryInfo:ST,getCPUInfo:pT,getTimeInfo:mT,getSystemInformation:AT,systemInformation:qZ,getTableSize:OT,getMetrics:bT};function mT(){return Zt.time()}a(mT,"getTimeInfo");async function pT(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Zt.cpu();l.cpu_speed=await Zt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...A}=await Zt.currentLoad();return A.cpus=[],T.forEach(R=>{let{raw_load:M,raw_load_idle:x,raw_load_irq:P,raw_load_nice:k,raw_load_system:B,raw_load_user:X,...z}=R;A.cpus.push(z)}),l.current_load=A,l}catch(e){return pi.error(`error in getCPUInfo: ${e}`),{}}}a(pT,"getCPUInfo");async function ST(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Zt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return pi.error(`error in getMemoryInfo: ${e}`),{}}}a(ST,"getMemoryInfo");async function TT(){let e={core:[],clustering:[]};try{let t=await Zt.processes(),r;try{r=Number.parseInt(await PZ.readFile(vZ.join(yT.get(Fd.CONFIG_PARAMS.ROOTPATH),Fd.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===Fd.NODE_ERROR_CODES.ENOENT)pi.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return pi.error(`error in getHDBProcessInfo: ${t}`),e}}a(TT,"getHDBProcessInfo");async function gT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Zt.fsStats();return e.read_write=_,e.size=await Zt.fsSize(),e}catch(t){return pi.error(`error in getDiskInfo: ${t}`),e}}a(gT,"getDiskInfo");async function RT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Zt.networkInterfaceDefault(),e.latency=await Zt.inetChecksite("google.com"),(await Zt.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=s;e.interfaces.push(f)}),(await Zt.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return pi.error(`error in getNetworkInfo: ${t}`),e}}a(RT,"getNetworkInfo");async function AT(){if(qd!==void 0)return qd;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Zt.osInfo();e=c;let u=await Zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,qd=e,qd}catch(t){return pi.error(`error in getSystemInformation: ${t}`),e}}a(AT,"getSystemInformation");async function OT(){let e=[],t=await HZ.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await BZ(s));return e}a(OT,"getTableSize");async function bT(){let e={};for(let t in gM){let r=e[t]={};for(let s in gM[t])try{let n=GZ({database:t,table:s}),i=n.getStats();i.readers=n.readerList().split(/\n\s+/).slice(1).map(o=>{let[c,u,_]=o.trim().split(" ");return{pid:c,thread:u,txnid:_}}),r[s]=i}catch(n){pi.notify(`Error getting stats for table ${s}: ${n}`)}}return e}a(bT,"getMetrics");async function RM(){if(yT.get(Fd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await SM.getNATSReferences(),t=await SM.listStreams(),r=[];for(let s of t){let n=[],i=await e.consumers.list(s.config.name);for await(let c of i)n.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:s.config.name,database:s.config.subjects[0].split(".")[1],table:s.config.subjects[0].split(".")[2],state:s.state,consumers:n};r.push(o)}return r}}a(RM,"getNatsStreamInfo");async function qZ(e){let t=new xZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await AT(),t.time=mT(),t.cpu=await pT(),t.memory=await ST(),t.disk=await gT(),t.network=await RT(),t.harperdb_processes=await TT(),t.table_size=await OT(),t.metrics=await bT(),t.threads=await TM(),t.replication=await RM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await AT();break;case"time":t.time=mT();break;case"cpu":t.cpu=await pT();break;case"memory":t.memory=await ST();break;case"disk":t.disk=await gT();break;case"network":t.network=await RT();break;case"harperdb_processes":t.harperdb_processes=await TT();break;case"table_size":t.table_size=await OT();break;case"database_metrics":case"metrics":t.metrics=await bT();break;case"threads":t.threads=await TM();break;case"replication":t.replication=await RM();break;default:break}return t}a(qZ,"systemInformation")});var Vd=g((LEe,OM)=>{"use strict";OM.exports={version:FZ,printVersion:kZ};var kd=iu();function FZ(){if(kd)return kd.version}a(FZ,"version");function kZ(){kd&&console.log(`HarperDB Version ${kd.version}`)}a(kZ,"printVersion")});var us=g((vEe,IM)=>{"use strict";var VZ=vr(),NT=Q(),$Z=require("util"),fo=L(),bM=ee();bM.initSync();var YZ=cT(),yM=Pr(),{Node:UEe,NodeSubscription:PEe}=mi(),KZ=na(),WZ=uM(),{RemotePayloadObject:QZ,RemotePayloadSubscription:zZ}=yu(),{handleHDBError:JZ,hdb_errors:XZ}=se(),{HTTP_STATUS_CODES:jZ,HDB_ERROR_MSGS:ZZ}=XZ,e5=tn(),t5=pa(),r5=Vd(),{getDatabases:s5}=(Re(),ie(Fe)),n5=$Z.promisify(YZ.authorize),i5=yM.searchByHash,o5=yM.searchByValue;IM.exports={authHeaderToUser:a5,isEmpty:c5,getNodeRecord:u5,upsertNodeRecord:l5,buildNodePayloads:_5,checkClusteringEnabled:d5,getAllNodeRecords:f5,getSystemInfo:E5,reverseSubscription:NM};async function a5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await n5(t,null),e}a(a5,"authHeaderToUser");function c5(e){return e==null}a(c5,"isEmpty");async function u5(e){let t=new KZ(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return i5(t)}a(u5,"getNodeRecord");async function l5(e){let t=new WZ(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return VZ.upsert(t)}a(l5,"upsertNodeRecord");function NM(e){if(NT.isEmpty(e.subscribe)||NT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(NM,"reverseSubscription");function _5(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=NT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=NM(c),E=s5()[u]?.[_],h=new zZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new QZ(r,t,n,s)}a(_5,"buildNodePayloads");function d5(){if(!bM.get(fo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw JZ(new Error,ZZ.CLUSTERING_NOT_ENABLED,jZ.BAD_REQUEST,void 0,void 0,!0)}a(d5,"checkClusteringEnabled");async function f5(){let e=new e5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await o5(e))}a(f5,"getAllNodeRecords");async function E5(){let e=await t5.getSystemInformation();return{hdb_version:r5.version(),node_version:e.node_version,platform:e.platform}}a(E5,"getSystemInfo")});var IT=g((HEe,vM)=>{"use strict";var $d=it(),wM=Q(),CM=ke(),DM=L(),Yd=$(),LM=Su(),h5=id(),{RemotePayloadObject:m5}=yu(),{handleHDBError:MM,hdb_errors:p5}=se(),{HTTP_STATUS_CODES:UM}=p5,{NodeSubscription:PM}=mi();vM.exports=S5;async function S5(e,t){let r;try{r=await $d.request(`${t}.${CM.REQUEST_SUFFIX}`,new m5(DM.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 MM(new Error,c,UM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===CM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw MM(new Error,o,UM.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===DM.SYSTEM_SCHEMA_NAME){await $d.createLocalTableStream(u,c);let h=new PM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=wM.doesSchemaExist(u),l=s[u]!==void 0,d=c?wM.doesTableExist(u,c):!0,f=c?s?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){n.push(o);continue}if(!_&&l&&(Yd.trace(`addNode creating schema: ${u}`),await LM.createSchema({operation:"create_schema",schema:u})),!d&&f){Yd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(s[u][c].attributes)}`);let h=new h5(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await LM.createTable(h)}await $d.createLocalTableStream(u,c);let E=new PM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(S5,"reviewSubscriptions")});var zd=g((GEe,xM)=>{"use strict";var{handleHDBError:Kd,hdb_errors:T5}=se(),{HTTP_STATUS_CODES:Wd}=T5,{addUpdateNodeValidator:g5}=vd(),Qd=$(),HM=L(),BM=ke(),R5=Q(),Nu=it(),Iu=us(),A5=ee(),O5=IT(),{Node:b5,NodeSubscription:y5}=mi(),{broadcast:N5}=Ke(),I5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",w5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",C5=A5.get(HM.CONFIG_PARAMS.CLUSTERING_NODENAME);xM.exports=D5;async function D5(e,t=!1){Qd.trace("addNode called with:",e),Iu.checkClusteringEnabled();let r=g5(e);if(r)throw Kd(r,r.message,Wd.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await Iu.getNodeRecord(s);if(!R5.isEmptyOrZeroLength(d))throw Kd(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,Wd.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await O5(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=I5,o;let c=Iu.buildNodePayloads(n,C5,HM.OPERATIONS_ENUM.ADD_NODE,await Iu.getSystemInfo()),u=[];for(let d=0,f=n.length;d<f;d++){let E=n[d];n[d].start_time===void 0&&delete n[d].start_time,u.push(new y5(E.schema,E.table,E.publish,E.subscribe))}Qd.trace("addNode sending remote payload:",c);let _;try{_=await Nu.request(`${s}.${BM.REQUEST_SUFFIX}`,c)}catch(d){Qd.error(`addNode received error from request: ${d}`);for(let E=0,h=n.length;E<h;E++){let p=n[E];p.publish=!1,p.subscribe=!1,await Nu.updateRemoteConsumer(p,s)}let f=Nu.requestErrorHandler(d,"add_node",s);throw Kd(new Error,f,Wd.INTERNAL_SERVER_ERROR,"error",f)}if(_.status===BM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${_.message}`;throw Kd(new Error,d,Wd.INTERNAL_SERVER_ERROR,"error",d)}Qd.trace(_);for(let d=0,f=n.length;d<f;d++){let E=n[d];await Nu.updateRemoteConsumer(E,s),E.subscribe===!0&&await Nu.updateConsumerIterator(E.schema,E.table,s,"start")}let l=new b5(s,u,_.system_info);return await Iu.upsertNodeRecord(l),N5({type:"nats_update"}),i.length>0?o.message=w5:o.message=`Successfully added '${s}' to manifest`,o}a(D5,"addNode")});var DT=g((kEe,FM)=>{"use strict";var{handleHDBError:wT,hdb_errors:L5}=se(),{HTTP_STATUS_CODES:CT}=L5,{addUpdateNodeValidator:M5}=vd(),wu=$(),qM=L(),GM=ke(),FEe=Q(),Cu=it(),Du=us(),U5=ee(),{cloneDeep:P5}=require("lodash"),v5=IT(),{Node:B5,NodeSubscription:H5}=mi(),{broadcast:x5}=Ke(),G5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",q5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",F5=U5.get(qM.CONFIG_PARAMS.CLUSTERING_NODENAME);FM.exports=k5;async function k5(e){wu.trace("updateNode called with:",e),Du.checkClusteringEnabled();let t=M5(e);if(t)throw wT(t,t.message,CT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await Du.getNodeRecord(r);n.length>0&&(s=P5(n));let{added:i,skipped:o}=await v5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=G5,c;let u=Du.buildNodePayloads(i,F5,qM.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}.${GM.REQUEST_SUFFIX}`,u)}catch(l){wu.error(`updateNode received error from request: ${l}`);let d=Cu.requestErrorHandler(l,"update_node",r);throw wT(new Error,d,CT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===GM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw wT(new Error,l,CT.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 s||(s=[new B5(r,[],_.system_info)]),await V5(s[0],i,_.system_info),o.length>0?c.message=q5:c.message=`Successfully updated '${r}'`,c}a(k5,"updateNode");async function V5(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=s.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new H5(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Du.upsertNodeRecord(s),x5({type:"nats_update"})}a(V5,"updateNodeTable")});var KM=g(($Ee,YM)=>{"use strict";var $M=require("joi"),{string:kM}=$M.types(),$5=Xe(),VM=L(),Y5=ee(),K5=ke();YM.exports=W5;function W5(e){let t=kM.invalid(Y5.get(VM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(K5.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=$M.object({operation:kM.valid(VM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return $5.validateBySchema(e,r)}a(W5,"removeNodeValidator")});var Xd=g((KEe,XM)=>{"use strict";var{handleHDBError:WM,hdb_errors:Q5}=se(),{HTTP_STATUS_CODES:QM}=Q5,z5=KM(),Lu=$(),zM=us(),J5=Q(),Jd=L(),JM=ke(),LT=it(),X5=ee(),{RemotePayloadObject:j5}=yu(),{NodeSubscription:Z5}=mi(),e8=ia(),t8=ii(),{broadcast:r8}=Ke(),s8=X5.get(Jd.CONFIG_PARAMS.CLUSTERING_NODENAME);XM.exports=n8;async function n8(e){Lu.trace("removeNode called with:",e),zM.checkClusteringEnabled();let t=z5(e);if(t)throw WM(t,t.message,QM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await zM.getNodeRecord(r);if(J5.isEmptyOrZeroLength(s))throw WM(new Error,`Node '${r}' was not found.`,QM.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new j5(Jd.OPERATIONS_ENUM.REMOVE_NODE,s8,[]),i,o=!1;for(let u=0,_=s.subscriptions.length;u<_;u++){let l=s.subscriptions[u];l.subscribe===!0&&await LT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await LT.updateRemoteConsumer(new Z5(l.schema,l.table,!1,!1),r)}catch(d){Lu.error(d)}}try{i=await LT.request(`${r}.${JM.REQUEST_SUFFIX}`,n),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 e8(Jd.SYSTEM_SCHEMA_NAME,Jd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await t8.deleteRecord(c),r8({type:"nats_update"}),i?.status===JM.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(n8,"removeNode")});var eU=g((QEe,ZM)=>{"use strict";var jM=require("joi"),{string:i8,array:o8}=jM.types(),a8=Xe(),c8=vd();ZM.exports=u8;function u8(e){let t=jM.object({operation:i8.valid("configure_cluster").required(),connections:o8.items(c8.validation_schema).required()});return a8.validateBySchema(e,t)}a(u8,"configureClusterValidator")});var MT=g((JEe,iU)=>{"use strict";var l8=L(),jd=$(),_8=Q(),d8=Xd(),f8=zd(),tU=us(),E8=eU(),{handleHDBError:rU,hdb_errors:h8}=se(),{HTTP_STATUS_CODES:sU}=h8,m8="Configure cluster complete.",p8="Failed to configure the cluster. Check the logs for more details.",S8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";iU.exports=T8;async function T8(e){jd.trace("configure cluster called with:",e),tU.checkClusteringEnabled();let t=E8(e);if(t)throw rU(t,t.message,sU.BAD_REQUEST,void 0,void 0,!0);let r=await tU.getAllNodeRecords(),s=[];for(let l=0,d=r.length;l<d;l++){let f=await nU(d8,{operation:l8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);s.push(f)}jd.trace("All results from configure_cluster remove node:",s);let n=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],f=await nU(f8,d,d.node_name);n.push(f)}jd.trace("All results from configure_cluster add node:",n);let o=[],c=[],u=!1,_=s.concat(n);for(let l=0,d=_.length;l<d;l++){let f=_[l];f.status==="rejected"&&(jd.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(_8.isEmptyOrZeroLength(o))return{message:m8,connections:c};if(u)return{message:S8,failed_nodes:o,connections:c};throw rU(new Error,p8,sU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(T8,"configureCluster");async function nU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){return{node_name:r,error:s,status:"rejected"}}}a(nU,"functionWrapper")});var uU=g((jEe,cU)=>{"use strict";var Mu=require("joi"),g8=Xe(),{validateSchemaExists:oU,validateTableExists:R8,validateSchemaName:aU}=Js(),A8=Mu.object({operation:Mu.string().valid("purge_stream"),schema:Mu.string().custom(oU).custom(aU).optional(),database:Mu.string().custom(oU).custom(aU).optional(),table:Mu.string().custom(R8).required()});function O8(e){return g8.validateBySchema(e,A8)}a(O8,"purgeStreamValidator");cU.exports=O8});var UT=g((ehe,lU)=>{"use strict";var{handleHDBError:b8,hdb_errors:y8}=se(),{HTTP_STATUS_CODES:N8}=y8,I8=uU(),w8=it(),C8=us();lU.exports=D8;async function D8(e){e.schema=e.schema??e.database;let t=I8(e);if(t)throw b8(t,t.message,N8.BAD_REQUEST,void 0,void 0,!0);C8.checkClusteringEnabled();let{schema:r,table:s,options:n}=e;return await w8.purgeTableStream(r,s,n),`Successfully purged table '${r}.${s}'`}a(D8,"purgeStream")});var BT=g((rhe,mU)=>{"use strict";var vT=us(),L8=it(),fU=ee(),Zd=L(),Eo=ke(),M8=Q(),PT=$(),{RemotePayloadObject:U8}=yu(),{ErrorCode:_U}=require("nats"),dU=fU.get(Zd.CONFIG_PARAMS.CLUSTERING_ENABLED),EU=fU.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);mU.exports={clusterStatus:P8,buildNodeStatus:hU};async function P8(){let e={node_name:EU,is_enabled:dU,connections:[]};if(!dU)return e;let t=await vT.getAllNodeRecords();if(M8.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(hU(t[s],e.connections));return await Promise.allSettled(r),e}a(P8,"clusterStatus");async function hU(e,t){let r=e.name,s=new U8(Zd.OPERATIONS_ENUM.CLUSTER_STATUS,EU,void 0,await vT.getSystemInfo()),n,i,o=Eo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await L8.request(Eo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===Eo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=Eo.CLUSTER_STATUS_STATUSES.CLOSED,PT.error(`Error getting node status from ${r} `,n))}catch(u){PT.warn(`Error getting node status from ${r}`,u),u.code===_U.NoResponders?o=Eo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===_U.Timeout?o=Eo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=Eo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new v8(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let u={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==Zd.PRE_4_0_0_VERSION&&await vT.upsertNodeRecord(u)}catch(u){PT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(hU,"buildNodeStatus");function v8(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(v8,"NodeStatusObject")});var xT=g((nhe,pU)=>{"use strict";var{handleHDBError:B8,hdb_errors:H8}=se(),{HTTP_STATUS_CODES:x8}=H8,G8=it(),q8=us(),HT=Q(),ef=require("joi"),F8=Xe(),k8=2e3,V8=ef.object({timeout:ef.number().min(1),connected_nodes:ef.boolean(),routes:ef.boolean()});pU.exports=$8;async function $8(e){q8.checkClusteringEnabled();let t=F8.validateBySchema(e,V8);if(t)throw B8(t,t.message,x8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||HT.autoCastBoolean(s),o=n===void 0||HT.autoCastBoolean(n),c={nodes:[]},u=await G8.getServerList(r??k8),_={};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:HT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a($8,"clusterNetwork")});var RU=g((ohe,gU)=>{"use strict";var GT=require("joi"),SU=Xe(),{route_constraints:TU}=tp();gU.exports={setRoutesValidator:Y8,deleteRoutesValidator:K8};function Y8(e){let t=GT.object({server:GT.valid("hub","leaf").required(),routes:TU.required()});return SU.validateBySchema(e,t)}a(Y8,"setRoutesValidator");function K8(e){let t=GT.object({routes:TU.required()});return SU.validateBySchema(e,t)}a(K8,"deleteRoutesValidator")});var FT=g((che,yU)=>{"use strict";var ho=lr(),qT=Q(),tf=L(),AU=RU(),{handleHDBError:OU,hdb_errors:W8}=se(),{HTTP_STATUS_CODES:bU}=W8,Q8="cluster routes successfully set",z8="cluster routes successfully deleted";yU.exports={setRoutes:J8,getRoutes:X8,deleteRoutes:j8};function J8(e){let t=AU.setRoutesValidator(e);if(t)throw OU(t,t.message,bU.BAD_REQUEST,void 0,void 0,!0);let r=ho.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=qT.autoCast(_.port);let l=s.some(f=>f.host===_.host&&f.port===_.port),d=n.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(s.push(_),o.push(_))}return e.server==="hub"?ho.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):ho.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:Q8,set:o,skipped:i}}a(J8,"setRoutes");function X8(){let e=ho.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(X8,"getRoutes");function j8(e){let t=AU.deleteRoutesValidator(e);if(t)throw OU(t,t.message,bU.BAD_REQUEST,void 0,void 0,!0);let r=ho.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=s.length;E<h;E++){let p=s[E];if(d.host===p.host&&d.port===p.port){s.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=n.length;h<p;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(s=qT.isEmptyOrZeroLength(s)?null:s,ho.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=qT.isEmptyOrZeroLength(n)?null:n,ho.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:z8,deleted:i,skipped:o}}a(j8,"deleteRoutes")});var IU=g((lhe,NU)=>{"use strict";var Uu=require("alasql"),mo=require("recursive-iterator"),xs=$(),Z8=Q(),Pu=L(),kT=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,t6(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(n=>Pu.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!Pu.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Pu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=e6(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:_});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function e6(e){return e.filter(t=>t[Pu.PERMS_CRUD_ENUM.READ])}a(e6,"filterReadRestrictedAttrs");function t6(e,t,r,s,n){r6(e,t,r,s,n)}a(t6,"interpretAST");function vu(e,t,r,s,n){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a(vu,"addSchemaTableToMap");function r6(e,t,r,s,n){if(!e){xs.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Uu.yy.Insert?o6(e,t,r):e instanceof Uu.yy.Select?s6(e,t,r,s,n):e instanceof Uu.yy.Update?n6(e,t,r):e instanceof Uu.yy.Delete?i6(e,t,r):xs.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(r6,"getRecordAttributesAST");function s6(e,t,r,s,n){if(!e){xs.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(Z8.isEmptyOrZeroLength(i)){xs.error("No schema specified");return}e.from.forEach(c=>{vu(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),vu(c.table,t,r,s,n)});let o=new mo(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{xs.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 mo(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{xs.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 mo(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=n.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{xs.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 mo(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{xs.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(s6,"getSelectAttributes");function n6(e,t,r){if(!e){xs.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new mo(e.columns),n=e.table.databaseid;vu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&VT(e.table.tableid,n,i.columnid,t,r)}a(n6,"getUpdateAttributes");function i6(e,t,r){if(!e){xs.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new mo(e.where),n=e.table.databaseid;vu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&VT(e.table.tableid,n,i.columnid,t,r)}a(i6,"getDeleteAttributes");function o6(e,t,r){if(!e){xs.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new mo(e.columns),n=e.into.databaseid;vu(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&VT(e.into.tableid,n,i.columnid,t,r)}a(o6,"getInsertAttributes");function VT(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(VT,"pushAttribute");NU.exports=kT});var KT=g((dhe,LU)=>{var rf=Xi(),wU=require("chalk"),Vr=$(),CU=require("prompt"),{promisify:a6}=require("util"),$T=L(),c6=require("fs-extra"),u6=require("path"),l6=Q(),_6=Vd(),DU=ee();DU.initSync();var d6=require("moment"),f6=a6(CU.get),E6=u6.join(DU.getHdbBasePath(),$T.LICENSE_KEY_DIR_NAME,$T.LICENSE_FILE_NAME,$T.LICENSE_FILE_NAME);LU.exports={getFingerprint:m6,setLicense:h6,parseLicense:YT,register:p6,getRegistrationInfo:T6};async function h6(e){if(e&&e.key&&e.company){try{Vr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await YT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Vr.error(r),Vr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(h6,"setLicense");async function m6(){let e={};try{e=await rf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Vr.error(r),Vr.error(t),new Error(r)}return e}a(m6,"getFingerprint");async function YT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Vr.info("Validating license input...");let r=rf.validateLicense(e,t);if(Vr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Vr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Vr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Vr.info("writing license to disk"),await c6.writeFile(E6,JSON.stringify({license_key:e,company:t}))}catch(s){throw Vr.error("Failed to write License"),s}return"Registration successful."}a(YT,"parseLicense");async function p6(){let e=await S6();return YT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(p6,"register");async function S6(){let e=await rf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:wU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:wU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{CU.start()}catch(s){Vr.error(s)}let r;try{r=await f6(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(S6,"promptForRegistration");async function T6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await rf.getLicense()}catch(r){throw Vr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(l6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=_6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=d6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(T6,"getRegistrationInfo")});var UU=g((Ehe,MU)=>{"use strict";var g6=ke(),WT=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+g6.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};MU.exports=WT});var BU=g((mhe,vU)=>{"use strict";var PU=ke(),QT=class{static{a(this,"LeafConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+PU.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+PU.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};vU.exports=QT});var xU=g((She,HU)=>{"use strict";var zT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};HU.exports=zT});var qU=g((ghe,GU)=>{"use strict";var R6=ke(),JT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+R6.SERVER_SUFFIX.ADMIN,this.password=r}};GU.exports=JT});var ZT=g((Ahe,VU)=>{"use strict";var Sa=require("path"),of=require("fs-extra"),A6=UU(),O6=BU(),b6=xU(),y6=qU(),XT=os(),ga=Q(),gr=lr(),nf=L(),Bu=ke(),{CONFIG_PARAMS:ft}=nf,Ra=$(),Hu=ee(),FU=Rn(),jT=it(),Ta="clustering",N6=1e4,kU=50;VU.exports={generateNatsConfig:w6,removeNatsConfig:C6,getHubConfigPath:I6};function I6(){let e=Hu.get(ft.ROOTPATH);return Sa.join(e,Ta,Bu.NATS_CONFIG_FILES.HUB_SERVER)}a(I6,"getHubConfigPath");async function w6(e=!1,t=void 0){Hu.initSync();let r=Hu.get(ft.ROOTPATH),s=Sa.join(r,Ta,Bu.PID_FILES.HUB),n=Sa.join(r,Ta,Bu.PID_FILES.LEAF),i=gr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Sa.join(r,Ta,Bu.NATS_CONFIG_FILES.HUB_SERVER),c=Sa.join(r,Ta,Bu.NATS_CONFIG_FILES.LEAF_SERVER),u=gr.getConfigFromFile(ft.CLUSTERING_TLS_CERTIFICATE),_=gr.getConfigFromFile(ft.CLUSTERING_TLS_PRIVATEKEY),l=gr.getConfigFromFile(ft.CLUSTERING_TLS_CERT_AUTH),d=gr.getConfigFromFile(ft.CLUSTERING_TLS_INSECURE),f=gr.getConfigFromFile(ft.CLUSTERING_TLS_VERIFY),E=gr.getConfigFromFile(ft.CLUSTERING_NODENAME),h=gr.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 XT.listUsers(),S=gr.getConfigFromFile(ft.CLUSTERING_USER),T=await XT.getClusterUser();(ga.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 sf(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await sf(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await sf(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),await sf(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],R=[];for(let[z,J]of p.entries())J.role.role===nf.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(A.push(new y6(J.username,FU.decrypt(J.hash))),R.push(new b6(J.username,FU.decrypt(J.hash))));let M=[],{hub_routes:x}=gr.getClusteringRoutes();if(!ga.isEmptyOrZeroLength(x))for(let z of x)M.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${z.host}:${z.port}`);let P=new A6(gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NAME),gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),M,A,R);l==null&&(delete P.tls.ca_file,delete P.leafnodes.tls.ca_file),t=ga.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===nf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await of.writeJson(o,P),Ra.trace(`Hub server config written to ${o}`));let k=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,B=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,X=new O6(gr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[k],[B],A,R,u,_,l,d);l==null&&delete X.tls.ca_file,(t===void 0||t===nf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await of.writeJson(c,X),Ra.trace(`Leaf server config written to ${c}`))}a(w6,"generateNatsConfig");async function sf(e){let t=Hu.get(e);return ga.isEmpty(t)&&af(`port undefined for '${e}'`),await ga.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(sf,"isPortAvailable");function af(e){let t=`Error generating clustering config: ${e}`;Ra.error(t),console.error(t),process.exit(1)}a(af,"generateNatsConfigError");async function C6(e){let{port:t,config_file:r}=jT.getServerConfig(e),{username:s,decrypt_hash:n}=await XT.getClusterUser(),i=0,o=2e3;for(;i<kU;){try{let l=await jT.createConnection(t,s,n,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){Ra.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&&Ra.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await ga.async_set_timeout(_)}let c="0".repeat(N6),u=Sa.join(Hu.get(ft.ROOTPATH),Ta,r);await of.writeFile(u,c),await of.remove(u),Ra.notify(e,"started.")}a(C6,"removeNatsConfig")});var zU=g((bhe,QU)=>{"use strict";var $r=ee(),D6=Xi(),he=L(),xu=ke(),Cn=require("path"),{PACKAGE_ROOT:uf}=L(),$U=ee(),cf=Q(),Aa="/dev/null",L6=Cn.join(uf,"launchServiceScripts"),YU=Cn.join(uf,"utility/scripts"),M6=Cn.join(YU,he.HDB_RESTART_SCRIPT),KU=Cn.resolve(uf,"dependencies",`${process.platform}-${process.arch}`,xu.NATS_BINARY_NAME);function WU(){let t=D6.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,s={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return cf.noBootFile()&&(s[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=cf.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:uf}}a(WU,"generateMainServerConfig");var U6=9930;function P6(){$r.initSync(!0);let e=$r.get(he.CONFIG_PARAMS.ROOTPATH),t=Cn.join(e,"clustering",xu.NATS_CONFIG_FILES.HUB_SERVER),r=Cn.join($r.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=$U.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=xu.LOG_LEVEL_FLAGS[$r.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==U6?"-"+s:""),script:KU,args:n?`${n} -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 $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Aa,i.error_file=Aa),i}a(P6,"generateNatsHubServerConfig");var v6=9940;function B6(){$r.initSync(!0);let e=$r.get(he.CONFIG_PARAMS.ROOTPATH),t=Cn.join(e,"clustering",xu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cn.join($r.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=$U.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=xu.LOG_LEVEL_FLAGS[$r.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==v6?"-"+s:""),script:KU,args:n?`${n} -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 $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Aa,i.error_file=Aa),i}a(B6,"generateNatsLeafServerConfig");function H6(){$r.initSync();let e=Cn.join($r.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:L6,autorestart:!1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Aa,t.error_file=Aa),t}a(H6,"generateClusteringUpgradeV4ServiceConfig");function x6(){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:YU},script:M6}}a(x6,"generateRestart");function G6(){return{apps:[WU()]}}a(G6,"generateAllServiceConfigs");QU.exports={generateAllServiceConfigs:G6,generateMainServerConfig:WU,generateRestart:x6,generateNatsHubServerConfig:P6,generateNatsLeafServerConfig:B6,generateClusteringUpgradeV4ServiceConfig:H6}});var uP=g((Ihe,cP)=>{"use strict";var ve=L(),q6=Q(),Ln=ZT(),lf=it(),Dn=ke(),Si=zU(),_f=ee(),Ti=$(),F6=us(),{startWorker:JU,onMessageFromWorkers:k6}=Ke(),V6=pa(),Nhe=require("util"),$6=require("child_process"),Y6=require("fs"),{execFile:K6}=$6,Ne;cP.exports={enterPM2Mode:W6,start:gi,stop:eg,reload:jU,restart:ZU,list:tg,describe:tP,connect:Mn,kill:j6,startAllServices:Z6,startService:rg,getUniqueServicesList:rP,restartAllServices:e9,isServiceRegistered:sP,reloadStopStart:nP,restartHdb:eP,deleteProcess:J6,startClusteringProcesses:oP,startClusteringThreads:aP,isHdbRestartRunning:X6,isClusteringRunning:r9,stopClustering:t9,reloadClustering:s9};var Gu=!1;k6(e=>{e.type==="restart"&&_f.initSync(!0)});function W6(){Gu=!0}a(W6,"enterPM2Mode");function Mn(){return Ne||(Ne=require("pm2")),new Promise((e,t)=>{Ne.connect((r,s)=>{Ti.setupConsoleLogging(),r&&t(r),e(s)})})}a(Mn,"connect");var Rr,Q6=10,XU;function gi(e,t=!1){if(Gu)return z6(e);let r=K6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Rr.indexOf(r);o>-1&&Rr.splice(o,1),!XU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<Q6&&(Y6.existsSync(Ln.getHubConfigPath())?gi(e):(await Ln.generateNatsConfig(!0),gi(e),await new Promise(c=>setTimeout(c,3e3)),await Ln.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ln.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=_f.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Dn.LOG_LEVEL_HIERARCHY[o]>=Dn.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Dn.LOG_LEVELS.ERR||l===Dn.LOG_LEVELS.WRN?Ti.OUTPUTS.STDERR:Ti.OUTPUTS.STDOUT;Ti.logCustomLevel(l||"info",E,s,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Dn.LOG_LEVELS[f]}if(Dn.LOG_LEVEL_HIERARCHY[o]>=Dn.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Dn.LOG_LEVELS.ERR||l===Dn.LOG_LEVELS.WRN?Ti.OUTPUTS.STDERR:Ti.OUTPUTS.STDOUT;Ti.logCustomLevel(l||"info",d,s,i.slice(_).trim())}}if(a(n,"extractMessages"),r.stdout.on("data",n),r.stderr.on("data",n),r.unref(),Rr=[],!Rr&&!t){let i=a(()=>{XU=!0,Rr&&(Rr.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)}Rr.push(r)}a(gi,"start");function z6(e){return new Promise(async(t,r)=>{try{await Mn()}catch(s){r(s)}Ne.start(e,(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(n)})})}a(z6,"startWithPM2");function eg(e){if(!Gu){for(let t of Rr||[])t.name===e&&(Rr.splice(Rr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Mn()}catch(s){r(s)}Ne.stop(e,async(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.delete(e,(i,o)=>{i&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(o)})})})}a(eg,"stop");function jU(e){return new Promise(async(t,r)=>{try{await Mn()}catch(s){r(s)}Ne.reload(e,(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(n)})})}a(jU,"reload");function ZU(e){if(!Gu)for(let t of Rr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Mn()}catch(s){r(s)}Ne.restart(e,(s,n)=>{Ne.disconnect(),t(n)})})}a(ZU,"restart");function J6(e){return new Promise(async(t,r)=>{try{await Mn()}catch(s){r(s)}Ne.delete(e,(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(n)})})}a(J6,"deleteProcess");async function eP(){await gi(Si.generateRestart())}a(eP,"restartHdb");async function X6(){let e=await tg();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(X6,"isHdbRestartRunning");function tg(){return new Promise(async(e,t)=>{try{await Mn()}catch(r){t(r)}Ne.list((r,s)=>{r&&(Ne.disconnect(),t(r)),Ne.disconnect(),e(s)})})}a(tg,"list");function tP(e){return new Promise(async(t,r)=>{try{await Mn()}catch(s){r(s)}Ne.describe(e,(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(n)})})}a(tP,"describe");function j6(){if(!Gu){for(let e of Rr||[])e.kill();Rr=[];return}return new Promise(async(e,t)=>{try{await Mn()}catch(r){t(r)}Ne.killDaemon((r,s)=>{r&&(Ne.disconnect(),t(r)),Ne.disconnect(),e(s)})})}a(j6,"kill");async function Z6(){try{await oP(),await aP(),await gi(Si.generateAllServiceConfigs())}catch(e){throw Ne?.disconnect(),e}}a(Z6,"startAllServices");async function rg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Si.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Si.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Si.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Si.generateNatsHubServerConfig(),await gi(r,t),await Ln.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Si.generateNatsLeafServerConfig(),await gi(r,t),await Ln.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Si.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await gi(r)}catch(r){throw Ne?.disconnect(),r}}a(rg,"startService");async function rP(){try{let e=await tg(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw Ne?.disconnect(),e}}a(rP,"getUniqueServicesList");async function e9(e=[]){try{let t=!1,r=await rP();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await ZU(o))}t&&await nP(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ne?.disconnect(),t}}a(e9,"restartAllServices");async function sP(e){if(Rr?.find(r=>r.name===e))return!0;let t=await V6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(sP,"isServiceRegistered");async function nP(e){let t=_f.get(ve.CONFIG_PARAMS.THREADS_COUNT)??_f.get(ve.CONFIG_PARAMS.THREADS),r=await tP(e),s=q6.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await eg(e),await rg(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await eP():await jU(e)}a(nP,"reloadStopStart");var iP;async function oP(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await rg(r,e)}}a(oP,"startClusteringProcesses");async function aP(){iP=JU(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await lf.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await lf.updateLocalStreams();let e=await F6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){Ti.info("Starting clustering upgrade 4.0.0 process"),JU(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(aP,"startClusteringThreads");async function t9(){for(let e in ve.CLUSTERING_PROCESSES)if(e!==ve.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ve.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await iP.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await eg(t)}}a(t9,"stopClustering");async function r9(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await sP(t)===!1)return!1}return!0}a(r9,"isClusteringRunning");async function s9(){await Ln.generateNatsConfig(!0),await lf.reloadNATSHub(),await lf.reloadNATSLeaf(),await Ln.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ln.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(s9,"reloadClustering")});var mP={};qe(mP,{compactOnStart:()=>n9,copyDb:()=>hP});async function n9(){Fu.notify("Running compact on start"),console.log("Running compact on start");let e=(0,sg.get)(Ri.CONFIG_PARAMS.ROOTPATH),t=new Map,r=dr();try{for(let s in r){if(s==="system")continue;let n;for(let u in r[s]){n=r[s][u].primaryStore.path;break}let i=(0,df.join)(e,"backup",s+".mdb"),o=(0,df.join)(e,Ri.DATABASES_DIR_NAME,s+"-copy.mdb"),c=await lP(s);console.log("Database",s,"before compact has a total record count of",c),t.set(s,{db_path:n,copy_dest:o,backup_dest:i,record_count:c}),await hP(s,o),console.log("Backing up",s,"to",i),await(0,po.move)(n,i,{overwrite:!0})}qu();for(let[s,{db_path:n,copy_dest:i}]of t)console.log("Moving copy compacted",s,"to",n),await(0,po.move)(i,n,{overwrite:!0}),await(0,po.remove)((0,df.join)(e,Ri.DATABASES_DIR_NAME,`${s}-copy.mdb-lock`));qu()}catch(s){Fu.error("Error compacting database, rolling back operation",s),console.error("Error compacting database, rolling back operation",s),(0,ng.updateConfigValue)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[n,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,po.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw qu(),s}for(let[s,{backup_dest:n,record_count:i}]of t){let o=!0,c=await lP(s);if(console.log("Database",s,"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 ${s}.
|
|
10
|
+
`,"")}a(sL,"runCommand");async function lj(){try{await F3.access(LS)}catch{return!1}let e=await sL(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return k3.eq(t,cj)}a(lj,"checkNATSServerInstalled");async function BS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await rL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bn.trace("create nats connection called");let i=await X3({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),iL()}),i}a(BS,"createConnection");function iL(){Er=void 0,io=void 0,oo=void 0,ao=void 0}a(iL,"clearClientCache");async function _j(){Er&&(await Er.drain(),Er=void 0,io=void 0,oo=void 0,ao=void 0)}a(_j,"closeConnection");var Er,ao;async function pu(){return ao||(ao=BS(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Er=await ao),Er||ao}a(pu,"getConnection");async function Su(){if(io)return io;co(Er)&&await pu();let{domain:e}=la(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await Er.jetstreamManager({domain:e,timeout:6e4}),io}a(Su,"getJetStreamManager");async function oL(){if(oo)return oo;co(Er)&&await pu();let{domain:e}=la(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=Er.jetstream({domain:e,timeout:6e4}),oo}a(oL,"getJetStream");async function ss(){let e=Er||await pu(),t=io||await Su(),r=oo||await oL();return{connection:e,jsm:t,js:r}}a(ss,"getNATSReferences");async function dj(e){let t=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await rL.getClusterUser(),s=await BS(t,r,n),i=vS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=nL.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(dj,"getServerList");async function HS(e,t){let{jsm:r}=await ss(),n=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:Z3.File,retention:ej.Limits,subjects:t,discard:tj.Old,max_msgs:s,max_bytes:i,max_age:n})}a(HS,"createLocalStream");async function aL(){let{jsm:e}=await ss(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(aL,"listStreams");async function fj(e){let{jsm:t}=await ss();await t.streams.delete(e)}a(fj,"deleteLocalStream");async function Ej(e){let{connection:t}=await ss(),r=[],n=vS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(nL.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(Ej,"listRemoteStreams");async function hj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=XD(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=PS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=MS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Vt.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(hj,"viewStream");async function*mj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=XD(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=PS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=MS(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(Vt.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(mj,"viewStreamIterator");async function pj(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=cL(n,r);let{js:s}=await ss(),i=await wd(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:tL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),oj(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 lL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await HS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(pj,"publishToStream");function cL(e,t){t===void 0&&(t=nj());let r=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Vt.MSG_HEADERS.ORIGIN)&&r&&t.append(Vt.MSG_HEADERS.ORIGIN,r),t}a(cL,"addNatsMsgHeader");function la(e){e=e.toLowerCase();let t=mu.join(Pt.get(Ne.CONFIG_PARAMS.ROOTPATH),aj);if(e===Ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(DS)&&(DS={port:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.HUB,config_file:Vt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:mu.join(t,Vt.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(CS)&&(CS={port:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,config_file:Vt.NATS_CONFIG_FILES.LEAF_SERVER,domain:Eu.getConfigFromFile(Ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,pid_file_path:mu.join(t,Vt.PID_FILES.LEAF),hdb_nats_path:t}),CS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(la,"getServerConfig");async function uL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:US.Explicit,durable_name:r,deliver_policy:PS.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(uL,"createConsumer");async function Sj(e,t,r){await e.consumers.delete(t,r)}a(Sj,"removeConsumer");function Tj(e){return e.split(".")[1]}a(Tj,"extractServerName");async function gj(e,t,r=6e4,n=vS()){if(!Nd.isObject(t))throw new Error("data param must be an object");let s=tL.encode(t),{connection:i}=await ss(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return MS(c.data)}a(gj,"request");function xS(e){return new Promise(async(t,r)=>{let n=K3(LS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(xS,"reloadNATS");async function Rj(){let{pid_file_path:e}=la(Ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await xS(e)}a(Rj,"reloadNATSHub");async function Aj(){let{pid_file_path:e}=la(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await xS(e)}a(Aj,"reloadNATSLeaf");function Oj(e,t,r){let n;switch(e.code){case jD.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case jD.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Oj,"requestErrorHandler");async function bj(e,t){let r=t+Vt.SERVER_SUFFIX.LEAF,{connection:n}=await ss(),{jsm:s}=await Mj(r),{schema:i,table:o}=e,c=Id.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await lL(async()=>{if(e.subscribe===!0)await uL(s,c,n.info.server_name,u);else try{await Sj(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(bj,"updateRemoteConsumer");async function yj(e,t,r,n){let s=Id.createNatsTableStreamName(e,t),i=r+Vt.SERVER_SUFFIX.LEAF,o={type:Ne.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!eL&&J3()<Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=wS();await c(o)}await Q3(o),n==="stop"&&await Nd.async_set_timeout(1e3)}a(yj,"updateConsumerIterator");function lL(e){return W3.writeTransaction(Ne.SYSTEM_SCHEMA_NAME,Ne.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(lL,"exclusiveLock");async function _L(e,t){let r=Id.createNatsTableStreamName(e,t),n=await wd(),s=Cj(e,t,n);await HS(r,[s])}a(_L,"createLocalTableStream");async function Nj(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await _L(n,s)}}a(Nj,"createTableStreams");async function dL(e,t,r=void 0){if(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Id.createNatsTableStreamName(e,t),{domain:s}=la(Ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await pu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(dL,"purgeTableStream");async function Ij(e,t){if(Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await dL(e,t[r])}a(Ij,"purgeSchemaTableStreams");async function wj(e){return(await Su()).streams.info(e)}a(wj,"getStreamInfo");function Cj(e,t,r){return`${Vt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Cj,"createSubjectName");async function wd(){if(hu)return hu;if(hu=(await Su())?.nc?.info?.server_name,hu===void 0)throw new Error("Unable to get jetstream manager server name");return hu}a(wd,"getJsmServerName");async function Dj(){let e=await Su(),t=await wd(),r=await aL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=Lj(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(Dj,"updateLocalStreams");function Lj(e){let{config:t}=e,r=!1,n=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Pt.get(Ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Pt.get(Ne.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(Lj,"updateStreamLimits");async function Mj(e){let t,r;try{t=await Er.jetstream({domain:e}),r=await Er.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(Mj,"connectToRemoteJS")});var Tu=g((Mfe,pL)=>{"use strict";var _a=y_(),da=AD(),Uj=$(),Pj=require("uuid").v4,Lfe=require("clone"),Dd=bs(),fa=L(),vj=require("util"),_i=Cn(),{handleHDBError:hr,hdb_errors:Bj}=ne(),{HDB_ERROR_MSGS:Cd,HTTP_STATUS_CODES:mr}=Bj,{SchemaEventMsg:Ld}=Mn(),EL=it(),{getDatabases:Hj}=(Re(),ie(Fe)),{transformReq:Ea}=Q();pL.exports={createSchema:xj,createSchemaStructure:hL,createTable:Gj,createTableStructure:mL,createAttribute:$j,dropSchema:qj,dropTable:Fj,dropAttribute:kj,getBackup:Yj};async function xj(e){let t=await hL(e);return Dd.signalSchemaChange(new Ld(process.pid,e.operation,e.schema)),t}a(xj,"createSchema");async function hL(e){let t=_a.schema_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);if(Ea(e),!await da.checkSchemaExists(e.schema))throw hr(new Error,Cd.SCHEMA_EXISTS_ERR(e.schema),mr.BAD_REQUEST,fa.LOG_LEVELS.ERROR,Cd.SCHEMA_EXISTS_ERR(e.schema),!0);return await _i.createSchema(e),`database '${e.schema}' successfully created`}a(hL,"createSchemaStructure");async function Gj(e){return Ea(e),e.hash_attribute=e.primary_key??e.hash_attribute,await mL(e)}a(Gj,"createTable");async function mL(e){let t=_a.create_table_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);if(_a.validateTableResidence(e.residence),!await da.checkSchemaTableExists(e.schema,e.table))throw hr(new Error,Cd.TABLE_EXISTS_ERR(e.schema,e.table),mr.BAD_REQUEST,fa.LOG_LEVELS.ERROR,Cd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:Pj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await _i.createTable(n,e);else throw hr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",mr.BAD_REQUEST);else await _i.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(mL,"createTableStructure");async function qj(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 hr(n,n.message,mr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let s=await da.checkSchemaExists(e.schema);if(s)throw hr(new Error,s,mr.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 _i.dropSchema(e),Dd.signalSchemaChange(new Ld(process.pid,e.operation,e.schema)),await EL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(qj,"dropSchema");async function Fj(e){let t=_a.table_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let r=await da.checkSchemaTableExists(e.schema,e.table);if(r)throw hr(new Error,r,mr.NOT_FOUND,fa.LOG_LEVELS.ERROR,r,!0);return await _i.dropTable(e),await EL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Fj,"dropTable");async function kj(e){let t=_a.attribute_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let r=await da.checkSchemaTableExists(e.schema,e.table);if(r)throw hr(new Error,r,mr.NOT_FOUND,fa.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw hr(new Error,"You cannot drop a hash attribute",mr.BAD_REQUEST,void 0,void 0,!0);if(fa.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw hr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,mr.BAD_REQUEST,void 0,void 0,!0);try{return await _i.dropAttribute(e),Vj(e),Dd.signalSchemaChange(new Ld(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Uj.error(`Got an error deleting attribute ${vj.inspect(e)}.`),n}}a(kj,"dropAttribute");function Vj(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(Vj,"dropAttributeFromGlobal");async function $j(e){Ea(e);let t=Hj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw hr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,mr.BAD_REQUEST,void 0,void 0,!0);return await _i.createAttribute(e),Dd.signalSchemaChange(new Ld(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a($j,"createAttribute");function Yj(e){return _i.getBackup(e)}a(Yj,"getBackup")});var TL=g((Pfe,SL)=>{"use strict";var{OPERATIONS_ENUM:Kj}=L(),GS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Kj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};SL.exports=GS});var qS=g((Hfe,bL)=>{"use strict";var Wj=Cn(),Bfe=TL(),Md=Q(),Ud=L(),Qj=ee(),{handleHDBError:gL,hdb_errors:zj}=ne(),{HDB_ERROR_MSGS:RL,HTTP_STATUS_CODES:AL}=zj,Jj=Object.values(Ud.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),OL="To use this operation audit log must be enabled in harperdb-config.yaml";bL.exports=jj;async function jj(e){if(Md.isEmpty(e.schema))throw new Error(RL.SCHEMA_REQUIRED_ERR);if(Md.isEmpty(e.table))throw new Error(RL.TABLE_REQUIRED_ERR);if(!Qj.get(Ud.CONFIG_PARAMS.LOGGING_AUDITLOG))throw gL(new Error,OL,AL.BAD_REQUEST,Ud.LOG_LEVELS.ERROR,OL,!0);let t=Md.checkSchemaTableExist(e.schema,e.table);if(t)throw gL(new Error,t,AL.NOT_FOUND,Ud.LOG_LEVELS.ERROR,t,!0);if(!Md.isEmpty(e.search_type)&&Jj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await Wj.readAuditLog(e)}a(jj,"readAuditLog")});var NL=g((Gfe,yL)=>{"use strict";var{OPERATIONS_ENUM:Xj}=L(),FS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Xj.GET_BACKUP,this.schema=t,this.table=r}};yL.exports=FS});var CL=g((Vfe,wL)=>{"use strict";var Zj=Cn(),Ffe=NL(),kS=Q(),eX=L(),kfe=ee(),{handleHDBError:tX,hdb_errors:rX}=ne(),{HDB_ERROR_MSGS:IL,HTTP_STATUS_CODES:nX}=rX;wL.exports=sX;async function sX(e){if(kS.isEmpty(e.schema))throw new Error(IL.SCHEMA_REQUIRED_ERR);if(kS.isEmpty(e.table))throw new Error(IL.TABLE_REQUIRED_ERR);let t=kS.checkSchemaTableExist(e.schema,e.table);if(t)throw tX(new Error,t,nX.NOT_FOUND,eX.LOG_LEVELS.ERROR,t,!0);return await Zj.getBackup(read_audit_log_object)}a(sX,"getBackup")});var vL=g((Yfe,PL)=>{var di=require("validate.js"),LL=je(),ha=L(),{handleHDBError:iX,hdb_errors:oX}=ne(),{HDB_ERROR_MSGS:dt,HTTP_STATUS_CODES:aX}=oX,VS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),cX={STRUCTURE_USER:"structure_user"},DL=Object.values(ha.ROLE_TYPES_ENUM),uX="attribute_permissions",lX="attribute_name",{PERMS_CRUD_ENUM:ma}=ha,_X=[uX,...Object.values(ma)],ML=[ma.READ,ma.INSERT,ma.UPDATE],dX=[lX,...ML];function fX(e){let t=VS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,UL(e,t)}a(fX,"addRoleValidation");function EX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,UL(e,t)}a(EX,"alterRoleValidation");function hX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,LL.validateObject(e,t)}a(hX,"dropRoleValidation");var mX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function UL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)mX.includes(n[o])||s.push(n[o]);s.length>0&&Tt(dt.INVALID_ROLE_JSON_KEYS(s),r);let i=LL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Tt(o,r)}),e.permission){let o=pX(e);o&&Tt(o,r),DL.forEach(c=>{e.permission[c]&&!di.isBoolean(e.permission[c])&&Tt(dt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(DL.indexOf(o)<0){if(o===cX.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=>{_X.includes(l)||Tt(dt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ma).forEach(l=>{di.isDefined(_[l])?di.isBoolean(_[l])||Tt(dt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):Tt(dt.TABLE_PERM_MISSING(l),r,o,u)}),di.isDefined(_.attribute_permissions)){if(!di.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=>{!dX.includes(p)&&p!==ma.DELETE&&Tt(dt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!di.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}ML.forEach(p=>{di.isDefined(E[p])?di.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 SX(r)}a(UL,"customValidate");PL.exports={addRoleValidation:fX,alterRoleValidation:EX,dropRoleValidation:hX};function pX(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(pX,"validateNoSUPerms");function SX(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 iX(new Error,n,aX.BAD_REQUEST)}else return null}a(SX,"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 zS=g((Wfe,GL)=>{"use strict";var BL=vr(),HL=Pr(),TX=ii(),YS=vL(),KS=bs(),gX=require("uuid").v4,RX=require("util"),Pd=L(),AX=Q(),WS=HL.searchByValue,OX=HL.searchByHash,bX=RX.promisify(TX.delete),yX=es(),NX=sa(),{hdb_errors:IX,handleHDBError:uo}=ne(),{HDB_ERROR_MSGS:xL,HTTP_STATUS_CODES:gu}=IX,{UserEventMsg:QS}=Mn();GL.exports={addRole:wX,alterRole:CX,dropRole:DX,listRoles:LX};function $S(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a($S,"scrubRoleDetails");async function wX(e){let t=YS.addRoleValidation(e);if(t)throw t;e=$S(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await WS(r)||[])}catch(i){throw uo(i)}if(n&&n.length>0)throw uo(new Error,xL.ROLE_ALREADY_EXISTS(e.role),gu.CONFLICT,void 0,void 0,!0);e.id||(e.id=gX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await BL.insert(s),KS.signalUserChange(new QS(process.pid)),e=$S(e),e}a(wX,"addRole");async function CX(e){let t=YS.alterRoleValidation(e);if(t)throw t;e=$S(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await BL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",gu.BAD_REQUEST,void 0,void 0,!0);return await KS.signalUserChange(new QS(process.pid)),e}a(CX,"alterRole");async function DX(e){let t=YS.dropRoleValidation(e);if(t)throw uo(new Error,t,gu.BAD_REQUEST,void 0,void 0,!0);let r=new NX(Pd.SYSTEM_SCHEMA_NAME,Pd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await OX(r));if(n.length===0)throw uo(new Error,xL.ROLE_NOT_FOUND,gu.NOT_FOUND,void 0,void 0,!0);let s=new yX(Pd.SYSTEM_SCHEMA_NAME,Pd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await WS(s)),o=!1;if(AX.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,gu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await bX(c),KS.signalUserChange(new QS(process.pid)),`${n[0].role} successfully deleted`}a(DX,"dropRole");async function LX(){return WS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(LX,"listRoles")});var VL=g((zfe,kL)=>{"use strict";var MX=ee(),fi=require("joi"),UX=je(),qL=require("moment"),PX=require("fs-extra"),JS=require("path"),vX=require("lodash"),Ru=L(),{LOG_LEVELS:lo}=L(),BX="YYYY-MM-DD hh:mm:ss",HX=JS.resolve(__dirname,"../logs");kL.exports=function(e){return UX.validateBySchema(e,xX)};var xX=fi.object({from:fi.custom(FL),until:fi.custom(FL),level:fi.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:fi.valid("asc","desc"),limit:fi.number().min(1),start:fi.number().min(0),log_name:fi.custom(GX)});function FL(e,t){if(qL(e,qL.ISO_8601).format(BX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(FL,"validateDatetime");function GX(e,t){if(vX.invert(Ru.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=MX.get(Ru.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Ru.LOG_NAMES.HDB:e,i=s===Ru.LOG_NAMES.INSTALL?JS.join(HX,Ru.LOG_NAMES.INSTALL):JS.join(n,s);return PX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(GX,"validateReadLogPath")});var XS=g((jfe,YL)=>{"use strict";var vd=L(),qX=$(),FX=ee(),kX=VL(),jS=require("path"),$L=require("fs-extra"),{once:VX}=require("events"),{handleHDBError:$X,hdb_errors:YX}=ne(),{PACKAGE_ROOT:KX}=L(),WX=jS.join(KX,"logs"),QX=1e3,zX=200;YL.exports=JX;async function JX(e){let t=kX(e);if(t)throw $X(t,t.message,YX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=FX.get(vd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?vd.LOG_NAMES.HDB:e.log_name,s=n===vd.LOG_NAMES.INSTALL?jS.join(WX,vd.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?QX: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($L.statSync(s).size-(h+5)*zX,0));let S=$L.createReadStream(s,{start:p});S.on("error",P=>{qX.error(P)});let T=0,b=[],R="",M;S.on("data",P=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;P=R+P;let H=0,j;for(;(j=k.exec(P))&&!S.destroyed;){M&&(M.message=P.slice(H,j.index),v(M));let[z,J,me]=j,ce=me.split("] ["),de=ce[0],Le=ce[1];ce.splice(0,2),M={timestamp:J,thread:de,level:Le,tags:ce,message:""},H=j.index+z.length}R=P.slice(H)}),S.on("end",P=>{S.destroyed||M&&(M.message=R.trim(),v(M))}),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&&(Ei(P,f,b),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&&(Ei(P,f,b),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&&(Ei(P,f,b),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&&(Ei(P,f,b),T++,T===h&&S.destroy());break;case i:P.level===o&&T<E?T++:P.level===o&&(Ei(P,f,b),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&&(Ei(P,f,b),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&&(Ei(P,f,b),T++,T===h&&S.destroy());break;default:T<E?T++:(Ei(P,f,b),T++,T===h&&S.destroy())}}return a(v,"onLogMessage"),await VX(S,"close"),b}a(JX,"readLog");function Ei(e,t,r){t==="desc"?jX(e,r):t==="asc"?XX(e,r):r.push(e)}a(Ei,"pushLineToResult");function jX(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(jX,"insertDescending");function XX(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(XX,"insertAscending")});var Bd=g((rEe,zL)=>{"use strict";var ZS=require("joi"),{string:Au,boolean:KL,date:ZX}=ZS.types(),eZ=je(),{validateSchemaExists:Zfe,validateTableExists:eEe,validateSchemaName:tEe}=zn(),tZ=L(),rZ=ke(),WL=ee();WL.initSync();var nZ=Au.invalid(WL.get(tZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(rZ.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(),QL={operation:Au.valid("add_node","update_node","set_node_replication"),node_name:nZ,subscriptions:ZS.array().items({table:Au.optional(),schema:Au.optional(),database:Au.optional(),subscribe:KL.required(),publish:KL.required().custom(iZ),start_time:ZX.iso()}).min(1).required()};function sZ(e){return eZ.validateBySchema(e,ZS.object(QL))}a(sZ,"addUpdateNodeValidator");function iZ(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(iZ,"checkForFalsy");zL.exports={addUpdateNodeValidator:sZ,validation_schema:QL}});var jL=g((sEe,JL)=>{var oZ=je(),aZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};JL.exports=function(e){return oZ.validateObject(e,aZ)}});var Hd=g((iEe,XL)=>{"use strict";var cZ=L().OPERATIONS_ENUM,eT=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=cZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};XL.exports=eT});var eM=g((aEe,ZL)=>{"use strict";var uZ={OPERATION:"operation",REFRESH:"refresh"},tT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},rT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};ZL.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:uZ,JWTRSAKeys:rT}});var yu=g((uEe,sM)=>{"use strict";var bu=require("jsonwebtoken"),nT=require("fs-extra"),sT=Q(),un=L(),{handleHDBError:pr,hdb_errors:lZ}=ne(),{HTTP_STATUS_CODES:Sr,AUTHENTICATION_ERROR_MSGS:Tr}=lZ,Ou=$(),tM=F_(),aT=an(),_Z=vr().update,dZ=Hd(),fZ=bs(),{UserEventMsg:EZ}=Mn(),hi=ee();hi.initSync();var iT=require("path"),{JWTTokens:hZ,JWTRSAKeys:mZ,TOKEN_TYPE_ENUM:xd}=eM(),pZ=hi.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?hi.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",SZ=hi.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?hi.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Gd="RS256",oT;sM.exports={createTokens:TZ,validateOperationToken:RZ,refreshOperationToken:gZ,validateRefreshToken:nM};async function TZ(e){if(sT.isEmpty(e)||typeof e!="object")throw pr(new Error,Tr.INVALID_AUTH_OBJECT,Sr.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.username))throw pr(new Error,Tr.USERNAME_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.password))throw pr(new Error,Tr.PASSWORD_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw pr(new Error,Tr.INVALID_CREDENTIALS,Sr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Ou.error(f),pr(new Error,Tr.INVALID_CREDENTIALS,Sr.UNAUTHORIZED,void 0,void 0,!0)}let r=await qd(),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 rM(i,r.private_key,r.passphrase),c=await bu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:SZ,algorithm:Gd,subject:xd.REFRESH}),u=tM.hash(c),_=new dZ(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await _Z(_)}catch(f){Ou.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw pr(new Error,Tr.REFRESH_TOKEN_SAVE_FAILED,Sr.INTERNAL_SERVER_ERROR);return fZ.signalUserChange(new EZ(process.pid)),new hZ(o,c)}a(TZ,"createTokens");async function rM(e,t,r){return await bu.sign(e,{key:t,passphrase:r},{expiresIn:pZ,algorithm:Gd,subject:xd.OPERATION})}a(rM,"signOperationToken");async function qd(){if(oT===void 0)try{let e=iT.join(hi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(hi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(hi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await nT.readFile(e)).toString(),s=(await nT.readFile(t)).toString(),i=(await nT.readFile(r)).toString();oT=new mZ(i,s,n)}catch(e){throw Ou.error(e),pr(new Error,Tr.NO_ENCRYPTION_KEYS,Sr.INTERNAL_SERVER_ERROR)}return oT}a(qd,"getJWTRSAKeys");async function gZ(e){if(!e)throw pr(new Error,Tr.INVALID_BODY,Sr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw pr(new Error,Tr.REFRESH_TOKEN_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);await nM(e.refresh_token);let t=await qd(),r=await bu.decode(e.refresh_token);return{operation_token:await rM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(gZ,"refreshOperationToken");async function RZ(e){try{let t=await qd(),r=await bu.verify(e,t.public_key,{algorithms:Gd,subject:xd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Ou.warn(t),t.name&&t.name==="TokenExpiredError"?pr(new Error,Tr.TOKEN_EXPIRED,Sr.FORBIDDEN):pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED)}}a(RZ,"validateOperationToken");async function nM(e){let t;try{let r=await qd(),n=await bu.verify(e,r.public_key,{algorithms:Gd,subject:xd.REFRESH});t=await aT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Ou.warn(r),r.name&&r.name==="TokenExpiredError"?pr(new Error,Tr.TOKEN_EXPIRED,Sr.FORBIDDEN):pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED)}if(!tM.validate(t.refresh_token,e))throw pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED);return t}a(nM,"validateRefreshToken")});var cT=g((dEe,aM)=>{"use strict";var AZ=jL(),pa=require("passport"),OZ=require("passport-local").Strategy,bZ=require("passport-http").BasicStrategy,yZ=require("util"),NZ=an(),oM=yZ.callbackify(NZ.findAndValidateUser),_Ee=Cr(),IZ=L(),iM=yu();pa.use(new OZ(function(e,t,r){oM(e,t,r)}));pa.use(new bZ(function(e,t,r){oM(e,t,r)}));pa.serializeUser(function(e,t){t(null,e)});pa.deserializeUser(function(e,t){t(null,e)});function wZ(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===IZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?iM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):iM.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(wZ,"authorize");function CZ(e,t){let r=AZ(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(CZ,"checkPermissions");aM.exports={authorize:wZ,checkPermissions:CZ}});var mi=g((EEe,cM)=>{"use strict";var uT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},lT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};cM.exports={Node:uT,NodeSubscription:lT}});var lM=g((mEe,uM)=>{"use strict";var DZ=L().OPERATIONS_ENUM,_T=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=DZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};uM.exports=_T});var Nu=g((SEe,_M)=>{"use strict";var dT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},fT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};_M.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var fM=g((gEe,dM)=>{"use strict";var ET=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};dM.exports=ET});var mM=g((yEe,hM)=>{"use strict";var LZ=fM(),AEe=ut(),EM=We(),MZ=$(),{getSchemaPath:OEe,getTransactionAuditStorePath:bEe}=Je(),{getDatabases:UZ}=(Re(),ie(Fe));hM.exports=PZ;async function PZ(e){let t=new LZ;try{let r=UZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await EM.environmentDataSize(schema_path,e.name),o=await EM.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){MZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(PZ,"lmdbGetTableSize")});var SM=g((IEe,pM)=>{"use strict";var hT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};pM.exports=hT});var Sa=g((MEe,OM)=>{"use strict";var vZ=require("fs-extra"),BZ=require("path"),Zt=require("systeminformation"),pi=$(),TM=it(),CEe=ke(),kd=L(),HZ=mM(),xZ=As(),{getThreadInfo:gM}=Ke(),yT=ee();yT.initSync();var GZ=SM(),{openEnvironment:DEe}=We(),{getSchemaPath:LEe}=Je(),{database:qZ,databases:RM}=(Re(),ie(Fe)),Fd;OM.exports={getHDBProcessInfo:TT,getNetworkInfo:RT,getDiskInfo:gT,getMemoryInfo:ST,getCPUInfo:pT,getTimeInfo:mT,getSystemInformation:AT,systemInformation:FZ,getTableSize:OT,getMetrics:bT};function mT(){return Zt.time()}a(mT,"getTimeInfo");async function pT(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Zt.cpu();l.cpu_speed=await Zt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...b}=await Zt.currentLoad();return b.cpus=[],T.forEach(R=>{let{raw_load:M,raw_load_idle:v,raw_load_irq:P,raw_load_nice:k,raw_load_system:H,raw_load_user:j,...z}=R;b.cpus.push(z)}),l.current_load=b,l}catch(e){return pi.error(`error in getCPUInfo: ${e}`),{}}}a(pT,"getCPUInfo");async function ST(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Zt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return pi.error(`error in getMemoryInfo: ${e}`),{}}}a(ST,"getMemoryInfo");async function TT(){let e={core:[],clustering:[]};try{let t=await Zt.processes(),r;try{r=Number.parseInt(await vZ.readFile(BZ.join(yT.get(kd.CONFIG_PARAMS.ROOTPATH),kd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===kd.NODE_ERROR_CODES.ENOENT)pi.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 pi.error(`error in getHDBProcessInfo: ${t}`),e}}a(TT,"getHDBProcessInfo");async function gT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Zt.fsStats();return e.read_write=_,e.size=await Zt.fsSize(),e}catch(t){return pi.error(`error in getDiskInfo: ${t}`),e}}a(gT,"getDiskInfo");async function RT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Zt.networkInterfaceDefault(),e.latency=await Zt.inetChecksite("google.com"),(await Zt.networkInterfaces()).forEach(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 Zt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return pi.error(`error in getNetworkInfo: ${t}`),e}}a(RT,"getNetworkInfo");async function AT(){if(Fd!==void 0)return Fd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Zt.osInfo();e=c;let u=await Zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Fd=e,Fd}catch(t){return pi.error(`error in getSystemInformation: ${t}`),e}}a(AT,"getSystemInformation");async function OT(){let e=[],t=await xZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await HZ(n));return e}a(OT,"getTableSize");async function bT(){let e={};for(let t in RM){let r=e[t]={};for(let n in RM[t])try{let s=qZ({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){pi.notify(`Error getting stats for table ${n}: ${s}`)}}return e}a(bT,"getMetrics");async function AM(){if(yT.get(kd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await TM.getNATSReferences(),t=await TM.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(AM,"getNatsStreamInfo");async function FZ(e){let t=new GZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await AT(),t.time=mT(),t.cpu=await pT(),t.memory=await ST(),t.disk=await gT(),t.network=await RT(),t.harperdb_processes=await TT(),t.table_size=await OT(),t.metrics=await bT(),t.threads=await gM(),t.replication=await AM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await AT();break;case"time":t.time=mT();break;case"cpu":t.cpu=await pT();break;case"memory":t.memory=await ST();break;case"disk":t.disk=await gT();break;case"network":t.network=await RT();break;case"harperdb_processes":t.harperdb_processes=await TT();break;case"table_size":t.table_size=await OT();break;case"database_metrics":case"metrics":t.metrics=await bT();break;case"threads":t.threads=await gM();break;case"replication":t.replication=await AM();break;default:break}return t}a(FZ,"systemInformation")});var $d=g((PEe,bM)=>{"use strict";bM.exports={version:kZ,printVersion:VZ};var Vd=ou();function kZ(){if(Vd)return Vd.version}a(kZ,"version");function VZ(){Vd&&console.log(`HarperDB Version ${Vd.version}`)}a(VZ,"printVersion")});var ln=g((xEe,wM)=>{"use strict";var $Z=vr(),NT=Q(),YZ=require("util"),_o=L(),yM=ee();yM.initSync();var KZ=cT(),NM=Pr(),{Node:BEe,NodeSubscription:HEe}=mi(),WZ=sa(),QZ=lM(),{RemotePayloadObject:zZ,RemotePayloadSubscription:JZ}=Nu(),{handleHDBError:jZ,hdb_errors:XZ}=ne(),{HTTP_STATUS_CODES:ZZ,HDB_ERROR_MSGS:e5}=XZ,t5=es(),r5=Sa(),n5=$d(),{getDatabases:s5}=(Re(),ie(Fe)),i5=YZ.promisify(KZ.authorize),o5=NM.searchByHash,a5=NM.searchByValue;wM.exports={authHeaderToUser:c5,isEmpty:u5,getNodeRecord:l5,upsertNodeRecord:_5,buildNodePayloads:d5,checkClusteringEnabled:f5,getAllNodeRecords:E5,getSystemInfo:h5,reverseSubscription:IM};async function c5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await i5(t,null),e}a(c5,"authHeaderToUser");function u5(e){return e==null}a(u5,"isEmpty");async function l5(e){let t=new WZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return o5(t)}a(l5,"getNodeRecord");async function _5(e){let t=new QZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return $Z.upsert(t)}a(_5,"upsertNodeRecord");function IM(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(IM,"reverseSubscription");function d5(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}=IM(c),E=s5()[u]?.[_],h=new JZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new zZ(r,t,s,n)}a(d5,"buildNodePayloads");function f5(){if(!yM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw jZ(new Error,e5.CLUSTERING_NOT_ENABLED,ZZ.BAD_REQUEST,void 0,void 0,!0)}a(f5,"checkClusteringEnabled");async function E5(){let e=new t5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await a5(e))}a(E5,"getAllNodeRecords");async function h5(){let e=await r5.getSystemInformation();return{hdb_version:n5.version(),node_version:e.node_version,platform:e.platform}}a(h5,"getSystemInfo")});var IT=g((qEe,BM)=>{"use strict";var Yd=it(),CM=Q(),DM=ke(),LM=L(),Kd=$(),MM=Tu(),m5=ad(),{RemotePayloadObject:p5}=Nu(),{handleHDBError:UM,hdb_errors:S5}=ne(),{HTTP_STATUS_CODES:PM}=S5,{NodeSubscription:vM}=mi();BM.exports=T5;async function T5(e,t){let r;try{r=await Yd.request(`${t}.${DM.REQUEST_SUFFIX}`,new p5(LM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Kd.trace("Response from remote describe all request:",r)}catch(o){Kd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Yd.requestErrorHandler(o,"add_node",t);throw UM(new Error,c,PM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===DM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw UM(new Error,o,PM.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===LM.SYSTEM_SCHEMA_NAME){await Yd.createLocalTableStream(u,c);let h=new vM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=CM.doesSchemaExist(u),l=n[u]!==void 0,d=c?CM.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(Kd.trace(`addNode creating schema: ${u}`),await MM.createSchema({operation:"create_schema",schema:u})),!d&&f){Kd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new m5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await MM.createTable(h)}await Yd.createLocalTableStream(u,c);let E=new vM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(T5,"reviewSubscriptions")});var Jd=g((kEe,GM)=>{"use strict";var{handleHDBError:Wd,hdb_errors:g5}=ne(),{HTTP_STATUS_CODES:Qd}=g5,{addUpdateNodeValidator:R5}=Bd(),zd=$(),xM=L(),HM=ke(),A5=Q(),Iu=it(),wu=ln(),O5=ee(),b5=IT(),{Node:y5,NodeSubscription:N5}=mi(),{broadcast:I5}=Ke(),w5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",C5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",D5=O5.get(xM.CONFIG_PARAMS.CLUSTERING_NODENAME);GM.exports=L5;async function L5(e,t=!1){zd.trace("addNode called with:",e),wu.checkClusteringEnabled();let r=R5(e);if(r)throw Wd(r,r.message,Qd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await wu.getNodeRecord(n);if(!A5.isEmptyOrZeroLength(d))throw Wd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Qd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await b5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=w5,o;let c=wu.buildNodePayloads(s,D5,xM.OPERATIONS_ENUM.ADD_NODE,await wu.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 N5(E.schema,E.table,E.publish,E.subscribe))}zd.trace("addNode sending remote payload:",c);let _;try{_=await Iu.request(`${n}.${HM.REQUEST_SUFFIX}`,c)}catch(d){zd.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 Iu.updateRemoteConsumer(p,n)}let f=Iu.requestErrorHandler(d,"add_node",n);throw Wd(new Error,f,Qd.INTERNAL_SERVER_ERROR,"error",f)}if(_.status===HM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw Wd(new Error,d,Qd.INTERNAL_SERVER_ERROR,"error",d)}zd.trace(_);for(let d=0,f=s.length;d<f;d++){let E=s[d];await Iu.updateRemoteConsumer(E,n),E.subscribe===!0&&await Iu.updateConsumerIterator(E.schema,E.table,n,"start")}let l=new y5(n,u,_.system_info);return await wu.upsertNodeRecord(l),I5({type:"nats_update"}),i.length>0?o.message=C5:o.message=`Successfully added '${n}' to manifest`,o}a(L5,"addNode")});var DT=g((YEe,kM)=>{"use strict";var{handleHDBError:wT,hdb_errors:M5}=ne(),{HTTP_STATUS_CODES:CT}=M5,{addUpdateNodeValidator:U5}=Bd(),Cu=$(),FM=L(),qM=ke(),$Ee=Q(),Du=it(),Lu=ln(),P5=ee(),{cloneDeep:v5}=require("lodash"),B5=IT(),{Node:H5,NodeSubscription:x5}=mi(),{broadcast:G5}=Ke(),q5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",F5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",k5=P5.get(FM.CONFIG_PARAMS.CLUSTERING_NODENAME);kM.exports=V5;async function V5(e){Cu.trace("updateNode called with:",e),Lu.checkClusteringEnabled();let t=U5(e);if(t)throw wT(t,t.message,CT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Lu.getNodeRecord(r);s.length>0&&(n=v5(s));let{added:i,skipped:o}=await B5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=q5,c;let u=Lu.buildNodePayloads(i,k5,FM.OPERATIONS_ENUM.UPDATE_NODE,await Lu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let f=i[l];Cu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),i[l].start_time===void 0&&delete i[l].start_time}Cu.trace("updateNode sending remote payload:",u);let _;try{_=await Du.request(`${r}.${qM.REQUEST_SUFFIX}`,u)}catch(l){Cu.error(`updateNode received error from request: ${l}`);let d=Du.requestErrorHandler(l,"update_node",r);throw wT(new Error,d,CT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===qM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw wT(new Error,l,CT.INTERNAL_SERVER_ERROR,"error",l)}Cu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];await Du.updateRemoteConsumer(f,r),f.subscribe===!0?await Du.updateConsumerIterator(f.schema,f.table,r,"start"):await Du.updateConsumerIterator(f.schema,f.table,r,"stop")}return n||(n=[new H5(r,[],_.system_info)]),await $5(n[0],i,_.system_info),o.length>0?c.message=F5:c.message=`Successfully updated '${r}'`,c}a(V5,"updateNode");async function $5(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 x5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Lu.upsertNodeRecord(n),G5({type:"nats_update"})}a($5,"updateNodeTable")});var WM=g((WEe,KM)=>{"use strict";var YM=require("joi"),{string:VM}=YM.types(),Y5=je(),$M=L(),K5=ee(),W5=ke();KM.exports=Q5;function Q5(e){let t=VM.invalid(K5.get($M.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(W5.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=YM.object({operation:VM.valid($M.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Y5.validateBySchema(e,r)}a(Q5,"removeNodeValidator")});var Xd=g((zEe,XM)=>{"use strict";var{handleHDBError:QM,hdb_errors:z5}=ne(),{HTTP_STATUS_CODES:zM}=z5,J5=WM(),Mu=$(),JM=ln(),j5=Q(),jd=L(),jM=ke(),LT=it(),X5=ee(),{RemotePayloadObject:Z5}=Nu(),{NodeSubscription:e8}=mi(),t8=ia(),r8=ii(),{broadcast:n8}=Ke(),s8=X5.get(jd.CONFIG_PARAMS.CLUSTERING_NODENAME);XM.exports=i8;async function i8(e){Mu.trace("removeNode called with:",e),JM.checkClusteringEnabled();let t=J5(e);if(t)throw QM(t,t.message,zM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await JM.getNodeRecord(r);if(j5.isEmptyOrZeroLength(n))throw QM(new Error,`Node '${r}' was not found.`,zM.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new Z5(jd.OPERATIONS_ENUM.REMOVE_NODE,s8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await LT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await LT.updateRemoteConsumer(new e8(l.schema,l.table,!1,!1),r)}catch(d){Mu.error(d)}}try{i=await LT.request(`${r}.${jM.REQUEST_SUFFIX}`,s),Mu.trace("Remove node reply from remote node:",r,i)}catch(u){Mu.error("removeNode received error from request:",u),o=!0}let c=new t8(jd.SYSTEM_SCHEMA_NAME,jd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await r8.deleteRecord(c),n8({type:"nats_update"}),i?.status===jM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Mu.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(i8,"removeNode")});var tU=g((jEe,eU)=>{"use strict";var ZM=require("joi"),{string:o8,array:a8}=ZM.types(),c8=je(),u8=Bd();eU.exports=l8;function l8(e){let t=ZM.object({operation:o8.valid("configure_cluster").required(),connections:a8.items(u8.validation_schema).required()});return c8.validateBySchema(e,t)}a(l8,"configureClusterValidator")});var MT=g((ZEe,oU)=>{"use strict";var _8=L(),Zd=$(),d8=Q(),f8=Xd(),E8=Jd(),rU=ln(),h8=tU(),{handleHDBError:nU,hdb_errors:m8}=ne(),{HTTP_STATUS_CODES:sU}=m8,p8="Configure cluster complete.",S8="Failed to configure the cluster. Check the logs for more details.",T8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";oU.exports=g8;async function g8(e){Zd.trace("configure cluster called with:",e),rU.checkClusteringEnabled();let t=h8(e);if(t)throw nU(t,t.message,sU.BAD_REQUEST,void 0,void 0,!0);let r=await rU.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let f=await iU(f8,{operation:_8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(f)}Zd.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 iU(E8,d,d.node_name);s.push(f)}Zd.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"&&(Zd.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(d8.isEmptyOrZeroLength(o))return{message:p8,connections:c};if(u)return{message:T8,failed_nodes:o,connections:c};throw nU(new Error,S8,sU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(g8,"configureCluster");async function iU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(iU,"functionWrapper")});var lU=g((the,uU)=>{"use strict";var Uu=require("joi"),R8=je(),{validateSchemaExists:aU,validateTableExists:A8,validateSchemaName:cU}=zn(),O8=Uu.object({operation:Uu.string().valid("purge_stream"),schema:Uu.string().custom(aU).custom(cU).optional(),database:Uu.string().custom(aU).custom(cU).optional(),table:Uu.string().custom(A8).required()});function b8(e){return R8.validateBySchema(e,O8)}a(b8,"purgeStreamValidator");uU.exports=b8});var UT=g((nhe,_U)=>{"use strict";var{handleHDBError:y8,hdb_errors:N8}=ne(),{HTTP_STATUS_CODES:I8}=N8,w8=lU(),C8=it(),D8=ln();_U.exports=L8;async function L8(e){e.schema=e.schema??e.database;let t=w8(e);if(t)throw y8(t,t.message,I8.BAD_REQUEST,void 0,void 0,!0);D8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await C8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(L8,"purgeStream")});var BT=g((ihe,pU)=>{"use strict";var vT=ln(),M8=it(),EU=ee(),ef=L(),fo=ke(),U8=Q(),PT=$(),{RemotePayloadObject:P8}=Nu(),{ErrorCode:dU}=require("nats"),fU=EU.get(ef.CONFIG_PARAMS.CLUSTERING_ENABLED),hU=EU.get(ef.CONFIG_PARAMS.CLUSTERING_NODENAME);pU.exports={clusterStatus:v8,buildNodeStatus:mU};async function v8(){let e={node_name:hU,is_enabled:fU,connections:[]};if(!fU)return e;let t=await vT.getAllNodeRecords();if(U8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(mU(t[n],e.connections));return await Promise.allSettled(r),e}a(v8,"clusterStatus");async function mU(e,t){let r=e.name,n=new P8(ef.OPERATIONS_ENUM.CLUSTER_STATUS,hU,void 0,await vT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await M8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,PT.error(`Error getting node status from ${r} `,s))}catch(u){PT.warn(`Error getting node status from ${r}`,u),u.code===dU.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===dU.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new B8(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!==ef.PRE_4_0_0_VERSION&&await vT.upsertNodeRecord(u)}catch(u){PT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(mU,"buildNodeStatus");function B8(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(B8,"NodeStatusObject")});var xT=g((ahe,SU)=>{"use strict";var{handleHDBError:H8,hdb_errors:x8}=ne(),{HTTP_STATUS_CODES:G8}=x8,q8=it(),F8=ln(),HT=Q(),tf=require("joi"),k8=je(),V8=2e3,$8=tf.object({timeout:tf.number().min(1),connected_nodes:tf.boolean(),routes:tf.boolean()});SU.exports=Y8;async function Y8(e){F8.checkClusteringEnabled();let t=k8.validateBySchema(e,$8);if(t)throw H8(t,t.message,G8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||HT.autoCastBoolean(n),o=s===void 0||HT.autoCastBoolean(s),c={nodes:[]},u=await q8.getServerList(r??V8),_={};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:HT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(Y8,"clusterNetwork")});var AU=g((uhe,RU)=>{"use strict";var GT=require("joi"),TU=je(),{route_constraints:gU}=tp();RU.exports={setRoutesValidator:K8,deleteRoutesValidator:W8};function K8(e){let t=GT.object({server:GT.valid("hub","leaf").required(),routes:gU.required()});return TU.validateBySchema(e,t)}a(K8,"setRoutesValidator");function W8(e){let t=GT.object({routes:gU.required()});return TU.validateBySchema(e,t)}a(W8,"deleteRoutesValidator")});var FT=g((_he,NU)=>{"use strict";var Eo=lr(),qT=Q(),rf=L(),OU=AU(),{handleHDBError:bU,hdb_errors:Q8}=ne(),{HTTP_STATUS_CODES:yU}=Q8,z8="cluster routes successfully set",J8="cluster routes successfully deleted";NU.exports={setRoutes:j8,getRoutes:X8,deleteRoutes:Z8};function j8(e){let t=OU.setRoutesValidator(e);if(t)throw bU(t,t.message,yU.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=qT.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(rf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(rf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:z8,set:o,skipped:i}}a(j8,"setRoutes");function X8(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(X8,"getRoutes");function Z8(e){let t=OU.deleteRoutesValidator(e);if(t)throw bU(t,t.message,yU.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=qT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(rf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=qT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(rf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:J8,deleted:i,skipped:o}}a(Z8,"deleteRoutes")});var wU=g((fhe,IU)=>{"use strict";var Pu=require("alasql"),ho=require("recursive-iterator"),Hn=$(),e6=Q(),vu=L(),kT=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,r6(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>vu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!vu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][vu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=t6(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!vu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Pu.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 t6(e){return e.filter(t=>t[vu.PERMS_CRUD_ENUM.READ])}a(t6,"filterReadRestrictedAttrs");function r6(e,t,r,n,s){n6(e,t,r,n,s)}a(r6,"interpretAST");function Bu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(Bu,"addSchemaTableToMap");function n6(e,t,r,n,s){if(!e){Hn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Pu.yy.Insert?a6(e,t,r):e instanceof Pu.yy.Select?s6(e,t,r,n,s):e instanceof Pu.yy.Update?i6(e,t,r):e instanceof Pu.yy.Delete?o6(e,t,r):Hn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(n6,"getRecordAttributesAST");function s6(e,t,r,n,s){if(!e){Hn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(e6.isEmptyOrZeroLength(i)){Hn.error("No schema specified");return}e.from.forEach(c=>{Bu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Bu(c.table,t,r,n,s)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Hn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Hn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Hn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Hn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(s6,"getSelectAttributes");function i6(e,t,r){if(!e){Hn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.table.tableid,s,i.columnid,t,r)}a(i6,"getUpdateAttributes");function o6(e,t,r){if(!e){Hn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.table.tableid,s,i.columnid,t,r)}a(o6,"getDeleteAttributes");function a6(e,t,r){if(!e){Hn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;Bu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.into.tableid,s,i.columnid,t,r)}a(a6,"getInsertAttributes");function VT(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(VT,"pushAttribute");IU.exports=kT});var KT=g((hhe,MU)=>{var nf=Ji(),CU=require("chalk"),Vr=$(),DU=require("prompt"),{promisify:c6}=require("util"),$T=L(),u6=require("fs-extra"),l6=require("path"),_6=Q(),d6=$d(),LU=ee();LU.initSync();var f6=require("moment"),E6=c6(DU.get),h6=l6.join(LU.getHdbBasePath(),$T.LICENSE_KEY_DIR_NAME,$T.LICENSE_FILE_NAME,$T.LICENSE_FILE_NAME);MU.exports={getFingerprint:p6,setLicense:m6,parseLicense:YT,register:S6,getRegistrationInfo:g6};async function m6(e){if(e&&e.key&&e.company){try{Vr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await YT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Vr.error(r),Vr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(m6,"setLicense");async function p6(){let e={};try{e=await nf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Vr.error(r),Vr.error(t),new Error(r)}return e}a(p6,"getFingerprint");async function YT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Vr.info("Validating license input...");let r=nf.validateLicense(e,t);if(Vr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Vr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Vr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Vr.info("writing license to disk"),await u6.writeFile(h6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Vr.error("Failed to write License"),n}return"Registration successful."}a(YT,"parseLicense");async function S6(){let e=await T6();return YT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(S6,"register");async function T6(){let e=await nf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:CU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:CU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{DU.start()}catch(n){Vr.error(n)}let r;try{r=await E6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(T6,"promptForRegistration");async function g6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await nf.getLicense()}catch(r){throw Vr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(_6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=d6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=f6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(g6,"getRegistrationInfo")});var PU=g((phe,UU)=>{"use strict";var R6=ke(),WT=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+R6.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"}};UU.exports=WT});var HU=g((The,BU)=>{"use strict";var vU=ke(),QT=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+vU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+vU.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"}};BU.exports=QT});var GU=g((Rhe,xU)=>{"use strict";var zT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};xU.exports=zT});var FU=g((Ohe,qU)=>{"use strict";var A6=ke(),JT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+A6.SERVER_SUFFIX.ADMIN,this.password=r}};qU.exports=JT});var ZT=g((yhe,$U)=>{"use strict";var Ta=require("path"),af=require("fs-extra"),O6=PU(),b6=HU(),y6=GU(),N6=FU(),jT=an(),Ra=Q(),gr=lr(),of=L(),Hu=ke(),{CONFIG_PARAMS:ft}=of,Aa=$(),xu=ee(),kU=Rs(),XT=it(),ga="clustering",I6=1e4,VU=50;$U.exports={generateNatsConfig:C6,removeNatsConfig:D6,getHubConfigPath:w6};function w6(){let e=xu.get(ft.ROOTPATH);return Ta.join(e,ga,Hu.NATS_CONFIG_FILES.HUB_SERVER)}a(w6,"getHubConfigPath");async function C6(e=!1,t=void 0){xu.initSync();let r=xu.get(ft.ROOTPATH),n=Ta.join(r,ga,Hu.PID_FILES.HUB),s=Ta.join(r,ga,Hu.PID_FILES.LEAF),i=gr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ta.join(r,ga,Hu.NATS_CONFIG_FILES.HUB_SERVER),c=Ta.join(r,ga,Hu.NATS_CONFIG_FILES.LEAF_SERVER),u=gr.getConfigFromFile(ft.CLUSTERING_TLS_CERTIFICATE),_=gr.getConfigFromFile(ft.CLUSTERING_TLS_PRIVATEKEY),l=gr.getConfigFromFile(ft.CLUSTERING_TLS_CERT_AUTH),d=gr.getConfigFromFile(ft.CLUSTERING_TLS_INSECURE),f=gr.getConfigFromFile(ft.CLUSTERING_TLS_VERIFY),E=gr.getConfigFromFile(ft.CLUSTERING_NODENAME),h=gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await XT.checkNATSServerInstalled()||cf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await jT.listUsers(),S=gr.getConfigFromFile(ft.CLUSTERING_USER),T=await jT.getClusterUser();(Ra.isEmpty(T)||T.active!==!0)&&cf(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await sf(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await sf(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await sf(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),await sf(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT));let b=[],R=[];for(let[z,J]of p.entries())J.role.role===of.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(b.push(new N6(J.username,kU.decrypt(J.hash))),R.push(new y6(J.username,kU.decrypt(J.hash))));let M=[],{hub_routes:v}=gr.getClusteringRoutes();if(!Ra.isEmptyOrZeroLength(v))for(let z of v)M.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${z.host}:${z.port}`);let P=new O6(gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NAME),gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),M,b,R);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===of.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await af.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 b6(gr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[k],[H],b,R,u,_,l,d);l==null&&delete j.tls.ca_file,(t===void 0||t===of.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await af.writeJson(c,j),Aa.trace(`Leaf server config written to ${c}`))}a(C6,"generateNatsConfig");async function sf(e){let t=xu.get(e);return Ra.isEmpty(t)&&cf(`port undefined for '${e}'`),await Ra.isPortTaken(t)&&cf(`'${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(sf,"isPortAvailable");function cf(e){let t=`Error generating clustering config: ${e}`;Aa.error(t),console.error(t),process.exit(1)}a(cf,"generateNatsConfigError");async function D6(e){let{port:t,config_file:r}=XT.getServerConfig(e),{username:n,decrypt_hash:s}=await jT.getClusterUser(),i=0,o=2e3;for(;i<VU;){try{let l=await XT.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>=VU)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(I6),u=Ta.join(xu.get(ft.ROOTPATH),ga,r);await af.writeFile(u,c),await af.remove(u),Aa.notify(e,"started.")}a(D6,"removeNatsConfig")});var JU=g((Ihe,zU)=>{"use strict";var $r=ee(),L6=Ji(),he=L(),Gu=ke(),Cs=require("path"),{PACKAGE_ROOT:lf}=L(),YU=ee(),uf=Q(),Oa="/dev/null",M6=Cs.join(lf,"launchServiceScripts"),KU=Cs.join(lf,"utility/scripts"),U6=Cs.join(KU,he.HDB_RESTART_SCRIPT),WU=Cs.resolve(lf,"dependencies",`${process.platform}-${process.arch}`,Gu.NATS_BINARY_NAME);function QU(){let t=L6.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 uf.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=uf.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:lf}}a(QU,"generateMainServerConfig");var P6=9930;function v6(){$r.initSync(!0);let e=$r.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.HUB_SERVER),r=Cs.join($r.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=YU.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[$r.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==P6?"-"+n:""),script:WU,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 $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Oa,i.error_file=Oa),i}a(v6,"generateNatsHubServerConfig");var B6=9940;function H6(){$r.initSync(!0);let e=$r.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cs.join($r.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=YU.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[$r.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==B6?"-"+n:""),script:WU,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 $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Oa,i.error_file=Oa),i}a(H6,"generateNatsLeafServerConfig");function x6(){$r.initSync();let e=Cs.join($r.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:M6,autorestart:!1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Oa,t.error_file=Oa),t}a(x6,"generateClusteringUpgradeV4ServiceConfig");function G6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return uf.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=uf.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:KU},script:U6}}a(G6,"generateRestart");function q6(){return{apps:[QU()]}}a(q6,"generateAllServiceConfigs");zU.exports={generateAllServiceConfigs:q6,generateMainServerConfig:QU,generateRestart:G6,generateNatsHubServerConfig:v6,generateNatsLeafServerConfig:H6,generateClusteringUpgradeV4ServiceConfig:x6}});var lP=g((Dhe,uP)=>{"use strict";var ve=L(),F6=Q(),Ls=ZT(),_f=it(),Ds=ke(),Si=JU(),df=ee(),Ti=$(),k6=ln(),{startWorker:jU,onMessageFromWorkers:V6}=Ke(),$6=Sa(),Che=require("util"),Y6=require("child_process"),K6=require("fs"),{execFile:W6}=Y6,Ie;uP.exports={enterPM2Mode:Q6,start:gi,stop:eg,reload:ZU,restart:eP,list:tg,describe:rP,connect:Ms,kill:Z6,startAllServices:e9,startService:rg,getUniqueServicesList:nP,restartAllServices:t9,isServiceRegistered:sP,reloadStopStart:iP,restartHdb:tP,deleteProcess:j6,startClusteringProcesses:aP,startClusteringThreads:cP,isHdbRestartRunning:X6,isClusteringRunning:n9,stopClustering:r9,reloadClustering:s9};var qu=!1;V6(e=>{e.type==="restart"&&df.initSync(!0)});function Q6(){qu=!0}a(Q6,"enterPM2Mode");function Ms(){return Ie||(Ie=require("pm2")),new Promise((e,t)=>{Ie.connect((r,n)=>{Ti.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ms,"connect");var Rr,z6=10,XU;function gi(e,t=!1){if(qu)return J6(e);let r=W6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Rr.indexOf(r);o>-1&&Rr.splice(o,1),!XU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<z6&&(K6.existsSync(Ls.getHubConfigPath())?gi(e):(await Ls.generateNatsConfig(!0),gi(e),await new Promise(c=>setTimeout(c,3e3)),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=df.get(ve.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?Ti.OUTPUTS.STDERR:Ti.OUTPUTS.STDOUT;Ti.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?Ti.OUTPUTS.STDERR:Ti.OUTPUTS.STDOUT;Ti.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Rr=[],!Rr&&!t){let i=a(()=>{XU=!0,Rr&&(Rr.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)}Rr.push(r)}a(gi,"start");function J6(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(J6,"startWithPM2");function eg(e){if(!qu){for(let t of Rr||[])t.name===e&&(Rr.splice(Rr.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(eg,"stop");function ZU(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(ZU,"reload");function eP(e){if(!qu)for(let t of Rr||[])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(eP,"restart");function j6(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(j6,"deleteProcess");async function tP(){await gi(Si.generateRestart())}a(tP,"restartHdb");async function X6(){let e=await tg();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(X6,"isHdbRestartRunning");function tg(){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(tg,"list");function rP(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(rP,"describe");function Z6(){if(!qu){for(let e of Rr||[])e.kill();Rr=[];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(Z6,"kill");async function e9(){try{await aP(),await cP(),await gi(Si.generateAllServiceConfigs())}catch(e){throw Ie?.disconnect(),e}}a(e9,"startAllServices");async function rg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Si.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Si.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Si.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Si.generateNatsHubServerConfig(),await gi(r,t),await Ls.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Si.generateNatsLeafServerConfig(),await gi(r,t),await Ls.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Si.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await gi(r)}catch(r){throw Ie?.disconnect(),r}}a(rg,"startService");async function nP(){try{let e=await tg(),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(nP,"getUniqueServicesList");async function t9(e=[]){try{let t=!1,r=await nP();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await eP(o))}t&&await iP(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ie?.disconnect(),t}}a(t9,"restartAllServices");async function sP(e){if(Rr?.find(r=>r.name===e))return!0;let t=await $6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(sP,"isServiceRegistered");async function iP(e){let t=df.get(ve.CONFIG_PARAMS.THREADS_COUNT)??df.get(ve.CONFIG_PARAMS.THREADS),r=await rP(e),n=F6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await eg(e),await rg(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await tP():await ZU(e)}a(iP,"reloadStopStart");var oP;async function aP(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await rg(r,e)}}a(aP,"startClusteringProcesses");async function cP(){oP=jU(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await _f.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await _f.updateLocalStreams();let e=await k6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){Ti.info("Starting clustering upgrade 4.0.0 process"),jU(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(cP,"startClusteringThreads");async function r9(){for(let e in ve.CLUSTERING_PROCESSES)if(e!==ve.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ve.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await oP.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await eg(t)}}a(r9,"stopClustering");async function n9(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await sP(t)===!1)return!1}return!0}a(n9,"isClusteringRunning");async function s9(){await Ls.generateNatsConfig(!0),await _f.reloadNATSHub(),await _f.reloadNATSLeaf(),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(s9,"reloadClustering")});var pP={};qe(pP,{compactOnStart:()=>i9,copyDb:()=>mP});async function i9(){ku.notify("Running compact on start"),console.log("Running compact on start");let e=(0,ng.get)(Ri.CONFIG_PARAMS.ROOTPATH),t=new Map,r=dr();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}let i=(0,ff.join)(e,"backup",n+".mdb"),o=(0,ff.join)(e,Ri.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await _P(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 mP(n,o),console.log("Backing up",n,"to",i),await(0,mo.move)(s,i,{overwrite:!0})}Fu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,mo.move)(i,s,{overwrite:!0}),await(0,mo.remove)((0,ff.join)(e,Ri.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Fu()}catch(n){ku.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,sg.updateConfigValue)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,mo.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Fu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await _P(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: ${
|
|
13
|
-
${r.stack}`;throw ug.error(s),yP(new Error)}}}a(T9,"getRolePermissions");function g9(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[Ar.SYSTEM_SCHEMA_NAME]=s[Ar.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=R9(t[i]);return}r[i]=CP(),s[i]?(s[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],u=t[i][o],_=A9(c,u);r[i].describe||LP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=lg()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=lg()})}),r}a(g9,"translateRolePermissions");function R9(e){let t=CP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=lg(!0,!0,!0,!0,!0)}),t}a(R9,"createStructureUserPermissions");function A9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return Ar.TIME_STAMP_NAMES.includes(d)&&(f=IP(d,l[Yu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=NP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=UP(l),n.attribute_permissions.push(l),c||O9(l,u)}else if(_!==o){let l;Ar.TIME_STAMP_NAMES.includes(_)?l=IP(_):l=NP(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=wP(n),n}else return e.describe=wP(e),e}a(A9,"getTableAttrPerms");function wP(e){return LP.filter(t=>e[t]).length>0}a(wP,"getSchemaTableDescribePerm");function UP(e){return MP.filter(t=>e[t]).length>0}a(UP,"getAttributeDescribePerm");function O9(e,t){MP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(O9,"checkForHashPerms")});var BP={};qe(BP,{Resources:()=>gf,keyArrayToString:()=>ba,resetResources:()=>b9,resources:()=>Ai});function b9(){return Ai=new gf}function ba(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var gf,Ai,Ku=ge(()=>{so();gf=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,s,n){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:s,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!n)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let s=2,n;for(;(s=t.indexOf("/",s))>-1;){let c=t.slice(0,s),u=this.get(c);if(u){if(u.relativeURL=t.slice(s),!u.hasSubPaths)return u;n=u}s+=2}if(n)return n;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return n=this.get(o),n?n.relativeURL=i>-1?t.slice(i):"":n||(n=this.get(""),n&&(t[0]!=="/"&&(t="/"+t),n.relativeURL=t)),n}getResource(t,r){let s=this.getMatch(t);if(s)return t=s.relativeURL,s.Resource.getResource(this.pathToId(t,s.Resource),r)}call(t,r,s){return je(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(b9,"resetResources");a(ba,"keyArrayToString")});var HP={};qe(HP,{Headers:()=>Oi,appendHeader:()=>fg});function fg(e,t,r,s){if(e.append)e.append(t,r,s);else if(e.set){let n=e.get(t);if(n)if(s)r=(typeof n=="string"?n:n.join(", "))+", "+r;else if(typeof n=="string")r=[n,r];else{n.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var Oi,Wu=ge(()=>{Oi=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase();if(!super.has(s))return super.set(s,[t,r])}append(t,r,s){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase(),i=super.get(n);if(i){let o=i[1];if(s)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(fg,"appendHeader")});var Qu={};qe(Qu,{authentication:()=>YP,bypassAuth:()=>L9,login:()=>U9,logout:()=>P9,start:()=>M9});function L9(){$P=!0}async function YP(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?w9?I9:[]:N9?y9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Oi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Rf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Rf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Rf){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(E);if(h>=0){let p=n.indexOf(";",h),S=n.indexOf("=",h);u=n.slice(S+1,p===-1?n.length:p),_=await GP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new ya.AuthAuditLog(E,h,vt.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===vt.AUTH_AUDIT_STATUS.SUCCESS?xP.notify(S):xP.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 st.getUser(E,null,null),l(E,vt.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(s){if(d=To.get(s),!d){let[E,h]=s.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await st.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Af.validateOperationToken)(h)}catch(T){if(T.message==="invalid token")try{return await(0,Af.validateRefreshToken)(h),c({status:-1})}catch{throw T}}break}}catch(T){return D9&&(To.get(h)||(To.set(h,h),l(p,vt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:bi({error:T.message},e)})}To.set(s,d),C9&&l(d.username,vt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await st.getUser(_.user,null,e):($P&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,FP.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,GP.put(E)},e.login=async function(E,h){e.user=await st.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")&&Ai.loginPath?(f.status=302,f.headers.set("Location",Ai.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 Oi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function M9({server:e,port:t}){e.request(YP,{port:t||"all"}),qP||(qP=!0,setInterval(()=>{To=new Map},_s.get(vt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),VP.user.addListener(()=>{To=new Map}))}async function U9(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function P9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var FP,Af,kP,_s,vt,ya,VP,xP,y9,N9,I9,w9,GP,Rf,$P,C9,D9,To,qP,Of=ge(()=>{FP=v(os());or();Ku();Af=v(bu());Re();kP=require("uuid"),_s=v(ee()),vt=v(L()),ya=v($()),VP=v(kc());Wu();Na();xP=(0,ya.loggerWithTag)("auth-event");_s.initSync();y9=_s.get(vt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),N9=_s.get(vt.CONFIG_PARAMS.HTTP_CORS),I9=_s.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),w9=_s.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),GP=lt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Rf=_s.get(vt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,$P=_s.get(vt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,C9=_s.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,D9=_s.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,To=new Map;st.onInvalidatedUser(()=>{To=new Map});a(L9,"bypassAuth");a(YP,"authentication");a(M9,"start");a(U9,"login");a(P9,"logout")});var jP=g((Whe,XP)=>{"use strict";var Ie=require("joi"),KP=require("fs-extra"),WP=require("path"),Pn=Xe(),QP=ee(),zP=L(),JP=$(),{hdb_errors:v9}=se(),{HDB_ERROR_MSGS:er}=v9,Un=/^[a-zA-Z0-9-_]+$/;XP.exports={getDropCustomFunctionValidator:H9,setCustomFunctionValidator:x9,addComponentValidator:k9,dropCustomFunctionProjectValidator:V9,packageComponentValidator:$9,deployComponentValidator:Y9,setComponentFileValidator:G9,getComponentFileValidator:F9,dropComponentFileValidator:q9};function bf(e,t,r){try{let s=QP.get(zP.CONFIG_PARAMS.COMPONENTSROOT),n=WP.join(s,t);return KP.existsSync(n)?e?t:r.message(er.PROJECT_EXISTS):e?r.message(er.NO_PROJECT):t}catch(s){return JP.error(s),r.message(er.VALIDATION_ERR)}}a(bf,"checkProjectExists");function zu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(zu,"checkFilePath");function B9(e,t,r,s){try{let n=QP.get(zP.CONFIG_PARAMS.COMPONENTSROOT),i=WP.join(n,e,t,r+".js");return KP.existsSync(i)?r:s.message(er.NO_FILE)}catch(n){return JP.error(n),s.message(er.VALIDATION_ERR)}}a(B9,"checkFileExists");function H9(e){let t=Ie.object({project:Ie.string().pattern(Un).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(Un).custom(B9.bind(null,e.project,e.type)).custom(zu).required().messages({"string.pattern.base":er.BAD_FILE_NAME})});return Pn.validateBySchema(e,t)}a(H9,"getDropCustomFunctionValidator");function x9(e){let t=Ie.object({project:Ie.string().pattern(Un).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(zu).required(),function_content:Ie.string().required()});return Pn.validateBySchema(e,t)}a(x9,"setCustomFunctionValidator");function G9(e){let t=Ie.object({project:Ie.string().pattern(Un).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Pn.validateBySchema(e,t)}a(G9,"setComponentFileValidator");function q9(e){let t=Ie.object({project:Ie.string().pattern(Un).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).optional()});return Pn.validateBySchema(e,t)}a(q9,"dropComponentFileValidator");function F9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(zu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Pn.validateBySchema(e,t)}a(F9,"getComponentFileValidator");function k9(e){let t=Ie.object({project:Ie.string().pattern(Un).custom(bf.bind(null,!1)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Pn.validateBySchema(e,t)}a(k9,"addComponentValidator");function V9(e){let t=Ie.object({project:Ie.string().pattern(Un).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Pn.validateBySchema(e,t)}a(V9,"dropCustomFunctionProjectValidator");function $9(e){let t=Ie.object({project:Ie.string().pattern(Un).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Pn.validateBySchema(e,t)}a($9,"packageComponentValidator");function Y9(e){let t=Ie.object({project:Ie.string().pattern(Un).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":er.BAD_PACKAGE}),package:Ie.string().optional()});return Pn.validateBySchema(e,t)}a(Y9,"deployComponentValidator")});var wf=g((zhe,iv)=>{"use strict";var yf=require("joi"),Nf=require("path"),ZP=require("fs-extra"),{exec:K9}=require("child_process"),W9=require("util"),ev=W9.promisify(K9),Ju=L(),{handleHDBError:Ia,hdb_errors:Q9}=se(),{HTTP_STATUS_CODES:wa}=Q9,Xu=ee(),z9=Xe(),Ca=$();Xu.initSync();var Eg=Xu.get(Ju.CONFIG_PARAMS.COMPONENTSROOT),tv="npm install --omit=dev --json",J9=`${tv} --dry-run`;iv.exports={installModules:e7,auditModules:t7,installAllRootModules:X9,uninstallRootModule:j9,linkHarperdb:Z9};async function X9(e=!1){await If(),await ju(e?"npm install --ignore-scripts":"npm install",Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(X9,"installAllRootModules");async function j9(e){await ju(`npm uninstall ${e}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(j9,"uninstallRootModule");async function Z9(){await If(),await ju(`npm link ${Ju.PACKAGE_ROOT}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(Z9,"linkHarperdb");async function ju(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await ev(e,{cwd:t}))}catch(n){throw new Error(n.stderr.replace(`
|
|
14
|
-
`,""))}return
|
|
15
|
-
`,"")}a(
|
|
12
|
+
Database backup has not been removed and can be found here: ${s}`;ku.error(u),console.error(u)}(0,ng.get)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,mo.remove)(s))}(0,sg.updateConfigValue)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function _P(e){let t=await(0,hP.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function mP(e,t){console.log("copyDb start");let r=dr()[e],n;for(let f in r){n=r[f].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,dP.open)(new fP.default(t)),c=o.openDB(Ef.INTERNAL_DBIS_NAME),u,_=0;for(let{key:f,value:E}of s.getRange({})){let h=E.is_hash_attribute||E.isPrimaryKey,p,S;if(h&&(p=E.compression,S=mf(),S?E.compression=S:delete E.compression,p?.dictionary?.toString()===S?.dictionary?.toString()&&(p=null,S=null)),c.put(f,E),!(h||E.indexed))continue;let T=new EP.default(!h,h);T.encoding="binary",T.compression=p;let b=n.openDB(f,T);b.decoder=null,T.compression=S;let R=o.openDB(f,T);R.encoder=null,console.log("copying",f,"from",e,"to",t),await d(b,R,h)}let l=n.openDB(Ef.AUDIT_STORE_NAME,hf);console.log("copying audit log"),d(i,l,!1);async function d(f,E,h){let p=0,S=0;for(let{key:T,value:b,version:R}of f.getRange({start:null,versions:h}))u=E.put(T,b,R),p++,S+=(T.length||10)+b.length,_++>5e3&&(await u,console.log("copied",p,"entries",S,"bytes"),_=0);console.log("finish copying, copied",p,"entries",S,"bytes")}a(d,"copyDbi"),await u,o.close(),console.log("copied database "+e+" to "+t)}var dP,ff,mo,ng,fP,EP,Ef,Ri,hP,sg,ku,SP=ge(()=>{Re();dP=require("lmdb"),ff=require("path"),mo=require("fs-extra"),ng=B(ee()),fP=B(Dc()),EP=B(Cc()),Ef=B(ut()),Ri=B(L());ei();hP=B(As()),sg=B(lr()),ku=B($());a(i9,"compactOnStart");a(_P,"getTotalDBRecordCount");a(mP,"copyDb")});var gf=g((Bhe,yP)=>{"use strict";var o9=require("minimist"),{isMainThread:og,parentPort:RP}=require("worker_threads"),et=L(),{PROCESS_DESCRIPTORS_VALIDATE:Vu}=et,is=$(),ag=Q(),Sf=ZT(),pf=it(),vhe=ke(),AP=lr(),os=lP(),TP=Sa(),{compactOnStart:a9}=(SP(),ie(pP)),c9=Uh(),{restartWorkers:Tf,onMessageByType:u9}=Ke(),{handleHDBError:l9,hdb_errors:_9}=ne(),{HTTP_STATUS_CODES:d9}=_9,Yu=ee();Yu.initSync();var $u=`Restarting HarperDB. This may take up to ${et.RESTART_TIMEOUT_MS/1e3} seconds.`,f9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",gP="Clustering is not enabled so cannot be restarted",E9="Invalid service",ba,_n;yP.exports={restart:OP,restartService:cg};og&&u9(et.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?cg({service:e.workerType}):OP({operation:"restart"})});async function OP(e){_n=Object.keys(e).length===0,ba=await os.isServiceRegistered(et.HDB_PROC_DESCRIPTOR);let t=o9(process.argv);if(t.service){await cg(t);return}if(_n&&!ba){console.error(f9);return}if(_n&&console.log($u),ba){os.enterPM2Mode(),is.notify($u);let r=c9(Object.keys(et.CONFIG_PARAM_MAP),!0);return ag.isEmptyOrZeroLength(Object.keys(r))||AP.updateConfigValue(void 0,void 0,r,!0,!0),h9(),$u}return og?(is.notify($u),Yu.get(et.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await a9(),setTimeout(()=>{Tf()},50)):RP.postMessage({type:et.ITC_EVENT_TYPES.RESTART}),$u}a(OP,"restart");async function cg(e){let{service:t}=e;if(et.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw l9(new Error,E9,d9.BAD_REQUEST,void 0,void 0,!0);if(ba=await os.isServiceRegistered(et.HDB_PROC_DESCRIPTOR),!og)return RP.postMessage({type:et.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Vu.clustering:if(!Yu.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=gP;break}_n&&console.log("Restarting clustering"),is.notify("Restarting clustering"),await bP();break;case Vu.clustering_config:case Vu["clustering config"]:if(!Yu.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=gP;break}_n&&console.log("Restarting clustering_config"),is.notify("Restarting clustering_config"),await os.reloadClustering();break;case"custom_functions":case"custom functions":case Vu.harperdb:case Vu.http_workers:if(_n&&!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}_n&&console.log("Restarting http_workers"),is.notify("Restarting http_workers"),_n?await os.restart(et.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Tf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(is.error(r),_n&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(cg,"restartService");async function h9(){await bP(),await os.restart(et.HDB_PROC_DESCRIPTOR),await ag.async_set_timeout(2e3),Yu.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await ig(),_n&&(await pf.closeConnection(),process.exit(0))}a(h9,"restartPM2Mode");async function bP(){if(!AP.getConfigFromFile(et.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await TP.getHDBProcessInfo()).clustering.length===0)is.trace("Clustering not running, restart will start clustering services"),await Sf.generateNatsConfig(!0),await os.startClusteringProcesses(),await os.startClusteringThreads(),await ig(),_n&&await pf.closeConnection();else{await Sf.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 TP.getHDBProcessInfo()).clustering.forEach(s=>{is.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await ag.async_set_timeout(3e3),await ig(),await pf.updateLocalStreams(),_n&&await pf.closeConnection(),is.trace("Restart clustering restarting ingest and reply service threads");let t=Tf(et.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Tf(et.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(bP,"restartClustering");async function ig(){await Sf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Sf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(ig,"removeNatsConfig")});var BP=g((Ghe,vP)=>{"use strict";var xhe=require("lodash"),Ar=L(),{handleHDBError:NP,hdb_errors:m9}=ne(),{HDB_ERROR_MSGS:p9,HTTP_STATUS_CODES:S9}=m9,ug=$();vP.exports={getRolePermissions:g9};var po=Object.create(null),T9=a(e=>({key:e,perms:{}}),"perms_template_obj"),DP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),LP=a((e=!1,t=!1,r=!1,n=!1)=>({[Ar.PERMS_CRUD_ENUM.READ]:e,[Ar.PERMS_CRUD_ENUM.INSERT]:t,[Ar.PERMS_CRUD_ENUM.UPDATE]:r,[Ar.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),lg=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...LP(t,r,n,s)}),"table_perms_template"),IP=a((e,t=LP())=>({attribute_name:e,describe:PP(t),[Ku]:t[Ku],[_g]:t[_g],[dg]:t[dg]}),"attr_perms_template"),wP=a((e,t=!1)=>({attribute_name:e,describe:t,[Ku]:t}),"timestamp_attr_perms_template"),{READ:Ku,INSERT:_g,UPDATE:dg}=Ar.PERMS_CRUD_ENUM,MP=Object.values(Ar.PERMS_CRUD_ENUM),UP=[Ku,_g,dg];function g9(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[Ar.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=R9(e,r);return po[t]?po[t].key=n:po[t]=T9(n),po[t].perms=s,s}catch(r){if(!e[Ar.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Ar.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Ar.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 ug.error(n),ug.debug(r),NP(new Error,p9.OUTDATED_PERMS_TRANSLATION_ERROR,S9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
13
|
+
${r.stack}`;throw ug.error(n),NP(new Error)}}}a(g9,"getRolePermissions");function R9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Ar.SYSTEM_SCHEMA_NAME]=n[Ar.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]=A9(t[i]);return}r[i]=DP(),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],_=O9(c,u);r[i].describe||MP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=lg()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=lg()})}),r}a(R9,"translateRolePermissions");function A9(e){let t=DP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=lg(!0,!0,!0,!0,!0)}),t}a(A9,"createStructureUserPermissions");function O9(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 Ar.TIME_STAMP_NAMES.includes(d)&&(f=wP(d,l[Ku])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=IP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=PP(l),s.attribute_permissions.push(l),c||b9(l,u)}else if(_!==o){let l;Ar.TIME_STAMP_NAMES.includes(_)?l=wP(_):l=IP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=CP(s),s}else return e.describe=CP(e),e}a(O9,"getTableAttrPerms");function CP(e){return MP.filter(t=>e[t]).length>0}a(CP,"getSchemaTableDescribePerm");function PP(e){return UP.filter(t=>e[t]).length>0}a(PP,"getAttributeDescribePerm");function b9(e,t){UP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(b9,"checkForHashPerms")});var HP={};qe(HP,{Resources:()=>Rf,keyArrayToString:()=>ya,resetResources:()=>y9,resources:()=>Ai});function y9(){return Ai=new Rf}function ya(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Rf,Ai,Wu=ge(()=>{ro();Rf=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(y9,"resetResources");a(ya,"keyArrayToString")});var xP={};qe(xP,{Headers:()=>Oi,appendHeader:()=>fg});function fg(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 Oi,Qu=ge(()=>{Oi=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(fg,"appendHeader")});var zu={};qe(zu,{authentication:()=>KP,bypassAuth:()=>M9,login:()=>P9,logout:()=>v9,start:()=>U9});function M9(){YP=!0}async function KP(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?C9?w9:[]:I9?N9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Oi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Af&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Af&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Af){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let p=s.indexOf(";",h),S=s.indexOf("=",h);u=s.slice(S+1,p===-1?s.length:p),_=await qP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Na.AuthAuditLog(E,h,vt.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===vt.AUTH_AUDIT_STATUS.SUCCESS?GP.notify(S):GP.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,vt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,Na.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,h]=n.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await nt.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Of.validateOperationToken)(h)}catch(T){if(T.message==="invalid token")try{return await(0,Of.validateRefreshToken)(h),c({status:-1})}catch{throw T}}break}}catch(T){return L9&&(So.get(h)||(So.set(h,h),l(p,vt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:bi({error:T.message},e)})}So.set(n,d),D9&&l(d.username,vt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await nt.getUser(_.user,null,e):(YP&&(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)());Af&&(e.session.update=function(E){if(!u){u=(0,VP.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,qP.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")&&Ai.loginPath?(f.status=302,f.headers.set("Location",Ai.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 Oi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function U9({server:e,port:t}){e.request(KP,{port:t||"all"}),FP||(FP=!0,setInterval(()=>{So=new Map},dn.get(vt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),$P.user.addListener(()=>{So=new Map}))}async function P9(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 v9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var kP,Of,VP,dn,vt,Na,$P,GP,N9,I9,w9,C9,qP,Af,YP,D9,L9,So,FP,bf=ge(()=>{kP=B(an());or();Wu();Of=B(yu());Re();VP=require("uuid"),dn=B(ee()),vt=B(L()),Na=B($()),$P=B(Vc());Qu();Ia();GP=(0,Na.loggerWithTag)("auth-event");dn.initSync();N9=dn.get(vt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),I9=dn.get(vt.CONFIG_PARAMS.HTTP_CORS),w9=dn.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),C9=dn.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),qP=lt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Af=dn.get(vt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,YP=dn.get(vt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,D9=dn.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,L9=dn.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,So=new Map;nt.onInvalidatedUser(()=>{So=new Map});a(M9,"bypassAuth");a(KP,"authentication");a(U9,"start");a(P9,"login");a(v9,"logout")});var ZP=g((Jhe,XP)=>{"use strict";var we=require("joi"),WP=require("fs-extra"),QP=require("path"),Ps=je(),zP=ee(),JP=L(),jP=$(),{hdb_errors:B9}=ne(),{HDB_ERROR_MSGS:er}=B9,Us=/^[a-zA-Z0-9-_]+$/;XP.exports={getDropCustomFunctionValidator:x9,setCustomFunctionValidator:G9,addComponentValidator:V9,dropCustomFunctionProjectValidator:$9,packageComponentValidator:Y9,deployComponentValidator:K9,setComponentFileValidator:q9,getComponentFileValidator:k9,dropComponentFileValidator:F9};function yf(e,t,r){try{let n=zP.get(JP.CONFIG_PARAMS.COMPONENTSROOT),s=QP.join(n,t);return WP.existsSync(s)?e?t:r.message(er.PROJECT_EXISTS):e?r.message(er.NO_PROJECT):t}catch(n){return jP.error(n),r.message(er.VALIDATION_ERR)}}a(yf,"checkProjectExists");function Ju(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Ju,"checkFilePath");function H9(e,t,r,n){try{let s=zP.get(JP.CONFIG_PARAMS.COMPONENTSROOT),i=QP.join(s,e,t,r+".js");return WP.existsSync(i)?r:n.message(er.NO_FILE)}catch(s){return jP.error(s),n.message(er.VALIDATION_ERR)}}a(H9,"checkFileExists");function x9(e){let t=we.object({project:we.string().pattern(Us).custom(yf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().pattern(Us).custom(H9.bind(null,e.project,e.type)).custom(Ju).required().messages({"string.pattern.base":er.BAD_FILE_NAME})});return Ps.validateBySchema(e,t)}a(x9,"getDropCustomFunctionValidator");function G9(e){let t=we.object({project:we.string().pattern(Us).custom(yf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().custom(Ju).required(),function_content:we.string().required()});return Ps.validateBySchema(e,t)}a(G9,"setCustomFunctionValidator");function q9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:we.string().custom(Ju).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(q9,"setComponentFileValidator");function F9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:we.string().custom(Ju).optional()});return Ps.validateBySchema(e,t)}a(F9,"dropComponentFileValidator");function k9(e){let t=we.object({project:we.string().required(),file:we.string().custom(Ju).required(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a(k9,"getComponentFileValidator");function V9(e){let t=we.object({project:we.string().pattern(Us).custom(yf.bind(null,!1)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(V9,"addComponentValidator");function $9(e){let t=we.object({project:we.string().pattern(Us).custom(yf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a($9,"dropCustomFunctionProjectValidator");function Y9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),skip_node_modules:we.boolean()});return Ps.validateBySchema(e,t)}a(Y9,"packageComponentValidator");function K9(e){let t=we.object({project:we.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),payload:we.string().optional().messages({"string.pattern.base":er.BAD_PACKAGE}),package:we.string().optional()});return Ps.validateBySchema(e,t)}a(K9,"deployComponentValidator")});var Cf=g((Xhe,ov)=>{"use strict";var Nf=require("joi"),If=require("path"),ev=require("fs-extra"),{exec:W9}=require("child_process"),Q9=require("util"),tv=Q9.promisify(W9),ju=L(),{handleHDBError:wa,hdb_errors:z9}=ne(),{HTTP_STATUS_CODES:Ca}=z9,Xu=ee(),J9=je(),Da=$();Xu.initSync();var Eg=Xu.get(ju.CONFIG_PARAMS.COMPONENTSROOT),rv="npm install --omit=dev --json",j9=`${rv} --dry-run`;ov.exports={installModules:t7,auditModules:r7,installAllRootModules:X9,uninstallRootModule:Z9,linkHarperdb:e7};async function X9(e=!1){await wf(),await Zu(e?"npm install --ignore-scripts":"npm install",Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(X9,"installAllRootModules");async function Z9(e){await Zu(`npm uninstall ${e}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(Z9,"uninstallRootModule");async function e7(){await wf(),await Zu(`npm link ${ju.PACKAGE_ROOT}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(e7,"linkHarperdb");async function Zu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await tv(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
14
|
+
`,""))}return n&&!n.includes("Debugger listening")&&Da.error("Error running NPM command:",e,n),Da.trace(r,n),r?.replace(`
|
|
15
|
+
`,"")}a(Zu,"runCommand");async function t7(e){Da.info(`starting installModules for request: ${e}`);let t=iv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?j9:rv;await wf(),await sv(r);let i={};for(let o=0,c=r.length;o<c;o++){let u=r[o];i[u]={npm_output:null,npm_error:null};let _=If.join(Eg,u),l,d=null;try{let{stdout:f,stderr:E}=await tv(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&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(rv,"parseNPMStdErr");async function t7(e){Ca.info(`starting auditModules for request: ${e}`);let t=nv(e);if(t)throw Ia(t,t.message,wa.BAD_REQUEST);let{projects:r}=e;await If(),await sv(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=Nf.join(Eg,o);s[o]={npm_output:null,npm_error:null};try{let u=await ju("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=rv(u.stderr)}}return Ca.info(`finished auditModules with response ${s}`),s}a(t7,"auditModules");async function If(){try{return await ju("npm -v"),!0}catch{throw Ia(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",wa.BAD_REQUEST,void 0,void 0,!0)}}a(If,"checkNPMInstalled");async function sv(e){if(!Array.isArray(e)||e.length===0)throw Ia(new Error,"projects argument must be an array with at least 1 element",wa.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=Nf.join(Eg,i.toString());if(!await ZP.pathExists(o)){t.push(i);continue}let u=Nf.join(o,"package.json");await ZP.pathExists(u)||r.push(i)}if(t.length>0)throw Ia(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,wa.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ia(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,wa.BAD_REQUEST,void 0,void 0,!0)}a(sv,"checkProjectPaths");function nv(e){let t=yf.object({projects:yf.array().min(1).items(yf.string()).required(),dry_run:yf.boolean().default(!1)});return z9.validateBySchema(e,t)}a(nv,"modulesValidator")});var mg=g((Xhe,lv)=>{"use strict";var Da=require("fs-extra"),hg=require("path"),Cf=$(),ov=Q(),Df=L(),uv=ee(),r7=lr();lv.exports=s7;async function s7(){let e=n7(),t=uv.get(Df.CONFIG_PARAMS.ROOTPATH),r=hg.join(t,"package.json"),s={dependencies:{harperdb:"file:"+Df.PACKAGE_ROOT}},n=hg.join(t,"node_modules");await Da.ensureDir(n);let i,o=!0,c=!1;try{i=await Da.readJson(r)}catch(u){if(ov.isEmptyOrZeroLength(e))return;if(u.code!==Df.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!ov.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await av(_);s.dependencies[u]=l+_}if(!o){Cf.notify("Installing components"),await cv(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await av(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(Cf.notify("Removing component",u),c=!0);c&&(Cf.notify("Updating components."),await cv(r,s,i))}a(s7,"installComponents");function n7(){let e=r7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(n7,"getComponentsConfig");async function av(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":hg.extname(e)||await Da.pathExists(e)?"file:":"github:"}a(av,"getPkgPrefix");async function cv(e,t,r){Cf.trace("npm installing components package.json",t),await Da.writeFile(e,JSON.stringify(t,null," "));try{await wf().installAllRootModules(uv.get(Df.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(s){throw r?await Da.writeFile(e,JSON.stringify(r,null," ")):await Da.unlink(e),s}}a(cv,"installPackages")});var Tg=g((eme,Ev)=>{"use strict";var Ve=require("fs-extra"),pg=require("fast-glob"),Te=require("path"),dv=require("tar-fs"),Zhe=require("uuid").v4,Sg=require("normalize-path"),cn=jP(),Nt=$(),Qe=L(),Tt=ee(),Zu=lr(),i7=Q(),{PACKAGE_ROOT:o7}=L(),{handleHDBError:Bt,hdb_errors:a7}=se(),{basename:c7}=require("path"),u7=mg(),fv=ee(),l7=L(),{Readable:_7}=require("stream"),{isMainThread:d7}=require("worker_threads"),{HDB_ERROR_MSGS:go,HTTP_STATUS_CODES:Ht}=a7,f7=Te.join(o7,"application-template"),_v=Te.join(Tt.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function E7(){Nt.trace("getting custom api status");let e={};try{e={port:Tt.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Bt(new Error,go.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,t)}return e}a(E7,"customFunctionsStatus");function h7(){Nt.trace("getting custom api endpoints");let e={},t=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{pg.sync(Sg(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:pg.sync(Sg(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:pg.sync(Sg(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Bt(new Error,go.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,r)}return e}a(h7,"getCustomFunctions");function m7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cn.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("getting custom api endpoint file content");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e,o=Te.join(r,s,n,i+".js");try{return Ve.readFileSync(o,{encoding:"utf8"})}catch(c){throw Bt(new Error,go.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(m7,"getCustomFunction");function p7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cn.setCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("setting custom function file content");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i,function_content:o}=e;try{return Ve.outputFileSync(Te.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Bt(new Error,go.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(p7,"setCustomFunction");function S7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cn.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function file");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e;try{return Ve.unlinkSync(Te.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Bt(new Error,go.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,o)}}a(S7,"dropCustomFunction");function T7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cn.addComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("adding component");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;try{let n=Te.join(r,s);return Ve.mkdirSync(n,{recursive:!0}),Ve.copySync(f7,n),`Successfully added project: ${s}`}catch(n){throw Bt(new Error,go.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,n)}}a(T7,"addComponent");function g7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cn.dropCustomFunctionProjectValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function project");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=Tt.get(Qe.CONFIG_PARAMS.APPS);if(!i7.isEmptyOrZeroLength(n)){let i=!1;for(let[o,c]of n.entries())if(c.name===s){n.splice(o,1),i=!0;break}if(i)return Zu.updateConfigValue(Qe.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=Te.join(r,s);return Ve.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw Bt(new Error,go.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,i)}}a(g7,"dropCustomFunctionProject");async function R7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cn.packageComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;Nt.trace("packaging component",s);let n;try{n=await Ve.realpath(Te.join(r,s))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{n=await Ve.realpath(Te.join(Tt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await Ve.ensureDir(_v);let i=Te.join(_v,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(n,"node_modules"))}),dv.pack(n,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:s,payload:c}}a(R7,"packageComponent");async function A7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cn.deployComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,payload:n,package:i}=e;if(Nt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(n){o=Te.join(r,s),i="file:"+o,await Ve.ensureDir(o);let f=_7.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe(dv.extract(o,{finish:h})).on("error",p)});let E=await Ve.readdir(o);E.length===1&&E[0]==="package"&&(await Ve.copy(Te.join(o,"package"),o),await Ve.remove(Te.join(o,"package")))}if(await Zu.addConfig(s,{package:i}),!n){await u7();let f=fv.get(l7.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",s)}if(d7)return;let c=new Map;c.isWorker=!0;let u=(Mf(),ie(Lf)),_;u.setErrorReporter(f=>_=f);let l=c7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Nt.info("Installed component"),`Successfully deployed: ${s}`}a(A7,"deployComponent");async function O7(){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=Te.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:Te.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return Nt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),s=await r(Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of s.entries)if(o.package){let c=await r(Te.join(Tt.get(Qe.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 s}a(O7,"getComponents");async function b7(e){let t=cn.getComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let s=Zu.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(fv.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),n=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ve.stat(Te.join(s,e.project,e.file));return{message:await Ve.readFile(Te.join(s,e.project,e.file),n),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(b7,"getComponentFile");async function y7(e){let t=cn.setComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=Te.join(Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Ve.ensureFile(s),await Ve.outputFile(s,e.payload,r)):await Ve.ensureDir(s),"Successfully set component: "+e.file}a(y7,"setComponentFile");async function N7(e){let t=cn.dropComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,s=Te.join(Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ve.pathExists(s)&&await Ve.remove(s),Zu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(N7,"dropComponent");Ev.exports={customFunctionsStatus:E7,getCustomFunctions:h7,getCustomFunction:m7,setCustomFunction:p7,dropCustomFunction:S7,addComponent:T7,dropCustomFunctionProject:g7,packageComponent:R7,deployComponent:A7,getComponents:O7,getComponentFile:b7,setComponentFile:y7,dropComponent:N7}});var gg=g((rme,mv)=>{"use strict";var un=require("joi"),hv=Xe();mv.exports={readTransactionLogValidator:I7,deleteTransactionLogsBeforeValidator:w7};function I7(e){let t=un.object({schema:un.string().required(),table:un.string().required(),from:un.date().timestamp(),to:un.date().timestamp(),limit:un.number().min(1)});return hv.validateBySchema(e,t)}a(I7,"readTransactionLogValidator");function w7(e){let t=un.object({schema:un.string().required(),table:un.string().required(),timestamp:un.date().timestamp().required()});return hv.validateBySchema(e,t)}a(w7,"deleteTransactionLogsBeforeValidator")});var Pf=g((nme,Rv)=>{"use strict";var Rg=L(),Uf=it(),pv=Q(),Sv=ee(),Tv=Rn(),{handleHDBError:La,hdb_errors:C7}=se(),{HTTP_STATUS_CODES:Ma}=C7,{readTransactionLogValidator:D7,deleteTransactionLogsBeforeValidator:L7}=gg(),gv="This operation relies on clustering and cannot run with it disable.",M7="Logs successfully deleted from transaction log.",U7="All logs successfully deleted from transaction log.";Rv.exports={readTransactionLog:P7,deleteTransactionLogsBefore:v7};async function*P7(e){let t=D7(e);if(t)throw La(t,t.message,Ma.BAD_REQUEST,void 0,void 0,!0);if(!Sv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw La(new Error,gv,Ma.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=pv.checkSchemaTableExist(r,s);if(n)throw La(new Error,n,Ma.NOT_FOUND,void 0,void 0,!0);let i=Tv.createNatsTableStreamName(r,s),o=await Uf.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===Rg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(P7,"readTransactionLog");async function v7(e){let t=L7(e);if(t)throw La(t,t.message,Ma.BAD_REQUEST,void 0,void 0,!0);if(!Sv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw La(new Error,gv,Ma.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=pv.checkSchemaTableExist(r,s);if(i)throw La(new Error,i,Ma.NOT_FOUND,void 0,void 0,!0);let o=Tv.createNatsTableStreamName(r,s),{jsm:c}=await Uf.getNATSReferences(),u=await Uf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(n<=_)return`No transactions exist before: ${n}`;let l=M7,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=U7):d=(await Uf.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(v7,"deleteTransactionLogsBefore")});var Ov=g((ome,Av)=>{"use strict";var Ag=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};Av.exports=Ag});var yv=g((cme,bv)=>{"use strict";var Og=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};bv.exports=Og});var yg=g((lme,Iv)=>{"use strict";var Nv=Ov(),B7=yv(),{HDB_ERROR_MSGS:H7}=Cr(),bg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=H7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new Nv(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new B7(c,n[c]);i.push(u)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Nv(r,s,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};Iv.exports=bg});var xf=g((dme,Vv)=>{"use strict";var Ng=vr(),vf=Pr(),Es=Su(),rl=An(),Ig=ii(),x7=qS(),G7=wL(),sl=os(),Bf=zS(),It=$(),q7=jS(),F7=zd(),k7=DT(),V7=Xd(),$7=MT(),Y7=UT(),K7=BT(),W7=xT(),wg=FT(),vn=Q(),Q7=IU(),Cg=KT(),Dv=Tf(),ds=L(),Lv=vP(),z7=pa(),Mv=bu(),Uv=(Of(),ie(Qu)),Pv=lr(),Yr=Tg(),J7=require("alasql"),vv=Pf(),Bv=wf(),Hv=yg(),{handleHDBError:Or,hdb_errors:xv}=se(),{HDB_ERROR_MSGS:$t,HTTP_STATUS_CODES:el}=xv,V=new Map,Gv="delete",yi="insert",Bn="read",Ro="update",tl="describe",wv=rl.describeSchema.name,Cv=rl.describeTable.name,qv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},X7="catchup",j7="handleGetJob",Z7="handleGetJobsByStartDate",Hf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},eee=[Es.createTable.name,Es.createAttribute.name,Es.dropTable.name,Es.dropAttribute.name],Fv={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,[yi]));V.set(Ng.update.name,new W(!1,[Ro]));V.set(Ng.upsert.name,new W(!1,[yi,Ro]));V.set(vf.searchByConditions.name,new W(!1,[Bn]));V.set(vf.searchByHash.name,new W(!1,[Bn]));V.set(vf.searchByValue.name,new W(!1,[Bn]));V.set(vf.search.name,new W(!1,[Bn]));V.set(Es.createSchema.name,new W(!0,[]));V.set(Es.createTable.name,new W(!0,[]));V.set(Es.createAttribute.name,new W(!1,[yi]));V.set(Es.dropSchema.name,new W(!0,[]));V.set(Es.dropTable.name,new W(!0,[]));V.set(Es.dropAttribute.name,new W(!0,[]));V.set(rl.describeSchema.name,new W(!1,[Bn]));V.set(rl.describeTable.name,new W(!1,[Bn]));V.set(Ig.deleteRecord.name,new W(!1,[Gv]));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(Bf.listRoles.name,new W(!0,[]));V.set(Bf.addRole.name,new W(!0,[]));V.set(Bf.alterRole.name,new W(!0,[]));V.set(Bf.dropRole.name,new W(!0,[]));V.set(q7.name,new W(!0,[]));V.set(F7.name,new W(!0,[]));V.set(k7.name,new W(!0,[]));V.set(V7.name,new W(!0,[]));V.set($7.name,new W(!0,[]));V.set(Y7.name,new W(!0,[]));V.set(wg.setRoutes.name,new W(!0,[]));V.set(wg.getRoutes.name,new W(!0,[]));V.set(wg.deleteRoutes.name,new W(!0,[]));V.set(Pv.setConfiguration.name,new W(!0,[]));V.set(K7.clusterStatus.name,new W(!0,[]));V.set(W7.name,new W(!0,[]));V.set(Cg.getFingerprint.name,new W(!0,[]));V.set(Cg.setLicense.name,new W(!0,[]));V.set(Ig.deleteFilesBefore.name,new W(!0,[]));V.set(Ig.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Dv.restart.name,new W(!0,[]));V.set(Dv.restartService.name,new W(!0,[]));V.set(x7.name,new W(!0,[]));V.set(G7.name,new W(!0,[Bn]));V.set(z7.systemInformation.name,new W(!0,[]));V.set(Pv.getConfiguration.name,new W(!0,[]));V.set(vv.readTransactionLog.name,new W(!0,[]));V.set(vv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Bv.installModules.name,new W(!0,[]));V.set(Bv.auditModules.name,new W(!0,[]));V.set(Mv.createTokens.name,new W(!1,[]));V.set(Mv.refreshOperationToken.name,new W(!1,[]));V.set(Uv.login.name,new W(!1,[]));V.set(Uv.logout.name,new W(!1,[]));V.set(Yr.customFunctionsStatus.name,new W(!0,[]));V.set(Yr.getCustomFunctions.name,new W(!0,[]));V.set(Yr.getComponents.name,new W(!0,[]));V.set(Yr.getComponentFile.name,new W(!0,[]));V.set(Yr.setComponentFile.name,new W(!0,[]));V.set(Yr.dropComponent.name,new W(!0,[]));V.set(Yr.getCustomFunction.name,new W(!0,[]));V.set(Yr.setCustomFunction.name,new W(!0,[]));V.set(Yr.dropCustomFunction.name,new W(!0,[]));V.set(Yr.addComponent.name,new W(!0,[]));V.set(Yr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Yr.packageComponent.name,new W(!0,[]));V.set(Yr.deployComponent.name,new W(!0,[]));V.set(Cg.getRegistrationInfo.name,new W(!1,[]));V.set(sl.userInfo.name,new W(!1,[]));V.set(rl.describeAll.name,new W(!1,[]));V.set(j7,new W(!1,[]));V.set(Z7,new W(!0,[]));V.set(X7,new W(!0,[]));V.set(Hf.CSV_DATA_LOAD,new W(!1,[yi,Ro]));V.set(Hf.CSV_URL_LOAD,new W(!1,[yi,Ro]));V.set(Hf.CSV_FILE_LOAD,new W(!1,[yi,Ro]));V.set(Hf.IMPORT_FROM_S3,new W(!1,[yi,Ro]));V.set(Fv.EXPORT_TO_S3,new W(!0,[]));V.set(Fv.EXPORT_LOCAL,new W(!0,[]));V.set(ds.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Gv]));V.set(ds.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bn]));V.set(ds.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[yi]));V.set(ds.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ro]));Vv.exports={verifyPerms:ree,verifyPermsAst:tee,verifyBulkLoadAttributePerms:nee};function tee(e,t,r){if(vn.isEmptyOrZeroLength(e))throw It.info("verify_perms_ast has an empty user parameter"),Or(new Error);if(vn.isEmptyOrZeroLength(t))throw It.info("verify_perms_ast has an empty user parameter"),Or(new Error);if(vn.isEmptyOrZeroLength(r))throw It.info("verify_perms_ast has a null operation parameter"),Or(new Error);try{let s=new Hv,n=new Q7(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw It.info("No schemas defined in verifyPermsAst(), will not continue."),Or(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&qv[r])throw Or(new Error,$t.DROP_SYSTEM,el.FORBIDDEN);if(c&&!u)return null;let _=Lv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof J7.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=n.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=kv(t,r,o,s);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=n.getAttributesBySchemaTableName(f,d[E]),p=Lg(t.role.permission,f,d[E]);Dg(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw Or(s)}}a(tee,"verifyPermsAst");function ree(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw It.info("null required parameter in verifyPerms"),Or(new Error,$t.DEFAULT_INVALID_REQUEST,el.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema??e.database,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new Hv;if(vn.isEmptyOrZeroLength(e.hdb_user.role)||vn.isEmptyOrZeroLength(e.hdb_user.role.permission))return It.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem($t.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(ds.SYSTEM_SCHEMA_NAME)||n===ds.SYSTEM_SCHEMA_NAME;if(l&&qv[r])throw Or(new Error,$t.DROP_SYSTEM,el.FORBIDDEN);if(u&&!l||_===!0&&(r===Es.createSchema.name||r===Es.dropSchema.name))return null;if(eee.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=Lv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===wv||r===Cv){if(n===ds.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem($t.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===wv&&(!d[n]||!d[n][tl]))return c.handleInvalidItem($t.SCHEMA_NOT_FOUND(n));if(r===Cv&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][tl]))return c.handleInvalidItem($t.TABLE_NOT_FOUND(n,i))}}let f=kv(e.hdb_user,r,o,c,s);if(f)return f;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&ds.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[n].tables[i];S[ds.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(A=>A[ds.PERMS_CRUD_ENUM.READ]).forEach(A=>{p.push(A.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let E=see(e),h=Lg(e.hdb_user.role.permission,n,i);return Dg(E,h,r,i,n,c,s),c.getPermsResponse()}a(ree,"verifyPerms");function kv(e,t,r,s,n){if(vn.arrayHasEmptyValues([e,t,r]))throw It.info("hasPermissions has an invalid parameter"),Or(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 It.info(`operation ${t} not found.`),Or(new Error,$t.OP_NOT_FOUND(t),el.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return It.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem($t.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][tl]===!1){s.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[tl]===!1)s.addInvalidItem($t.TABLE_NOT_FOUND(u,l));else try{let f=[],E=V.get(t).perms;!vn.isEmpty(n)&&E.includes(n)&&(E=[n]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(It.info(`Required ${p} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&s.addUnauthorizedTable(u,l,f)}catch(f){let E=$t.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw It.error(E),It.error(f),Or(xv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(kv,"hasPermissions");function Dg(e,t,r,s,n,i,o){if(!e||!t)throw It.info("no attributes specified in checkAttributePerms."),Or(new Error);let c=V.get(r).perms;if(!c||c==="")throw It.info(`no permissions found for ${r} in checkAttributePerms().`),Or(new Error);if(vn.isEmptyOrZeroLength(t))return It.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[tl]===!1){i.addInvalidItem($t.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let f of c){if(ds.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Bn)throw Or(new Error,$t.SYSTEM_TIMESTAMP_PERMS_ERR,el.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem($t.ATTR_NOT_FOUND(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(Dg,"checkAttributePerms");function see(e){let t=new Set;try{if(e.action)return t;if(e.operation===ds.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){It.info(r)}return t}a(see,"getRecordAttributes");function Lg(e,t,r){let s=new Map;if(vn.isEmpty(e))return It.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{It.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(Lg,"getAttributePermissions");function nee(e,t,r,s,n,i,o){let c=new Set(i),u=Lg(e,s,n);Dg(c,u,t,n,s,o,r)}a(nee,"verifyBulkLoadAttributePerms")});var qf=g((Eme,Qv)=>{"use strict";Qv.exports={evaluateSQL:pee,processAST:Wv,convertSQLToAST:Kv,checkASTPermissions:Yv};var iee=vr(),$v=require("util"),oee=$v.callbackify(iee.insert),aee=Pr().search,cee=ED().update,uee=$v.callbackify(cee),lee=mD().convertDelete,Ni=require("alasql"),_ee=xf(),Gf=$(),dee=fd(),fee=Q(),nl=L(),{hdb_errors:Eee,handleHDBError:Mg}=se(),{HTTP_STATUS_CODES:Ug}=Eee;dee(Ni);var hee=403,mee="There was a problem performing this insert. Please check the logs and try again.",Pg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function pee(e,t){let r=e.parsed_sql_object;if(!r){r=Kv(e.sql);let s,n=r.ast.statements[0];if(n instanceof Ni.yy.Insert?s=n.into.databaseid:n instanceof Ni.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Ni.yy.Update||n instanceof Ni.yy.Delete?s=n.table.databaseid:Gf.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Ni.yy.Select)&&fee.isEmptyOrZeroLength(s))return t("No schema specified",null)}Wv(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(pee,"evaluateSQL");function Yv(e,t){let r;try{r=_ee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(Yv,"checkASTPermissions");function Kv(e){let t=new Pg;if(!e)throw Mg(new Error,"The 'sql' parameter is missing from the request body",Ug.BAD_REQUEST);try{let r=e.trim(),s=Ni.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
19
|
-
`);throw s[1]?Mg(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ug.BAD_REQUEST):Mg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ug.BAD_REQUEST)}return t}a(Kv,"convertSQLToAST");function Wv(e,t,r){try{let s=See;if(!e.bypass_auth&&!t.permissions_checked){let i=Yv(e,t);if(i&&i.length>0)return r(hee,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case nl.VALID_SQL_OPS_ENUM.SELECT:s=aee,n=t.ast.statements[0];break;case nl.VALID_SQL_OPS_ENUM.INSERT:s=Tee;break;case nl.VALID_SQL_OPS_ENUM.UPDATE:s=uee;break;case nl.VALID_SQL_OPS_ENUM.DELETE:s=lee;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(Wv,"processAST");function See(e,t){Gf.info(e),t("unknown sql statement")}a(See,"nullFunction");function Tee({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=gee(i,e.values)}catch(o){return r(o)}oee(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Gf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Tee,"convertInsert");function gee(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=Ni.compile(`SELECT ${n.toString()} AS [${nl.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw Gf.error(r),new Error(mee)}}a(gee,"createDataObjects")});var vg=g((mme,Jv)=>{"use strict";var{S3:Ree,GetObjectCommand:Aee}=require("@aws-sdk/client-s3");Jv.exports={getFileStreamFromS3:Oee,getS3AuthObj:zv};async function Oee(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 Aee(r))).Body}a(Oee,"getFileStreamFromS3");function zv(e,t,r){return new Ree({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(zv,"getS3AuthObj")});var Ff=g((Sme,i0)=>{"use strict";var Hg=Pr(),bee=qf(),yee=vg(),{AsyncParser:Nee,Transform:Iee}=require("json2csv"),ol=require("stream"),Kr=Q(),Bg=require("fs-extra"),wee=require("path"),hs=$(),{promisify:Zv}=require("util"),il=Q(),{handleHDBError:gt,hdb_errors:Cee}=se(),{HDB_ERROR_MSGS:br,HTTP_STATUS_CODES:Rt}=Cee,{streamAsJSON:Dee}=(em(),ie(Db)),{Upload:Lee}=require("@aws-sdk/lib-storage"),Xv=["search_by_value","search_by_hash","sql","search_by_conditions"],jv=["json","csv"],e0="json",t0="csv",Mee="Successfully exported JSON locally.",Uee="Successfully exported CSV locally.",Pee=1e3,vee=Hg.searchByHash,Bee=Hg.searchByValue,Hee=Zv(bee.evaluateSQL),xee=Zv(ol.finished);i0.exports={export_to_s3:kee,export_local:Gee,toCsvStream:r0};async function Gee(e){hs.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=s0(e);if(!Kr.isEmpty(t))throw hs.error(t),gt(new Error,t,Rt.BAD_REQUEST,void 0,void 0,!0);if(Kr.isEmpty(e.path))throw hs.error(br.MISSING_VALUE("path")),gt(new Error,br.MISSING_VALUE("path"),Rt.BAD_REQUEST,void 0,void 0,!0);let r=(Kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(wee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Kr.buildFolderPath(e.path,r);await qee(e.path);let n=await n0(e);return await Fee(s,e.format,n)}a(Gee,"export_local");async function qee(e){if(hs.trace("in confirmPath"),Kr.isEmptyOrZeroLength(e))throw gt(new Error,`Invalid path: ${e}`,Rt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Bg.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,hs.error(s),gt(new Error,s,Rt.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 hs.error(r),gt(new Error,r,Rt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(qee,"confirmPath");async function Fee(e,t,r){if(hs.trace("in saveToLocal"),il.isEmptyOrZeroLength(e))throw gt(new Error,br.INVALID_VALUE("file_path"),Rt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmptyOrZeroLength(t))throw gt(new Error,br.INVALID_VALUE("Source format"),Rt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmpty(r))throw gt(new Error,br.NOT_FOUND("Data"),Rt.BAD_REQUEST,void 0,void 0,!0);if(t===e0){let s=Bg.createWriteStream(e);return Dee(r).pipe(s),await xee(s),{message:Mee,path:e}}else if(t===t0){let s=Bg.createWriteStream(e),n=ol.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Nee(i,c).fromInput(n).toOutput(s).promise(!1),{message:Uee,path:e}}throw gt(new Error,br.INVALID_VALUE("format"),Rt.BAD_REQUEST)}a(Fee,"saveToLocal");async function kee(e){if(!e.s3||Object.keys(e.s3).length===0)throw gt(new Error,br.MISSING_VALUE("S3 object"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw gt(new Error,br.MISSING_VALUE("aws_access_key_id"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw gt(new Error,br.MISSING_VALUE("aws_secret_access_key"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.bucket))throw gt(new Error,br.MISSING_VALUE("bucket"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.key))throw gt(new Error,br.MISSING_VALUE("key"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.region))throw gt(new Error,br.MISSING_VALUE("region"),Rt.BAD_REQUEST);let t=s0(e);if(!Kr.isEmpty(t))throw gt(new Error,t,Rt.BAD_REQUEST);hs.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await n0(e)}catch(u){throw hs.error(u),u}let s,n=await yee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new ol.PassThrough;if(e.format===t0){i=e.s3.key+".csv";let u=r0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===e0){i=e.s3.key+".json";let u=new ol.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%Pee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw gt(new Error,br.INVALID_VALUE("format"),Rt.BAD_REQUEST);return new Lee({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(kee,"export_to_s3");function r0(e,t){let r=ol.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),s={};t&&(s.fields=t.map(o=>({label:o,value:o})));let n={objectMode:!0},i=new Iee(s,n);return r.pipe(i)}a(r0,"toCsvStream");function s0(e){if(hs.trace("in exportCoreValidation"),Kr.isEmpty(e.format))return"format missing";if(jv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${jv.join(", ")}`;let t=e.search_operation.operation;if(Kr.isEmpty(t))return"search_operation.operation missing";if(Xv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${Xv.join(", ")}`}a(s0,"exportCoreValidation");async function n0(e){hs.trace("in getRecords");let t,r;if(il.isEmpty(e.search_operation)||il.isEmptyOrZeroLength(e.search_operation.operation))throw gt(new Error,br.INVALID_VALUE("Search operation"),Rt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Bee;break;case"search_by_hash":t=vee;break;case"search_by_conditions":t=Hg.searchByConditions;break;case"sql":t=Hee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,hs.error(r),gt(new Error,r,Rt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(n0,"getRecords")});var f0={};qe(f0,{contentTypes:()=>kg,findBestSerializer:()=>Vf,getDeserializer:()=>Oo,registerContentHandlers:()=>Vg,serialize:()=>$f,serializeMessage:()=>bi});function Vee(e){try{return e?.[0]===123?Fg(e):e}catch{return e}}function Vg(e){e.register(Yee,{serializers:[{regex:/^application\/json$/,serializer:Ac},{regex:/^application\/cbor$/,serializer:function(t){return new Ao.EncoderStream(cl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?kf.Readable.from((0,ln.encodeIter)(t,cl)):(0,ln.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,ln.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,Ao.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function Vf(e){let r=(e.headers.asObject||e.headers).accept,s,n=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=xt.get(_);if(E){let h=(E.q||1)*d;h>n&&(s=E,i=E.type||_,n=h,o=f)}}if(!s){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(xt.keys()).join(", "))}};s=xt.get("application/json"),i="application/json"}return{serializer:s,type:i,parameters:o}}function $f(e,t,r){let s=a0&&t.headers.asObject?.["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),n=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=Vf(t);if(i.serializer.compressible===!1&&(s=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Hn.createBrotliCompress)({params:{[Hn.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hn.constants.BROTLI_MODE_TEXT:Hn.constants.BROTLI_MODE_GENERIC,[Hn.constants.BROTLI_PARAM_QUALITY]:2}}))),o}n=i.serializer.serialize(e,r)}return s&&n?.length>a0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hn.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function bi(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return al(e);let r=t.serialize;if(r)return r(e);let s=Vf(t);return r=t.serialize=s.serializer.serialize,r(e)}function Kee(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function Oo(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=xt.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=xt.get(e)?.deserialize||c0(e,s);return o=>Kee(o).then(i)}return e&&xt.get(e)?.deserialize||c0(e,s)}function c0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return s=>({contentType:e,data:s.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Fg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Wee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let s=r.next();return s.then?s.then(n=>({value:t(n.value),done:n.done})):{value:t(s.value),done:s.done}},return(s){return r.return(s)},throw(s){return r.throw(s)}}}}}var xg,ln,Ao,Hn,kf,u0,Gg,qg,l0,_0,al,Fg,cl,xt,kg,o0,d0,$ee,Yee,a0,Na=ge(()=>{em();xg=v(Ff()),ln=require("msgpackr"),Ao=require("cbor-x"),Hn=require("zlib"),kf=require("stream");or();u0=require("../index"),Gg=v(ee()),qg=v(L()),l0=v(require("yaml")),_0=Gg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,al=_0?Gi:JSON.stringify,Fg=_0?Zh:JSON.parse,cl={useRecords:!1,useToJSON:!0},xt=new Map,kg=xt;st.contentTypes=kg;(0,u0._assignPackageExport)("contentTypes",kg);xt.set("application/json",{serializeStream:Ac,serialize:al,deserialize:Fg,q:.8});o0=new Ao.Encoder(cl);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ao.EncoderStream(cl).end(e)},serialize:o0.encode,deserialize:o0.decode,q:1});xt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?kf.Readable.from((0,ln.encodeIter)(e,cl)):(0,ln.pack)(e)},serialize:ln.pack,deserialize:ln.unpack,q:.9});xt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(e,e?.getColumns?.())},q:.1});xt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});xt.set("text/yaml",{serialize(e){return l0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});xt.set("text/event-stream",{serializeStream:function(e){return kf.Readable.from(Wee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
20
|
-
`),e.data){let r=e.data;typeof r=="object"&&(r=
|
|
17
|
+
`,""):null}catch(f){f.stderr?i[u].npm_error=nv(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(t7,"installModules");function nv(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(nv,"parseNPMStdErr");async function r7(e){Da.info(`starting auditModules for request: ${e}`);let t=iv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r}=e;await wf(),await sv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=If.join(Eg,o);n[o]={npm_output:null,npm_error:null};try{let u=await Zu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=nv(u.stderr)}}return Da.info(`finished auditModules with response ${n}`),n}a(r7,"auditModules");async function wf(){try{return await Zu("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(wf,"checkNPMInstalled");async function sv(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=If.join(Eg,i.toString());if(!await ev.pathExists(o)){t.push(i);continue}let u=If.join(o,"package.json");await ev.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(sv,"checkProjectPaths");function iv(e){let t=Nf.object({projects:Nf.array().min(1).items(Nf.string()).required(),dry_run:Nf.boolean().default(!1)});return J9.validateBySchema(e,t)}a(iv,"modulesValidator")});var mg=g((eme,_v)=>{"use strict";var La=require("fs-extra"),hg=require("path"),Df=$(),av=Q(),Lf=L(),lv=ee(),n7=lr();_v.exports=s7;async function s7(){let e=i7(),t=lv.get(Lf.CONFIG_PARAMS.ROOTPATH),r=hg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Lf.PACKAGE_ROOT}},s=hg.join(t,"node_modules");await La.ensureDir(s);let i,o=!0,c=!1;try{i=await La.readJson(r)}catch(u){if(av.isEmptyOrZeroLength(e))return;if(u.code!==Lf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!av.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await cv(_);n.dependencies[u]=l+_}if(!o){Df.notify("Installing components"),await uv(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await cv(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Df.notify("Removing component",u),c=!0);c&&(Df.notify("Updating components."),await uv(r,n,i))}a(s7,"installComponents");function i7(){let e=n7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(i7,"getComponentsConfig");async function cv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":hg.extname(e)||await La.pathExists(e)?"file:":"github:"}a(cv,"getPkgPrefix");async function uv(e,t,r){Df.trace("npm installing components package.json",t),await La.writeFile(e,JSON.stringify(t,null," "));try{await Cf().installAllRootModules(lv.get(Lf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await La.writeFile(e,JSON.stringify(r,null," ")):await La.unlink(e),n}}a(uv,"installPackages")});var Tg=g((nme,hv)=>{"use strict";var Ve=require("fs-extra"),pg=require("fast-glob"),Te=require("path"),fv=require("tar-fs"),rme=require("uuid").v4,Sg=require("normalize-path"),as=ZP(),Nt=$(),Qe=L(),gt=ee(),el=lr(),o7=Q(),{PACKAGE_ROOT:a7}=L(),{handleHDBError:Bt,hdb_errors:c7}=ne(),{basename:u7}=require("path"),l7=mg(),Ev=ee(),_7=L(),{Readable:d7}=require("stream"),{isMainThread:f7}=require("worker_threads"),{HDB_ERROR_MSGS:To,HTTP_STATUS_CODES:Ht}=c7,E7=Te.join(a7,"application-template"),dv=Te.join(gt.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function h7(){Nt.trace("getting custom api status");let e={};try{e={port:gt.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Bt(new Error,To.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,t)}return e}a(h7,"customFunctionsStatus");function m7(){Nt.trace("getting custom api endpoints");let e={},t=gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{pg.sync(Sg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:pg.sync(Sg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:pg.sync(Sg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Bt(new Error,To.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,r)}return e}a(m7,"getCustomFunctions");function p7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("getting custom api endpoint file content");let r=gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return Ve.readFileSync(o,{encoding:"utf8"})}catch(c){throw Bt(new Error,To.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(p7,"getCustomFunction");function S7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.setCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("setting custom function file content");let r=gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Ve.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Bt(new Error,To.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(S7,"setCustomFunction");function T7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function file");let r=gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Ve.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Bt(new Error,To.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,o)}}a(T7,"dropCustomFunction");function g7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.addComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("adding component");let r=gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return Ve.mkdirSync(s,{recursive:!0}),Ve.copySync(E7,s),`Successfully added project: ${n}`}catch(s){throw Bt(new Error,To.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,s)}}a(g7,"addComponent");function R7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.dropCustomFunctionProjectValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function project");let r=gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=gt.get(Qe.CONFIG_PARAMS.APPS);if(!o7.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return el.updateConfigValue(Qe.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return Ve.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Bt(new Error,To.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,i)}}a(R7,"dropCustomFunctionProject");async function A7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.packageComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Nt.trace("packaging component",n);let s;try{s=await Ve.realpath(Te.join(r,n))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{s=await Ve.realpath(Te.join(gt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Ve.ensureDir(dv);let i=Te.join(dv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),fv.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(A7,"packageComponent");async function O7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.deployComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Nt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await Ve.ensureDir(o);let f=d7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{f.pipe(fv.extract(o,{finish:h})).on("error",p)});let E=await Ve.readdir(o);E.length===1&&E[0]==="package"&&(await Ve.copy(Te.join(o,"package"),o),await Ve.remove(Te.join(o,"package")))}if(await el.addConfig(n,{package:i}),!s){await l7();let f=Ev.get(_7.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",n)}if(f7)return;let c=new Map;c.isWorker=!0;let u=(Uf(),ie(Mf)),_;u.setErrorReporter(f=>_=f);let l=u7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Nt.info("Installed component"),`Successfully deployed: ${n}`}a(O7,"deployComponent");async function b7(){let e=el.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await Ve.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Te.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:Te.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return Nt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(gt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(Uf(),ie(Mf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(b7,"getComponents");async function y7(e){let t=as.getComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let n=el.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(Ev.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ve.stat(Te.join(n,e.project,e.file));return{message:await Ve.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(y7,"getComponentFile");async function N7(e){let t=as.setComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(gt.get(Qe.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(N7,"setComponentFile");async function I7(e){let t=as.dropComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(gt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ve.pathExists(n)&&await Ve.remove(n),el.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(I7,"dropComponent");hv.exports={customFunctionsStatus:h7,getCustomFunctions:m7,getCustomFunction:p7,setCustomFunction:S7,dropCustomFunction:T7,addComponent:g7,dropCustomFunctionProject:R7,packageComponent:A7,deployComponent:O7,getComponents:b7,getComponentFile:y7,setComponentFile:N7,dropComponent:I7}});var gg=g((ime,pv)=>{"use strict";var cs=require("joi"),mv=je();pv.exports={readTransactionLogValidator:w7,deleteTransactionLogsBeforeValidator:C7};function w7(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 mv.validateBySchema(e,t)}a(w7,"readTransactionLogValidator");function C7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),timestamp:cs.date().timestamp().required()});return mv.validateBySchema(e,t)}a(C7,"deleteTransactionLogsBeforeValidator")});var Pf=g((ame,Av)=>{"use strict";var Rg=L(),tl=it(),Sv=Q(),Tv=ee(),gv=Rs(),{handleHDBError:Ma,hdb_errors:D7}=ne(),{HTTP_STATUS_CODES:Ua}=D7,{readTransactionLogValidator:L7,deleteTransactionLogsBeforeValidator:M7}=gg(),Rv="This operation relies on clustering and cannot run with it disable.",U7="Logs successfully deleted from transaction log.",P7="All logs successfully deleted from transaction log.";Av.exports={readTransactionLog:v7,deleteTransactionLogsBefore:B7};async function*v7(e){let t=L7(e);if(t)throw Ma(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!Tv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,Rv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Sv.checkSchemaTableExist(r,n);if(s)throw Ma(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=gv.createNatsTableStreamName(r,n),o=await tl.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===Rg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(v7,"readTransactionLog");async function B7(e){let t=M7(e);if(t)throw Ma(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!Tv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,Rv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Sv.checkSchemaTableExist(r,n);if(i)throw Ma(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=gv.createNatsTableStreamName(r,n),{jsm:c}=await tl.getNATSReferences(),u=await tl.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=U7,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=P7):d=(await tl.viewStream(o,parseInt(s),1))[0].nats_sequence,await tl.purgeTableStream(r,n,{seq:d}),l}a(B7,"deleteTransactionLogsBefore")});var bv=g((ume,Ov)=>{"use strict";var Ag=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};Ov.exports=Ag});var Nv=g((_me,yv)=>{"use strict";var Og=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};yv.exports=Og});var yg=g((fme,wv)=>{"use strict";var Iv=bv(),H7=Nv(),{HDB_ERROR_MSGS:x7}=Cr(),bg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=x7.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 Iv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new H7(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 Iv(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}};wv.exports=bg});var xf=g((hme,$v)=>{"use strict";var Ng=vr(),vf=Pr(),En=Tu(),sl=As(),Ig=ii(),G7=qS(),q7=CL(),il=an(),Bf=zS(),It=$(),F7=XS(),k7=Jd(),V7=DT(),$7=Xd(),Y7=MT(),K7=UT(),W7=BT(),Q7=xT(),wg=FT(),vs=Q(),z7=wU(),Cg=KT(),Lv=gf(),fn=L(),Mv=BP(),J7=Sa(),Uv=yu(),Pv=(bf(),ie(zu)),vv=lr(),Yr=Tg(),j7=require("alasql"),Bv=Pf(),Hv=Cf(),xv=yg(),{handleHDBError:Or,hdb_errors:Gv}=ne(),{HDB_ERROR_MSGS:$t,HTTP_STATUS_CODES:rl}=Gv,V=new Map,qv="delete",yi="insert",Bs="read",go="update",nl="describe",Cv=sl.describeSchema.name,Dv=sl.describeTable.name,Fv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},X7="catchup",Z7="handleGetJob",eee="handleGetJobsByStartDate",Hf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},tee=[En.createTable.name,En.createAttribute.name,En.dropTable.name,En.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,[yi]));V.set(Ng.update.name,new W(!1,[go]));V.set(Ng.upsert.name,new W(!1,[yi,go]));V.set(vf.searchByConditions.name,new W(!1,[Bs]));V.set(vf.searchByHash.name,new W(!1,[Bs]));V.set(vf.searchByValue.name,new W(!1,[Bs]));V.set(vf.search.name,new W(!1,[Bs]));V.set(En.createSchema.name,new W(!0,[]));V.set(En.createTable.name,new W(!0,[]));V.set(En.createAttribute.name,new W(!1,[yi]));V.set(En.dropSchema.name,new W(!0,[]));V.set(En.dropTable.name,new W(!0,[]));V.set(En.dropAttribute.name,new W(!0,[]));V.set(sl.describeSchema.name,new W(!1,[Bs]));V.set(sl.describeTable.name,new W(!1,[Bs]));V.set(Ig.deleteRecord.name,new W(!1,[qv]));V.set(il.addUser.name,new W(!0,[]));V.set(il.alterUser.name,new W(!0,[]));V.set(il.dropUser.name,new W(!0,[]));V.set(il.listUsersExternal.name,new W(!0,[]));V.set(Bf.listRoles.name,new W(!0,[]));V.set(Bf.addRole.name,new W(!0,[]));V.set(Bf.alterRole.name,new W(!0,[]));V.set(Bf.dropRole.name,new W(!0,[]));V.set(F7.name,new W(!0,[]));V.set(k7.name,new W(!0,[]));V.set(V7.name,new W(!0,[]));V.set($7.name,new W(!0,[]));V.set(Y7.name,new W(!0,[]));V.set(K7.name,new W(!0,[]));V.set(wg.setRoutes.name,new W(!0,[]));V.set(wg.getRoutes.name,new W(!0,[]));V.set(wg.deleteRoutes.name,new W(!0,[]));V.set(vv.setConfiguration.name,new W(!0,[]));V.set(W7.clusterStatus.name,new W(!0,[]));V.set(Q7.name,new W(!0,[]));V.set(Cg.getFingerprint.name,new W(!0,[]));V.set(Cg.setLicense.name,new W(!0,[]));V.set(Ig.deleteFilesBefore.name,new W(!0,[]));V.set(Ig.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Lv.restart.name,new W(!0,[]));V.set(Lv.restartService.name,new W(!0,[]));V.set(G7.name,new W(!0,[]));V.set(q7.name,new W(!0,[Bs]));V.set(J7.systemInformation.name,new W(!0,[]));V.set(vv.getConfiguration.name,new W(!0,[]));V.set(Bv.readTransactionLog.name,new W(!0,[]));V.set(Bv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Hv.installModules.name,new W(!0,[]));V.set(Hv.auditModules.name,new W(!0,[]));V.set(Uv.createTokens.name,new W(!1,[]));V.set(Uv.refreshOperationToken.name,new W(!1,[]));V.set(Pv.login.name,new W(!1,[]));V.set(Pv.logout.name,new W(!1,[]));V.set(Yr.customFunctionsStatus.name,new W(!0,[]));V.set(Yr.getCustomFunctions.name,new W(!0,[]));V.set(Yr.getComponents.name,new W(!0,[]));V.set(Yr.getComponentFile.name,new W(!0,[]));V.set(Yr.setComponentFile.name,new W(!0,[]));V.set(Yr.dropComponent.name,new W(!0,[]));V.set(Yr.getCustomFunction.name,new W(!0,[]));V.set(Yr.setCustomFunction.name,new W(!0,[]));V.set(Yr.dropCustomFunction.name,new W(!0,[]));V.set(Yr.addComponent.name,new W(!0,[]));V.set(Yr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Yr.packageComponent.name,new W(!0,[]));V.set(Yr.deployComponent.name,new W(!0,[]));V.set(Cg.getRegistrationInfo.name,new W(!1,[]));V.set(il.userInfo.name,new W(!1,[]));V.set(sl.describeAll.name,new W(!1,[]));V.set(Z7,new W(!1,[]));V.set(eee,new W(!0,[]));V.set(X7,new W(!0,[]));V.set(Hf.CSV_DATA_LOAD,new W(!1,[yi,go]));V.set(Hf.CSV_URL_LOAD,new W(!1,[yi,go]));V.set(Hf.CSV_FILE_LOAD,new W(!1,[yi,go]));V.set(Hf.IMPORT_FROM_S3,new W(!1,[yi,go]));V.set(kv.EXPORT_TO_S3,new W(!0,[]));V.set(kv.EXPORT_LOCAL,new W(!0,[]));V.set(fn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[qv]));V.set(fn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bs]));V.set(fn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[yi]));V.set(fn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[go]));$v.exports={verifyPerms:nee,verifyPermsAst:ree,verifyBulkLoadAttributePerms:iee};function ree(e,t,r){if(vs.isEmptyOrZeroLength(e))throw It.info("verify_perms_ast has an empty user parameter"),Or(new Error);if(vs.isEmptyOrZeroLength(t))throw It.info("verify_perms_ast has an empty user parameter"),Or(new Error);if(vs.isEmptyOrZeroLength(r))throw It.info("verify_perms_ast has a null operation parameter"),Or(new Error);try{let n=new xv,s=new z7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw It.info("No schemas defined in verifyPermsAst(), will not continue."),Or(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Fv[r])throw Or(new Error,$t.DROP_SYSTEM,rl.FORBIDDEN);if(c&&!u)return null;let _=Mv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof j7.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=Vv(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=Lg(t.role.permission,f,d[E]);Dg(h,p,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw Or(n)}}a(ree,"verifyPermsAst");function nee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw It.info("null required parameter in verifyPerms"),Or(new Error,$t.DEFAULT_INVALID_REQUEST,rl.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new xv;if(vs.isEmptyOrZeroLength(e.hdb_user.role)||vs.isEmptyOrZeroLength(e.hdb_user.role.permission))return It.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem($t.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(fn.SYSTEM_SCHEMA_NAME)||s===fn.SYSTEM_SCHEMA_NAME;if(l&&Fv[r])throw Or(new Error,$t.DROP_SYSTEM,rl.FORBIDDEN);if(u&&!l||_===!0&&(r===En.createSchema.name||r===En.dropSchema.name))return null;if(tee.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=Mv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Cv||r===Dv){if(s===fn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem($t.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Cv&&(!d[s]||!d[s][nl]))return c.handleInvalidItem($t.SCHEMA_NOT_FOUND(s));if(r===Dv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][nl]))return c.handleInvalidItem($t.TABLE_NOT_FOUND(s,i))}}let f=Vv(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&&fn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[fn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(b=>b[fn.PERMS_CRUD_ENUM.READ]).forEach(b=>{p.push(b.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let E=see(e),h=Lg(e.hdb_user.role.permission,s,i);return Dg(E,h,r,i,s,c,n),c.getPermsResponse()}a(nee,"verifyPerms");function Vv(e,t,r,n,s){if(vs.arrayHasEmptyValues([e,t,r]))throw It.info("hasPermissions has an invalid parameter"),Or(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 It.info(`operation ${t} not found.`),Or(new Error,$t.OP_NOT_FOUND(t),rl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return It.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem($t.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][nl]===!1){n.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[nl]===!1)n.addInvalidItem($t.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)&&(It.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=$t.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw It.error(E),It.error(f),Or(Gv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Vv,"hasPermissions");function Dg(e,t,r,n,s,i,o){if(!e||!t)throw It.info("no attributes specified in checkAttributePerms."),Or(new Error);let c=V.get(r).perms;if(!c||c==="")throw It.info(`no permissions found for ${r} in checkAttributePerms().`),Or(new Error);if(vs.isEmptyOrZeroLength(t))return It.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[nl]===!1){i.addInvalidItem($t.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(fn.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Bs)throw Or(new Error,$t.SYSTEM_TIMESTAMP_PERMS_ERR,rl.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem($t.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Dg,"checkAttributePerms");function see(e){let t=new Set;try{if(e.action)return t;if(e.operation===fn.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){It.info(r)}return t}a(see,"getRecordAttributes");function Lg(e,t,r){let n=new Map;if(vs.isEmpty(e))return It.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{It.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Lg,"getAttributePermissions");function iee(e,t,r,n,s,i,o){let c=new Set(i),u=Lg(e,n,s);Dg(c,u,t,s,n,o,r)}a(iee,"verifyBulkLoadAttributePerms")});var qf=g((pme,zv)=>{"use strict";zv.exports={evaluateSQL:See,processAST:Qv,convertSQLToAST:Wv,checkASTPermissions:Kv};var oee=vr(),Yv=require("util"),aee=Yv.callbackify(oee.insert),cee=Pr().search,uee=hD().update,lee=Yv.callbackify(uee),_ee=pD().convertDelete,Ni=require("alasql"),dee=xf(),Gf=$(),fee=hd(),Eee=Q(),ol=L(),{hdb_errors:hee,handleHDBError:Mg}=ne(),{HTTP_STATUS_CODES:Ug}=hee;fee(Ni);var mee=403,pee="There was a problem performing this insert. Please check the logs and try again.",Pg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function See(e,t){let r=e.parsed_sql_object;if(!r){r=Wv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ni.yy.Insert?n=s.into.databaseid:s instanceof Ni.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ni.yy.Update||s instanceof Ni.yy.Delete?n=s.table.databaseid:Gf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ni.yy.Select)&&Eee.isEmptyOrZeroLength(n))return t("No schema specified",null)}Qv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(See,"evaluateSQL");function Kv(e,t){let r;try{r=dee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Kv,"checkASTPermissions");function Wv(e){let t=new Pg;if(!e)throw Mg(new Error,"The 'sql' parameter is missing from the request body",Ug.BAD_REQUEST);try{let r=e.trim(),n=Ni.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
19
|
+
`);throw n[1]?Mg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ug.BAD_REQUEST):Mg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ug.BAD_REQUEST)}return t}a(Wv,"convertSQLToAST");function Qv(e,t,r){try{let n=Tee;if(!e.bypass_auth&&!t.permissions_checked){let i=Kv(e,t);if(i&&i.length>0)return r(mee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ol.VALID_SQL_OPS_ENUM.SELECT:n=cee,s=t.ast.statements[0];break;case ol.VALID_SQL_OPS_ENUM.INSERT:n=gee;break;case ol.VALID_SQL_OPS_ENUM.UPDATE:n=lee;break;case ol.VALID_SQL_OPS_ENUM.DELETE:n=_ee;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(Qv,"processAST");function Tee(e,t){Gf.info(e),t("unknown sql statement")}a(Tee,"nullFunction");function gee({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=Ree(i,e.values)}catch(o){return r(o)}aee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Gf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(gee,"convertInsert");function Ree(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ni.compile(`SELECT ${s.toString()} AS [${ol.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Gf.error(r),new Error(pee)}}a(Ree,"createDataObjects")});var vg=g((Tme,jv)=>{"use strict";var{S3:Aee,GetObjectCommand:Oee}=require("@aws-sdk/client-s3");jv.exports={getFileStreamFromS3:bee,getS3AuthObj:Jv};async function bee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Jv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Oee(r))).Body}a(bee,"getFileStreamFromS3");function Jv(e,t,r){return new Aee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Jv,"getS3AuthObj")});var Ff=g((Rme,o0)=>{"use strict";var Hg=Pr(),yee=qf(),Nee=vg(),{AsyncParser:Iee,Transform:wee}=require("json2csv"),cl=require("stream"),Kr=Q(),Bg=require("fs-extra"),Cee=require("path"),hn=$(),{promisify:e0}=require("util"),al=Q(),{handleHDBError:Rt,hdb_errors:Dee}=ne(),{HDB_ERROR_MSGS:br,HTTP_STATUS_CODES:At}=Dee,{streamAsJSON:Lee}=(em(),ie(Db)),{Upload:Mee}=require("@aws-sdk/lib-storage"),Xv=["search_by_value","search_by_hash","sql","search_by_conditions"],Zv=["json","csv"],t0="json",r0="csv",Uee="Successfully exported JSON locally.",Pee="Successfully exported CSV locally.",vee=1e3,Bee=Hg.searchByHash,Hee=Hg.searchByValue,xee=e0(yee.evaluateSQL),Gee=e0(cl.finished);o0.exports={export_to_s3:Vee,export_local:qee,toCsvStream:n0};async function qee(e){hn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=s0(e);if(!Kr.isEmpty(t))throw hn.error(t),Rt(new Error,t,At.BAD_REQUEST,void 0,void 0,!0);if(Kr.isEmpty(e.path))throw hn.error(br.MISSING_VALUE("path")),Rt(new Error,br.MISSING_VALUE("path"),At.BAD_REQUEST,void 0,void 0,!0);let r=(Kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Cee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Kr.buildFolderPath(e.path,r);await Fee(e.path);let s=await i0(e);return await kee(n,e.format,s)}a(qee,"export_local");async function Fee(e){if(hn.trace("in confirmPath"),Kr.isEmptyOrZeroLength(e))throw Rt(new Error,`Invalid path: ${e}`,At.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Bg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,hn.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 hn.error(r),Rt(new Error,r,At.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Fee,"confirmPath");async function kee(e,t,r){if(hn.trace("in saveToLocal"),al.isEmptyOrZeroLength(e))throw Rt(new Error,br.INVALID_VALUE("file_path"),At.BAD_REQUEST,void 0,void 0,!0);if(al.isEmptyOrZeroLength(t))throw Rt(new Error,br.INVALID_VALUE("Source format"),At.BAD_REQUEST,void 0,void 0,!0);if(al.isEmpty(r))throw Rt(new Error,br.NOT_FOUND("Data"),At.BAD_REQUEST,void 0,void 0,!0);if(t===t0){let n=Bg.createWriteStream(e);return Lee(r).pipe(n),await Gee(n),{message:Uee,path:e}}else if(t===r0){let n=Bg.createWriteStream(e),s=cl.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Iee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Pee,path:e}}throw Rt(new Error,br.INVALID_VALUE("format"),At.BAD_REQUEST)}a(kee,"saveToLocal");async function Vee(e){if(!e.s3||Object.keys(e.s3).length===0)throw Rt(new Error,br.MISSING_VALUE("S3 object"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Rt(new Error,br.MISSING_VALUE("aws_access_key_id"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Rt(new Error,br.MISSING_VALUE("aws_secret_access_key"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.bucket))throw Rt(new Error,br.MISSING_VALUE("bucket"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.key))throw Rt(new Error,br.MISSING_VALUE("key"),At.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.region))throw Rt(new Error,br.MISSING_VALUE("region"),At.BAD_REQUEST);let t=s0(e);if(!Kr.isEmpty(t))throw Rt(new Error,t,At.BAD_REQUEST);hn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await i0(e)}catch(u){throw hn.error(u),u}let n,s=await Nee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new cl.PassThrough;if(e.format===r0){i=e.s3.key+".csv";let u=n0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===t0){i=e.s3.key+".json";let u=new cl.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%vee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Rt(new Error,br.INVALID_VALUE("format"),At.BAD_REQUEST);return new Mee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Vee,"export_to_s3");function n0(e,t){let r=cl.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new wee(n,s);return r.pipe(i)}a(n0,"toCsvStream");function s0(e){if(hn.trace("in exportCoreValidation"),Kr.isEmpty(e.format))return"format missing";if(Zv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${Zv.join(", ")}`;let t=e.search_operation.operation;if(Kr.isEmpty(t))return"search_operation.operation missing";if(Xv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${Xv.join(", ")}`}a(s0,"exportCoreValidation");async function i0(e){hn.trace("in getRecords");let t,r;if(al.isEmpty(e.search_operation)||al.isEmptyOrZeroLength(e.search_operation.operation))throw Rt(new Error,br.INVALID_VALUE("Search operation"),At.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Hee;break;case"search_by_hash":t=Bee;break;case"search_by_conditions":t=Hg.searchByConditions;break;case"sql":t=xee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,hn.error(r),Rt(new Error,r,At.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(i0,"getRecords")});var E0={};qe(E0,{contentTypes:()=>kg,findBestSerializer:()=>Vf,getDeserializer:()=>Ao,registerContentHandlers:()=>Vg,serialize:()=>$f,serializeMessage:()=>bi});function $ee(e){try{return e?.[0]===123?Fg(e):e}catch{return e}}function Vg(e){e.register(Kee,{serializers:[{regex:/^application\/json$/,serializer:Oc},{regex:/^application\/cbor$/,serializer:function(t){return new Ro.EncoderStream(ll).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,ll)):(0,us.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,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=xt.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(xt.keys()).join(", "))}};n=xt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function $f(e,t,r){let n=c0&&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>c0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function bi(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return ul(e);let r=t.serialize;if(r)return r(e);let n=Vf(t);return r=t.serialize=n.serializer.serialize,r(e)}function Wee(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=xt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=xt.get(e)?.deserialize||u0(e,n);return o=>Wee(o).then(i)}return e&&xt.get(e)?.deserialize||u0(e,n)}function u0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Fg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Qee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var xg,us,Ro,Hs,kf,l0,Gg,qg,_0,d0,ul,Fg,ll,xt,kg,a0,f0,Yee,Kee,c0,Ia=ge(()=>{em();xg=B(Ff()),us=require("msgpackr"),Ro=require("cbor-x"),Hs=require("zlib"),kf=require("stream");or();l0=require("../index"),Gg=B(ee()),qg=B(L()),_0=B(require("yaml")),d0=Gg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,ul=d0?xi:JSON.stringify,Fg=d0?Zh:JSON.parse,ll={useRecords:!1,useToJSON:!0},xt=new Map,kg=xt;nt.contentTypes=kg;(0,l0._assignPackageExport)("contentTypes",kg);xt.set("application/json",{serializeStream:Oc,serialize:ul,deserialize:Fg,q:.8});a0=new Ro.Encoder(ll);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ro.EncoderStream(ll).end(e)},serialize:a0.encode,deserialize:a0.decode,q:1});xt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?kf.Readable.from((0,us.encodeIter)(e,ll)):(0,us.pack)(e)},serialize:us.pack,deserialize:us.unpack,q:.9});xt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(e,e?.getColumns?.())},q:.1});xt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});xt.set("text/yaml",{serialize(e){return _0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});xt.set("text/event-stream",{serializeStream:function(e){return kf.Readable.from(Qee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
20
|
+
`),e.data){let r=e.data;typeof r=="object"&&(r=ul(r)),t+="data: "+r+`
|
|
21
21
|
`}return e.id&&(t+="id: "+e.id+`
|
|
22
22
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
23
23
|
`),t+`
|
|
24
|
-
`}else return typeof e=="object"?`data: ${
|
|
24
|
+
`}else return typeof e=="object"?`data: ${ul(e)}
|
|
25
25
|
|
|
26
26
|
`:`data: ${e}
|
|
27
27
|
|
|
28
|
-
`},compressible:!1,q:.8});xt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,s]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let n=t[r];Array.isArray(n)?n.push(s):t.key=[n,s]}else t[r]=s},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});d0={type:"application/json",serializeStream:Ac,serialize:al,deserialize:Vee,q:.8};xt.set("*/*",d0);xt.set("",d0);a(Vee,"tryJSONParse");a(Vg,"registerContentHandlers");$ee=require("fastify-plugin"),Yee=$ee(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Vf(s.raw);n.type(c),n.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{n.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Vf,"findBestSerializer");a0=Gg.default.get(qg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a($f,"serialize");a(bi,"serializeMessage");a(Kee,"streamToBuffer");a(Oo,"getDeserializer");a(c0,"deserializerUnknownType");a(Wee,"transformIterable")});function Kg(e,t,r,s,n,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?Kg(d.conditions,d.operator,r,s,n,i,o,c):va(d,s,d.descending||n.reverse===!0,r,n.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let A=h.operator==="or",R=l(h.conditions,!A,E);return A?(M,x)=>R.some(P=>P(M,x)):(M,x)=>R.every(P=>P(M,x))}let S=(h.attribute||h[0])===r.primaryKey,T=Qg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=rte(r.primaryStore,h.estimated_count,E)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function va(e,t,r,s,n,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let A=o[0],R=Gn(s.attributes,A);if(R.relationship){if(o.length<2)throw new Wr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let M=R.definition?.tableClass||R.elements?.definition?.tableClass,x=new Map,P=va({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,M,n,x);if(R.relationship.to){i[o[0]]=x;let k=!!Gn(M.attributes,R.relationship.to)?.elements;P=jee(P,R,M.primaryStore,k,x)}if(R.relationship.from){let k=a(B=>va({attribute:R.relationship.from,value:B},t,r,s,n,x),"searchEntry");R.elements?(i[o[0]]=x,P=Zee(P,R,M.primaryStore,x,k)):P=P.flatMap(k)}return P}else if(o.length===1)o=o[0];else throw new Wr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Wg[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]=_n.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 Wr.ClientError(`Unknown query comparator "${u}"`)}if(r){let A=_;_=l,l=A,A=!f,f=!d,d=A}let h=o===s.primaryKey||o==null,p=h?s.primaryStore:s.indices[o],S;if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(n===!1&&!p)throw new Wr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(n===!1&&E)throw new Wr.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 Wr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Wr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Qg(e),!S)throw new Wr.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:R,value:M}){return this.isSync?M&&S(M)?R:Ii.SKIP:new Promise((x,P)=>setImmediate(()=>{try{x(M&&S(M)?R:Ii.SKIP)}catch(k){P(k)}}))}:R=>R.value==null?Ii.SKIP:R);return A.hasEntries=!0,A}else return p?p.getRange(T).map(S?function({key:A,value:R}){return this.isSync?S({[o]:A})?R:Ii.SKIP:new Promise((M,x)=>setImmediate(()=>{try{M(S({[o]:A})?R:Ii.SKIP)}catch(P){x(P)}}))}:({value:A})=>A):s.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:A,value:R}){return this.isSync?R&&S(R)?A:Ii.SKIP:new Promise((M,x)=>setImmediate(()=>{try{M(R&&S(R)?A:Ii.SKIP)}catch(P){x(P)}}))})}function Gn(e,t){if(Array.isArray(t))if(t.length>1){let r=Gn(e,t[0]),s=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return s?Gn(s,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function jee(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i;n.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=Gs(l),o=!0);let E=n.get(f);E?E.push(d):n.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&&!n.filters?.some(E=>!E(d)))if(s)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}return i=(o?n:n.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function Zee(e,t,r,s,n){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 _=Gs(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;s.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Gs(d)));for(let l of e){if(s.filters){let d=r.get(l);if(s.filters.some(f=>!f(d)))continue}_.set(Gs(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=n(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Qg(e,t,r,s,n,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=Gn(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=s?.[l],h=Qg({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,R)=>{let M,x;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let k of h.idFilter.idSet)e={attribute:p.from,value:k};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let P=S(A);return S.idFilter&&(T.idFilter=S.idFilter),P}x=p(A,r,R),M=x?.value}else M=A[l];return M?Array.isArray(M)?M.some(h):h(M,x):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Wg[o]||o){case $g.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,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,_n.compareKeys)(l,u[0])>=0&&(0,_n.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,_n.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,_n.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,_n.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,_n.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,_n.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Wr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!n&&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 R=A[l],M;if(typeof R!="object"||!R||E?M=d(R):Array.isArray(R)?M=R.some(d):R instanceof Date&&(M=d(R.getTime())),f&&(S++,!M&&!T.idFilter&&++p/S*(i-S)>h)){let x=va(e,r.transaction.getReadTxn(),!1,t).map(Gs),P=new Set(x);T.idFilter=k=>P.has(Gs(k)),T.idFilter.idSet=P}return M}return a(T,"recordFilter"),n&&(T.idFilter=d),T}a(_,"attributeComparator")}function Kf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let n;if(r.operator==="or"){n=0;for(let i of r.conditions)t(i),n+=i.estimated_count}else{n=1/0;for(let i of r.conditions)t(i),n=isFinite(n)?n*i.estimated_count/xn(e.primaryStore):i.estimated_count}return r.estimated_count=n,r.estimated_count}let s=r.comparator||r.search_type;if(s=Wg[s]||s,s===$g.SEARCH_TYPES.EQUALS||!s){let n=r[0]??r.attribute;if(n==null||n===e.primaryKey)r.estimated_count=1;else if(Array.isArray(n)&&n.length>1){let i=Gn(e.attributes,n[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Kf(o)({value:r.value,attribute:n.length>2?n.slice(1):n[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*xn(e.indices[i.relationship.from])/(xn(o.primaryStore)||1):c)}else{let i=e.indices[n];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(s==="contains"||s==="ends_with"||s==="ne"){let n=r[0]??r.attribute,i=e.indices[n];r.value===null&&s==="ne"?r.estimated_count=xn(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else s==="starts_with"||s==="prefix"?r.estimated_count=Jee*xn(e.primaryStore)+1:s==="between"?r.estimated_count=zee*xn(e.primaryStore)+1:s==="sort"?r.estimated_count=xn(e.primaryStore)+1:r.estimated_count=Qee*xn(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,Ua.lastIndex=0,ete.test(e))try{let t=ul(new Pa,"");if(yr!==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 ${yr} in '${wi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function ul(e,t){let r=Ua,s,n,i,o,c,u=decodeURIComponent,_;for(;s=r.exec(wi);){yr=r.lastIndex;let[,l,d]=s;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(n){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=E0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");n=ll(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Xee[d],u=Yg[i]?E0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);n=ll(l);break;case"|":case"&":case"":case void 0:if(n==null){if(n===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:n,value:u(l)};i==="eq"&&h0(h,l),Yf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),n=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(ll(l)),n=void 0;break;case"(":Ua.lastIndex=yr;let E=ul(l?[]:new Pa,")");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=m0(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}wi[yr]===","?r.lastIndex=++yr:o=!0,n=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");Ua.lastIndex=yr,f=ul([],"}"),f.name=l,e.push(f),wi[yr]===","?r.lastIndex=++yr:o=!0;break;case"[":Ua.lastIndex=yr,l?(f=ul(new Pa,"]"),f.name=l):f=ul(e.conditions?new Pa:[],"]"),e.conditions?(Yf(e,_),e.conditions.push(f),n=null):e.push(f),wi[yr]===","?r.lastIndex=++yr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(n){let h={comparator:i||"equals",attribute:n,value:u(l)};i==="eq"&&h0(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(ll(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=n?tte:Ua,r.lastIndex=yr),yr===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 ll(e){return e.indexOf(".")>-1?e.split(".").map(ll):decodeURIComponent(e)}function E0(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new Wr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function h0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Wr.ClientError("wildcard can only be used at the end of a string")}function m0(e){let t=p0(e[0]);return e.length>1&&(t.next=m0(e.slice(1))),t}function p0(e){if(Array.isArray(e)){let t=p0(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 Gs(e){return Array.isArray(e)?e.join("\0"):e}function xn(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function rte(e,t,r){return t*r/xn(e)}var Wr,$g,_n,Ii,Qee,zee,Jee,Xee,Yg,Wg,ete,Ua,tte,yr,wi,Pa,Qf=ge(()=>{Wr=v(se()),$g=v(ut()),_n=require("ordered-binary"),Ii=require("lmdb"),Qee=.3,zee=.1,Jee=.05,Xee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Yg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Kg,"executeConditions");a(va,"searchByIndex");a(Gn,"findAttribute");a(jee,"joinTo");a(Zee,"joinFrom");Wg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Qg,"filterByType");a(Kf,"estimateCondition");ete=/[()[\]|!<>.]|(=\w*=)/,Ua=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,tte=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Wf,"parseQuery");a(ul,"parseBlock");a(Yf,"assignOperator");a(ll,"decodeProperty");a(E0,"typedDecoding");a(h0,"wildcardDecoding");a(m0,"toSortObject");a(p0,"toSortEntry");Pa=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}};a(Gs,"flattenKey");a(xn,"estimatedEntryCount");a(rte,"intersectionEstimate")});function A0(e){let t={openapi:ste,info:{title:"HarperDB HTTP REST interface",version:(0,R0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,s]of e){if(!s.path)continue;let{path:n}=s,i=n.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=s.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:M,elements:x,relationship:P,definition:k}of o){if(P)R==="array"?_[M]={type:"array",items:{$ref:Ci+x.type}}:_[M]={$ref:Ci+R};else{let B=k??x?.definition;if(B){if(!t.components.schemas[B.type]){let X={};B.properties.forEach(z=>{X[z.name]=new jg(zg[z.type],z.type)}),t.components.schemas[B.type]=new g0(X)}R==="array"?_[M]={type:"array",items:{$ref:Ci+B.type}}:_[M]={$ref:Ci+B.type}}else R==="array"?x.type==="Any"||x.type=="ID"?_[M]={type:"array",items:{format:x.type}}:_[M]={type:"array",items:new jg(zg[x.type],x.type)}:R==="Any"||R=="ID"?_[M]={format:R}:_[M]=new jg(zg[R],R)}l.push(new Zg(M,"query",_[M]))}let d=Object.keys(_),f=new Zg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Zg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new g0(_);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="/"+n+"/";h&&(t.paths[A]={},t.paths[A].post=new nte(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[A]||(t.paths[A]={}),t.paths[A].get=new Jg(l,r,{200:new Xg({$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 T0(l,r,"delete all the records that match the provided query",{204:new S0})),A="/"+n+"/{"+c+"}",S&&(t.paths[A]={},t.paths[A].get=new Jg([f],r,{200:new Xg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[A]||(t.paths[A]={}),t.paths[A].put=new ite([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 T0([f],r,"delete a record with the given primary key",{204:new S0})),S&&E.schema.enum.length>0&&(A="/"+n+"/{"+c+"}.{property}",t.paths[A]={},t.paths[A].get=new Jg([f,E],r,{200:new Xg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function nte(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ci+e}}}},this.security=t,this.responses={200:{description:eR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Jg(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.responses=r}function Xg(e){this.description=eR,this.content={"application/json":{schema:e}}}function S0(){this.description="successfully processed request, no content returned to client"}function ite(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ci+r}}}},this.responses={200:{description:eR}}}function T0(e,t,r,s){this.description=r,this.parameters=e,this.security=t,this.responses=s}function g0(e){this.type="object",this.properties=e}function jg(e,t){this.type=e,this.format=t}function Zg(e,t,r){this.name=e,this.in=t,this.schema=r}var R0,ste,zg,Ci,eR,O0=ge(()=>{R0=v(Vd()),ste="3.0.3",zg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ci="#/components/schemas/",eR="successful operation";a(A0,"generateJsonApi");a(nte,"Post");a(Jg,"Get");a(Xg,"Response200");a(S0,"Response204");a(ite,"Put");a(T0,"Delete");a(g0,"ResourceSchema");a(jg,"Type");a(Zg,"Parameter")});var Jf={};qe(Jf,{start:()=>cte});async function ate(e,t){let r=e.headers.asObject,s=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Wf(e);let n=new Oi;try{e.responseHeaders=n;let i=e.url.slice(1),o,c;if(i!==b0){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 je(e,()=>{if(s==="POST"||s==="PUT"||s==="PATCH"||s==="QUERY")try{e.data=Oo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new Ba.ClientError(h,400)}if(e.authorize=!0,i===b0&&s==="GET"){if(e?.user?.role?.permission?.super_user)return A0(zf);throw new Ba.ServerError("Forbidden",403)}switch(s){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":n.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 Ba.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ba.ServerError(`Method ${s} is not recognized`,501)}}),l=200,d;if(_==null)l=s==="GET"||s==="HEAD"?404:204,tR.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){ote[0]=d;let h=String.fromCharCode(34,(Yt[0]&63)+62,(Yt[0]>>6)+(Yt[1]<<2&63)+62,(Yt[1]>>4)+(Yt[2]<<4&63)+62,(Yt[2]>>2)+62,(Yt[3]&63)+62,(Yt[3]>>6)+(Yt[4]<<2&63)+62,(Yt[4]>>4)+(Yt[5]<<4&63)+62,(Yt[5]>>2)+62,(Yt[6]&63)+62,(Yt[6]>>6)+(Yt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):n.setIfNone("ETag",h),tR.lastModified&&n.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&n.setIfNone("Location",e.newLocation);let f={status:l,headers:n,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&n.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=$f(_,e,f),s==="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"),n.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:n,body:void 0};return o.body=$f(i.contentType?i:i.toString(),e,o),o}}function cte(e){tR=e,!y0&&(y0=!0,zf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return ate(t,r)}),e.server.ws(async(t,r,s)=>{_l++;let n=new ys;N0||(N0=!0,uu(l=>{_l>0&&l.push({metric:"ws-connections",connections:_l,byThread:!0})}));let i;t.on("error",l=>{i=!0,bo.warn(l)});let o;t.on("message",a(function(d){o||(o=Oo(r.headers.asObject["content-type"]));let f=o(d);n.push(f)},"message"));let c;t.on("close",()=>{_l--,as(!i,"connection","ws","disconnect"),n.emit("close"),c&&c.return()}),await s;let u=r.url.slice(1),_=zf.getMatch(u);if(as(!!_,"connection","ws","connect"),!_)t.send(bi(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,kr(h=>({count:h.count,total:_l}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await je(r,()=>d.connect(l,n,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=bi(E.value,r);t.send(h),kr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var bo,Ba,Yt,ote,tR,b0,y0,zf,N0,_l,I0=ge(()=>{Na();wn();bo=v($()),Ba=v(se());Qf();gc();so();Wu();O0();Yt=new Uint8Array(8),ote=new Float64Array(Yt.buffer,0,1),tR={},b0="openapi";a(ate,"http");_l=0;a(cte,"start")});var rR=g((Bme,w0)=>{var{recordAction:Xf,recordActionBinary:ute}=(wn(),ie(lu)),lte=require("fastify-plugin"),_te=200;w0.exports=lte(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n,i)=>{let o=n.getResponseTime(),c=performance.now(),u=n.request.routeOptions,_,l,d;u.config?.isOperation?(_=s.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Xf(o,"duration",_,d,l),ute(n.raw.statusCode<400,"success",_,d,l);let f=_te;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Xf(performance.now()-c,"transfer",_,d,l),Xf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Xf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);n.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var cR=g((Gme,M0)=>{var tE=require("clone"),rE=Xe(),dte=Q(),Zf=L(),Hme=$(),sR=require("fs"),iR=require("joi"),{string:eE}=iR.types(),{hdb_errors:fte,handleHDBError:jf}=se(),{HDB_ERROR_MSGS:xme,HTTP_STATUS_CODES:nR}=fte,{common_validators:Ha}=Js(),C0=" is required",Ete=["insert","update","upsert"],oR={database:{presence:!1,format:Ha.schema_format,length:Ha.schema_length},schema:{presence:!1,format:Ha.schema_format,length:Ha.schema_length},table:{presence:!0,format:Ha.schema_format,length:Ha.schema_length},action:{inclusion:{within:Ete,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},hte={schema:eE.required(),table:eE.required(),action:eE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:mte,AWS_SECRET:pte,AWS_BUCKET:Ste,AWS_FILE_KEY:Tte,REGION:gte}=Zf.S3_BUCKET_AUTH_KEYS,Rte={s3:{presence:!0},[`s3.${mte}`]:{presence:!0,type:"String"},[`s3.${pte}`]:{presence:!0,type:"String"},[`s3.${Ste}`]:{presence:!0,type:"String"},[`s3.${Tte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${gte}`]:{presence:!0,type:"String"}},D0=tE(oR);D0.data.presence={message:C0};var L0=tE(oR);L0.file_path.presence={message:C0};var Ate=Object.assign(tE(oR),Rte),aR=tE(hte);aR.csv_url=eE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();aR.passthrough_headers=iR.object();function Ote(e){let t=rE.validateObject(e,D0);return sE(e,t)}a(Ote,"dataObject");function bte(e){let t=rE.validateBySchema(e,iR.object(aR));return sE(e,t)}a(bte,"urlObject");function yte(e){let t=rE.validateObject(e,L0);return sE(e,t)}a(yte,"fileObject");function Nte(e){let t=rE.validateObject(e,Ate);return sE(e,t)}a(Nte,"s3FileObject");function sE(e,t){if(!t){let r=dte.checkGlobalSchemaTable(e.schema,e.table);if(r)return jf(new Error,r,nR.BAD_REQUEST);if(e.operation===Zf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{sR.accessSync(e.file_path,sR.constants.R_OK|sR.constants.F_OK)}catch(s){return s.code===Zf.NODE_ERROR_CODES.ENOENT?jf(s,`No such file or directory ${s.path}`,nR.BAD_REQUEST):s.code===Zf.NODE_ERROR_CODES.EACCES?jf(s,`Permission denied ${s.path}`,nR.BAD_REQUEST):jf(s)}}return t}a(sE,"postValidateChecks");M0.exports={dataObject:Ote,urlObject:bte,fileObject:yte,s3FileObject:Nte}});var uR=g((Fme,U0)=>{"use strict";var dl=$(),nE=L();async function Ite(e,t,r,s=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===nE.OPERATIONS_ENUM.INSERT||t.operation===nE.OPERATIONS_ENUM.UPDATE||t.operation===nE.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===nE.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(dl.info(i.message),i):i.http_resp_msg?(dl.error(`Error calling operation: ${e.name}`),dl.error(i.http_resp_msg),i):(dl.error(`Error calling operation: ${e.name}`),dl.error(i),i)}}a(Ite,"callOperationFunctionAsAwait");U0.exports={callOperationFunctionAsAwait:Ite}});var v0=g((Vme,P0)=>{"use strict";var lR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}},_R=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};P0.exports={BulkLoadFileObject:lR,BulkLoadDataObject:_R}});var H0=g((Yme,B0)=>{"use strict";var dR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};B0.exports=dR});var SR=g((Xme,eB)=>{"use strict";var iE=vr(),aE=cR(),wte=require("needle"),qs=L(),Wme=ke(),xa=Q(),{handleHDBError:ot,hdb_errors:K0}=se(),{HTTP_STATUS_CODES:Kt,HDB_ERROR_MSGS:wt,CHECK_LOGS_WRAPPER:No}=K0,Ga=$(),fR=require("papaparse");xa.promisifyPapaParse();var Fs=require("fs-extra"),Cte=require("path"),{chain:x0}=require("stream-chain"),G0=require("stream-json/streamers/StreamArray"),q0=require("stream-json/utils/Batch"),F0=require("stream-chain/utils/comp"),{finished:k0}=require("stream"),Dte=ee(),W0=uR(),Lte=vg(),{BulkLoadFileObject:hR,BulkLoadDataObject:Mte}=v0(),mR=yg(),{verifyBulkLoadAttributePerms:Q0}=xf(),Qme=H0(),zme=it(),Jme=Rn(),{databases:Ute}=(Re(),ie(Fe)),{coerceType:Pte}=(cE(),ie(TR)),V0="No records parsed from csv file.",yo=`${Dte.get("HDB_ROOT")}/tmp`,{schema_regex:vte}=Js(),$0=1024*1024*2,Y0=5e3,Bte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};eB.exports={csvDataLoad:Hte,csvURLLoad:xte,csvFileLoad:Gte,importFromS3:qte};async function Hte(e,t){let r=aE.dataObject(e);if(r)throw ot(r,r.message,Kt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=X0(e.schema,e.table),i=fR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:ER.bind(null,n),dynamicTyping:!1}),o=new mR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&Q0(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw ot(new Error,c,Kt.BAD_REQUEST,void 0,void 0,!0);let u=new Mte(e.action,e.schema,e.table,i.data);return s=await W0.callOperationFunctionAsAwait(j0,u,null),s.message===V0?V0:Z0(s.records,s.number_written)}catch(n){throw Io(n)}}a(Hte,"csvDataLoad");async function xte(e){let t=aE.urlObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${yo}/${r}`;try{await Fte(e,r)}catch(n){throw Ga.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+n),ot(n,No(wt.DOWNLOAD_FILE_ERR(r)))}try{let n=new hR(this.job_operation_function.name,e.action,e.schema,e.table,s,qs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await pR(n);return await oE(s),i}catch(n){throw await oE(s),Io(n)}}a(xte,"csvURLLoad");async function Gte(e){let t=aE.fileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=new hR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,qs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await pR(r)}catch(s){throw Io(s)}}a(Gte,"csvFileLoad");async function qte(e){let t=aE.s3FileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=Cte.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${yo}/${n}`;let i=new hR(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await kte(n,e);let o=await pR(i);return await oE(r),o}catch(s){throw await oE(r),Io(s)}}a(qte,"importFromS3");async function Fte(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await wte("get",e.csv_url,s)}catch(s){let n=`Error downloading CSV file from ${e.csv_url}, status code: ${s.statusCode}. Check the log for more information.`;throw ot(s,n,s.statusCode,qs.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}$te(r,e.csv_url),await Vte(t,r.raw)}a(Fte,"downloadCSVFile");async function kte(e,t){try{let r=`${yo}/${e}`;await Fs.mkdirp(yo),await Fs.writeFile(`${yo}/${e}`,"",{flag:"a+"});let s=await Fs.createWriteStream(r),n=await Lte.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){Ga.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ga.error(wt.S3_DOWNLOAD_ERR+" - "+r),ot(r,No(wt.S3_DOWNLOAD_ERR))}}a(kte,"downloadFileFromS3");async function Vte(e,t){try{await Fs.mkdirp(yo),await Fs.writeFile(`${yo}/${e}`,t)}catch(r){throw Ga.error(wt.WRITE_TEMP_FILE_ERR),ot(r,No(wt.DEFAULT_BULK_LOAD_ERR))}}a(Vte,"writeFileToTempFolder");async function oE(e){if(e)try{await Fs.access(e),await Fs.unlink(e)}catch{Ga.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(oE,"deleteTempFile");function $te(e,t){if(e.statusCode!==K0.HTTP_STATUS_CODES.OK)throw ot(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Kt.BAD_REQUEST);if(!Bte[e.headers["content-type"]])throw ot(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Kt.BAD_REQUEST);if(!e.raw)throw ot(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Kt.BAD_REQUEST)}a($te,"validateURLResponse");async function pR(e){try{let t;switch(e.file_type){case qs.VALID_S3_FILE_TYPES.CSV:t=await Yte(e);break;case qs.VALID_S3_FILE_TYPES.JSON:t=await Kte(e);break;default:throw ot(new Error,wt.DEFAULT_BULK_LOAD_ERR,Kt.BAD_REQUEST,qs.LOG_LEVELS.ERROR,wt.INVALID_FILE_EXT_ERR(e))}return Z0(t.records,t.number_written)}catch(t){throw Io(t)}}a(pR,"fileLoad");async function z0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await iE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&Q0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=ot(c);r(u)}}a(z0,"validateChunk");async function J0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;xa.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!xa.isEmpty(c)&&!xa.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 W0.callOperationFunctionAsAwait(j0,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=ot(c,No(wt.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(J0,"insertChunk");async function Yte(e){let t={records:0,number_written:0},r=X0(e.schema,e.table);try{let s=new mR,n=Fs.createReadStream(e.file_path,{highWaterMark:$0});n.setEncoding("utf8"),await fR.parsePromise(n,z0.bind(null,e,s),ER.bind(null,r));let i=s.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);return n=Fs.createReadStream(e.file_path,{highWaterMark:$0}),n.setEncoding("utf8"),await fR.parsePromise(n,J0.bind(null,e,t),ER.bind(null,r)),n.destroy(),t}catch(s){throw ot(s,No(wt.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+s)}}a(Yte,"callPapaParse");function X0(e,t){let r=Ute[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>Pte(i,n));return s}a(X0,"createTransformMap");function ER(e,t,r){let s=e.get(r);return s?s(t):xa.autoCast(t)}a(ER,"typeFunction");async function Kte(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new mR,n=x0([Fs.createReadStream(e.file_path,{encoding:"utf-8"}),G0.withParser(),c=>c.value,new q0({batchSize:Y0}),F0(async c=>{await z0(e,s,r,c)})]);await new Promise((c,u)=>{k0(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);let o=x0([Fs.createReadStream(e.file_path,{encoding:"utf-8"}),G0.withParser(),c=>c.value,new q0({batchSize:Y0}),F0(async c=>{await J0(e,t,r,c)})]);return await new Promise((c,u)=>{k0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw ot(s,No(wt.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+s)}}a(Kte,"insertJson");async function j0(e){let t={};try{e.data&&e.data.length>0&&Wte(e.data[0])?t=await Qte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ga.info(t.message))}catch(r){throw Io(r)}return t}a(j0,"callBulkFileLoad");function Wte(e){let t=Object.keys(e);for(let r of t)if(!vte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Wte,"validateColumnNames");async function Qte(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=iE.insert;break;case"update":i=iE.update;break;case"upsert":i=iE.upsert;break;default:throw ot(new Error,wt.INVALID_ACTION_PARAM_ERR(s),Kt.BAD_REQUEST,qs.LOG_LEVELS.ERROR,wt.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=xa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Io(o)}}a(Qte,"bulkFileLoad");function Z0(e,t){return`successfully loaded ${t} of ${e} records`}a(Z0,"buildResponseMsg");function Io(e){return ot(e,No(wt.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Io,"buildTopLevelErrMsg")});var rB=g((Zme,tB)=>{"use strict";var gR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};tB.exports=gR});var iB=g((tpe,nB)=>{"use strict";var zte=L(),sB=require("moment"),Jte=require("uuid").v4,RR=class{static{a(this,"JobObject")}constructor(){this.id=Jte(),this.type=void 0,this.start_datetime=sB().valueOf(),this.created_datetime=sB().valueOf(),this.end_datetime=void 0,this.status=zte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};nB.exports=RR});var AR=g((spe,_B)=>{"use strict";var Xte=require("uuid").v4,cB=vr(),uB=Pr(),jte=tn(),Zte=na(),ere=rB(),at=L(),tre=iB(),rre=Bd(),ms=$(),sre=Bc(),qa=Q(),{promisify:nre}=require("util"),wo=require("moment"),ire=qf(),uE=cR(),oB=Ym(),{deleteTransactionLogsBeforeValidator:ore}=gg(),{handleHDBError:are,hdb_errors:cre}=se(),{HTTP_STATUS_CODES:ure}=cre,aB=uB.searchByValue,lre=uB.searchByHash,_re=cB.insert,dre=nre(ire.evaluateSQL),fre=cB.update;_B.exports={addJob:mre,updateJob:Sre,handleGetJob:Ere,handleGetJobsByStartDate:hre,getJobById:lB};async function Ere(e){try{let t=await lB(e.id);return qa.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 ms.error("There was an error getting job",t),new Error(r)}}a(Ere,"handleGetJob");async function hre(e){try{let t=await pre(e);if(ms.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 ms.error(r),new Error(r)}}a(hre,"handleGetJobsByStartDate");async function mre(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||qa.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return ms.info(l),t.error=l,t}if(!at.JOB_TYPE_ENUM[e.operation])return ms.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case at.OPERATIONS_ENUM.CSV_FILE_LOAD:s=uE.fileObject(e);break;case at.OPERATIONS_ENUM.CSV_URL_LOAD:s=uE.urlObject(e);break;case at.OPERATIONS_ENUM.CSV_DATA_LOAD:s=uE.dataObject(e);break;case at.OPERATIONS_ENUM.IMPORT_FROM_S3:s=uE.s3FileObject(e);break;case at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=oB(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=oB(e,"timestamp");break;case at.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=ore(e);break;default:break}if(s)throw are(s,s.message,ure.BAD_REQUEST,void 0,void 0,!0);let n=new tre;n.type=e.operation===at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new jte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await aB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return ms.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=Xte();try{o=await aB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return ms.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return ms.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new sre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await _re(u)}catch(l){return ms.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,ms.trace(l)}return t}a(mre,"addJob");async function pre(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 s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new ere(s,e.hdb_user);try{return await dre(n)}catch(i){throw ms.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(pre,"getJobsInDateRange");async function lB(e){if(qa.isEmptyOrZeroLength(e))return qa.errorizeMessage("Invalid job ID specified.");let t=new Zte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await lre(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return ms.error(s),qa.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(lB,"getJobById");async function Sre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(qa.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 rre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await fre(t),r}a(Sre,"updateJob")});var pB=g((ipe,mB)=>{"use strict";var dB=Q(),Nr=L(),Tre=require("moment"),lE=SR(),_E=$(),fB=AR(),EB=Ff(),hB=ii(),gre=Ke(),Rre=Pf(),OR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Are(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(dB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(dB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Nr.JOB_TYPE_ENUM.csv_file_load:await qn(e,lE.csvFileLoad);break;case Nr.JOB_TYPE_ENUM.csv_url_load:await qn(e,lE.csvURLLoad);break;case Nr.JOB_TYPE_ENUM.csv_data_load:await qn(e,lE.csvDataLoad);break;case Nr.JOB_TYPE_ENUM.import_from_s3:await qn(e,lE.importFromS3);break;case Nr.JOB_TYPE_ENUM.empty_trash:break;case Nr.JOB_TYPE_ENUM.export_local:await qn(e,EB.export_local);break;case Nr.JOB_TYPE_ENUM.export_to_s3:await qn(e,EB.export_to_s3);break;case Nr.JOB_TYPE_ENUM.delete_files_before:case Nr.JOB_TYPE_ENUM.delete_records_before:await qn(e,hB.deleteFilesBefore);break;case Nr.JOB_TYPE_ENUM.delete_audit_logs_before:await qn(e,hB.deleteAuditLogsBefore);break;case Nr.JOB_TYPE_ENUM.delete_transaction_logs_before:await qn(e,Rre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Are,"parseMessage");async function qn(e,t){try{e.job.status=Nr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Tre().valueOf(),await fB.updateJob(e.job),await Ore(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):_E.error(`There was an error running ${t.name} job with id ${e.job.id}`),_E.error(s),e.job.message=s,e.job.status=Nr.JOB_STATUS_ENUM.ERROR;try{await fB.updateJob(e.job)}catch(n){throw _E.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(qn,"runJob");async function Ore(e){_E.trace("launching job thread:",e),gre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Ore,"launchJobThread");mB.exports={parseMessage:Are,RunnerMessage:OR}});var TB=g((ape,SB)=>{"use strict";var bR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};SB.exports=bR});var BB=g((upe,DR)=>{"use strict";var mE=Pr(),IR=qf(),dE=SR(),Fn=Su(),fE=An(),El=ii(),bre=qS(),fl=os(),EE=zS(),Wt=Tg(),hE=$(),yre=jS(),Nre=zd(),gB=DT(),Ire=Xd(),wre=MT(),Cre=UT(),Dre=BT(),Lre=xT(),yR=FT(),RB=Ff(),Mre=xf(),wR=AR(),q=L(),{hdb_errors:ml,handleHDBError:hl}=se(),{HTTP_STATUS_CODES:AB}=ml,NR=KT(),OB=Tf(),MB=require("util"),Fa=vr(),Ure=On(),Pre=pa(),bB=pB(),yB=bu(),NB=(Of(),ie(Qu)),IB=lr(),wB=Pf(),CB=wf(),{setServerUtilities:vre}=(cE(),ie(TR)),{CONTEXT:Bre}=(Ns(),ie(Gp)),{_assignPackageExport:Hre}=require("../index"),{transformReq:xre}=Q(),{server:Gre}=(or(),ie(xi)),tr=hE.loggerWithTag("operation"),qre=uR(),DB=mE.searchByHash,Fre=mE.searchByValue,kre=MB.promisify(mE.search),Vre=MB.promisify(IR.evaluateSQL),$re={[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=TB();async function UB(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:s,hdb_auth_header:n,password:i,...o}=e.body;tr.info(o)}}catch(s){tr.error(s)}let r=await qre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return $re[e.body.operation]&&Ure.setSchemaDataToGlobal(s=>{s&&tr.error(s)}),r}a(UB,"processLocalTransaction");var LB=Kre();DR.exports={chooseOperation:PB,getOperationFunction:vB,operation:CR,processLocalTransaction:UB};vre(DR.exports);Gre.operation=CR;function PB(e){let t;try{t=vB(e)}catch(n){throw tr.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=IR.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=IR.checkASTPermissions(e,i);if(o)throw tr.error(`${AB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),hl(new Error,o,ml.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Mre.verifyPerms(i,n);if(o)throw tr.error(`${AB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),hl(new Error,o,ml.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw hl(n,"There was an error when trying to choose an operation path")}return r}a(PB,"chooseOperation");function vB(e){if(tr.trace(`getOperationFunction with operation: ${e.operation}`),LB.has(e.operation))return LB.get(e.operation);throw hl(new Error,ml.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),ml.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(vB,"getOperationFunction");Hre("operation",CR);function CR(e,t){e.hdb_user=this[Bre]?.user,e.bypass_auth=!t;let r=PB(e);return UB({body:e},r)}a(CR,"operation");async function Yre(e){tr.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await Fa.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await Fa.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await Fa.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await El.deleteRecord(i);break;default:tr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){tr.info("Invalid operation in transaction"),tr.error(o)}}a(Yre,"catchup");async function dn(e){xre(e);let t,r;try{r=await wR.addJob(e),t=r.createdJob,tr.info("addJob result",r);let s=new bB.RunnerMessage(t,e);return await bB.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw tr.error(n),hl(s,n)}}a(dn,"executeJob");function Kre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y(Fa.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y(Fa.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y(Fa.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(mE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(DB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(DB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(Fre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(kre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(Vre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(dn,dE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(dn,dE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(dn,dE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(dn,dE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fn.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fn.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Fn.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fn.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(El.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(fl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(fl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(fl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(fl.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(fl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(yre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Nre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(gB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(gB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(Ire)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(wre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(Cre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(IB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Dre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Lre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(yR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(yR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(yR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(dn,RB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(dn,El.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(dn,El.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(dn,RB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(wR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(wR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(NR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(NR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(NR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(OB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(OB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(Yre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Pre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(dn,El.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(bre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(yB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(yB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(NB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(NB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(IB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Wt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Wt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Wt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Wt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Wt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Wt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Wt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Wt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Wt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Wt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Wt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Wt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Wt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Wt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Wt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Wt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(wB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(dn,wB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(CB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(CB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fn.getBackup)),e}a(Kre,"initializeOperationFunctionMap")});var SE=g((_pe,GB)=>{"use strict";var LR=L(),Wre=Q(),pl=$(),{handleHDBError:MR,hdb_errors:pE}=se(),{isMainThread:Qre}=require("worker_threads"),{Readable:zre}=require("stream"),HB=require("os"),Jre=require("util"),Xre=cT(),jre=Jre.promisify(Xre.authorize),xB=BB(),{createGzip:Zre,constants:ese}=require("zlib");function tse(e){let t=`Found an uncaught exception with message: ${e.message}. ${HB.EOL}Stack: ${e.stack} ${HB.EOL}Terminating ${Qre?"HDB":"thread"}.`;console.error(t),pl.fatal(t),process.exit(1)}a(tse,"handleServerUncaughtException");function rse(e,t,r){if(pl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:pE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(rse,"serverErrorHandler");function sse(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=MR(new Error,"Invalid JSON.",pE.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(Wre.isEmpty(e.body.operation)){let s=MR(new Error,"Request body must include an 'operation' property.",pE.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(sse,"reqBodyValidationHandler");function nse(e,t,r){let s;e.body.operation!==LR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==LR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==LR.OPERATIONS_ENUM.LOGOUT?jre(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{pl.warn(n),pl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(MR(n,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(nse,"authHandler");async function ise(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=xB.chooseOperation(e.body);let n=await xB.processLocalTransaction(e,s);if(n instanceof zre&&n.headers){for(let[i,o]of n.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),n=n.pipe(Zre({level:ese.Z_BEST_SPEED})))}return n}catch(n){throw pl.error(n),n}}a(ise,"handlePostRequest");GB.exports={authHandler:nse,handlePostRequest:ise,handleServerUncaughtException:tse,serverErrorHandler:rse,reqBodyValidationHandler:sse}});var VB=g((fpe,kB)=>{"use strict";var ose=require("fastify-plugin"),{handlePostRequest:qB,authHandler:ase,reqBodyValidationHandler:cse}=SE();async function use(e){e.decorate("hdbCore",{preValidation:[cse,ase],request:t=>FB(qB(t,response)),requestWithoutAuthentication:(t,r)=>FB(qB(t,r,!0))})}a(use,"hdbCore");async function FB(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(FB,"convertAsyncIterators");kB.exports=ose(use)});var KB=g((mpe,YB)=>{"use strict";var hpe=require("fs"),UR=ee();UR.initSync();var{CONFIG_PARAMS:$B}=L(),lse=1024*1024*1024;function _se(e){let t=UR.get($B.HTTP_TIMEOUT),r=UR.get($B.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:lse,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(_se,"getServerOptions");YB.exports=_se});var zB=g((Spe,QB)=>{"use strict";var PR=ee();PR.initSync();var{CONFIG_PARAMS:WB}=L();function dse(){let e=PR.get(WB.HTTP_CORSACCESSLIST),t=PR.get(WB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(dse,"getCORSOptions");QB.exports=dse});var jB=g((gpe,XB)=>{"use strict";var JB=ee();JB.initSync();var fse=L();function Ese(){return JB.get(fse.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Ese,"getHeaderTimeoutConfig");XB.exports=Ese});var BR={};qe(BR,{customFunctionsServer:()=>pse,ready:()=>fH,start:()=>mse});function mse(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){kn||(kn=dH(t),st.http((await kn).server));let o=await kn,c=(0,vR.dirname)(n),u=(0,vR.dirname)(s);if(u.startsWith("/")&&(u=u.slice(1)),!ZB.has(c)){ZB.add(c);try{o.register(Tse(c,u))}catch(_){if(_.message==="Root plugin has already booted")$e.warn(`Could not load root fastify route for ${n}, this may require a restart to install properly`);else throw _}}},ready:fH}}async function pse(){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 Sse();let e=iH.get(oH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=kn=await dH(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 Sse(){try{$e.info("Custom Functions starting configuration."),await aH.setUsersToGlobal(),$e.info("Custom Functions completed configuration.")}catch(e){$e.error(e)}}function Tse(e,t){return async function(r){try{$e.info("Custom Functions starting buildRoutes"),$e.trace("Loading fastify routes folder "+e),(0,eH.existsSync)(e)&&r.register(nH.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:$e.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?$e.error(n.message):n&&$e.error(n),o()})}catch(s){$e.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function dH(e){$e.info("Custom Functions starting buildServer.");let t=(0,cH.default)(e),r=(0,tH.default)(t);r.server.headersTimeout=(0,lH.default)(),r.setErrorHandler(_H.serverErrorHandler);let s=(0,uH.default)();return s&&r.register(rH.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(sH.default),await r.register(hse),await r.after(),Vg(r),$e.info("Custom Functions completed buildServer."),r}function fH(){if(kn)return kn.then?kn.then(e=>e.ready()):kn.ready()}var vR,eH,tH,rH,sH,nH,iH,oH,$e,hse,aH,cH,uH,lH,_H,kn,ZB,EH=ge(()=>{vR=require("path"),eH=require("fs"),tH=v(require("fastify")),rH=v(require("@fastify/cors")),sH=v(rR()),nH=v(require("@fastify/autoload")),iH=v(ee()),oH=v(L()),$e=v($()),hse=v(VB()),aH=v(os()),cH=v(KB()),uH=v(zB()),lH=v(jB()),_H=v(SE());Na();or();ZB=new Set;a(mse,"start");a(pse,"customFunctionsServer");a(Sse,"setUp");a(Tse,"buildRouteFolder");a(dH,"buildServer");a(fH,"ready")});var HR={};qe(HR,{start:()=>gse});function gse(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,TH.default)(r,e);return e.server.http(async(n,i)=>{if(!n.isWebSocket)return new Promise(o=>s(n._nodeRequest,n._nodeResponse,()=>{o(i(n))}))}),!0}},handleFile(t,r,s){mH||(mH=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=hH.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,pH.default)(n,(0,SH.realpathSync)(o))}}return i(n)},{runFirst:!0})),hH.set(r,s)}}}var pH,SH,TH,hH,mH,gH=ge(()=>{pH=v(require("send")),SH=require("fs"),TH=v(require("serve-static")),hH=new Map;a(gse,"start")});function Ose(e,t=1,r){if(xR++,(0,Co.startWorker)("server/threads/threadServer.js",{name:RE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(_){_.type===RE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});Ase.push(n),await n,ka.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=gE.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=ka.indexOf(s);o>-1&&ka.splice(o,1)}if(a(i,"removeWorker"),Va){let o=Va;Va=[];for(let c of o)bH[c.localPort](null,c)}}}),r){let s=setInterval(()=>{GR?GR=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Co.shutdownWorkers)(),xR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function yH(e=0,t){if(typeof e=="string")try{(0,AE.existsSync)(e)&&(0,AE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=bse:r=yse(t):r=FR;let s=(0,$a.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=bH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),GR=!0,r(o,(c,u)=>{if(!c){if(RH){let l=o._socket||new $a.Socket({handle:o,writable:!0,readable:!0});RH.deliverSocket(l,e,u),l.resume()}else xR>0?(Va.length===0&&setTimeout(()=>{Va.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,Va.push(o)):(console.log("start up a dynamic thread to handle request"),Ose(0));kr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new $a.Socket({handle:o,writable:!0,readable:!0});Cse(l,c,e)}kr(!0,"socket-routed")})};let n=iu();qR.info(`HarperDB ${n.version} Server running on port ${e}`)}return s.on("error",n=>{console.error("Error in socket server",n)}),process.env._UNREF_SERVER&&s.unref(),s}function FR(e,t){let r,s=0;for(let n of ka){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=TE)return TE=i,t(r);s=i}TE=0,t(r)}function bse(e,t){let r={};e.getpeername(r);let s=r.address,n=Ya.get(s),i=Date.now();if(n&&n.worker.threadId!==-1)return n.lastUsed=i,t(n.worker);FR(e,o=>{Ya.set(s,{worker:o,lastUsed:i}),t(o)})}function yse(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){let i=new $a.Socket({handle:s,readable:!0,writable:!0});s._socket=i,i.on("data",o=>{s.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ya.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,n(_.worker);FR(s,d=>{Ya.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function Ise(){TE=0;for(let e of ka)e.expectedIdle=e.recentELU.idle+Nse,e.requests=1;ka.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Cse(e,t,r){let s=wse++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),gE.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),gE.delete(s)),n.event=="destroy"&&(e.destroy(),gE.delete(s))})}var Co,$a,RE,qR,AE,OH,Rse,ka,Va,bH,RH,xR,Ase,GR,TE,AH,Ya,Nse,gE,wse,NH=ge(()=>{Co=v(Ke()),$a=require("net"),RE=v(L()),qR=v($()),AE=require("fs");wn();OH=require("worker_threads"),Rse=v(Xi()),ka=[],Va=[],bH=[],xR=0,Ase=[];OH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Ose,"startHTTPWorker");a(yH,"startSocketServer");TE=0;a(FR,"findMostIdleWorker");AH=36e5,Ya=new Map;a(bse,"findByRemoteAddressAffinity");a(yse,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ya)r.lastUsed+AH<e&&Ya.delete(t)},AH).unref();Nse=1e3;a(Ise,"updateWorkerIdleness");(0,Co.setMonitorListener)(Ise);gE=new Map,wse=1;a(Cse,"proxySocket")});var YR={};qe(YR,{Request:()=>kR,createReuseportFd:()=>OE});var IH,kR,VR,$R,OE,bE=ge(()=>{IH=require("os"),kR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let s=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=s,this.headers=new $R(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new VR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},VR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},$R=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,s]of this)t(s,r,this)}};(0,IH.platform)()!="win32"&&(OE=require("node-unix-socket").createReuseportFd)});var LH=g((vpe,DH)=>{"use strict";var Dse=require("cluster"),Do=ee();Do.initSync();var CH=L(),Dpe=require("util"),Vn=$(),Lpe=require("fs"),Lse=require("fastify"),Mpe=iu(),Mse=require("@fastify/cors"),Use=require("@fastify/compress"),Pse=require("@fastify/static"),vse=rR(),Bse=require("path"),{PACKAGE_ROOT:Hse}=L(),xse=On(),Gse=Q(),qse=os(),Fse=Xi(),{server:kse}=(or(),ie(xi)),{node_request_key:Upe}=(bE(),ie(YR)),{authHandler:Vse,handlePostRequest:$se,serverErrorHandler:Yse,reqBodyValidationHandler:Kse}=SE(),Ppe=require("net"),{registerContentHandlers:Wse}=(Na(),ie(f0)),Qse=6e4,zse=1024*1024*1024,Jse="TRUE",{CONFIG_PARAMS:Sl}=CH,Ka;DH.exports={hdbServer:wH,start:wH};async function wH(e){try{Vn.info("In Fastify server"+process.cwd()),Vn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Dse.isMaster,await Xse();let t=e.securePort>0;Ka=jse(t),await Ka.ready(),e||(e={}),e.isOperationsServer=!0;try{kse.http(Ka.server,e),Ka.server.closeIdleConnections||await Ka.listen({port:0,host:"::"})}catch(r){throw Ka.close(),Vn.error(r),Vn.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vn.fatal(t),process.exit(1)}}a(wH,"operationsServer");async function Xse(){Vn.trace("Configuring HarperDB process."),xse.setSchemaDataToGlobal(),await qse.setUsersToGlobal(),await Fse.getLicense()}a(Xse,"setUp");function jse(e){Vn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Zse(e),r=Lse(t);r.server.headersTimeout=tne(),r.setErrorHandler(Yse);let s=ene();s&&r.register(Mse,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(vse),r.register(Use),r.register(Pse,{root:Bse.join(Hse,"studio/build-local")}),Wse(r);let n=Do.get(CH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Gse.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Kse,Vse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),$se(i,o)}),r.get("/health",()=>"HarperDB is running."),Vn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(jse,"buildServer");function Zse(e){let t=Do.get(Sl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(Sl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:zse,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Zse,"getServerOptions");function ene(){let e=Do.get(Sl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(Sl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Jse)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(ene,"getCORSOpts");function tne(){return Do.get(Sl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Qse}a(tne,"getHeaderTimeoutConfig")});var XR={};qe(XR,{disableNATS:()=>sne,publishToStream:()=>IE,setNATSReplicator:()=>KR,setPublishToStream:()=>nne,setSubscription:()=>JR,start:()=>rne});function rne(){Tl.default.get(gl.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&one()}function sne(e=!0){BH=e}function nne(e,t){IE=e,JR=t}function one(){if(BH||process.env._DISABLE_NATS)return;let e=dr(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];KR(n,r,i)}}jR((r,s)=>{KR(r.tableName,r.databaseName,r),s&&xH(r)}),!MH&&(MH=!0)}function KR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(n=>n?.isNATSReplicator))return;r.sourcedFrom(class extends Ft{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Me],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Me]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Me],record:i})}patch(i){return s(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Me],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Me]})}static defineSchema(i){xH(i)}static subscribe(){let i=new ys;return JR(t,e,i),i}static subscribeOnThisThread(i){return i<(Tl.default.get(gl.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??ine)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function s(n){let i=n?.transaction?.nats;if(!i)if(n?.transaction){n.transaction.nats=i=new yE(n.transaction,n);let o=n.transaction;for(;o.next;)o=o.next;o.next=n.transaction.nats,i.user=n.user,i.context=n}else i=HH;return i}a(s,"getNATSTransaction")}function xH(e){let t=Tl.default.get(gl.default.CONFIG_PARAMS.CLUSTERING_NODENAME);IE(`${QR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,zR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var UH,QR,zR,PH,vH,Tl,gl,NE,BH,IE,JR,ine,HH,MH,yE,WR,GH=ge(()=>{Re();Ns();UH=v(it()),QR=v(ke()),zR=v(Rn());gc();PH=v(wS()),vH=v(Dr()),Tl=v(ee()),gl=v(L()),NE=v($());a(rne,"start");a(sne,"disableNATS");IE=UH.publishToStream,JR=PH.setSubscription;a(nne,"setPublishToStream");ine=2;a(one,"assignReplicationSource");a(KR,"setNATSReplicator");a(xH,"publishSchema");yE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let s=this.writes_by_db.get(t);s||this.writes_by_db.set(t,s=[]),s.push(r)}commit({timestamp:t}){let r=Tl.default.get(gl.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(NE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&s.push(IE(`${QR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,zR.createNatsTableStreamName)(n,u.table),void 0,u)?.catch(l=>{throw NE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(s)}},WR=class extends yE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,vH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};HH=new WR});var ex=g(Lo=>{"use strict";var{isMainThread:YH,parentPort:Al,threadId:wE}=require("worker_threads"),{Socket:ane,createServer:cne}=require("net"),{createServer:une,IncomingMessage:lne}=require("http"),{createServer:_ne}=require("https"),{readFileSync:Wa,unlinkSync:qH,existsSync:dne}=require("fs"),rr=$(),we=ee(),Et=L(),{server:ME}=(or(),ie(xi)),{WebSocketServer:fne}=require("ws"),{createServer:Ene}=require("tls"),{getTicketKeys:hne,restartNumber:mne,getWorkerIndex:DE}=Ke(),{Headers:KH,appendHeader:pne}=(Wu(),ie(HP)),{recordAction:Rl,recordActionBinary:Sne}=(wn(),ie(lu)),{Request:WH,createReuseportFd:FH}=(bE(),ie(YR)),{checkMemoryLimit:Tne}=Xi(),QH=require("tls"),kH=QH.createSecureContext;QH.createSecureContext=function(e){if(!e.cert||!e.key)return kH(e);let t={...e};delete t.key,delete t.cert;let r=kH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var zH=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG);if(zH){let e;if(YH)e=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){rr.info("Could not close debugger",t)}});else{let t=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&DE()>=0&&(e=t+DE())}if(e){let t=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(s){rr.trace(`Could not start debugging on port ${e}, you may already be debugging:`,s.message)}}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){mne<=1&&rr.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:kpe,CONFIG_PARAMS:gne}=Et;we.initSync();var Rne=we.get(gne.HTTP_SESSIONAFFINITY),fn={};Lo.registerServer=sA;Lo.httpServer=nA;Lo.deliverSocket=rA;Lo.startServers=JH;Lo.when_components_loaded=null;ME.http=nA;ME.request=yne;ME.socket=Nne;ME.ws=Ine;var ZR={},CE={},Ane,Di={},LE={},One=[],eA=[];function JH(){return Lo.when_components_loaded=iA().loadRootComponents(!0).then(()=>{Al?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)rA(s,r,n);else if(t.requestId)bne(t);else if(t.type===Et.ITC_EVENT_TYPES.SHUTDOWN){rr.trace("received shutdown request",wE);for(let i in fn){let o=fn[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?rr.info(`Closing ${E.length} idle connections`):f&&rr.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});xt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});f0={type:"application/json",serializeStream:Oc,serialize:ul,deserialize:$ee,q:.8};xt.set("*/*",f0);xt.set("",f0);a($ee,"tryJSONParse");a(Vg,"registerContentHandlers");Yee=require("fastify-plugin"),Kee=Yee(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");c0=Gg.default.get(qg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a($f,"serialize");a(bi,"serializeMessage");a(Wee,"streamToBuffer");a(Ao,"getDeserializer");a(u0,"deserializerUnknownType");a(Qee,"transformIterable")});function Kg(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?Kg(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 b=h.operator==="or",R=l(h.conditions,!b,E);return b?(M,v)=>R.some(P=>P(M,v)):(M,v)=>R.every(P=>P(M,v))}let S=(h.attribute||h[0])===r.primaryKey,T=Qg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=nte(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 b=o[0],R=Gs(n.attributes,b);if(R.relationship){if(o.length<2)throw new Wr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let M=R.definition?.tableClass||R.elements?.definition?.tableClass,v=new Map,P=Ba({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,M,s,v);if(R.relationship.to){i[o[0]]=v;let k=!!Gs(M.attributes,R.relationship.to)?.elements;P=Zee(P,R,M.primaryStore,k,v)}if(R.relationship.from){let k=a(H=>Ba({attribute:R.relationship.from,value:H},t,r,n,s,v),"searchEntry");R.elements?(i[o[0]]=v,P=ete(P,R,M.primaryStore,v,k)):P=P.flatMap(k)}return P}else if(o.length===1)o=o[0];else throw new Wr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Wg[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 Wr.ClientError(`Unknown query comparator "${u}"`)}if(r){let b=_;_=l,l=b,b=!f,f=!d,d=b}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 Wr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&E)throw new Wr.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 Wr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Wr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Qg(e),!S)throw new Wr.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 b=p.getRange(T).map(S?function({key:R,value:M}){return this.isSync?M&&S(M)?R:Ii.SKIP:new Promise((v,P)=>setImmediate(()=>{try{v(M&&S(M)?R:Ii.SKIP)}catch(k){P(k)}}))}:R=>R.value==null?Ii.SKIP:R);return b.hasEntries=!0,b}else return p?p.getRange(T).map(S?function({key:b,value:R}){return this.isSync?S({[o]:b})?R:Ii.SKIP:new Promise((M,v)=>setImmediate(()=>{try{M(S({[o]:b})?R:Ii.SKIP)}catch(P){v(P)}}))}:({value:b})=>b):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:b,value:R}){return this.isSync?R&&S(R)?b:Ii.SKIP:new Promise((M,v)=>setImmediate(()=>{try{M(R&&S(R)?b: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 Zee(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=xn(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 ete(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=xn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(xn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(f=>!f(d)))continue}_.set(xn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Qg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=Gs(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=Qg({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((b,R)=>{let M,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(b);return S.idFilter&&(T.idFilter=S.idFilter),P}v=p(b,r,R),M=v?.value}else M=b[l];return M?Array.isArray(M)?M.some(h):h(M,v):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Wg[o]||o){case $g.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,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 Wr.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(b){let R=b[l],M;if(typeof R!="object"||!R||E?M=d(R):Array.isArray(R)?M=R.some(d):R instanceof Date&&(M=d(R.getTime())),f&&(S++,!M&&!T.idFilter&&++p/S*(i-S)>h)){let v=Ba(e,r.transaction.getReadTxn(),!1,t).map(xn),P=new Set(v);T.idFilter=k=>P.has(xn(k)),T.idFilter.idSet=P}return M}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=Wg[n]||n,n===$g.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=Gs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=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=jee*xs(e.primaryStore)+1:n==="between"?r.estimated_count=Jee*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,tte.test(e))try{let t=_l(new va,"");if(yr!==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 ${yr} in '${wi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function _l(e,t){let r=Pa,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(wi);){yr=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=h0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=dl(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Xee[d],u=Yg[i]?h0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=dl(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&m0(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(dl(l)),s=void 0;break;case"(":Pa.lastIndex=yr;let E=_l(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=p0(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}wi[yr]===","?r.lastIndex=++yr: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=yr,f=_l([],"}"),f.name=l,e.push(f),wi[yr]===","?r.lastIndex=++yr:o=!0;break;case"[":Pa.lastIndex=yr,l?(f=_l(new va,"]"),f.name=l):f=_l(e.conditions?new va:[],"]"),e.conditions?(Yf(e,_),e.conditions.push(f),s=null):e.push(f),wi[yr]===","?r.lastIndex=++yr: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"&&m0(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(dl(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?rte:Pa,r.lastIndex=yr),yr===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 dl(e){return e.indexOf(".")>-1?e.split(".").map(dl):decodeURIComponent(e)}function h0(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new Wr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function m0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Wr.ClientError("wildcard can only be used at the end of a string")}function p0(e){let t=S0(e[0]);return e.length>1&&(t.next=p0(e.slice(1))),t}function S0(e){if(Array.isArray(e)){let t=S0(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function xn(e){return Array.isArray(e)?e.join("\0"):e}function xs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function nte(e,t,r){return t*r/xs(e)}var Wr,$g,ls,Ii,zee,Jee,jee,Xee,Yg,Wg,tte,Pa,rte,yr,wi,va,Qf=ge(()=>{Wr=B(ne()),$g=B(ut()),ls=require("ordered-binary"),Ii=require("lmdb"),zee=.3,Jee=.1,jee=.05,Xee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Yg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Kg,"executeConditions");a(Ba,"searchByIndex");a(Gs,"findAttribute");a(Zee,"joinTo");a(ete,"joinFrom");Wg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Qg,"filterByType");a(Kf,"estimateCondition");tte=/[()[\]|!<>.]|(=\w*=)/,Pa=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,rte=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Wf,"parseQuery");a(_l,"parseBlock");a(Yf,"assignOperator");a(dl,"decodeProperty");a(h0,"typedDecoding");a(m0,"wildcardDecoding");a(p0,"toSortObject");a(S0,"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(xn,"flattenKey");a(xs,"estimatedEntryCount");a(nte,"intersectionEstimate")});function O0(e){let t={openapi:ste,info:{title:"HarperDB HTTP REST interface",version:(0,A0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:M,elements:v,relationship:P,definition:k}of o){if(P)R==="array"?_[M]={type:"array",items:{$ref:Ci+v.type}}:_[M]={$ref:Ci+R};else{let H=k??v?.definition;if(H){if(!t.components.schemas[H.type]){let j={};H.properties.forEach(z=>{j[z.name]=new Xg(zg[z.type],z.type)}),t.components.schemas[H.type]=new R0(j)}R==="array"?_[M]={type:"array",items:{$ref:Ci+H.type}}:_[M]={$ref:Ci+H.type}}else R==="array"?v.type==="Any"||v.type=="ID"?_[M]={type:"array",items:{format:v.type}}:_[M]={type:"array",items:new Xg(zg[v.type],v.type)}:R==="Any"||R=="ID"?_[M]={format:R}:_[M]=new Xg(zg[R],R)}l.push(new Zg(M,"query",_[M]))}let d=Object.keys(_),f=new Zg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Zg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new R0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",b="/"+s+"/";h&&(t.paths[b]={},t.paths[b].post=new ite(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[b]||(t.paths[b]={}),t.paths[b].get=new Jg(l,r,{200:new jg({$ref:Ci+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[b]||(t.paths[b]={}),t.paths[b].delete=new g0(l,r,"delete all the records that match the provided query",{204:new T0})),b="/"+s+"/{"+c+"}",S&&(t.paths[b]={},t.paths[b].get=new Jg([f],r,{200:new jg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[b]||(t.paths[b]={}),t.paths[b].put=new ote([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[b]||(t.paths[b]={}),t.paths[b].delete=new g0([f],r,"delete a record with the given primary key",{204:new T0})),S&&E.schema.enum.length>0&&(b="/"+s+"/{"+c+"}.{property}",t.paths[b]={},t.paths[b].get=new Jg([f,E],r,{200:new jg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function ite(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ci+e}}}},this.security=t,this.responses={200:{description:eR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Jg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function jg(e){this.description=eR,this.content={"application/json":{schema:e}}}function T0(){this.description="successfully processed request, no content returned to client"}function ote(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ci+r}}}},this.responses={200:{description:eR}}}function g0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function R0(e){this.type="object",this.properties=e}function Xg(e,t){this.type=e,this.format=t}function Zg(e,t,r){this.name=e,this.in=t,this.schema=r}var A0,ste,zg,Ci,eR,b0=ge(()=>{A0=B($d()),ste="3.0.3",zg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ci="#/components/schemas/",eR="successful operation";a(O0,"generateJsonApi");a(ite,"Post");a(Jg,"Get");a(jg,"Response200");a(T0,"Response204");a(ote,"Put");a(g0,"Delete");a(R0,"ResourceSchema");a(Xg,"Type");a(Zg,"Parameter")});var Jf={};qe(Jf,{start:()=>ute});async function cte(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Wf(e);let s=new Oi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==y0){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(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")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===y0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return O0(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,tR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){ate[0]=d;let h=String.fromCharCode(34,(Yt[0]&63)+62,(Yt[0]>>6)+(Yt[1]<<2&63)+62,(Yt[1]>>4)+(Yt[2]<<4&63)+62,(Yt[2]>>2)+62,(Yt[3]&63)+62,(Yt[3]>>6)+(Yt[4]<<2&63)+62,(Yt[4]>>4)+(Yt[5]<<4&63)+62,(Yt[5]>>2)+62,(Yt[6]&63)+62,(Yt[6]>>6)+(Yt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),tR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let 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 ute(e){tR=e,!N0&&(N0=!0,zf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return cte(t,r)}),e.server.ws(async(t,r,n)=>{fl++;let s=new yn;I0||(I0=!0,lu(l=>{fl>0&&l.push({metric:"ws-connections",connections:fl,byThread:!0})}));let i;t.on("error",l=>{i=!0,Oo.warn(l)});let o;t.on("message",a(function(d){o||(o=Ao(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{fl--,cn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=zf.getMatch(u);if(cn(!!_,"connection","ws","connect"),!_)t.send(bi(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,kr(h=>({count:h.count,total:fl}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Xe(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=bi(E.value,r);t.send(h),kr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var Oo,Ha,Yt,ate,tR,y0,N0,zf,I0,fl,w0=ge(()=>{Ia();ws();Oo=B($()),Ha=B(ne());Qf();Rc();ro();Qu();b0();Yt=new Uint8Array(8),ate=new Float64Array(Yt.buffer,0,1),tR={},y0="openapi";a(cte,"http");fl=0;a(ute,"start")});var rR=g((Gme,C0)=>{var{recordAction:jf,recordActionBinary:lte}=(ws(),ie(_u)),_te=require("fastify-plugin"),dte=200;C0.exports=_te(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),lte(s.raw.statusCode<400,"success",_,d,l);let f=dte;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 cR=g((kme,U0)=>{var tE=require("clone"),rE=je(),fte=Q(),Zf=L(),qme=$(),nR=require("fs"),iR=require("joi"),{string:eE}=iR.types(),{hdb_errors:Ete,handleHDBError:Xf}=ne(),{HDB_ERROR_MSGS:Fme,HTTP_STATUS_CODES:sR}=Ete,{common_validators:xa}=zn(),D0=" is required",hte=["insert","update","upsert"],oR={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:hte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},mte={schema:eE.required(),table:eE.required(),action:eE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:pte,AWS_SECRET:Ste,AWS_BUCKET:Tte,AWS_FILE_KEY:gte,REGION:Rte}=Zf.S3_BUCKET_AUTH_KEYS,Ate={s3:{presence:!0},[`s3.${pte}`]:{presence:!0,type:"String"},[`s3.${Ste}`]:{presence:!0,type:"String"},[`s3.${Tte}`]:{presence:!0,type:"String"},[`s3.${gte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Rte}`]:{presence:!0,type:"String"}},L0=tE(oR);L0.data.presence={message:D0};var M0=tE(oR);M0.file_path.presence={message:D0};var Ote=Object.assign(tE(oR),Ate),aR=tE(mte);aR.csv_url=eE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();aR.passthrough_headers=iR.object();function bte(e){let t=rE.validateObject(e,L0);return nE(e,t)}a(bte,"dataObject");function yte(e){let t=rE.validateBySchema(e,iR.object(aR));return nE(e,t)}a(yte,"urlObject");function Nte(e){let t=rE.validateObject(e,M0);return nE(e,t)}a(Nte,"fileObject");function Ite(e){let t=rE.validateObject(e,Ote);return nE(e,t)}a(Ite,"s3FileObject");function nE(e,t){if(!t){let r=fte.checkGlobalSchemaTable(e.schema,e.table);if(r)return Xf(new Error,r,sR.BAD_REQUEST);if(e.operation===Zf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{nR.accessSync(e.file_path,nR.constants.R_OK|nR.constants.F_OK)}catch(n){return n.code===Zf.NODE_ERROR_CODES.ENOENT?Xf(n,`No such file or directory ${n.path}`,sR.BAD_REQUEST):n.code===Zf.NODE_ERROR_CODES.EACCES?Xf(n,`Permission denied ${n.path}`,sR.BAD_REQUEST):Xf(n)}}return t}a(nE,"postValidateChecks");U0.exports={dataObject:bte,urlObject:yte,fileObject:Nte,s3FileObject:Ite}});var uR=g(($me,P0)=>{"use strict";var El=$(),sE=L();async function wte(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")?(El.info(i.message),i):i.http_resp_msg?(El.error(`Error calling operation: ${e.name}`),El.error(i.http_resp_msg),i):(El.error(`Error calling operation: ${e.name}`),El.error(i),i)}}a(wte,"callOperationFunctionAsAwait");P0.exports={callOperationFunctionAsAwait:wte}});var B0=g((Kme,v0)=>{"use strict";var lR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},_R=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};v0.exports={BulkLoadFileObject:lR,BulkLoadDataObject:_R}});var x0=g((Qme,H0)=>{"use strict";var dR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};H0.exports=dR});var SR=g((epe,tB)=>{"use strict";var iE=vr(),aE=cR(),Cte=require("needle"),Gn=L(),Jme=ke(),Ga=Q(),{handleHDBError:ot,hdb_errors:W0}=ne(),{HTTP_STATUS_CODES:Kt,HDB_ERROR_MSGS:wt,CHECK_LOGS_WRAPPER:yo}=W0,qa=$(),fR=require("papaparse");Ga.promisifyPapaParse();var qn=require("fs-extra"),Dte=require("path"),{chain:G0}=require("stream-chain"),q0=require("stream-json/streamers/StreamArray"),F0=require("stream-json/utils/Batch"),k0=require("stream-chain/utils/comp"),{finished:V0}=require("stream"),Lte=ee(),Q0=uR(),Mte=vg(),{BulkLoadFileObject:hR,BulkLoadDataObject:Ute}=B0(),mR=yg(),{verifyBulkLoadAttributePerms:z0}=xf(),jme=x0(),Xme=it(),Zme=Rs(),{databases:Pte}=(Re(),ie(Fe)),{coerceType:vte}=(cE(),ie(TR)),$0="No records parsed from csv file.",bo=`${Lte.get("HDB_ROOT")}/tmp`,{schema_regex:Bte}=zn(),Y0=1024*1024*2,K0=5e3,Hte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};tB.exports={csvDataLoad:xte,csvURLLoad:Gte,csvFileLoad:qte,importFromS3:Fte};async function xte(e,t){let r=aE.dataObject(e);if(r)throw ot(r,r.message,Kt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=X0(e.schema,e.table),i=fR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:ER.bind(null,s),dynamicTyping:!1}),o=new mR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&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,Kt.BAD_REQUEST,void 0,void 0,!0);let u=new Ute(e.action,e.schema,e.table,i.data);return n=await Q0.callOperationFunctionAsAwait(Z0,u,null),n.message===$0?$0:eB(n.records,n.number_written)}catch(s){throw No(s)}}a(xte,"csvDataLoad");async function Gte(e){let t=aE.urlObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${bo}/${r}`;try{await kte(e,r)}catch(s){throw qa.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+s),ot(s,yo(wt.DOWNLOAD_FILE_ERR(r)))}try{let s=new hR(this.job_operation_function.name,e.action,e.schema,e.table,n,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await pR(s);return await oE(n),i}catch(s){throw await oE(n),No(s)}}a(Gte,"csvURLLoad");async function qte(e){let t=aE.fileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=new hR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await pR(r)}catch(n){throw No(n)}}a(qte,"csvFileLoad");async function Fte(e){let t=aE.s3FileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Dte.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${bo}/${s}`;let i=new hR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Vte(s,e);let o=await pR(i);return await oE(r),o}catch(n){throw await oE(r),No(n)}}a(Fte,"importFromS3");async function kte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Cte("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,Gn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}Yte(r,e.csv_url),await $te(t,r.raw)}a(kte,"downloadCSVFile");async function Vte(e,t){try{let r=`${bo}/${e}`;await qn.mkdirp(bo),await qn.writeFile(`${bo}/${e}`,"",{flag:"a+"});let n=await qn.createWriteStream(r),s=await Mte.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(wt.S3_DOWNLOAD_ERR+" - "+r),ot(r,yo(wt.S3_DOWNLOAD_ERR))}}a(Vte,"downloadFileFromS3");async function $te(e,t){try{await qn.mkdirp(bo),await qn.writeFile(`${bo}/${e}`,t)}catch(r){throw qa.error(wt.WRITE_TEMP_FILE_ERR),ot(r,yo(wt.DEFAULT_BULK_LOAD_ERR))}}a($te,"writeFileToTempFolder");async function oE(e){if(e)try{await qn.access(e),await qn.unlink(e)}catch{qa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(oE,"deleteTempFile");function Yte(e,t){if(e.statusCode!==W0.HTTP_STATUS_CODES.OK)throw ot(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Kt.BAD_REQUEST);if(!Hte[e.headers["content-type"]])throw ot(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Kt.BAD_REQUEST);if(!e.raw)throw ot(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Kt.BAD_REQUEST)}a(Yte,"validateURLResponse");async function pR(e){try{let t;switch(e.file_type){case Gn.VALID_S3_FILE_TYPES.CSV:t=await Kte(e);break;case Gn.VALID_S3_FILE_TYPES.JSON:t=await Wte(e);break;default:throw ot(new Error,wt.DEFAULT_BULK_LOAD_ERR,Kt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,wt.INVALID_FILE_EXT_ERR(e))}return eB(t.records,t.number_written)}catch(t){throw No(t)}}a(pR,"fileLoad");async function J0(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(J0,"validateChunk");async function j0(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 Q0.callOperationFunctionAsAwait(Z0,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=ot(c,yo(wt.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(j0,"insertChunk");async function Kte(e){let t={records:0,number_written:0},r=X0(e.schema,e.table);try{let n=new mR,s=qn.createReadStream(e.file_path,{highWaterMark:Y0});s.setEncoding("utf8"),await fR.parsePromise(s,J0.bind(null,e,n),ER.bind(null,r));let i=n.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);return s=qn.createReadStream(e.file_path,{highWaterMark:Y0}),s.setEncoding("utf8"),await fR.parsePromise(s,j0.bind(null,e,t),ER.bind(null,r)),s.destroy(),t}catch(n){throw ot(n,yo(wt.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+n)}}a(Kte,"callPapaParse");function X0(e,t){let r=Pte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>vte(i,s));return n}a(X0,"createTransformMap");function ER(e,t,r){let n=e.get(r);return n?n(t):Ga.autoCast(t)}a(ER,"typeFunction");async function Wte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new mR,s=G0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),q0.withParser(),c=>c.value,new F0({batchSize:K0}),k0(async c=>{await J0(e,n,r,c)})]);await new Promise((c,u)=>{V0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);let o=G0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),q0.withParser(),c=>c.value,new F0({batchSize:K0}),k0(async c=>{await j0(e,t,r,c)})]);return await new Promise((c,u)=>{V0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw ot(n,yo(wt.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+n)}}a(Wte,"insertJson");async function Z0(e){let t={};try{e.data&&e.data.length>0&&Qte(e.data[0])?t=await zte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",qa.info(t.message))}catch(r){throw No(r)}return t}a(Z0,"callBulkFileLoad");function Qte(e){let t=Object.keys(e);for(let r of t)if(!Bte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Qte,"validateColumnNames");async function zte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=iE.insert;break;case"update":i=iE.update;break;case"upsert":i=iE.upsert;break;default:throw ot(new Error,wt.INVALID_ACTION_PARAM_ERR(n),Kt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,wt.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 No(o)}}a(zte,"bulkFileLoad");function eB(e,t){return`successfully loaded ${t} of ${e} records`}a(eB,"buildResponseMsg");function No(e){return ot(e,yo(wt.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(No,"buildTopLevelErrMsg")});var nB=g((rpe,rB)=>{"use strict";var gR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};rB.exports=gR});var oB=g((spe,iB)=>{"use strict";var Jte=L(),sB=require("moment"),jte=require("uuid").v4,RR=class{static{a(this,"JobObject")}constructor(){this.id=jte(),this.type=void 0,this.start_datetime=sB().valueOf(),this.created_datetime=sB().valueOf(),this.end_datetime=void 0,this.status=Jte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};iB.exports=RR});var AR=g((ope,dB)=>{"use strict";var Xte=require("uuid").v4,uB=vr(),lB=Pr(),Zte=es(),ere=sa(),tre=nB(),at=L(),rre=oB(),nre=Hd(),mn=$(),sre=Hc(),Fa=Q(),{promisify:ire}=require("util"),Io=require("moment"),ore=qf(),uE=cR(),aB=Ym(),{deleteTransactionLogsBeforeValidator:are}=gg(),{handleHDBError:cre,hdb_errors:ure}=ne(),{HTTP_STATUS_CODES:lre}=ure,cB=lB.searchByValue,_re=lB.searchByHash,dre=uB.insert,fre=ire(ore.evaluateSQL),Ere=uB.update;dB.exports={addJob:pre,updateJob:Tre,handleGetJob:hre,handleGetJobsByStartDate:mre,getJobById:_B};async function hre(e){try{let t=await _B(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 mn.error("There was an error getting job",t),new Error(r)}}a(hre,"handleGetJob");async function mre(e){try{let t=await Sre(e);if(mn.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 mn.error(r),new Error(r)}}a(mre,"handleGetJobsByStartDate");async function pre(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 mn.info(l),t.error=l,t}if(!at.JOB_TYPE_ENUM[e.operation])return mn.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=aB(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=aB(e,"timestamp");break;case at.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=are(e);break;default:break}if(n)throw cre(n,n.message,lre.BAD_REQUEST,void 0,void 0,!0);let s=new rre;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 Zte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await cB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return mn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Xte();try{o=await cB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return mn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return mn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new sre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await dre(u)}catch(l){return mn.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,mn.trace(l)}return t}a(pre,"addJob");async function Sre(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 tre(n,e.hdb_user);try{return await fre(s)}catch(i){throw mn.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(Sre,"getJobsInDateRange");async function _B(e){if(Fa.isEmptyOrZeroLength(e))return Fa.errorizeMessage("Invalid job ID specified.");let t=new ere(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await _re(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return mn.error(n),Fa.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(_B,"getJobById");async function Tre(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 nre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Ere(t),r}a(Tre,"updateJob")});var SB=g((cpe,pB)=>{"use strict";var fB=Q(),Nr=L(),gre=require("moment"),lE=SR(),_E=$(),EB=AR(),hB=Ff(),mB=ii(),Rre=Ke(),Are=Pf(),OR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Ore(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(fB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(fB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Nr.JOB_TYPE_ENUM.csv_file_load:await qs(e,lE.csvFileLoad);break;case Nr.JOB_TYPE_ENUM.csv_url_load:await qs(e,lE.csvURLLoad);break;case Nr.JOB_TYPE_ENUM.csv_data_load:await qs(e,lE.csvDataLoad);break;case Nr.JOB_TYPE_ENUM.import_from_s3:await qs(e,lE.importFromS3);break;case Nr.JOB_TYPE_ENUM.empty_trash:break;case Nr.JOB_TYPE_ENUM.export_local:await qs(e,hB.export_local);break;case Nr.JOB_TYPE_ENUM.export_to_s3:await qs(e,hB.export_to_s3);break;case Nr.JOB_TYPE_ENUM.delete_files_before:case Nr.JOB_TYPE_ENUM.delete_records_before:await qs(e,mB.deleteFilesBefore);break;case Nr.JOB_TYPE_ENUM.delete_audit_logs_before:await qs(e,mB.deleteAuditLogsBefore);break;case Nr.JOB_TYPE_ENUM.delete_transaction_logs_before:await qs(e,Are.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Ore,"parseMessage");async function qs(e,t){try{e.job.status=Nr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=gre().valueOf(),await EB.updateJob(e.job),await bre(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=Nr.JOB_STATUS_ENUM.ERROR;try{await EB.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 bre(e){_E.trace("launching job thread:",e),Rre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(bre,"launchJobThread");pB.exports={parseMessage:Ore,RunnerMessage:OR}});var gB=g((lpe,TB)=>{"use strict";var bR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};TB.exports=bR});var HB=g((dpe,DR)=>{"use strict";var mE=Pr(),IR=qf(),dE=SR(),Fs=Tu(),fE=As(),ml=ii(),yre=qS(),hl=an(),EE=zS(),Wt=Tg(),hE=$(),Nre=XS(),Ire=Jd(),RB=DT(),wre=Xd(),Cre=MT(),Dre=UT(),Lre=BT(),Mre=xT(),yR=FT(),AB=Ff(),Ure=xf(),wR=AR(),q=L(),{hdb_errors:Sl,handleHDBError:pl}=ne(),{HTTP_STATUS_CODES:OB}=Sl,NR=KT(),bB=gf(),UB=require("util"),ka=vr(),Pre=Os(),vre=Sa(),yB=SB(),NB=yu(),IB=(bf(),ie(zu)),wB=lr(),CB=Pf(),DB=Cf(),{setServerUtilities:Bre}=(cE(),ie(TR)),{CONTEXT:Hre}=(Nn(),ie(Gp)),{_assignPackageExport:xre}=require("../index"),{transformReq:Gre}=Q(),{server:qre}=(or(),ie(Hi)),tr=hE.loggerWithTag("operation"),Fre=uR(),LB=mE.searchByHash,kre=mE.searchByValue,Vre=UB.promisify(mE.search),$re=UB.promisify(IR.evaluateSQL),Yre={[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=gB();async function PB(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;tr.info(o)}}catch(n){tr.error(n)}let r=await Fre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Yre[e.body.operation]&&Pre.setSchemaDataToGlobal(n=>{n&&tr.error(n)}),r}a(PB,"processLocalTransaction");var MB=Wre();DR.exports={chooseOperation:vB,getOperationFunction:BB,operation:CR,processLocalTransaction:PB};Bre(DR.exports);qre.operation=CR;function vB(e){let t;try{t=BB(e)}catch(s){throw tr.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=IR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=IR.checkASTPermissions(e,i);if(o)throw tr.error(`${OB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Ure.verifyPerms(i,s);if(o)throw tr.error(`${OB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw pl(s,"There was an error when trying to choose an operation path")}return r}a(vB,"chooseOperation");function BB(e){if(tr.trace(`getOperationFunction with operation: ${e.operation}`),MB.has(e.operation))return MB.get(e.operation);throw pl(new Error,Sl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Sl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(BB,"getOperationFunction");xre("operation",CR);function CR(e,t){e.hdb_user=this[Hre]?.user,e.bypass_auth=!t;let r=vB(e);return PB({body:e},r)}a(CR,"operation");async function Kre(e){tr.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 ml.deleteRecord(i);break;default:tr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){tr.info("Invalid operation in transaction"),tr.error(o)}}a(Kre,"catchup");async function _s(e){Gre(e);let t,r;try{r=await wR.addJob(e),t=r.createdJob,tr.info("addJob result",r);let n=new yB.RunnerMessage(t,e);return await yB.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 tr.error(s),pl(n,s)}}a(_s,"executeJob");function Wre(){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(LB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(LB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(kre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(Vre)),e.set(q.OPERATIONS_ENUM.SQL,new Y($re)),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(ml.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(hl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(hl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(hl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(hl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(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(hl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(Nre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Ire)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(RB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(RB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(wre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Cre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(Dre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(wB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Lre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Mre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(yR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(yR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(yR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(_s,AB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(_s,ml.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(_s,ml.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(_s,AB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(wR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(wR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(NR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(NR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(NR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(bB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(bB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(Kre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(vre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(_s,ml.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(yre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(NB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(NB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(IB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(IB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(wB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Wt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Wt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Wt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Wt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Wt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Wt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Wt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Wt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Wt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Wt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Wt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Wt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Wt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Wt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Wt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Wt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(CB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(_s,CB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(DB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(DB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(Wre,"initializeOperationFunctionMap")});var SE=g((Epe,qB)=>{"use strict";var LR=L(),Qre=Q(),Tl=$(),{handleHDBError:MR,hdb_errors:pE}=ne(),{isMainThread:zre}=require("worker_threads"),{Readable:Jre}=require("stream"),xB=require("os"),jre=require("util"),Xre=cT(),Zre=jre.promisify(Xre.authorize),GB=HB(),{createGzip:ene,constants:tne}=require("zlib");function rne(e){let t=`Found an uncaught exception with message: ${e.message}. ${xB.EOL}Stack: ${e.stack} ${xB.EOL}Terminating ${zre?"HDB":"thread"}.`;console.error(t),Tl.fatal(t),process.exit(1)}a(rne,"handleServerUncaughtException");function nne(e,t,r){if(Tl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode: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(nne,"serverErrorHandler");function sne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=MR(new Error,"Invalid JSON.",pE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Qre.isEmpty(e.body.operation)){let n=MR(new Error,"Request body must include an 'operation' property.",pE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(sne,"reqBodyValidationHandler");function ine(e,t,r){let n;e.body.operation!==LR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==LR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==LR.OPERATIONS_ENUM.LOGOUT?Zre(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Tl.warn(s),Tl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(MR(s,i,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(ine,"authHandler");async function one(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=GB.chooseOperation(e.body);let s=await GB.processLocalTransaction(e,n);if(s instanceof Jre&&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(ene({level:tne.Z_BEST_SPEED})))}return s}catch(s){throw Tl.error(s),s}}a(one,"handlePostRequest");qB.exports={authHandler:ine,handlePostRequest:one,handleServerUncaughtException:rne,serverErrorHandler:nne,reqBodyValidationHandler:sne}});var $B=g((mpe,VB)=>{"use strict";var ane=require("fastify-plugin"),{handlePostRequest:FB,authHandler:cne,reqBodyValidationHandler:une}=SE();async function lne(e){e.decorate("hdbCore",{preValidation:[une,cne],request:t=>kB(FB(t,response)),requestWithoutAuthentication:(t,r)=>kB(FB(t,r,!0))})}a(lne,"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");VB.exports=ane(lne)});var WB=g((Tpe,KB)=>{"use strict";var Spe=require("fs"),UR=ee();UR.initSync();var{CONFIG_PARAMS:YB}=L(),_ne=1024*1024*1024;function dne(e){let t=UR.get(YB.HTTP_TIMEOUT),r=UR.get(YB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:_ne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(dne,"getServerOptions");KB.exports=dne});var JB=g((Rpe,zB)=>{"use strict";var PR=ee();PR.initSync();var{CONFIG_PARAMS:QB}=L();function fne(){let e=PR.get(QB.HTTP_CORSACCESSLIST),t=PR.get(QB.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(fne,"getCORSOptions");zB.exports=fne});var ZB=g((Ope,XB)=>{"use strict";var jB=ee();jB.initSync();var Ene=L();function hne(){return jB.get(Ene.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(hne,"getHeaderTimeoutConfig");XB.exports=hne});var BR={};qe(BR,{customFunctionsServer:()=>Sne,ready:()=>EH,start:()=>pne});function pne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=fH(t),nt.http((await ks).server));let o=await ks,c=(0,vR.dirname)(s),u=(0,vR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!eH.has(c)){eH.add(c);try{o.register(gne(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:EH}}async function Sne(){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 Tne();let e=oH.get(aH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await fH(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 Tne(){try{$e.info("Custom Functions starting configuration."),await cH.setUsersToGlobal(),$e.info("Custom Functions completed configuration.")}catch(e){$e.error(e)}}function gne(e,t){return async function(r){try{$e.info("Custom Functions starting buildRoutes"),$e.trace("Loading fastify routes folder "+e),(0,tH.existsSync)(e)&&r.register(iH.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 fH(e){$e.info("Custom Functions starting buildServer.");let t=(0,uH.default)(e),r=(0,rH.default)(t);r.server.headersTimeout=(0,_H.default)(),r.setErrorHandler(dH.serverErrorHandler);let n=(0,lH.default)();return n&&r.register(nH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(sH.default),await r.register(mne),await r.after(),Vg(r),$e.info("Custom Functions completed buildServer."),r}function EH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var vR,tH,rH,nH,sH,iH,oH,aH,$e,mne,cH,uH,lH,_H,dH,ks,eH,hH=ge(()=>{vR=require("path"),tH=require("fs"),rH=B(require("fastify")),nH=B(require("@fastify/cors")),sH=B(rR()),iH=B(require("@fastify/autoload")),oH=B(ee()),aH=B(L()),$e=B($()),mne=B($B()),cH=B(an()),uH=B(WB()),lH=B(JB()),_H=B(ZB()),dH=B(SE());Ia();or();eH=new Set;a(pne,"start");a(Sne,"customFunctionsServer");a(Tne,"setUp");a(gne,"buildRouteFolder");a(fH,"buildServer");a(EH,"ready")});var HR={};qe(HR,{start:()=>Rne});function Rne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,gH.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){pH||(pH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=mH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,SH.default)(s,(0,TH.realpathSync)(o))}}return i(s)},{runFirst:!0})),mH.set(r,n)}}}var SH,TH,gH,mH,pH,RH=ge(()=>{SH=B(require("send")),TH=require("fs"),gH=B(require("serve-static")),mH=new Map;a(Rne,"start")});function bne(e,t=1,r){if(xR++,(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)});One.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)yH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{GR?GR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,wo.shutdownWorkers)(),xR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function NH(e=0,t){if(typeof e=="string")try{(0,AE.existsSync)(e)&&(0,AE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=yne:r=Nne(t):r=FR;let n=(0,Ya.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=yH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),GR=!0,r(o,(c,u)=>{if(!c){if(AH){let l=o._socket||new Ya.Socket({handle:o,writable:!0,readable:!0});AH.deliverSocket(l,e,u),l.resume()}else xR>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"),bne(0));kr(!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});Dne(l,c,e)}kr(!0,"socket-routed")})};let s=ou();qR.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function FR(e,t){let r,n=0;for(let s of 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 yne(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);FR(e,o=>{Ka.set(n,{worker:o,lastUsed:i}),t(o)})}function Nne(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);FR(n,d=>{Ka.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function wne(){TE=0;for(let e of Va)e.expectedIdle=e.recentELU.idle+Ine,e.requests=1;Va.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Dne(e,t,r){let n=Cne++;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,qR,AE,bH,Ane,Va,$a,yH,AH,xR,One,GR,TE,OH,Ka,Ine,gE,Cne,IH=ge(()=>{wo=B(Ke()),Ya=require("net"),RE=B(L()),qR=B($()),AE=require("fs");ws();bH=require("worker_threads"),Ane=B(Ji()),Va=[],$a=[],yH=[],xR=0,One=[];bH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(bne,"startHTTPWorker");a(NH,"startSocketServer");TE=0;a(FR,"findMostIdleWorker");OH=36e5,Ka=new Map;a(yne,"findByRemoteAddressAffinity");a(Nne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ka)r.lastUsed+OH<e&&Ka.delete(t)},OH).unref();Ine=1e3;a(wne,"updateWorkerIdleness");(0,wo.setMonitorListener)(wne);gE=new Map,Cne=1;a(Dne,"proxySocket")});var YR={};qe(YR,{Request:()=>kR,createReuseportFd:()=>OE});var wH,kR,VR,$R,OE,bE=ge(()=>{wH=require("os"),kR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new $R(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new VR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},VR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},$R=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,wH.platform)()!="win32"&&(OE=require("node-unix-socket").createReuseportFd)});var MH=g((xpe,LH)=>{"use strict";var Lne=require("cluster"),Co=ee();Co.initSync();var DH=L(),Upe=require("util"),Vs=$(),Ppe=require("fs"),Mne=require("fastify"),vpe=ou(),Une=require("@fastify/cors"),Pne=require("@fastify/compress"),vne=require("@fastify/static"),Bne=rR(),Hne=require("path"),{PACKAGE_ROOT:xne}=L(),Gne=Os(),qne=Q(),Fne=an(),kne=Ji(),{server:Vne}=(or(),ie(Hi)),{node_request_key:Bpe}=(bE(),ie(YR)),{authHandler:$ne,handlePostRequest:Yne,serverErrorHandler:Kne,reqBodyValidationHandler:Wne}=SE(),Hpe=require("net"),{registerContentHandlers:Qne}=(Ia(),ie(E0)),zne=6e4,Jne=1024*1024*1024,jne="TRUE",{CONFIG_PARAMS:gl}=DH,Wa;LH.exports={hdbServer:CH,start:CH};async function CH(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=Lne.isMaster,await Xne();let t=e.securePort>0;Wa=Zne(t),await Wa.ready(),e||(e={}),e.isOperationsServer=!0;try{Vne.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(CH,"operationsServer");async function Xne(){Vs.trace("Configuring HarperDB process."),Gne.setSchemaDataToGlobal(),await Fne.setUsersToGlobal(),await kne.getLicense()}a(Xne,"setUp");function Zne(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=ese(e),r=Mne(t);r.server.headersTimeout=rse(),r.setErrorHandler(Kne);let n=tse();n&&r.register(Une,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Bne),r.register(Pne),r.register(vne,{root:Hne.join(xne,"studio/build-local")}),Qne(r);let s=Co.get(DH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!qne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Wne,$ne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Yne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Zne,"buildServer");function ese(e){let t=Co.get(gl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Co.get(gl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Jne,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(ese,"getServerOptions");function tse(){let e=Co.get(gl.OPERATIONSAPI_NETWORK_CORS),t=Co.get(gl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===jne)&&(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(tse,"getCORSOpts");function rse(){return Co.get(gl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??zne}a(rse,"getHeaderTimeoutConfig")});var jR={};qe(jR,{disableNATS:()=>sse,publishToStream:()=>IE,setNATSReplicator:()=>KR,setPublishToStream:()=>ise,setSubscription:()=>JR,start:()=>nse});function nse(){Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&ase()}function sse(e=!0){HH=e}function ise(e,t){IE=e,JR=t}function ase(){if(HH||process.env._DISABLE_NATS)return;let e=dr(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];KR(s,r,i)}}XR((r,n)=>{KR(r.tableName,r.databaseName,r),n&&GH(r)}),!UH&&(UH=!0)}function KR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Ft{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Me],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Me]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Me],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Me],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Me]})}static defineSchema(i){GH(i)}static subscribe(){let i=new yn;return JR(t,e,i),i}static subscribeOnThisThread(i){return i<(Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??ose)}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 yE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=xH;return i}a(n,"getNATSTransaction")}function GH(e){let t=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME);IE(`${QR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,zR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var PH,QR,zR,vH,BH,Rl,Al,NE,HH,IE,JR,ose,xH,UH,yE,WR,qH=ge(()=>{Re();Nn();PH=B(it()),QR=B(ke()),zR=B(Rs());Rc();vH=B(wS()),BH=B(Dr()),Rl=B(ee()),Al=B(L()),NE=B($());a(nse,"start");a(sse,"disableNATS");IE=PH.publishToStream,JR=vH.setSubscription;a(ise,"setPublishToStream");ose=2;a(ase,"assignReplicationSource");a(KR,"setNATSReplicator");a(GH,"publishSchema");yE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(NE.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(`${QR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,zR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw NE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},WR=class extends yE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,BH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};xH=new WR});var tx=g(Do=>{"use strict";var{isMainThread:KH,parentPort:bl,threadId:wE}=require("worker_threads"),{Socket:cse,createServer:use}=require("net"),{createServer:lse,IncomingMessage:_se}=require("http"),{createServer:dse}=require("https"),{readFileSync:Qa,unlinkSync:FH,existsSync:fse}=require("fs"),rr=$(),Ce=ee(),Et=L(),{server:ME}=(or(),ie(Hi)),{WebSocketServer:Ese}=require("ws"),{createServer:hse}=require("tls"),{getTicketKeys:mse,restartNumber:pse,getWorkerIndex:DE}=Ke(),{Headers:WH,appendHeader:Sse}=(Qu(),ie(xP)),{recordAction:Ol,recordActionBinary:Tse}=(ws(),ie(_u)),{Request:QH,createReuseportFd:kH}=(bE(),ie(YR)),{checkMemoryLimit:gse}=Ji(),zH=require("tls"),VH=zH.createSecureContext;zH.createSecureContext=function(e){if(!e.cert||!e.key)return VH(e);let t={...e};delete t.key,delete t.cert;let r=VH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var JH=Ce.get(Et.CONFIG_PARAMS.THREADS_DEBUG);if(JH){let e;if(KH)e=Ce.get(Et.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){rr.info("Could not close debugger",t)}});else{let t=Ce.get(Et.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&DE()>=0&&(e=t+DE())}if(e){let t=Ce.get(Et.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=Ce.get(Et.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){rr.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){pse<=1&&rr.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:Ype,CONFIG_PARAMS:Rse}=Et;Ce.initSync();var Ase=Ce.get(Rse.HTTP_SESSIONAFFINITY),ds={};Do.registerServer=nA;Do.httpServer=sA;Do.deliverSocket=rA;Do.startServers=jH;Do.when_components_loaded=null;ME.http=sA;ME.request=Nse;ME.socket=Ise;ME.ws=wse;var ZR={},CE={},Ose,Di={},LE={},bse=[],eA=[];function jH(){return Do.when_components_loaded=iA().loadRootComponents(!0).then(()=>{bl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)rA(n,r,s);else if(t.requestId)yse(t);else if(t.type===Et.ITC_EVENT_TYPES.SHUTDOWN){rr.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?rr.info(`Closing ${E.length} idle connections`):f&&rr.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(
|
|
32
|
-
`)}a($H,"defaultNotFound")});async function nx({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await oA.get(e,{returnNonexistent:!0});n=new uA(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await oA.get(e);i&&i.delete()}n=new PE(e,t)}return s&&(s.id=e,s.user={username:t?.username},Ol.put(s)),n}function aA(){return UE++,UE>65500&&(UE=1),UE}function cA(e,t,r){let{topic:s,retain:n}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Ai.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return je(r,()=>n?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var tx,Li,rx,sx,oA,Ol,UE,PE,uA,ix=ge(()=>{Re();Ku();tx=v(Dr()),Li=v($());so();rx=v(Ke()),sx=v(ex());or();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"}]}}]}),Ol=lt({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,rx.getWorkerIndex)()===0&&(async()=>{await sx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Ol.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await st.getUser(r.user.username)),je(r,()=>{try{cA(r,t,r)}catch{(0,Li.warn)("Failed to publish will",t)}Ol.delete(e.id,r)})}})();a(nx,"getSession");UE=1;a(aA,"getNextMessageId");PE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,rh:i,startTime:o}=t,c=n.indexOf("?"),u,_;if(c>-1?(u=n.slice(c),_=n.slice(0,c)):_=n,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(T=>T.topic===n),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Li.trace)("Resuming subscription from",n,"from",o);let E=Ai.getMatch(_);if(!E){let T=new Error(`The topic ${n} 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("/"),R;for(let P=0;P<A.length;P++)if(A[P].indexOf("+")>-1)if(A[P]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(s&&R)throw new Error("Filters can not be combined");let M=!0;A[A.length-1]==="#"&&(A.length--,M=!1),R&&(s=a(P=>{let k=P.id;if(!Array.isArray(k)||M&&k.length!==A.length)return!1;for(let B=0;B<A.length;B++)if(A[B]!=="+"&&A[B]!==k[B])return!1;return!0},"filter"));let x=A.indexOf("+");f.url="/"+(x>-1?A.slice(0,x):A).concat("").join("/")}}let h=E.path,p=E.Resource,S=await je(f,async()=>{let T=await p.subscribe(f,this.createContext());if(!T)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!T[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let A of T)try{let R;if(A.type&&A.type!=="put"&&A.type!=="delete"&&A.type!=="message"&&A.type!=="patch"||s&&!s(A))continue;r?(A.topic=n,R=this.needsAcknowledge(A)):(A.acknowledge?.(),R=aA());let M=A.id;Array.isArray(M)&&(M=ba(M)),M==null&&(M=""),this.listener(h+"/"+M,A.value,R,t)}catch(R){(0,Li.warn)(R)}})(),T});return S.topic=n,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(s=>s.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){let r=this.createContext();je(r,async()=>{if(!t){let s=await Ol.get(this.sessionId,r);s?.doesExist()&&await cA(s,s.data,r)}await Ol.delete(this.sessionId,r)}).catch(s=>{(0,Li.warn)(`Error publishing MQTT will for ${this.sessionId}`,s)});for(let s of this.subscriptions)s.end();this.subscriptions=[]}};a(cA,"publish");uA=class extends PE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=aA(),s={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(s.acknowledge=t.acknowledge),this.awaitingAcks.set(r,s),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Li.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&this.saveSubscriptions(),t.qos}removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t),s=super.removeSubscription(t);return r.qos>0&&this.saveSubscriptions(),s}saveSubscriptions(){this.sessionRecord.subscriptions=this.subscriptions.map(t=>{let r=t.startTime;return r||(r=t.startTime=(0,tx.getNextMonotonicTime)()),(0,Li.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),oA.put(this.sessionRecord)}}});var dA={};qe(dA,{bypassAuth:()=>wne,start:()=>Cne});function wne(){ux=!0}function Cne({server:e,port:t,network:r,webSocket:s,securePort:n,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return s&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){Qr.debug("Received WSS connection for MQTT from",_._socket.remoteAddress);let{onMessage:f,onClose:E}=ax(_,(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=>{Qr.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},s))),(t||n)&&(c=e.socket(async _=>{let l;if(Qr.debug("Received connection for MQTT from",_.remoteAddress),u){if(_.authorized)try{let E=u.user;E!==null?((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null),(0,bl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&lA.notify({username:l.username,status:zr.AUTH_AUDIT_STATUS.SUCCESS,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})):Qr.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(E){Qr.error(E)}else if(u.required)return Qr.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&ux&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,cx.getSuperUser)(),Qr.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:f}=ax(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{Qr.info("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function ax(e,t,r,s,n){ox||(ox=!0,uu(d=>{vE>0&&d.push({metric:"mqtt-connections",connections:vE,byThread:!0})}));let i;vE++;let o,c={protocolVersion:4},u=(0,BE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){vE--,i||(i=!0,o?.disconnect(),n.sessions.delete(o),as(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{s?.then&&(s=await s),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{s=await st.getUser(d.username,d.password.toString(),r),(0,bl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&lA.notify({username:s.username,status:zr.AUTH_AUDIT_STATUS.SUCCESS,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,bl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&lA.error({username:s.username,status:zr.AUTH_AUDIT_STATUS.FAILURE,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!s&&n.requireAuthentication)return as(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(n.authorizeClient?.(d,s),d.will){let R=e.deserialize||(e.deserialize=Oo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?R(d.will.payload):void 0,delete d.will.payload}o=nx({user:s,...d}),o=await o,o.socket=e,r&&(o.request=r),n.sessions.add(o)}catch(R){return Qr.error(R),as(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:R.code||5,returnCode:R.code||128})}as(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((R,M,x,P)=>{try{let k=R.indexOf("/",1),B=k>0?R.slice(0,k):R;f({cmd:"publish",topic:R,payload:E(M),messageId:x||Math.floor(Math.random()*1e8),qos:P.qos},B)}catch(k){Qr.error(k),o?.disconnect(),n.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let R of d.subscriptions){let M;try{M=(await o.addSubscription(R,R.qos>=1)).qos||0}catch(x){Qr.error(x),M=c.protocolVersion<5?128:x.statusCode===403?135:x.statusCode===404?143:128}h.push(M)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let R=[];for(let M of d.unsubscriptions)R.push(o.removeSubscription(M)?0:17);f({cmd:"unsuback",granted:R,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(R){Qr.warn(R),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),n.sessions.delete(o),as(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){Qr.error(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,BE.generate)(h,c);t(S),kr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return bi(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var BE,cx,bl,zr,_A,lA,Qr,ux,ox,vE,lx=ge(()=>{BE=require("mqtt-packet");ix();cx=v(os());Na();wn();or();bl=v(ee()),zr=v(L()),_A=v($()),lA=(0,_A.loggerWithTag)("auth-event"),Qr=(0,_A.loggerWithTag)("mqtt"),ux=(0,bl.get)(zr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(wne,"bypassAuth");a(Cne,"start");vE=0;a(ax,"onSocket")});var Lf={};qe(Lf,{component_errors:()=>za,loadComponent:()=>HE,loadComponentDirectories:()=>Tx,setErrorReporter:()=>Une});function Tx(e,t){t&&(EA=t),e&&(hA=e);let r=[];if((0,ks.existsSync)(fA)){let n=(0,ks.readdirSync)(fA,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,At.join)(fA,o);r.push(HE(c,EA,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(HE(s,EA,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{Sx=!0})}function Une(e){Nl=e}async function HE(e,t,r,s,n,i){if(!dx.has(e)){dx.set(e,!0),n&&(hA=n);try{let o;s&&(za=new Map);let c=(0,At.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,ks.existsSync)(c)?o=s?(0,px.getConfigObj)():(0,fx.parseDocument)((0,ks.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=mA;let u=[],_=s;for(let l in o){let d=o[l];if(za.set(s?l:(0,At.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let A=e,R;for(;!(0,ks.existsSync)(R=(0,At.join)(A,"node_modules",l));)if(A=(0,At.dirname)(A),A.length<(0,mx.getHdbBasePath)().length){R=null;break}if(R)f=await HE(R,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=Mne[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(Qa.isMainThread&&(f=await f.startOnMainThread?.({server:st,ensureTable:h,port:T,securePort:S,resources:t,...d})||f,s&&p))for(let A of[T,S])try{if(+A&&!_x.includes(A)){let R=pA.get(SA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);R&&yl.default.warn("Session affinity is not recommended and may cause memory leaks"),(R||!OE)&&(_x.push(A),yH(A,R))}}catch(R){console.error("Error listening on socket",A,R,l)}if(t.isWorker&&(f=await f.start?.({server:st,ensureTable:h,port:T,securePort:S,resources:t,...d})||f),hA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,hx.handleHDBError)("Can not reference parent directories");let A=(0,At.join)(e,d.files).replace(/\\/g,"/"),R=A.indexOf("/*");if(R>-1&&d.files!==mA[l]?.files&&!(0,ks.existsSync)(A.slice(0,R)))throw new Error(`The path '${A.slice(0,R)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let M=(0,At.basename)(e),x=d.path||"/";x=x.startsWith("/")?x:x.startsWith("./")?"/"+M+x.slice(2):x==="."?"/"+M:"/"+M+"/"+x;let P,k,B;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",k=(0,At.join)(e,z)}else(B=A.indexOf("/*"))>-1&&(k=A.slice(0,B+1),P=(0,At.relative)(e,k));let X=!1;if(Qa.isMainThread&&f.setupDirectory&&(X=await f.setupDirectory?.(x,k,t)),t.isWorker&&f.handleDirectory&&(X=await f.handleDirectory?.(x,k,t)),X)continue;for(let z of await(0,Ex.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:J,dirent:me}=z;_=!0;let ce=(0,At.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=x+(x.endsWith("/")?"":"/")+ce;try{if(me.isFile()){let Le=await Lne(J);Qa.isMainThread&&await f.setupFile?.(Le,de,J,t),t.isWorker&&await f.handleFile?.(Le,de,J,t)}else Qa.isMainThread&&await f.setupDirectory?.(de,J,t),t.isWorker&&await f.handleDirectory?.(de,J,t)}catch(Le){Le.message=`Could not load ${me.isFile()?"file":"directory"} '${J}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${Le.message}`,Nl?.(Le),((0,Ja.getWorkerIndex)()===0?console:yl.default).error(Le),t.set(d.path||"/",new Il(Le)),za.set(s?l:(0,At.basename)(e),Le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,At.basename)(e)}' due to: ${h.message}`,Nl?.(h),((0,Ja.getWorkerIndex)()===0?console:yl.default).error(h),t.set(d.path||"/",new Il(h),null,!0),za.set(s?l:(0,At.basename)(e),h.message)}}if(Qa.isMainThread&&!Sx&&i&&(0,Ja.watchDir)(e,async()=>Tx()),o.extensionModule)return await u_((0,At.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;Nl?.(new Error(l)),((0,Ja.getWorkerIndex)()===0?console:yl.default).error(l),za.set((0,At.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Nl?.(o),t.set("",new Il(o))}}}var ks,At,Qa,fx,pA,SA,Ex,Ja,yl,hx,mx,Dne,px,Lne,fA,hA,Sx,EA,za,Mne,mA,_x,dx,Nl,Il,Mf=ge(()=>{ks=require("fs"),At=require("path"),Qa=require("worker_threads"),fx=require("yaml"),pA=v(ee()),SA=v(L());Sb();Ab();Ob();I0();EH();gH();Ex=v(require("fast-glob")),Ja=v(Ke()),yl=v($());Wh();or();hx=v(se());Ns();Re();NH();mx=v(ee()),Dne=v(LH());Of();GH();lx();px=v(lr());bE();({readFile:Lne}=ks.promises),fA=pA.get(SA.CONFIG_PARAMS.COMPONENTSROOT),hA=new Map,za=new Map;a(Tx,"loadComponentDirectories");Mne={REST:Jf,rest:Jf,graphqlSchema:Kh,jsResource:zh,fastifyRoutes:BR,login:Xh,static:HR,operationsApi:Dne,customFunctions:{},http:{},clustering:XR,authentication:Qu,mqtt:dA},mA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(mA,"static",{value:{files:"web/**"}});_x=[],dx=new Map;a(Une,"setErrorReporter");a(HE,"loadComponent");Il=class extends Ft{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var iA=g((ESe,Rx)=>{var{isMainThread:gx}=require("worker_threads"),{getTables:Pne}=(Re(),ie(Fe)),{loadComponentDirectories:vne,loadComponent:Bne}=(Mf(),ie(Lf)),{resetResources:Hne}=(Ku(),ie(BP)),xne=mg(),Gne=lr(),{dirname:qne}=require("path"),{getConnection:Fne}=it(),kne=ee(),Vne=L(),TA=new Map;async function $ne(e=!1){!gx&&kne.get(Vne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Fne();try{gx&&await xne()}catch(s){console.error(s)}let t=Hne();Pne(),t.isWorker=e,await Bne(qne(Gne.getConfigFilePath()),t,"hdb",!0,TA),await vne(TA,t);let r=[];for(let[s]of TA)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a($ne,"loadRootComponents");Rx.exports.loadRootComponents=$ne});var Ke=g((mSe,Ui)=>{"use strict";var{Worker:Yne,MessageChannel:Kne,parentPort:En,isMainThread:bA,threadId:Wne,workerData:$n}=require("worker_threads"),{PACKAGE_ROOT:Qne}=L(),{join:yx,isAbsolute:zne,extname:Jne}=require("path"),{server:Nx}=(or(),ie(xi)),{watch:Xne,readdir:jne}=require("fs/promises"),{totalmem:Ax}=require("os"),wl=L(),Ix=ee(),Yn=$(),{randomBytes:Zne}=require("crypto"),{_assignPackageExport:eie}=require("../index"),tie=L(),Ox=1024*1024,Mi=[],ps=[],rie=50,yA=1e4,sie="restart",wx="request_thread_info",Cx="resource_report",Dx="thread_info",Lx="added-port",nie="ack",gA;eie("threads",ps);Ui.exports={startWorker:RA,restartWorkers:IA,shutdownWorkers:uie,workers:Mi,setMonitorListener:pie,onMessageFromWorkers:lie,onMessageByType:xx,broadcast:die,broadcastWithAcknowledgement:Eie,setChildListenerByType:cie,getWorkerIndex:Mx,getWorkerCount:Ux,getTicketKeys:vx,setMainIsWorker:oie,setTerminateTimeout:iie,restartNumber:$n?.restartNumber||1};ps.onMessageByType=xx;ps.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ps.find(s=>s.threadId===e);if(r)return r.postMessage(t),!0};var NA;function iie(e){yA=e}a(iie,"setTerminateTimeout");function Mx(){return $n?$n.workerIndex:NA?0:void 0}a(Mx,"getWorkerIndex");function Ux(){return $n?$n.workerCount:NA?1:void 0}a(Ux,"getWorkerCount");function oie(e){NA=e}a(oie,"setMainIsWorker");var Px=1,xE;function vx(){return xE||(xE=bA?Zne(48):$n.ticketKeys,xE)}a(vx,"getTicketKeys");Object.defineProperty(Nx,"workerIndex",{get(){return Mx()}});Object.defineProperty(Nx,"workerCount",{get(){return Ux()}});var Bx={[wx](e,t){hie(t)},[Cx](e,t){mie(t,e)}};function RA(e,t={}){let r=process.constrainedMemory?.()||Ax();r=Math.min(r,Ax(),2e4*Ox);let s=Ix.get(wl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Ox/(10+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>6,16),64),i=[],o=[];for(let u of ps){let _=new Kne;_.existingPort=u,i.push(_),o.push(_.port2)}Jne(e)||(e+=".js");let c=new Yne(zne(e)?e:yx(Qne,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Px=t.threadCount,name:t.name,restartNumber:Ui.exports.restartNumber,ticketKeys:vx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Lx,port:u,threadId:c.threadId},[u]);return qE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>RA(e,t),c.on("error",u=>{console.error("Worker error:",u),Yn.error("Worker error:",u)}),c.on("exit",u=>{Mi.splice(Mi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<rie?(t.unexpectedRestarts=c.unexpectedRestarts+1,RA(e,t)):Yn.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{Bx[u.type]?.(u,c)}),Mi.push(c),Tie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(RA,"startWorker");var aie=[wl.THREAD_TYPES.HTTP];async function IA(e=null,t=Math.max(Px>3,1),r=!0){if(bA){if(r){let{loadRootComponents:o}=iA();await o()}Ui.exports.restartNumber++,t<1&&(t=t*Mi.length);let s=[],n=[];for(let o of Mi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Yn.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=aie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),yA*2).unref();o.on("exit",()=>{clearTimeout(l),s.splice(s.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(s.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===tie.ITC_EVENT_TYPES.CHILD_STARTED&&(Yn.trace("Worker has started",_.threadId),d(),n.splice(n.indexOf(l)),_.off("message",f))},"startListener");Yn.trace("Waiting for worker to start",_.threadId),_.on("message",f)});n.push(l),s.length>=t&&await Promise.race(s),n.length>=t&&await Promise.race(n)}}await Promise.all(s),await Promise.all(n);let{restartService:i}=Tf();r&&(e==="http"||!e)&&Ix.get(wl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else En.postMessage({type:sie,workerType:e})}a(IA,"restartWorkers");function cie(e,t){Bx[e]=t}a(cie,"setChildListenerByType");function uie(e){return IA(e,1/0,!1)}a(uie,"shutdownWorkers");var Hx=[];function lie(e){Hx.push(e)}a(lie,"onMessageFromWorkers");var AA=new Map;function xx(e,t){let r=AA.get(e);r||AA.set(e,r=[]),r.push(t)}a(xx,"onMessageByType");var _ie=10;async function die(e){let t=0;for(let r of ps)try{r.postMessage(e),t++>_ie&&(t=0,await new Promise(setImmediate))}catch(s){Yn.error("Unable to send message to worker",s)}}a(die,"broadcast");var GE=new Map,fie=1;function Eie(e){return new Promise(t=>{let r=0;for(let s of ps)try{let n=fie++,i=a(()=>{GE.delete(n),--r===0&&t(),s!==En&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,GE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of GE)o.port===s&&o()})),s.postMessage(e),r++}catch(n){Yn.error("Unable to send message to worker",n)}r===0&&t()})}a(Eie,"broadcastWithAcknowledgement");function hie(e){e.postMessage({type:Dx,workers:Gx()})}a(hie,"sendThreadInfo");function Gx(){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(Gx,"getChildWorkerInfo");function mie(e,t){e.resources=t,e.resources.updated=Date.now()}a(mie,"recordResourceReport");var OA;function pie(e){OA=e}a(pie,"setMonitorListener");var Sie=1e3,bx=!1;function Tie(){bx||(bx=!0,setInterval(()=>{for(let e of Mi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}OA&&OA()},Sie).unref())}a(Tie,"startMonitoring");var gie=1e3;if(En){qE(En);for(let e=0,t=$n.addPorts.length;e<t;e++){let r=$n.addPorts[e];r.threadId=$n.addThreadIds[e],qE(r)}setInterval(()=>{let e=process.memoryUsage();En.postMessage({type:Cx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},gie).unref(),gA=a(()=>new Promise((e,t)=>{En.on("message",r),En.postMessage({type:wx});function r(s){s.type===Dx&&(En.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else gA=Gx;Ui.exports.getThreadInfo=gA;function qE(e,t){ps.push(e),e.on("message",r=>{if(r.type===Lx)r.port.threadId=r.threadId,qE(r.port);else if(r.type===nie){let s=GE.get(r.id);s&&s()}else{for(let n of Hx)n(r,e);let s=AA.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){Yn.error(i)}}}).on("close",()=>{ps.splice(ps.indexOf(e),1)}).on("exit",()=>{ps.splice(ps.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(qE,"addPort");if(bA){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await jne(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(yx(s,i.name));try{for await(let{filename:i}of Xne(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await IA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",s,i)}},"watch_dir");Ui.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else En.on("message",async e=>{let{type:t}=e;t===wl.ITC_EVENT_TYPES.SHUTDOWN&&(Ui.exports.restartNumber=e.restartNumber,En.unref(),setTimeout(()=>{Yn.warn("Thread did not voluntarily terminate",Wne),process.exit(0)},yA).unref())})});var CC={};qe(CC,{AUDIT_STORE_OPTIONS:()=>Ef,createAuditEntry:()=>E_,openAuditStore:()=>$E,readAuditEntry:()=>Mt,setAuditRetention:()=>Aie,transactionKeyEncoder:()=>Qx});function $E(e){let t=e.auditStore=e.openDB(Yx.AUDIT_STORE_NAME,Ef);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let s=null;function n(i=FE){clearTimeout(s),s=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-wA})){if((_[0]&15)===LA){let l=Mt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Rie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,wA/10)),n(i)}},i).unref()}return a(n,"scheduleAuditCleanup"),t.scheduleAuditCleanup=n,(0,VE.getWorkerIndex)()===(0,VE.getWorkerCount)()-1&&n(FE),t}function Aie(e,t=FE){wA=e,FE=t}function E_(e,t,r,s,n,i,o){let c=zx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;s&&(s>1?Xa.setFloat64(0,s):Ss.set(fm),u=9),f(0),f(t),d(r),Xa.setFloat64(u,e),u+=8,n?d(n):Ss[u++]=0,Ss[s?8:0]=c;let l=Ss.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,ja.writeKey)(E,Ss,u);let p=u-h-1;p>127?p>16383?(UA.error("Key or username was too large for audit entry",E),u=h+1,Ss[h]=0):(Ss.copyWithin(h+2,h+1,u),Xa.setUint16(h,p|32768),u++):Ss[h]=p}function f(E){E<128?Ss[u++]=E:E<16384?(Xa.setUint16(u,E|32768),u+=2):E<1056964608?(Xa.setUint32(u,E|3221225472),u+=4):(Ss[u]=255,Xa.setUint32(u+1,E),u+=5)}}function Mt(e){try{let t=e.dataView||(e.dataView=new MA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let s=t.readInt(),n=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:zx[s&7],tableId:i,get recordId(){return $x(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?$x(e,l,d):void 0},getValue(f,E,h){if(s&CA||s&DA&&!E)return f.decoder.decode(e.subarray(t.position));if(s&DA&&h)return PA(f.getEntry(this.recordId),h,f)}}}catch(t){return UA.error("Reading audit entry error",t,e),{}}}function $x(e,t,r){let s=e.subarray(t,r);return(0,ja.readKey)(s,0,r-t)}var ja,kE,Yx,Kx,VE,Wx,UA,Ss,Xa,Qx,Ef,wA,Rie,FE,CA,DA,qx,LA,Fx,kx,Vx,zx,MA,ei=ge(()=>{ja=require("ordered-binary"),kE=v(ee()),Yx=v(ut()),Kx=v(L()),VE=v(Ke()),Wx=v(Q());Ic();UA=v($());YE();(0,kE.initSync)();Ss=Buffer.alloc(1024),Xa=new DataView(Ss.buffer,Ss.byteOffset,1024),Qx={writeKey(e,t,r){return e===Nc?(t.set(Nc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,ja.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,ja.readKey)(e,t,r)}},Ef={encoding:"binary",keyEncoder:Qx},wA=(0,Wx.convertToMS)((0,kE.get)(Kx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Rie=1e3,FE=1e4;a($E,"openAuditStore");a(Aie,"setAuditRetention");CA=16,DA=32,qx=1,LA=2,Fx=3,kx=4,Vx=5,zx={put:qx|CA,[qx]:"put",delete:LA,[LA]:"delete",message:Fx|CA,[Fx]:"message",invalidate:kx,[kx]:"invalidate",patch:Vx|DA,[Vx]:"patch"};a(E_,"createAuditEntry");a(Mt,"readAuditEntry");MA=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a($x,"readKeySafely")});var vA={};qe(vA,{add:()=>KE,applyReverse:()=>Jx,getRecordAtTime:()=>PA,rebuildUpdateBefore:()=>WE});function KE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function WE(e,t){let r=null;for(let s in e)if(s in t){let n=t[s];if(n?.__op__){let i=e[s];if(i?.__op__)if(i.__op__===n.__op__)r||(r={}),r[s]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[s]=i,KE(r,s,n)}}else r||(r={}),r[s]=e[s];return r}function Jx(e,t){for(let r in t){let s=t[r];if(s?.__op__){let n=Oie[s.__op__]?.reverse;if(n)n(e,r,{value:s.value});else throw new Error(`Unsupported operation ${s.__op__}`)}else e[r]=Xx}}function PA(e,t,r){let s=r.rootStore.auditStore,n=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=s.get(i),_=Mt(u);switch(_.type){case"put":n=_.getValue(r);break;case"patch":Jx(n,_.getValue(r));break;case"delete":n=null}i=_.previousLocalTime}let o={},c=0;for(let u in n)n[u]===Xx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=s.get(i),_=Mt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(n[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)n[u]=null;return n}var Oie,Xx,YE=ge(()=>{ei();a(KE,"add");KE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Oie={add:KE};a(WE,"rebuildUpdateBefore");a(Jx,"applyReverse");Xx={};a(PA,"getRecordAtTime")});function Jr(e){return e[Ct]||(e[Ct]=Object.create(null))}function jE(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[ye])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new Ts.ClientError(`${c} must be a string, attempt to assign ${l}`);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 Ts.ClientError(`${c} must be a string, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new Ts.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new Ts.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new Ts.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new Ts.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Ts.ClientError(`${c} must be a boolean, attempt to assign ${l}`);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 Ts.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 Ts.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 Ts.ClientError(`${c} must be an object, attempt to assign ${l}`);Jr(this)[c]=l},"set")}_={get(){let l=this[Ct];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=Zx(d,o);if(f)return l||(l=this[Ct]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,s[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Ct];return u?.[o]!==void 0?u[o]:this[_e]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Ts.ClientError("Can not add a property to a sealed table schema");Jr(this)[o]=c}),i("deleteProperty",function(o){Jr(this)[o]=void 0}),i("toJSON",function(){let o=this[Ct],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 Zx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){if(n?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=n}},jE(r,t)),new r(e)):new QE(e);case Array:let s=new JE(e.length);s[_e]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=Zx(o,t?.elements)),s[n]=o}return s;default:return e}}function ld(e){let t=e[Ct],r;for(let n in t){r||(r=Object.assign({},e[_e]));let i=t[n];if(i&&typeof i=="object")if(i.__op__){let o=r[n];i=i.update(o)}else i=ld(i);r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[_e])),Object.assign(r,e)),r||e[_e]}function Uo(e,t=e[Ct]){let r;if(jx.call(e,_e)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=Uo(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[s]=i}return Object.freeze(r)}for(let s in t){r||(r=Object.assign({},e[_e]));let n=t[s];if(n&&typeof n=="object")if(n.__op__){let i=vA[n?.__op__];if(i)i(r,s,n);else throw new Error("Invalid CRDT operation "+n.__op__);continue}else n=Uo(n);r[s]=n}return r?Object.freeze(r):jx.call(e,_e)?e[_e]:e}function zE(e){let t=e[_e];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Mo]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[_e]===n){if(zE(i))return!0}else return!0}}else{let r=e[Ct];if(r&&!t)return!0;for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[_e]===i){if(zE(n))return!0}else return!0}else return!0}}return!1}var Ts,Ct,QE,jx,Mo,JE,XE,_d=ge(()=>{Ns();Ts=v(se());YE();Ct=Symbol("own-data");a(Jr,"getChanges");a(jE,"assignTrackedAccessors");a(Zx,"trackObject");QE=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}};jE(QE,{});a(ld,"collapseData");jx=Object.prototype.hasOwnProperty;a(Uo,"deepFreeze");a(zE,"hasChanges");Mo=Symbol.for("has-array-changes"),JE=class extends Array{static{a(this,"TrackedArray")}[Mo];constructor(t){super(t)}splice(...t){return this[Mo]=!0,super.splice(...t)}push(...t){return this[Mo]=!0,super.push(...t)}pop(){return this[Mo]=!0,super.pop()}unshift(...t){return this[Mo]=!0,super.unshift(...t)}shift(){return this[Mo]=!0,super.shift()}};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:()=>ye,ID_PROPERTY:()=>Me,IS_COLLECTION:()=>gs,RECORD_PROPERTY:()=>_e,Resource:()=>Ft,snake_case:()=>yie,transformForSelect:()=>eh});function yie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function eG(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("/"),s=new HA;for(let n=0;n<r.length;n++){let i=r[n];if(!i&&n===r.length-1){Cl=!0;break}s[n]=t.coerceId(decodeURIComponent(i))}return s}function Xr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[ye]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[ye]||i):l=i:(l=n,c=l[Me]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[ye]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(o=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[],_=!0;for(let E of n){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=n.id??null,c==null&&(_=!0))}else c=n??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return je(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 ZE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new ZE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function jr(e,t){let r=new sG.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function BA(e,t,r){let s=e[_e];if(s){let n=e[Ct];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:n&&i in n?n[i]:(c=t?.[i])?c(e,r):s[i]}}else return t?n=>{let i=t[n];return i?i(e,r):e[n]}:n=>e[n]}function eh(e,t){let r=t?.propertyResolvers,s=t[ye],n;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):BA(c,r,s)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(BA(u,r,s));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(BA(u,r,s)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){n||(n={});let u=n[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=n[c.name]=eh(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var tG,rG,sG,ye,Me,gs,_e,bie,Ft,ZE,Cl,HA,Ns=ge(()=>{tG=require("crypto");gc();rG=require("../index"),sG=v(se());_d();so();Qf();ye=Symbol.for("context"),Me=Symbol.for("primary-key"),gs=Symbol("is-collection"),_e=Symbol("stored-record"),bie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Ft=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Me]=t;let s=r?.[ye];this[ye]=s!==void 0?s:r||null}static get=Xr(function(t,r,s,n){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=eh(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,s,n){if(Array.isArray(n)&&t[gs]){let i=[],o=s.authorize;for(let c of n){let u=t.constructor,_=u.getResource(c[u.primaryKey],s,{async:!0});_.then?i.push(_.then(l=>l.put(c,s))):i.push(_.put(c,s))}return Promise.all(i)}return t.put?t.put(n,r):jr(t,"put")},{hasContent:!0,type:"update"});static patch=Xr(function(t,r,s,n){return t.patch?t.patch(n,r):jr(t,"patch")},{hasContent:!0,type:"update"});static delete=Xr(function(t,r,s,n){return t.delete?t.delete(r):jr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,tG.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),je(s,()=>{let i=new this(n,s),o=i.update?i.update(r,!0):jr(i,"update");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=Xr(function(t,r,s,n){return t.invalidate?t.invalidate(r):jr(t,"delete")},{hasContent:!1,type:"update"});static post=Xr(function(t,r,s,n){return t[Me]!=null&&t.update?.(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Xr(function(t,r,s,n){return t.connect?t.connect(n,r):jr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Xr(function(t,r,s,n){return t.subscribe?t.subscribe(r):jr(t,"subscribe")},{type:"read"});static publish=Xr(function(t,r,s,n){return t[Me]!=null&&t.update?.(),t.publish?t.publish(n,r):jr(t,"publish")},{hasContent:!0,type:"create"});static search=Xr(function(t,r,s,n){let i=t.search?t.search(r):jr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=eh(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Xr(function(t,r,s,n){return t.search?t.search(n,r):jr(t,"search")},{hasContent:!0,type:"read"});static copy=Xr(function(t,r,s,n){return t.copy?t.copy(n,r):jr(t,"copy")},{type:"create"});static move=Xr(function(t,r,s,n){return t.move?t.move(n,r):jr(t,"move")},{type:"delete"});post(t){if(this[gs])return this.constructor.create(this[Me],t,this[ye]);jr(this,"post")}static isCollection(t){return t?.[gs]}static coerceId(t){return t}static parseQuery(t){return Wf(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let o=t.slice(n+1);t=t.slice(0,n);let c=r?.headers&&bie[o];if(c)r.headers.set("accept",c);else if(s)s.property=o;else return{query:{property:o},id:eG(t,this),isCollection:Cl}}let i=eG(t,this);return Cl?{id:i,isCollection:!0}:i}static getResource(t,r,s){let n,i=r[ye],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=s?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(n=_?.find(l=>l.constructor===c),n)return n;_||u.asMap.set(t,_=[]),_.push(n=new c(t,i))}else{if(n=u.find(_=>_[Me]===t&&_.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Me],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else n=new c(t,i);return o&&(n[gs]=!0),n}subscribe(t){return new ys}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new ys}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Me]}getContext(){return this[ye]}};Ft.prototype[ye]=null;(0,rG._assignPackageExport)("Resource",Ft);a(yie,"snake_case");ZE=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(eG,"pathToId");HA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Xr,"transactional");a(jr,"missingMethod");a(BA,"selectFromObject");a(eh,"transformForSelect")});function iG(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;Za||((0,th.onMessageByType)(nG,l=>{oG(l.path)}),Za=Object.create(null));let o=Za[n]||(Za[n]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=ba(t);let u=new GA(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function oG(e,t){if(!Za)return;let r=Za[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(n){throw n.message+=" in "+e,n}let s;for(let{key:n,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=n;let o=Mt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=ba(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=n){(0,xA.info)("omitting",u,h.startTime,n);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(s?s.push(h):s=[h]),h.txnInProgress=o.version),h.listener(u,o,n,p)}catch(p){console.error(p),(0,xA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(s)for(let n of s)n.txnInProgress=null,n.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function aG(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",()=>{(0,th.broadcast)({type:nG,path:n}),oG(n,!0)})}}var xA,th,nG,Za,xSe,GA,cG=ge(()=>{xA=v($()),th=v(Ke());gc();Ku();ei();nG="transaction",xSe=Buffer.alloc(4096);a(iG,"addSubscription");GA=class extends ys{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(oG,"notifyFromTransactionData");a(aG,"listenToCommits")});var TR={};qe(TR,{coerceType:()=>rh,makeTable:()=>ih,setServerUtilities:()=>Pie,updateResource:()=>sh});function ih(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,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=[]),aG(i,u);let T=mm(i,s,u),A=0,R,M,x={},P=Promise.resolve(),k,B,X;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(B=K),K.expiresAt&&(X=K),K.isPrimaryKey&&(x=K);let z,J=[],me=[],ce=1,de=2,Le={},Be={},Lt=864e5,Wl,Ql,Qn,oO=!1,Ah,Oh,dq=i.getRange({start:!1,end:!1}).constructor,fq=10,Eq=6;h&&uO();class ze extends Ft{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=k;static updatedTimeProperty=B;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),M=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(D=>{let N=this.sources.slice(0,-1);if(N=N.filter(U=>U[D]&&(!U[D].reliesOnPrototype||U.prototype[D])),N.length>0)if(N.length===1){let U=N[0];return(F,C,H)=>{if(F?.source!==U)return U[D](C,H,F)}}else return(U,F,C)=>{let H=[];for(let G of N){if(U?.source===G)break;H.push(G[D](F,C,U))}return Promise.all(H)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],b=a(D=>{if(y[D]&&(!y[D].reliesOnPrototype||y.prototype[D]))return(N,U,F)=>{if(!N?.source)return y[D](U,F,N)}},"getApplyToCanonicalSource");return Le={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},Be={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let D=!1,N=a(async(U,F)=>{let C=U.value,H=U.table?nt[c][U.table]:ze;if(c===$s.SYSTEM_SCHEMA_NAME&&(U.table===$s.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===$s.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),U.id===void 0&&(U.id=C[H.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let G=await H.getResource(U.id,F,ec);switch(U.type){case"put":return G._writeUpdate(C,!0,ec);case"patch":return G._writeUpdate(C,!1,ec);case"delete":return G._writeDelete(ec);case"publish":return G._writePublish(C,ec);case"invalidate":return G.invalidate(ec);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,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,C=U&&F&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let H;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,H)if(G.beginTxn)H.resolve();else{N(G,H);continue}if(G.type==="end_txn")continue;let pe=je(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ae}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ae of G.attributes)te.find(Ge=>Ge.name===ae.name)||(te.push(ae),Pe=!0);Pe&&(lt({table:n,database:c,attributes:te,origin:"cluster"}),Bl.signalSchemaChange(new Hl.SchemaEventMsg(process.pid,$s.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return G.beginTxn?(H=G,N(G,G),new Promise(te=>{H.resolve=te})):N(G,G)});D&&(await pe,Bl.signalUserChange(new Hl.UserEventMsg(process.pid))),G.onCommit&&(pe?.then?pe.then(G.onCommit):G.onCommit())}catch(ne){tt.error("error in subscription handler",ne)}}}catch(U){tt.error(U)}})(),this}static getResource(m,O,I){let y=super.getResource(m,O,I);if(m!=null){ic(m);try{if(y.hasOwnProperty(_e))return y;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=Os(O),N=D.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return bh(m,O,{transaction:N},b,U=>{if(U?sh(y,U):y[_e]=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new Rs.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let F=yh(m,U,O,y);if(F)return D?.disregardReadTxn(),y[qA]=!0,kA(F,C=>(sh(y,C),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return y}ensureLoaded(){let m=yh(this[Me],this[Zr],this[ye]);if(m)return this[qA]=!0,kA(m,O=>{this[Zr]=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,Lt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(f<0)throw new Error("Expiration can not be negative");Lt=Lt||(f+E)/4,Ih()}static enableAuditing(m=!0){h=m,m&&uO(),ze.audit=m}static coerceId(m){return m===""?null:rh(m,x)}static async dropTable(){if(delete nt[c][n],c===o){for(let m of S)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Bl.signalSchemaChange(new Hl.SchemaEventMsg(process.pid,$s.OPERATIONS_ENUM.DROP_TABLE,c,n))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[gs])return this.search(m);if(this[Me]===null){if(m?.conditions)return this.search(m);let O=ze.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:n,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,O){let I=Jl(m);if(I?.read){if(I.isSuperUser)return!0;let y=I.attribute_permissions,b=O?.select;if(y?.length>0||oO&&b){if(O||(O={}),b){let D=y?.length>0&&FA(y,"read");O.select=b.map(N=>{let U=N.name||N;if(!D||D[U]){let F=Qn[U]?.definition?.tableClass;if(F){if(N.name||(N={name:N}),!F.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else O.select=y.filter(D=>D.read&&!Qn[D.attribute_name]).map(D=>D.attribute_name);return O}else return!0}}allowUpdate(m,O){let I=Jl(m);if(I?.update){let y=I.attribute_permissions;if(y?.length>0){let b=FA(y,"update");for(let D in O)if(!b[D])return!1;for(let D of y){let N=D.attribute_name;!D.update&&!(N in O)&&(O[N]=this.getProperty(N))}}return!0}}allowCreate(m,O){if(this[gs]){let I=Jl(m);if(I?.insert){let y=I.attribute_permissions;if(y?.length>0){let b=FA(y,"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(!Os(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[_e]={},this[Ct]=m):(y=this[Ct],y&&(m=Object.assign(y,m)),this[Ct]=y=m)),this._writeUpdate(this[Ct],O),this}addTo(m,O){if(typeof O=="number")this[Dl]===lG?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[ye],I=this[Me];ic(I),Os(this[ye]).addWrite({key:I,store:i,invalidated:!0,entry:this[Zr],nodeName:this[ye]?.nodeName,before:Le.invalidate?.bind(this,O,I),beforeIntermediate:Be.invalidate?.bind(this,O,I),commit:(b,D)=>{if(D?.version>b)return;let N=null;for(let U in r)N||(N={}),N[U]=this.getProperty(U);T(I,N,this[Zr],b,Ll,h,this[ye],0,"invalidate")}})}static evict(m,O,I){let y=this.Source,b;if(!((M||h)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==I))){if(M){if(i.hasLock(m,b.version))return;let D;for(let N in r)D||(D={}),D[N]=O[N];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||=n,m.schema||=c,mG.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,I){let y=this[ye],b=Os(y),D=this[Me];ic(D);let N=this[Zr];this[Dl]=O?lG:Lie;let U={key:D,store:i,entry:N,nodeName:y?.nodeName,validate:F=>{m||(m=this[Ct]),O||m&&zE(m)?y?.source||(b.checkOverloaded(),this.validate(m,!O),B&&(m[B.name]=B.type==="Date"?new Date(F):B.type==="String"?new Date(F).toISOString():F),O&&(t&&m[t]!==D&&(m[t]=D),k&&(N?.value?m[k.name]=N?.value[k.name]:m[k.name]=k.type==="Date"?new Date(F):k.type==="String"?new Date(F).toISOString():F),m=Uo(m))):b.removeWrite(U)},before:O?Le.put?()=>Le.put(y,D,m):null:Le.patch?()=>Le.patch(y,D,m):Le.put?()=>Le.put(y,D,Uo(this)):null,beforeIntermediate:O?Be.put?()=>Be.put(y,D,m):null:Be.patch?()=>Be.patch(y,D,m):Be.put?()=>Be.put(y,D,Uo(this)):null,commit:(F,C,H)=>{if(H){if(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),this[Zr]=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[Ct]=m,this[Pl]=F;let G=C?.value,ne=m;if(this[Dl]=0,C?.version>=F)if(h){let ae=C.localTime,Ge=C.version;for(;ne&&(ae>F||Ge>=F&&ae>0);){let re=u.get(ae);if(!re)break;let j=Mt(re);if(Ge=j.version,Ge>F){if(j.type==="patch"){let Oe=j.getValue(i);ne=WE(ne,Oe)}else if(j.type==="put"||j.type==="delete")return}else if(Ge===F)return;ae=j.previousLocalTime}}else{if(O)return;ne=WE(ne,G)}let pe;if(O?pe=ne:(this[_e]=G,pe=O?ne:Uo(this,ne)),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 Pe=O?"put":"patch";T(D,pe,C,F,0,h,y,y.expiresAt||(f?f+Date.now():0),Pe,!1,te)}};b.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[gs]){for await(let O of this.search(m))(await ze.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[_e]?this._writeDelete(m):!1}_writeDelete(m){let O=Os(this[ye]),I=this[Me];ic(I);let y=this[ye];return O.addWrite({key:I,store:i,resource:this,nodeName:y?.nodeName,before:Le.delete?.bind(this,y,I),beforeIntermediate:Be.delete?.bind(this,y,I),commit:(b,D,N)=>{let U=D?.value;N&&(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),sh(this,D)),!(D?.version>b)&&(zl(this[Me],U),tt.trace("Write delete entry",I,b),h||p?(T(I,null,this[Zr],b,0,h,this[ye],0,"delete"),h||Ih()):i.remove(this[Me]))}}),!0}search(m){let O=this[ye],I=Os(O);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Me]&&(y=[{attribute:null,comparator:"prefix",value:this[Me]}].concat(y));let b,D={};function N(j,Oe){let He;switch(Oe){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');He=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Oe)}let Ys=He&&{},zn;for(let Ye of j){if(Ye.conditions){Ye.conditions=N(Ye.conditions,Ye.operator);continue}let Gt=Ye[0]??Ye.attribute,rs=Gt==null?x:Gn(S,Gt);if(rs){if(He){let Ks=Gs(Gt),qt=Ys[Ks];qt?(qt.push(Ye),zn=!0):Ys[Ks]=[Ye]}(rs.type||Yg[Ye.comparator])&&(Ye[1]===void 0?Ye.value=F(Ye.value,rs):Ye[1]=F(Ye[1],rs))}else if(Gt!=null)throw(0,Rs.handleHDBError)(new Error,`${Gt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(zn)for(let Ye in Ys){let Gt=Ys[Ye],rs=Gt.length;if(rs>1)for(let Ks=0;Ks<rs;Ks++){let qt=Gt[Ks];if(qt.comparator==="ge"||qt.comparator==="greater_than_equal")for(let Jn=0;Jn<rs;Jn++){let Go=Gt[Jn];(Go.comparator==="le"||Go.comparator==="less_than_equal")&&(qt.comparator="between",qt.value=[qt.value,Go.value],j.splice(j.indexOf(Go),1))}if(qt.comparator==="equals"||!qt.comparator){for(let Jn=0;Jn<rs;Jn++)if(Jn!==Ks){let Go=Gt[Jn];j.splice(j.indexOf(Go),1)}break}}}return j}a(N,"prepareConditions");function U(j,Oe){if(m.enforceExecutionOrder)return j;for(let He of j)He.conditions&&(He.conditions=U(He.conditions,He.operator));return j.length>1&&Oe!=="or"?(0,hG.sortBy)(j,Kf(ze)):j}a(U,"orderConditions");function F(j,Oe){return Array.isArray(j)?j.map(He=>rh(He,Oe)):rh(j,Oe)}a(F,"coerceTypedValues");let C=m.operator;(y.length>0||C)&&(y=N(y,C));let H=typeof m.sort=="object"&&m.sort,G;if(H&&C!=="or"){let j=H.attribute;if(b=y.find(Oe=>Gs(Oe.attribute)===Gs(j)),!b){if(!Gn(S,j))throw(0,Rs.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);b={attribute:j,comparator:"sort"},y.push(b)}b.descending=!!H.descending}y=U(y,C),H&&(y[0]===b?H.next&&(G={dbOrderedAttribute:H.attribute,attribute:H.next.attribute,descending:H.next.descending,next:H.next.next}):(b&&y.splice(y.indexOf(b),1),G=H));let ne=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:C,postOrdering:G,selectApplied:!!ne};let pe=I.useReadTxn(),te=Kg(y,C,ze,pe,m,O,(j,Oe)=>aO(j,ne,O,pe,Oe),D),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ae=ze.transformEntryForSelect(ne,O,pe,D,Pe,!0),Ge=ze.transformToOrderedSelect(te,ne,G,pe,O,ae);function re(j){return m.offset||m.limit!==void 0?j.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):j}return a(re,"applyOffset"),G&&(Ge=re(Ge)),Ge.onDone=()=>{Ge.onDone=null,I.doneReadTxn()},Ge.selectApplied=!0,Ge.getColumns=()=>{if(ne){let j=[];for(let Oe of ne)Oe==="*"?j.push(...S.map(He=>He.name)):j.push(Oe.name||Oe);return j}return S.map(j=>j.name)},Ge}static transformToOrderedSelect(m,O,I,y,b,D){let N=new dq;if(I){m=aO(m,O,y,b,null);let U;N.iterate=function(){let C,H=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,ne=I.dbOrderedAttribute,pe,te,Pe=!0;function ae(re){let j=re.next&&ae(re.next),Oe=re.descending;return(He,Ys)=>{let zn=Nh(He,re.attribute,y),Ye=Nh(Ys,re.attribute,y),Gt=Oe?(0,Bo.compareKeys)(Ye,zn):(0,Bo.compareKeys)(zn,Ye);return Gt===0?j?.(He,Ys)||0:Gt}}a(ae,"createComparator");let Ge=ae(I);return{async next(){let re;if(C)if(re=C.next(),re.done){if(G)return N.onDone&&N.onDone(),re}else return{value:await D.call(this,re.value)};U=[],pe&&U.push(pe);do if(re=await H.next(),re.done){if(G=!0,U.length)break;return N.onDone&&N.onDone(),re}else{let j=re.value;if(j?.then&&(j=await j),ne){let Oe=Nh(j,ne,y);if(Pe)Pe=!1,te=Oe;else if(Oe!==te){te=Oe,pe=j;break}}U.push(j)}while(!0);return I.isGrouped,U.sort(Ge),C=U[Symbol.iterator](),re=C.next(),re.done?(N.onDone&&N.onDone(),re):{value:await D.call(this,re.value)}},return(){N.onDone&&N.onDone(),H.return()},throw(){N.onDone&&N.onDone(),H.throw()}}};let F=a(C=>{if(typeof O=="object"&&Array.isArray(C.attribute))for(let H=0;H<O.length;H++){let G=O[H],ne;if(G.name===C.attribute[0]){for(ne=G.sort||(G.sort={});ne.next;)ne=ne.next;ne.attribute=C.attribute.slice(1),ne.descending=C.descending}else G===C.attribute[0]&&(O[H]=ne={name:G,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&F(C.next)},"applySortingOnSelect");F(I)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(D);return N}static transformEntryForSelect(m,O,I,y,b,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(H=>H?.key??H,"transform");return m===t?C:m.asArray?H=>[C(H)]:H=>({[t]:C(H)})}let N;b&&M&&!m?.every(C=>{let H;return typeof C=="object"?H=C.name:H=C,r[H]||H===t})&&(N=!0);let U,F=a(function(C){let H;if(C!=null){if(Ah=C,H=C.value||C.deref?.(),!H&&(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));H=C?.value}if(N&&(C.metadataFlags&(Ll|Ml)||C.expiresAt&&C.expiresAt<Date.now())){let G=yh(C.key??C,C,O);if(G?.then)return G.then(F)}}if(H==null)return D?Po.SKIP:H;if(m&&!(m[0]==="*"&&m.length===1)){let G,ne=a((te,Pe)=>{let ae;typeof te=="object"?ae=te.name:ae=te;let Ge=Qn?.[ae],re;if(Ge){let j=y?.[ae];if(j)if(j.hasMappings){let He=Ge.from?H[Ge.from]:Gs(C.key);re=j.get(He),re||(re=[])}else re=j.fromRecord?.(H);else re=Ge(H,O,C);let Oe=a(He=>{if(He&&typeof He=="object"){let Ys=Ge.definition?.tableClass||ze;U||(U={});let zn=U[ae]||(U[ae]=Ys.transformEntryForSelect(ae===te?null:te.select||(Array.isArray(te)?te:null),O,I,j,b));if(Array.isArray(He)){let Ye=[],Gt=Ys.transformToOrderedSelect(He,te.select,typeof te.sort=="object"&&te.sort,O,I,zn)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),rs=a(qt=>{for(;!qt.done;){if(qt?.then)return qt.then(rs);Ye.push(qt.value),qt=Gt.next()}Pe(Ye,ae)},"nextValue"),Ks=rs(Gt.next());Ks&&(G||(G=[]),G.push(Ks));return}else if(He=zn.call(this,He),He?.then){G||(G=[]),G.push(He.then(Ye=>Pe(Ye,ae)));return}}Pe(He,ae)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(Oe))):Oe(re);return}else re=H[ae],re&&typeof re=="object"&&ae!==te&&(re=ze.transformEntryForSelect(te.select||te,O,I,null)({value:re}));Pe(re,ae)},"selectAttribute"),pe;if(typeof m=="string")ne(m,te=>{pe=te});else if(Array.isArray(m))if(m.asArray)pe=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=H:ne(te,ae=>pe[Pe]=ae)});else{pe={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ae in H)pe[ae]=H[ae];else ne(Pe,(ae,Ge)=>{ae===void 0&&te&&(ae=null),pe[Ge]=ae})}else throw new Rs.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>pe):pe}return H},"transform");return F}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||lt({table:n,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let O=!m.rawEvents,I=iG(ze,this[Me]??null,function(N,U,F,C){try{let H=U.getValue?.(i,O);if(!H&&U.type==="patch"&&O){let G=i.getEntry(N);G?.version===U.version?H=G.value:H=U.getValue?.(i,!0,F),U.type="put"}this.send({id:N,timestamp:F,value:H,version:U.version,type:U.type,beginTxn:C})}catch(H){tt.error(H)}},m.startTime||0,this[gs]);this[gs]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let y=this[Me],b=m.previousCount;b>1e3&&(b=1e3);let D=m.startTime;if(this[gs]){if(D){if(b)throw new Rs.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:D,exclusiveStart:!0})){let F=Mt(U);if(F.tableId!==s)continue;let C=F.recordId;if(y==null||fG(y,C)){let H=F.getValue(i,O,N);I.send({id:C,timestamp:N,value:H,version:F.version,type:F.type})}I.startTime=N}}else if(b){let N=[];for(let{key:U,value:F}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Mt(F);if(C.tableId!==s)continue;let H=C.recordId;if(y==null||fG(y,H)){let G=C.getValue(i,O,U);if(N.push({id:H,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=N.length;U>0;)I.send(N[--U]);N[0]&&(I.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:F,localTime:C}of i.getRange({start:y??!1,end:y==null?void 0:[y,Bo.MAXIMUM_KEY],versions:!0}))U&&I.send({id:N,timestamp:C,value:U,version:F,type:"put"})}else{b&&!D&&(D=0);let N=this[Zr]?.localTime;if(N===hm&&(i.cache?.delete(y),this[Zr]=i.getEntry(y),tt.trace("re-retrieved record",N,this[Zr]?.localTime),N=this[Zr]?.localTime),tt.trace("Subscription from",D,"from",y,N),D<N){let U=[],F=N;do{let C=u.get(F);if(C){m.omitCurrent=!0;let H=Mt(C),G=H.getValue(i,O,F);O&&(H.type="put"),U.push({id:y,value:G,timestamp:F,...H}),F=H.previousLocalTime}else break;b&&b--}while(F>D&&b!==0);for(let C=U.length;C>0;)I.send(U[--C]);I.startTime=N}!m.omitCurrent&&this.doesExist()&&I.send({id:y,timestamp:N,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=Os(this[ye]),y=this[Me]||null;ic(y);let b=this[ye];I.addWrite({key:y,store:i,entry:this[Zr],nodeName:b?.nodeName,validate:()=>{b?.source||(I.checkOverloaded(),this.validate(m))},before:Le.publish?.bind(this,b,y,m),beforeIntermediate:Be.publish?.bind(this,b,y,m),commit:(D,N,U)=>{N===void 0&&p&&!h&&Ih(),T(y,N?.value??null,N,N?.version||D,0,!0,b,N?.expiresAt,"message",!1,m)}})}validate(m,O){let I,y=a((b,D,N)=>{if(D.type&&b!=null)if(O&&b.__op__&&(b=b.value),D.properties){typeof b!="object"&&(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be an object${D.type?" ("+D.type+")":""}`);let U=D.properties;for(let F=0,C=U.length;F<C;F++){let H=U[F],G=y(b[H.name],H,N+"."+H.name);G&&(b[H.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 ${N}`)}else switch(D.type){case"Int":(typeof b!="number"||b>>0!==b)&&(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(U=>typeof U=="string")||(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be a string`);break;case"Boolean":typeof b!="boolean"&&(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be a bigint`)}break;case"Bytes":b instanceof Uint8Array||(I||(I=[])).push(`Value ${Vs(b)} in property ${N} 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],H=y(C,D.elements,N+"[*]");H&&(b[U]=H)}}else(I||(I=[])).push(`Value ${Vs(b)} in property ${N} must be a Buffer or Uint8Array`);break}D.nullable===!1&&b==null&&(I||(I=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let b=0,D=S.length;b<D;b++){let N=S[b];if(!N.relationship&&(!O||N.name in m)){let U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}if(d)for(let b in m)S.find(D=>D.name===b)||(I||(I=[])).push(`Property ${b} is not allowed`);if(I)throw new Rs.ClientError(I.join(". "))}getUpdatedTime(){return this[Pl]}wasLoadedFromSource(){return M?!!this[qA]:void 0}static async addAttributes(m){let O=S.slice(0);for(let I of m){if(!I.name)throw new Rs.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new Rs.ClientError("Attribute names cannot include backticks or forward slashes");O.push(I)}return lt({table:n,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static async removeAttributes(m){let O=S.filter(I=>!m.includes(I.name));return lt({table:n,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,I=5e3,y=1e3,b;O>I&&!m?.exactCount&&(b=y);let D=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:b}))N!=null&&D++;if(b){let N=D;D=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Pe!=null&&D++;let U=b*2,F=(D+N)/U,C=Math.pow((D-N+1)/b/2,2)+F*(1-F)/U,H=Math.max(Math.sqrt(C)*O,1),G=Math.round(F*O),ne=Math.max(G-1.96*H,0),pe=Math.min(G+1.96*H,O),te=Math.pow(10,Math.round(Math.log10(H)));return te>G&&(te=te/10),D=Math.round(G/te)*te,{recordCount:D,estimatedRange:[Math.round(ne),Math.round(pe)]}}return{recordCount:D}}static updatedAttributes(){Qn=this.propertyResolvers={$id:(m,O,I)=>({value:I.key}),$updatedtime:(m,O,I)=>I.version,$record:(m,O,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),oO=!0,O.to)m.elements?.definition?(Qn[m.name]=m.resolve=(I,y,b)=>{let D=I[O.from?O.from:t],N=m.elements.definition.tableClass;return b?va({attribute:O.to,value:D},Os(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:O.to,value:D}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${n}" must have an array type referencing a table as the elements`);else if(O.from){let I=m.definition||m.elements?.definition;I?(Qn[m.name]=m.resolve=(y,b,D)=>{let N=y[O.from];if(N!==void 0){if(m.elements){let U,F=N.map(C=>{let H=D?I.tableClass.primaryStore.getEntry(C,{transaction:Os(b).getReadTxn()}):I.tableClass.get(C,b);return H?.then&&(U=!0),H});return O.filterMissing?U?Promise.all(F).then(C=>C.filter(EG)):F.filter(EG):U?Promise.all(F):F}return D?I.tableClass.primaryStore.getEntry(N,{transaction:Os(b).getReadTxn()}):I.tableClass.get(N,b)}},m.set=(y,b)=>{if(Array.isArray(b)){let D=b.map(N=>N[Me]||N[I.tableClass.primaryKey]);y[O.from]=D}else{let D=b[Me]||b[I.tableClass.primaryKey];y[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 "${n}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${n}" must use either "from" or "to" arguments`)}jE(this,this)}static async deleteHistory(m=0){let O;for(let{key:I,value:y}of u.getRange({start:0,end:m}))await Ul(),Mt(y).tableId===s&&(O=u.remove(I));await O}static async*getHistory(m=0,O=1/0){for(let{key:I,value:y}of u.getRange({start:m,end:O})){await Ul();let b=Mt(y);b.tableId===s&&(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 y=I.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await Ul();let D=u.get(y);if(D){let N=Mt(D);O.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){z?.remove()}}ze.updatedAttributes();let hq=ze.prototype;return hq[Die]=!0,f&&ze.setTTLExpiration(f/1e3),X&&mq(),ze;function zl(K,m,O){let I;for(let y in r){let b=r[y],D=b.isIndexing,N=O?.[y],U=m?.[y];if(N===U&&!D)continue;I=!0;let F=b.indexNulls,C=(0,vl.getIndexedValues)(N,F),H=(0,vl.getIndexedValues)(U,F);if(H?.length>0){let G=new Set(H);if(C=C?C.filter(ne=>{if(G.has(ne))G.delete(ne);else return!0}):[],H=Array.from(G),(H.length>0||C.length>0)&&uG){let ne=H.concat(C).map(pe=>({key:pe,value:K}));b.prefetch(ne,dG)}for(let ne=0,pe=H.length;ne<pe;ne++)b.remove(H[ne],K)}else C?.length>0&&uG&&b.prefetch(C.map(G=>({key:G,value:K})),dG);if(C)for(let G=0,ne=C.length;G<ne;G++)b.put(C[G],K)}return I}a(zl,"updateIndices");function ic(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>_G)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Bo.writeKey)(K,Mie,0)>_G)throw new Error("Primary key size is too large: "+K.length);return!0}a(ic,"checkValidId");function bh(K,m,O,I,y){let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return y(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)),y(D,K)},"whenPrefetched");return I?b():ce>0?(ce--,b()):new Promise((D,N)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),F()})):(J.push(K),me.push(F),J.length>Eq&&(ce--,U()));function U(){if(J.length>0){let C=me;i.prefetch(J,()=>{ce===-1?U():ce++;for(let H of C)H()}),J=[],me=[],de>2&&de--}else ce=de,de<fq&&de++}a(U,"prefetch");function F(){try{D(b())}catch(C){N(C)}}a(F,"load")})}a(bh,"loadLocalRecord");function Jl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return Uie;let O=m[c],I,y=O?.tables;if(y)return y[n];if(c==="data"&&(I=m[n])&&!I.tables)return I}a(Jl,"getTablePermissions");function yh(K,m,O,I){if(M){let y;if(O.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Ll|Ml)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,as(!y,"cache-hit",n)),y){let b=cO(K,m,O).then(D=>(D?.value?.[_e]&&tt.error("Can not assign a record with a record property"),O&&(D?.version>(O.lastModified||0)&&(O.lastModified=D.version),O.lastRefreshed=Date.now()),D));if(O?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,K)){if(b.catch(D=>tt.warn(D)),O?.onlyIfCached&&!I.doesExist())throw new Rs.ServerError("Entry is not cached",504);return}else return b}}}a(yh,"ensureLoadedFromSource");function Os(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 ro,m.lmdbDb=i,m;m=O}while(!0)}else return new cd}a(Os,"txnForContext");function Nh(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=Qn,D=I;for(let N=0,U=m.length;N<U;N++){let F=m[N],C=b?.[F];D=C&&D?C(D,O,!0)?.value:D?.[F],b=C?.definition?.tableClass?.propertyResolvers}return D}let y=Qn[m];return y?y(I,O):I[m]}a(Nh,"getAttributeValue");function aO(K,m,O,I,y){let b=y?.length,D={transaction:I,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(F,C){let H=F?.value;if(!H)return Po.SKIP;for(let G=0;G<b;G++)if(!N?.includes(G)&&!y[G](H,F))return Po.SKIP;return C!==void 0&&(F.key=C),F}if(a(U,"processEntry"),b>0||!K.hasEntries){let F=K.map(C=>{if(N=null,typeof C=="object"&&C.key!==void 0)return b>0?U(C):C;if(C==null)return Po.SKIP;for(let H=0;H<b;H++){let ne=y[H].idFilter;if(ne){if(!ne(C))return Po.SKIP;N||(N=[]),N.push(H)}}return bh(C,O,D,!1,U)});return Array.isArray(K)&&(F=F.filter(C=>C!==Po.SKIP)),F.hasEntries=!0,F}return K}a(aO,"transformToEntries");async function cO(K,m,O){let I=m?.metadataFlags,y=m?.version,b,D;if(!i.attemptLock(K,y,()=>{clearTimeout(D);let C=i.getEntry(K);!C||!C.value||C.metadataFlags&(Ll|Ml)?b(cO(K,i.getEntry(K),O)):b(C)}))return new Promise(C=>{b=C,D=setTimeout(()=>{i.unlock(K,y)},Cie)});let N=m?.value,U={requestContext:O,replacingRecord:N,replacingVersion:y,source:null,resourceCache:O?.resourceCache},F=O?.responseHeaders;return new Promise((C,H)=>{let G;kA(je(U,async ne=>{let pe=performance.now(),te,Pe,ae;try{for(let Oe of ze.sources)if(Oe.get&&(!Oe.get.reliesOnPrototype||Oe.prototype.get)&&(U.source=Oe,te=await Oe.get(K,U),te))break;ae=I⋘let re=U.lastModified||ae&&y;Pe=ae||re>y||!N,re||(re=(0,vl.getNextMonotonicTime)());let j=performance.now()-pe;if(kr(j,"cache-resolution",n),F&&fg(F,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),ne.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 ${n}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(C({version:y,value:N}),tt.trace(re.message,"(returned stale record)")):H(re),U.transaction.abort();return}if(O?.noCacheStore){U.transaction.abort();return}Os(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,j)=>{if(j?.version!==y)return;let Oe=zl(K,N,te);te?(Be.put?.(U,K,te),T(K,te,j,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ae)):(Be.delete?.(U,K),h||p?T(K,null,j,re,0,h&&Pe||null,U,0,"delete",!!ae):i.remove(K,y))}})}),()=>{i.unlock(K,y)},ne=>{i.unlock(K,y),G&&tt.error("Error committing cache update",ne)})})}a(cO,"getFromSource");function Ih(){if(Lt!==Wl&&(Wl=Lt,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(Ql&&clearTimeout(Ql),!Lt)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())/Lt)*Lt+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+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Ql);return}let y=50,b=new Array(y),D=0;tt.trace(`Starting cleanup scan for ${n}`);try{let N=0;for(let{key:U,value:F,version:C,expiresAt:H}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;F===null&&!h&&C+wie<Date.now()?G=i.remove(U,C):H&&H+E<Date.now()&&(G=ze.evict(U,F,C),N++),G&&(await b[D],b[D]=G.catch(ne=>{tt.error("Cleanup error",ne)}),++D>=y&&(D=0)),await Ul()}tt.trace(`Finished cleanup scan for ${n}, evicted ${N} entries`)}catch(N){tt.trace(`Error in cleanup scan for ${n}:`,N)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");O(m)}}a(Ih,"scheduleCleanup");function uO(){z=u?.addDeleteRemovalCallback(s,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(uO,"addDeleteRemoval");function mq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!Oh){Oh=!0;try{let K=X.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${X} 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 y=i.getEntry(I);y?.value?y.value[K]<Date.now()&&ze.evict(I,y.value,y.version):i.ifVersion(I,y?.version,()=>m.remove(O,I))}await Ul()}}catch(K){tt.error("Error in evicting old records",K)}finally{Oh=!1}}},Iie).unref()}a(mq,"runRecordExpirationEviction")}function FA(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function dG(){}function Pie(e){mG=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"?(typeof e!="number"&&!vie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,nh.autoCast)(e):e}function fG(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}function kA(e,t,r){return e?.then?e.then(t,r):t(e)}function sh(e,t){e[Zr]=t,e[_e]=t?.value??null,e[Pl]=t?.version}function EG(e){return e!=null}function Vs(e){try{return JSON.stringify(e)}catch{return e}}var $s,Po,vl,hG,xl,Rs,Bl,Hl,tt,Bo,vo,nh,Nie,mG,Iie,wie,uG,Cie,Pl,Die,Zr,Dl,lG,Lie,qA,ec,Ll,Ml,Mie,_G,Uie,rTe,vie,Ul,cE=ge(()=>{$s=v(L()),Po=require("lmdb"),vl=v(Dr()),hG=require("lodash");Ns();oS();xl=v(ee());cG();Rs=v(se()),Bl=v(bn()),Hl=v(Ms());Re();Qf();tt=v($());_d();so();Bo=require("ordered-binary"),vo=v(Ke());ei();nh=v(Q());Ic();wn();YE();Wu();Nie=new Uint8Array(9);Nie[8]=192;Iie=6e4,wie=864e5;xl.initSync();uG=xl.get($s.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Cie=1e4,Pl=Symbol.for("version"),Die=Symbol.for("incremental-update"),Zr=Symbol("entry"),Dl=Symbol("is-saving"),lG=1,Lie=2,qA=Symbol("loaded-from-source"),ec={isNotification:!0,ensureLoaded:!1},Ll=1,Ml=8,Mie=Buffer.allocUnsafeSlow(8192),_G=1978,Uie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},rTe=(0,nh.convertToMS)(xl.get($s.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(ih,"makeTable");a(FA,"attributesAsObject");a(dG,"noop");a(Pie,"setServerUtilities");vie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(rh,"coerceType");a(fG,"isDescendantId");Ul=a(()=>new Promise(setImmediate),"rest");a(kA,"when");a(sh,"updateResource");a(EG,"exists");a(Vs,"stringify")});var Fe={};qe(Fe,{database:()=>tu,databases:()=>nt,dropDatabase:()=>_S,dropTableMeta:()=>qie,getDatabases:()=>dr,getDefaultCompression:()=>hf,getTables:()=>Bie,onUpdatedTable:()=>jR,readMetaDb:()=>Gl,resetDatabases:()=>qu,table:()=>lt,tables:()=>Lr});function Bie(){return lh||dr(),Lr||{}}function dr(){if(lh)return nt;lh=!0,sc=new Map;let e=(0,ht.getHdbBasePath)()&&(0,rt.join)((0,ht.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),t=(0,ht.get)(Dt.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)(Dt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,es.existsSync)(e)?e:(0,rt.join)((0,ht.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,es.existsSync)(e))for(let r of(0,es.readdirSync)(e,{withFileTypes:!0})){let s=(0,rt.basename)(r.name,".mdb");r.isFile()&&(0,rt.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Gl((0,rt.join)(e,r.name),null,s)}if((0,es.existsSync)((0,rc.getBaseSchemaPath)())){for(let r of(0,es.readdirSync)((0,rc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,rt.join)((0,rc.getBaseSchemaPath)(),r.name),n=(0,rt.join)((0,rc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,es.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,rt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,rt.join)(n,i.name);Gl((0,rt.join)(s,i.name),(0,rt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,es.existsSync)(n))for(let o of(0,es.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,rt.extname)(o.name).toLowerCase()===".mdb"&&Gl((0,rt.join)(n,o.name),(0,rt.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,rt.join)(c.path,(0,rt.basename)(o+".mdb"));(0,es.existsSync)(u)&&Gl(u,o,r,null,!0)}}for(let r in nt){let s=sc.get(r);if(s){let n=nt[r];r.includes("delete")&&As.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(As.trace(`delete table class ${i}`),delete n[i])}else if(delete nt[r],r==="data"){for(let n in Lr)delete Lr[n];delete Lr[dh]}}return sc=null,nt}}function qu(){lh=!1;for(let[,e]of Pi)e.needsDeletion=!0;dr();for(let[e,t]of Pi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Pi.delete(e));return nt}function Gl(e,t,r=YA,s,n){let i=new VA.default(e,!1);try{let o=Pi.get(e);o?o.needsDeletion=!1:(o=(0,ah.open)(i),Pi.set(e,o));let c=new Ho.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(oh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,es.existsSync)(s)&&(i.path=s,_=(0,ah.open)(i),_.isLegacy=!0):_=$E(o));let l=gG(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){As.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[E],A={},R=[],M,x,P=typeof S.audit=="boolean"?S.audit:(0,ht.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=S.trackDeletes,B=S.expiration,X=S.eviction,z=S.sealed;if(T)A=T.indices,R=T.attributes,T.schemaVersion++;else{M=S.tableId,M?M>=(u.get(tc)||0)&&u.putSync(tc,M+1):(S.tableId=M=u.get(tc),M||(M=1),u.putSync(tc,M+1),u.putSync(S.key,S));let J=new Ho.default(!S.is_hash_attribute,S.is_hash_attribute);if(J.compression=S.compression,J.compression){let me=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||TG;J.compression.threshold=me}x=h_(o.openDB(S.key,J)),x.rootStore=o,x.tableId=M}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 Ho.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=R.find(ce=>ce.name===J.name);me?R.splice(R.indexOf(me),1,J):R.push(J)}}catch(me){As.error("Error trying to update attribute",J,R,A,me)}}if(!T){T=RG(l,E,ih({primaryStore:x,auditStore:_,audit:P,sealed:z,expirationMS:B&&B*1e3,evictionMS:X&&X*1e3,trackDeletes:k,tableName:E,tableId:M,primaryKey:S.name,databasePath:n?r+"/"+E:r,databaseName:r,indices:A,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let J of KA)J(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function gG(e){let t=nt[e];if(t||(e==="data"?t=nt[e]=Lr:e==="system"?Object.defineProperty(nt,"system",{value:t=Object.create(null),configurable:!0}):t=nt[e]=Object.create(null)),sc&&!sc.has(e)){let r=new Set;t[dh]=r,sc.set(e,r)}return t}function RG(e,t,r){return e[t]=r,r}function tu({database:e,table:t}){e||(e=YA),dr();let r=gG(e),s=(0,rt.join)((0,ht.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),n=(0,ht.get)(Dt.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(n.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&n[e]?.tables?.[t]?.path;s=i||n[e]?.path||process.env.STORAGE_PATH||(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_PATH)||((0,es.existsSync)(s)?s:(0,rt.join)((0,ht.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME));let o=(0,rt.join)(s,(i?t:e)+".mdb"),c=Pi.get(o);if(!c){let u=new VA.default(o,!1);c=(0,ah.open)(u),Pi.set(o,c)}return c}async function _S(e){if(!nt[e])throw new Error("Schema does not exist");let t=nt[e];for(let r in t){let n=t[r].primaryStore.rootStore;Pi.delete(n.path),n.status==="open"&&(await n.close(),await _h.remove(n.path))}if(e==="data"){for(let r in Lr)delete Lr[r];delete Lr[dh]}delete nt[e]}function lt({table:e,database:t,expiration:r,eviction:s,scanInterval:n,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=YA);let d=tu({database:t,table:e}),f=nt[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 Ho.default(!1);for(let B of i)B.attribute?(B.name=B.attribute,B.indexed=!0):B.attribute=B.name,B.expiresAt&&(B.indexed=!0);let R,M;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 B=d.auditStore;B||(B=$E(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)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),s&&(p.eviction=s),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),As.trace(`${e} table loading, opening primary store`);let X=new Ho.default(!1,!0);X.compression=p.compression;let z=e+"/",J=h_(d.openDB(z,X));J.rootStore=d,T=d.dbisDb=d.openDB(oh.INTERNAL_DBIS_NAME,A),J.tableId=T.get(tc),J.tableId||(J.tableId=1),T.putSync(tc,J.tableId+1),p.tableId=J.tableId,E=RG(f,e,ih({primaryStore:J,auditStore:B,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:s&&s*1e3,primaryKey:h,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),E.schemaVersion=1,R=!0,k(),T.put(z,p)}S=E.indices,T=T||(d.dbisDb=d.openDB(oh.INTERNAL_DBIS_NAME,A)),E.dbisDB=T;let x=[];for(let{key:B,value:X}of T.getRange({start:!0})){let[z,J]=B.toString().split("/");if(J===""&&(J=X.name),J){if(z!==e)continue}else J=z;if(!i.find(ce=>ce.name===J)?.indexed&&X.indexed&&!X.isPrimaryKey){k(),R=!0,T.remove(B);let ce=E.indices[z];ce&&x.push(ce)}}let P=[];try{for(let B of i||[]){if(B.relationship)continue;let X=e+"/"+(B.name||"");Object.defineProperty(B,"key",{value:X,configurable:!0});let z=T.get(X);if(B.isPrimaryKey){if(z=z||T.get(X=e+"/")||{},o!==E.audit||c!==c||(+r||void 0)!==(+z.expiration||void 0)||(+s||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),s&&(me.eviction=+s),c!==void 0&&(me.sealed=c),R=!0,k(),T.put(X,me)}continue}z?.attribute&&!z.name&&(z.indexed=!0);let J=!z||z.type!==B.type||z.indexed!==B.indexed||z.nullable!==B.nullable||JSON.stringify(z.attributes)!==JSON.stringify(B.attributes)||JSON.stringify(z.elements)!==JSON.stringify(B.elements);if(B.indexed){let me=new Ho.default(!0,!1),ce=d.openDB(X,me);(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(R=!0,k(),z=T.get(X),(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(R=!0,B.indexNulls===void 0&&(B.indexNulls=!0),E.primaryStore.getStats().entryCount>0&&(B.lastIndexedKey=z?.lastIndexedKey||!1,B.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(B,"dbi",{value:ce}),P.push(B))),T.put(X,B)),z?.indexNulls&&B.indexNulls===void 0&&(B.indexNulls=!0),ce.indexNulls=B.indexNulls,S[B.name]=ce}else J&&(R=!0,k(),T.put(X,B))}}finally{M&&M()}if(R&&(E.schemaVersion++,E.updatedAttributes()),As.trace(`${e} table loading, running index`),P.length>0||x.length>0?E.indexingOperation=Gie(E,P,x):R&&ch.signalSchemaChange(new uh.SchemaEventMsg(process.pid,"schema-change",E.databaseName,E.tableName)),E.origin=l,R)for(let B of KA)B(E,l!=="cluster");return(r||s||n)&&E.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),As.trace(`${e} table loaded`),E;function k(){M||d.transactionSync(()=>({then(B){M=B}}))}a(k,"startTxn")}async function Gie(e,t,r){try{let s=e.schemaVersion;await ch.signalSchemaChange(new uh.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,n=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,pG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)E.dbi.put(p[S],_)}}),n.then(()=>u--,f=>{u--,As.error(f)}),ql.workerData&&ql.workerData.restartNumber!==SG.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>Hie?await n:u>xie&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,n=e.dbisDB.put(_.key,_)}await n,await ch.signalSchemaChange(new uh.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){As.error("Error in indexing",s)}}function qie({table:e,database:t}){let r=tu({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function jR(e){KA.push(e)}function hf(){let e=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||TG,s={startingOffset:32};return t&&(s.dictionary=_h.readFileSync(t)),r&&(s.threshold=r),e&&s}var ht,oh,ah,rt,es,rc,Ho,VA,Dt,_h,$A,pG,ch,uh,ql,As,SG,YA,dh,TG,Lr,nt,tc,KA,lh,Pi,sc,Hie,xie,Re=ge(()=>{ht=v(ee()),oh=v(ut()),ah=require("lmdb"),rt=require("path"),es=require("fs"),rc=v(Je());cE();Ho=v(wc()),VA=v(Cc()),Dt=v(L()),_h=v(require("fs-extra")),$A=require("../index"),pG=v(Dr()),ch=v(bn()),uh=v(Ms()),ql=require("worker_threads"),As=v($()),SG=v(Ke());ei();Ic();YA="data",dh=Symbol("defined-tables"),TG=((0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,ht.initSync)();Lr=Object.create(null),nt=Object.create(null);(0,$A._assignPackageExport)("databases",nt);(0,$A._assignPackageExport)("tables",Lr);tc=Symbol.for("next-table-id"),KA=[],Pi=new Map;a(Bie,"getTables");a(dr,"getDatabases");a(qu,"resetDatabases");a(Gl,"readMetaDb");a(gG,"ensureDB");a(RG,"setTable");a(tu,"database");a(_S,"dropDatabase");a(lt,"table");Hie=1e3,xie=10;a(Gie,"runIndexing");a(qie,"dropTableMeta");a(jR,"onUpdatedTable");a(hf,"getDefaultCompression")});var Q=g((_Te,vG)=>{"use strict";var vi=require("path"),NG=require("fs-extra"),Ir=$(),AG=require("fs-extra"),fh=require("os"),Fie=require("net"),kie=require("recursive-iterator"),ct=L(),Vie=kO(),OG=require("papaparse"),Eh=require("moment"),{inspect:$ie}=require("util"),bG=require("is-number"),lTe=require("lodash"),Yie=require("minimist"),Kie=require("https"),Wie=require("http"),{hdb_errors:hh}=se(),Qie=/^((\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)))$/,IG=require("util").promisify(setTimeout),zie=100,Jie=5,Xie="",jie=4,yG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};vG.exports={isEmpty:ts,isEmptyOrZeroLength:hn,arrayHasEmptyValues:toe,arrayHasEmptyOrZeroLengthValues:roe,buildFolderPath:soe,isBoolean:wG,errorizeMessage:Zie,stripFileExtension:ioe,autoCast:ooe,autoCastJSON:CG,autoCastJSONDeep:QA,removeDir:aoe,compareVersions:coe,isCompatibleDataVersion:uoe,escapeRawValue:loe,unescapeValue:_oe,stringifyProps:doe,timeoutPromise:Eoe,isClusterOperation:moe,getClusterUser:Soe,checkGlobalSchemaTable:poe,getHomeDir:LG,getPropsFilePath:foe,promisifyPapaParse:Toe,removeBOM:MG,createEventPromise:goe,checkProcessRunning:Roe,checkSchemaTableExist:Aoe,checkSchemaExists:UG,checkTableExists:PG,getStartOfTomorrowInSeconds:Ooe,getLimitKey:boe,isObject:noe,isNotEmptyAndHasValue:eoe,autoCasterIsNumberCheck:DG,backtickASTSchemaItems:yoe,isPortTaken:hoe,createForkArgs:Noe,autoCastBoolean:Ioe,async_set_timeout:IG,getTableHashAttribute:woe,doesSchemaExist:Coe,doesTableExist:Doe,stringifyObj:Loe,ms_to_time:Moe,changeExtension:Uoe,getEnvCliRootPath:zA,noBootFile:Poe,httpRequest:voe,transformReq:Boe,convertToMS:Hoe,PACKAGE_ROOT:ct.PACKAGE_ROOT};function Zie(e){return e instanceof Error?e:new Error(e)}a(Zie,"errorizeMessage");function ts(e){return e==null}a(ts,"isEmpty");function eoe(e){return!ts(e)&&(e||e===0||e===""||wG(e))}a(eoe,"isNotEmptyAndHasValue");function hn(e){return ts(e)||e.length===0||e.size===0}a(hn,"isEmptyOrZeroLength");function toe(e){if(ts(e))return!0;for(let t=0;t<e.length;t++)if(ts(e[t]))return!0;return!1}a(toe,"arrayHasEmptyValues");function roe(e){if(hn(e))return!0;for(let t=0;t<e.length;t++)if(hn(e[t]))return!0;return!1}a(roe,"arrayHasEmptyOrZeroLengthValues");function soe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(soe,"buildFolderPath");function wG(e){return ts(e)?!1:e===!0||e===!1}a(wG,"isBoolean");function noe(e){return ts(e)?!1:typeof e=="object"}a(noe,"isObject");function ioe(e){return hn(e)?Xie:e.slice(0,-jie)}a(ioe,"stripFileExtension");function ooe(e){return ts(e)||e===""||typeof e!="string"?e:yG[e]!==void 0?yG[e]:DG(e)===!0?Number(e):Qie.test(e)?new Date(e):e}a(ooe,"autoCast");function CG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(CG,"autoCastJSON");function QA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=QA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=QA(r);s!==r&&(e[t]=s)}return e}else return CG(e)}a(QA,"autoCastJSONDeep");function DG(e){if(e.startsWith("0.")&&bG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&bG(e))}a(DG,"autoCasterIsNumberCheck");async function aoe(e){if(hn(e))throw new Error(`Directory path: ${e} does not exist`);try{await AG.emptyDir(e),await AG.remove(e)}catch(t){throw Ir.error(`Error removing files in ${e} -- ${t}`),t}}a(aoe,"removeDir");function coe(e,t){if(hn(e)){Ir.info("Invalid current version sent as parameter.");return}if(hn(t)){Ir.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(coe,"compareVersions");function uoe(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(uoe,"isCompatibleDataVersion");function loe(e){if(ts(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(loe,"escapeRawValue");function _oe(e){if(ts(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(_oe,"unescapeValue");function doe(e,t){if(ts(e))return Ir.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+fh.EOL}!hn(s)&&s[0]===";"?r+=" "+s+n+fh.EOL:hn(s)||(r+=s+"="+n+fh.EOL)}catch{Ir.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(doe,"stringifyProps");function LG(){let e;try{e=fh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(LG,"getHomeDir");function foe(){let e=vi.join(LG(),ct.HDB_HOME_DIR_NAME,ct.BOOT_PROPS_FILE_NAME);return NG.existsSync(e)||(e=vi.join(__dirname,"../","hdb_boot_properties.file")),e}a(foe,"getPropsFilePath");function Eoe(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(Eoe,"timeoutPromise");async function hoe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=Fie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(hoe,"isPortTaken");function moe(e){try{return ct.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Ir.error(`Error checking operation against cluster ops ${t}`)}return!1}a(moe,"isClusterOperation");function poe(e,t){let r=(Re(),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(poe,"checkGlobalSchemaTable");function Soe(e,t){if(ts(t)){Ir.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ts(e)||hn(e)){Ir.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){Ir.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Ir.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Soe,"getClusterUser");function Toe(){OG.parsePromise=function(e,t,r){return new Promise(function(s,n){OG.parse(e,{header:!0,transformHeader:MG,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(Toe,"promisifyPapaParse");function MG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(MG,"removeBOM");function goe(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Ir.info(`Got cluster status event response: ${$ie(n)}`);try{i.cancel()}catch{Ir.error("Error trying to cancel timeout.")}s(n)})})}a(goe,"createEventPromise");async function Roe(e){let t=!0,r=0;do await IG(zie*r++),(await Vie.findPs(e)).length>0&&(t=!1);while(t&&r<Jie);if(t)throw new Error(`process ${e} was not started`)}a(Roe,"checkProcessRunning");function Aoe(e,t){let r=UG(e);if(r)return r;let s=PG(e,t);if(s)return s}a(Aoe,"checkSchemaTableExist");function UG(e){let{getDatabases:t}=(Re(),ie(Fe));if(!t()[e])return hh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(UG,"checkSchemaExists");function PG(e,t){let{getDatabases:r}=(Re(),ie(Fe));if(!r()[e][t])return hh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(PG,"checkTableExists");function Ooe(){let e=Eh().utc().add(1,ct.MOMENT_DAYS_TAG).startOf(ct.MOMENT_DAYS_TAG).unix(),t=Eh().utc().unix();return e-t}a(Ooe,"getStartOfTomorrowInSeconds");function boe(){return Eh().utc().format("DD-MM-YYYY")}a(boe,"getLimitKey");function yoe(e){try{let t=new kie(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){Ir.error("Got an error back ticking items."),Ir.error(t)}}a(yoe,"backtickASTSchemaItems");function Noe(e){return[e]}a(Noe,"createForkArgs");function Ioe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Ioe,"autoCastBoolean");function woe(e,t){let{getDatabases:r}=(Re(),ie(Fe)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(woe,"getTableHashAttribute");function Coe(e){let{getDatabases:t}=(Re(),ie(Fe));return t()[e]!==void 0}a(Coe,"doesSchemaExist");function Doe(e,t){let{getDatabases:r}=(Re(),ie(Fe));return r()[e]?.[t]!==void 0}a(Doe,"doesTableExist");function Loe(e){try{return JSON.stringify(e)}catch{return e}}a(Loe,"stringifyObj");function Moe(e){let t=Eh.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(Moe,"ms_to_time");function Uoe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(Uoe,"changeExtension");function zA(){if(process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Yie(process.argv);if(e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(zA,"getEnvCliRootPath");var WA;function Poe(){if(WA)return WA;let e=zA();zA()&&NG.pathExistsSync(vi.join(e,ct.HDB_CONFIG_FILE))&&(WA=!0)}a(Poe,"noBootFile");function voe(e,t){let r;return e.protocol==="http:"?r=Wie:r=Kie,new Promise((s,n)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(voe,"httpRequest");function Boe(e){if(!e.schema&&!e.database){e.schema=ct.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Boe,"transformReq");function Hoe(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(Hoe,"convertToMS")});var ee=g((fTe,GG)=>{"use strict";var JA=require("fs-extra"),xo=require("path"),BG=require("os"),xoe=require("properties-reader"),kl=$(),Fl=Q(),ue=L(),mh=lr(),Goe="Error initializing environment manager",ph="BOOT_PROPS_FILE_PATH",HG=!1,qoe={[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},Kn={};GG.exports={BOOT_PROPS_FILE_PATH:ph,getHdbBasePath:Foe,setHdbBasePath:koe,get:xG,initSync:$oe,setProperty:Ue,initTestEnvironment:Yoe};function Foe(){return Kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Foe,"getHdbBasePath");function koe(e){Kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(koe,"setHdbBasePath");function xG(e){let t=mh.getConfigValue(e);return t===void 0?Kn[e]:t}a(xG,"get");function Ue(e,t){qoe[e]&&(Kn[e]=t),mh.updateConfigObject(e,t)}a(Ue,"setProperty");function Voe(){let e;try{e=Fl.getPropsFilePath(),JA.accessSync(e,JA.constants.F_OK|JA.constants.R_OK),HG=!0;let t=xoe(e);return Kn[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Kn[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Kn[ph]=e,!0}catch{return kl.trace(`Environment manager found no properties file at ${e}`),!1}}a(Voe,"doesPropFileExist");function $oe(e=!1){try{(HG||Voe()||Fl.noBootFile())&&(mh.initConfig(e),Kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=mh.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){kl.error(Goe),kl.error(t),console.error(t),process.exit(1)}}a($oe,"initSync");function Yoe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=xo.join(__dirname,"../../","unitTests");Kn[ph]=xo.join(u,"hdb_boot_properties.file"),Ue(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xo.join(u,"settings.test")),Ue(ue.HDB_SETTINGS_NAMES.INSTALL_USER,BG.userInfo()?BG.userInfo().username:void 0),Ue(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ue(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xo.join(u,"envDir","log")),Ue(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xo.join(u,"envDir")),Ue(ue.CONFIG_PARAMS.STORAGE_PATH,xo.join(u,"envDir")),n&&(Ue(ue.CONFIG_PARAMS.HTTP_SECUREPORT,xG(ue.CONFIG_PARAMS.HTTP_PORT)),Ue(ue.CONFIG_PARAMS.HTTP_PORT,null)),Ue(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Ue(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ue(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Fl.isEmpty(i)?!1:i),Ue(ue.CONFIG_PARAMS.HTTP_CORS,Fl.isEmpty(i)?!1:i),Ue(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ue(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ue(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Fl.isEmpty(c)?!1:c),o&&(Ue("CORS_ACCESSLIST",o),Ue(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ue(ue.CONFIG_PARAMS.HTTP_TIMEOUT,s)),t&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ue(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ue(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(Yoe,"initTestEnvironment")});var $G=g((hTe,VG)=>{"use strict";var kG=require("joi"),{string:Vl,boolean:qG,array:Koe}=kG.types(),FG=L(),Woe=Xe();VG.exports=Qoe;function Qoe(e){let t=kG.object({operation:Vl.valid(FG.OPERATIONS_ENUM.ADD_NODE,FG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Vl.required(),subscriptions:Koe.items({schema:Vl.required(),table:Vl.optional(),hash_attribute:Vl.optional(),subscribe:qG.required(),publish:qG.required()}).min(1).required()});return Woe.validateBySchema(e,t)}a(Qoe,"updateRemoteSourceValidator")});var $l=g((pTe,YG)=>{"use strict";var XA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,s=void 0){this.status=t,this.message=r,this.system_info=s}};YG.exports=XA});var JG=g((TTe,zG)=>{"use strict";var zoe=$G(),Wn=$(),jA=ke(),KG=L(),ZA=us(),Bi=it(),WG=Su(),Joe=id(),{Node:Xoe,NodeSubscription:QG}=mi(),eO=$l(),tO=Q(),joe=ee(),{cloneDeep:Zoe}=require("lodash"),{broadcast:eae}=Ke();zG.exports=tae;async function tae(e){try{let t=zoe(e);if(t)return Wn.error(`Validation error in updateRemoteSource: ${t.message}`),new eO(jA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:s,system_info:n}=e,i=[],o=Zoe(await ZA.getNodeRecord(s)),c=!tO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Wn.trace(`Existing record found for ${s}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!tO.doesSchemaExist(f)){Wn.trace(`updateRemoteSource creating schema: ${f}`);try{await WG.createSchema({operation:"create_schema",schema:f})}catch(h){Wn.error(h)}}if(E&&!tO.doesTableExist(f,E)){let h=new Joe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Wn.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await WG.createTable(h)}catch(p){Wn.error(p)}Wn.trace(`Creating local stream for ${f}.${E}`),await Bi.createLocalTableStream(f,E)}if(f===KG.SYSTEM_SCHEMA_NAME&&await Bi.createLocalTableStream(f,E),c?(await Bi.updateConsumerIterator(f,E,s,"stop"),await Bi.updateRemoteConsumer(d,s),d.subscribe===!0&&await Bi.updateConsumerIterator(f,E,s,"start")):(await Bi.updateRemoteConsumer(d,s),d.subscribe===!0?await Bi.updateConsumerIterator(f,E,s,"start"):await Bi.updateConsumerIterator(f,E,s,"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 QG(f,E,d.publish,d.subscribe))}else i.push(new QG(f,E,d.publish,d.subscribe))}c||(o=new Xoe(s,i,void 0),Wn.trace(`No record found for ${s}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=n,await ZA.upsertNodeRecord(u),eae({type:"nats_update"}),new eO(jA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${joe.get(KG.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await ZA.getSystemInfo())}catch(t){Wn.error(t);let r=t.message?t.message:t;return new eO(jA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(tae,"updateRemoteSource")});var eq=g((RTe,ZG)=>{"use strict";var jG=require("joi"),{string:XG}=jG.types(),rae=L(),sae=Xe();ZG.exports=nae;function nae(e){let t=jG.object({operation:XG.valid(rae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:XG.required()});return sae.validateBySchema(e,t)}a(nae,"removeRemoteSourceValidator")});var sq=g((OTe,rq)=>{"use strict";var iae=eq(),Sh=$(),Th=ke(),rO=L(),oae=us(),aae=Q(),tq=it(),cae=ee(),gh=$l(),{NodeSubscription:uae}=mi(),lae=ia(),_ae=ii(),{broadcast:dae}=Ke(),fae=cae.get(rO.CONFIG_PARAMS.CLUSTERING_NODENAME);rq.exports=Eae;async function Eae(e){try{let t=iae(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,s=await oae.getNodeRecord(r);if(aae.isEmptyOrZeroLength(s)){let i=`No record found for node '${r}'`;return Sh.error(i),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}s=s[0];for(let i=0,o=s.subscriptions.length;i<o;i++){let c=s.subscriptions[i];Sh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new uae(c.schema,c.table,!1,!1);await tq.updateConsumerIterator(c.schema,c.table,r,"stop"),await tq.updateRemoteConsumer(u,r)}let n=new lae(rO.SYSTEM_SCHEMA_NAME,rO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await _ae.deleteRecord(n),dae({type:"nats_update"}),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${fae} 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(Eae,"removeRemoteSource")});var aq=g((yTe,oq)=>{"use strict";var Rh=$(),Yl=L(),nq=ke(),sO=ee(),hae=Q(),iq=$l(),mae=us(),pae=Bd(),Sae=vr();oq.exports=Tae;async function Tae(e){try{Rh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=hae.ms_to_time(t),s=new gae(sO.get(Yl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),sO.get(Yl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??sO.get(Yl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await mae.getSystemInfo());try{let n={name:e.node_name,system_info:e.system_info},i=new pae(Yl.SYSTEM_SCHEMA_NAME,Yl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[n]);await Sae.update(i)}catch(n){Rh.error("Get remote config encountered an error updating system info for node:",e.node_name,n)}return Rh.trace("getRemoteSourceConfig response:",s),new iq(nq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){Rh.error(t);let r=t.message?t.message:t;return new iq(nq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Tae,"getRemoteSourceConfig");function gae(e,t,r,s){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=s}a(gae,"ConfigResponseObject")});var _q=g((ITe,lq)=>{"use strict";var cq=ee();cq.initSync();var uq=it(),Kl=$(),nc=L(),nO=ke(),Rae=JG(),Aae=sq(),Oae=aq(),bae=$l(),{encode:yae,decode:Nae}=require("msgpackr"),Iae=On(),wae=An(),Cae=require("util"),Dae=L(),{isMainThread:Lae,parentPort:Mae}=require("worker_threads");Ke();var Uae=Cae.promisify(Iae.setSchemaDataToGlobal),iO=cq.get(nc.CONFIG_PARAMS.CLUSTERING_NODENAME);lq.exports=Pae;async function Pae(){try{Kl.notify("Starting reply service."),await Uae();let e=await uq.getConnection(),t=`${iO}.__request__`,r=e.subscribe(t,{queue:iO});await vae(r)}catch(e){Kl.error(e)}}a(Pae,"initialize");async function vae(e){for await(let t of e){let r=Nae(t.data),s;switch(r.operation){case nc.OPERATIONS_ENUM.ADD_NODE:case nc.OPERATIONS_ENUM.UPDATE_NODE:s=await Rae(r);break;case nc.OPERATIONS_ENUM.REMOVE_NODE:s=await Aae(r);break;case nc.OPERATIONS_ENUM.CLUSTER_STATUS:s=await Oae(r);break;case nc.OPERATIONS_ENUM.DESCRIBE_ALL:s=await Bae();break;default:let n=`node '${iO}' reply service received unrecognized request operation`;Kl.error(n),s=new bae(nO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,n)}Kl.trace(s),t.respond(yae(s))}}a(vae,"handleRequest");async function Bae(){try{return{status:nO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await wae.describeAll()}}catch(e){return Kl.error(e),{status:nO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(Bae,"getRemoteDescribeAll");Lae||Mae.on("message",async e=>{let{type:t}=e;t===Dae.ITC_EVENT_TYPES.SHUTDOWN&&uq.closeConnection()})});var Hae=_q();(async()=>{try{await Hae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|
|
31
|
+
`))}},25).unref()}o.close?.(()=>{if(Ce.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&DE()==0)try{FH(Ce.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,wE),o.cantCleanupProperly||rr.warn("Had to forcefully exit the thread",wE),process.exit(0)},5e3).unref()})}if(JH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){rr.info("Could not close debugger",i)}}}).ref();let e=[];if(kH&&!Ase)for(let t in ds){let r=ds[t];if(isNaN(t)&&DE()==0){fse(t)&&FH(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),rr.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(),rr.trace("Listening on port "+t,wE)}).on("error",i)}))}Promise.all(e).then(()=>{bl?.postMessage({type:Et.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(jH,"startServers");KH||jH();function rA(e,t,r){let n=e?.read?e:new cse({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):(rr.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(rA,"deliverSocket");var $H=new Map;function yse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=$H.get(s),r){case"connection":i=rA(void 0,t),$H.set(s,i),i.write=(c,u,_)=>(bl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(bl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),bl.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(yse,"proxyRequest");function nA(e,t,r=!0){!+t&&t!==Ce.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(Ce.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",YH),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",YH)}a(nA,"registerServer");function XH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],Ce.get(Et.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:Ce.get(Et.CONFIG_PARAMS.HTTP_PORT),secure:Ce.get(Et.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),Ce.get(Et.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:Ce.get(Et.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&Ce.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:Ce.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(XH,"getPorts");function sA(e,t){for(let{port:r,secure:n}of XH(t))ZH(r,n,t?.isOperationsServer),typeof e=="function"?eA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,nA(e,r,!1)),LE[r]=tA(eA,r),Ose=tA(bse,r)}a(sA,"httpServer");function ZH(e,t,r){if(!Di[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:Ce.get(n+"_keepAliveTimeout"),headersTimeout:Ce.get(n+"_headersTimeout"),requestTimeout:Ce.get(n+"_timeout")},i=Ce.get(n+"_mtls"),o=Ce.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=Ce.get(n+"tls_privateKey"),_=Ce.get(n+"tls_certificate"),l=Ce.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:Qa(u),ciphers:Ce.get("tls_ciphers"),cert:Qa(_),ca:l&&Qa(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:mse(),maxHeaderSize:Ce.get(Et.CONFIG_PARAMS.HTTP_MAXHEADERSIZE)})}let c=gse();Di[e]=(t?dse:lse)(s,async(u,_)=>{try{let d=performance.now(),f=new QH(u,_);r&&(f.isOperationsServer=!0);let E=await LE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=ex(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,Di[e].emit("unhandled",u,_)}let h=E.status||200,p=performance.now(),S=p-d,T=E.body,b;if(!E.handlesHeaders){let v=E.headers||new WH;T?T.length>=0&&(typeof T=="string"?v.set("Content-Length",Buffer.byteLength(T)):v.set("Content-Length",T.length),b=!0):(v.set("Content-Length","0"),b=!0);let P=`hdb;dur=${S.toFixed(2)}`;E.wasCacheMiss&&(P+=", miss"),Sse(v,"Server-Timing",P,!0),_.writeHead(h,v&&(v[Symbol.iterator]?Array.from(v):v)),b&&_.end(T)}let R=f.handlerPath,M=f.method;if(Ol(S,"duration",R,M,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),Tse(h<400,"success",R,M),!b)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let v=0;T.on("data",P=>{v+=P.length}),T.on("end",()=>{Ol(performance.now()-p,"transfer",R,M),Ol(v,"bytes-sent",R,M)})}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?rr.warn(d):rr.info(d):rr.error(d)}a(l,"onError")}),i&&(Di[e].mtlsConfig=i),t&&(Di[e].on("secureConnection",u=>{u._parent.startTime&&Ol(performance.now()-u._parent.startTime,"tls-handshake",e),Ol(u.isSessionReused(),"tls-reused",e)}),Di[e].isSecure=!0),nA(Di[e],e)}return Di[e]}a(ZH,"getHTTPServer");function tA(e,t){let r=ex;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(tA,"makeCallbackChain");function ex(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new WH}}a(ex,"unhandled");function Nse(e,t){sA(e,{requestOnly:!0,...t})}a(Nse,"onRequest");function Ise(e,t){let r;if(t.securePort){let n=Ce.get("tls_privateKey"),s=Ce.get("tls_certificate"),i=t.mtls?.certificateAuthority||Ce.get("tls_certificateAuthority");r=hse({ciphers:Ce.get("tls_ciphers"),key:Qa(n),cert:Qa(s),ca:i&&Qa(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),ds[t.securePort]=r}return t.port&&(r=use(e),ds[t.port]=r),r}a(Ise,"onSocket");Object.defineProperty(_se.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 wse(e,t){let r;for(let{port:n,secure:s}of XH(t)){CE[n]||(CE[n]=new Ese({server:r=ZH(n,s)}),CE[n].on("connection",async(c,u)=>{try{let _=new QH(u);_.isWebSocket=!0;let l=LE[n](_),d=u.headers["sec-websocket-protocol"]||"",f=ZR[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(_){rr.warn("Error handling WebSocket connection",_)}}),CE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=ZR[n];o||(o=ZR[n]=[]),o.push({listener:e,protocol:i}),LE[n]=tA(eA,n)}return r}a(wse,"onWebSocket");function YH(e,t){t.writeHead(404),t.end(`Not found
|
|
32
|
+
`)}a(YH,"defaultNotFound")});async function ix({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await oA.get(e,{returnNonexistent:!0});s=new uA(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await oA.get(e);i&&i.delete()}s=new PE(e,t)}return n&&(n.id=e,n.user={username:t?.username},yl.put(n)),s}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=Ai.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 rx,Li,nx,sx,oA,yl,UE,PE,uA,ox=ge(()=>{Re();Wu();rx=B(Dr()),Li=B($());ro();nx=B(Ke()),sx=B(tx());or();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"}]}}]}),yl=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,nx.getWorkerIndex)()===0&&(async()=>{await sx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of yl.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)}yl.delete(e.id,r)})}})();a(ix,"getSession");UE=1;a(aA,"getNextMessageId");PE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;request;socket;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(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=Ai.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 b=T.split("/"),R;for(let P=0;P<b.length;P++)if(b[P].indexOf("+")>-1)if(b[P]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&R)throw new Error("Filters can not be combined");let M=!0;b[b.length-1]==="#"&&(b.length--,M=!1),R&&(n=a(P=>{let k=P.id;if(!Array.isArray(k)||M&&k.length!==b.length)return!1;for(let H=0;H<b.length;H++)if(b[H]!=="+"&&b[H]!==k[H])return!1;return!0},"filter"));let v=b.indexOf("+");f.url="/"+(v>-1?b.slice(0,v):b).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 b=await p.subscribe(f,T);if(!b)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!b[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let R of b)try{let M;if(R.type&&R.type!=="put"&&R.type!=="delete"&&R.type!=="message"&&R.type!=="patch"||n&&!n(R))continue;r?(R.topic=s,M=this.needsAcknowledge(R)):(R.acknowledge?.(),M=aA());let v=R.id;Array.isArray(v)&&(v=ya(v)),v==null&&(v=""),this.listener(h+"/"+v,R.value,M,t)}catch(M){(0,Li.warn)(M)}})(),b});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){let r=this.createContext();Xe(r,async()=>{if(!t){let n=await yl.get(this.sessionId);n?.doesExist()&&await cA(n,n.data,r)}await yl.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=[]}};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,rx.getNextMonotonicTime)()),(0,Li.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),oA.put(this.sessionRecord)}}});var dA={};qe(dA,{bypassAuth:()=>Cse,start:()=>Dse});function Cse(){lx=!0}function Dse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){Qr.debug("Received WSS connection for MQTT from",_._socket.remoteAddress);let{onMessage:f,onClose:E}=cx(_,(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=>{Qr.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(Qr.debug("Received connection for MQTT from",_.remoteAddress),u){if(_.authorized)try{let E=u.user;E!==null?((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null),(0,Nl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&lA.notify({username:l.username,status:zr.AUTH_AUDIT_STATUS.SUCCESS,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})):Qr.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(E){Qr.error(E)}else if(u.required)return Qr.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&lx&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,ux.getSuperUser)(),Qr.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:f}=cx(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{Qr.info("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function cx(e,t,r,n,s){ax||(ax=!0,lu(d=>{vE>0&&d.push({metric:"mqtt-connections",connections:vE,byThread:!0})}));let i;vE++;let o,c={protocolVersion:4},u=(0,BE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){vE--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),cn(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await nt.getUser(d.username,d.password.toString(),r),(0,Nl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&lA.notify({username:n.username,status:zr.AUTH_AUDIT_STATUS.SUCCESS,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,Nl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&lA.error({username:n.username,status:zr.AUTH_AUDIT_STATUS.FAILURE,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return cn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let R=e.deserialize||(e.deserialize=Ao(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?R(d.will.payload):void 0,delete d.will.payload}o=ix({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(R){return Qr.error(R),cn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:R.code||5,returnCode:R.code||128})}cn(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((R,M,v,P)=>{try{let k=R.indexOf("/",1),H=k>0?R.slice(0,k):R;f({cmd:"publish",topic:R,payload:E(M),messageId:v||Math.floor(Math.random()*1e8),qos:P.qos},H)}catch(k){Qr.error(k),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let R of d.subscriptions){let M;try{M=(await o.addSubscription(R,R.qos>=1)).qos||0}catch(v){Qr.error(v),M=c.protocolVersion<5?128:v.statusCode===403?135:v.statusCode===404?143:128}h.push(M)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let R=[];for(let M of d.unsubscriptions)R.push(o.removeSubscription(M)?0:17);f({cmd:"unsuback",granted:R,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,b;try{b=await o.publish(d,T)}catch(R){Qr.warn(R),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:b===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),cn(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){Qr.error(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,BE.generate)(h,c);t(S),kr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return bi(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var BE,ux,Nl,zr,_A,lA,Qr,lx,ax,vE,_x=ge(()=>{BE=require("mqtt-packet");ox();ux=B(an());Ia();ws();or();Nl=B(ee()),zr=B(L()),_A=B($()),lA=(0,_A.loggerWithTag)("auth-event"),Qr=(0,_A.loggerWithTag)("mqtt"),lx=(0,Nl.get)(zr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Cse,"bypassAuth");a(Dse,"start");vE=0;a(cx,"onSocket")});var Mf={};qe(Mf,{component_errors:()=>Ja,loadComponent:()=>HE,loadComponentDirectories:()=>gx,setErrorReporter:()=>Pse});function gx(e,t){t&&(EA=t),e&&(hA=e);let r=[];if((0,Fn.existsSync)(fA)){let s=(0,Fn.readdirSync)(fA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Ot.join)(fA,o);r.push(HE(c,EA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(HE(n,EA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{Tx=!0})}function Pse(e){wl=e}async function HE(e,t,r,n,s,i){if(!fx.has(e)){fx.set(e,!0),s&&(hA=s);try{let o;n&&(Ja=new Map);let c=(0,Ot.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,Fn.existsSync)(c)?o=n?(0,Sx.getConfigObj)():(0,Ex.parseDocument)((0,Fn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=mA;let u=[],_=n;for(let l in o){let d=o[l];if(Ja.set(n?l:(0,Ot.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let b=e,R;for(;!(0,Fn.existsSync)(R=(0,Ot.join)(b,"node_modules",l));)if(b=(0,Ot.dirname)(b),b.length<(0,px.getHdbBasePath)().length){R=null;break}if(R)f=await HE(R,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=Use[l];if(!f)continue;u.push(f);let h=a(b=>(b.origin=r,lt(b)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,T=!p?.https&&p?.port;if(za.isMainThread&&(f=await f.startOnMainThread?.({server:nt,ensureTable:h,port:T,securePort:S,resources:t,...d})||f,n&&p))for(let b of[T,S])try{if(+b&&!dx.includes(b)){let R=pA.get(SA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);R&&Il.default.warn("Session affinity is not recommended and may cause memory leaks"),(R||!OE)&&(dx.push(b),NH(b,R))}}catch(R){console.error("Error listening on socket",b,R,l)}if(t.isWorker&&(f=await f.start?.({server:nt,ensureTable:h,port:T,securePort:S,resources:t,...d})||f),hA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,mx.handleHDBError)("Can not reference parent directories");let b=(0,Ot.join)(e,d.files).replace(/\\/g,"/"),R=b.indexOf("/*");if(R>-1&&d.files!==mA[l]?.files&&!(0,Fn.existsSync)(b.slice(0,R)))throw new Error(`The path '${b.slice(0,R)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let M=(0,Ot.basename)(e),v=d.path||"/";v=v.startsWith("/")?v:v.startsWith("./")?"/"+M+v.slice(2):v==="."?"/"+M:"/"+M+"/"+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=b.indexOf("/*"))>-1&&(k=b.slice(0,H+1),P=(0,Ot.relative)(e,k));let j=!1;if(za.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,hx.default)(b,{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 Le=await Mse(J);za.isMainThread&&await f.setupFile?.(Le,de,J,t),t.isWorker&&await f.handleFile?.(Le,de,J,t)}else za.isMainThread&&await f.setupDirectory?.(de,J,t),t.isWorker&&await f.handleDirectory?.(de,J,t)}catch(Le){Le.message=`Could not load ${me.isFile()?"file":"directory"} '${J}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${Le.message}`,wl?.(Le),((0,ja.getWorkerIndex)()===0?console:Il.default).error(Le),t.set(d.path||"/",new Cl(Le)),Ja.set(n?l:(0,Ot.basename)(e),Le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Ot.basename)(e)}' due to: ${h.message}`,wl?.(h),((0,ja.getWorkerIndex)()===0?console:Il.default).error(h),t.set(d.path||"/",new Cl(h),null,!0),Ja.set(n?l:(0,Ot.basename)(e),h.message)}}if(za.isMainThread&&!Tx&&i&&(0,ja.watchDir)(e,async()=>gx()),o.extensionModule)return await __((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?`;wl?.(new Error(l)),((0,ja.getWorkerIndex)()===0?console:Il.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}`,wl?.(o),t.set("",new Cl(o))}}}var Fn,Ot,za,Ex,pA,SA,hx,ja,Il,mx,px,Lse,Sx,Mse,fA,hA,Tx,EA,Ja,Use,mA,dx,fx,wl,Cl,Uf=ge(()=>{Fn=require("fs"),Ot=require("path"),za=require("worker_threads"),Ex=require("yaml"),pA=B(ee()),SA=B(L());Sb();Ab();Ob();w0();hH();RH();hx=B(require("fast-glob")),ja=B(Ke()),Il=B($());Wh();or();mx=B(ne());Nn();Re();IH();px=B(ee()),Lse=B(MH());bf();qH();_x();Sx=B(lr());bE();({readFile:Mse}=Fn.promises),fA=pA.get(SA.CONFIG_PARAMS.COMPONENTSROOT),hA=new Map,Ja=new Map;a(gx,"loadComponentDirectories");Use={REST:Jf,rest:Jf,graphqlSchema:Kh,jsResource:zh,fastifyRoutes:BR,login:jh,static:HR,operationsApi:Lse,customFunctions:{},http:{},clustering:jR,authentication:zu,mqtt:dA},mA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(mA,"static",{value:{files:"web/**"}});dx=[],fx=new Map;a(Pse,"setErrorReporter");a(HE,"loadComponent");Cl=class extends Ft{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var iA=g((pSe,Ax)=>{var{isMainThread:Rx}=require("worker_threads"),{getTables:vse}=(Re(),ie(Fe)),{loadComponentDirectories:Bse,loadComponent:Hse}=(Uf(),ie(Mf)),{resetResources:xse}=(Wu(),ie(HP)),Gse=mg(),qse=lr(),{dirname:Fse}=require("path"),{getConnection:kse}=it(),Vse=ee(),$se=L(),TA=new Map;async function Yse(e=!1){!Rx&&Vse.get($se.CONFIG_PARAMS.CLUSTERING_ENABLED)&&kse();try{Rx&&await Gse()}catch(n){console.error(n)}let t=xse();vse(),t.isWorker=e,await Hse(Fse(qse.getConfigFilePath()),t,"hdb",!0,TA),await Bse(TA,t);let r=[];for(let[n]of TA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Yse,"loadRootComponents");Ax.exports.loadRootComponents=Yse});var Ke=g((TSe,Ui)=>{"use strict";var{Worker:Kse,MessageChannel:Wse,parentPort:Es,isMainThread:bA,threadId:Qse,workerData:$s}=require("worker_threads"),{PACKAGE_ROOT:zse}=L(),{join:Nx,isAbsolute:Jse,extname:jse}=require("path"),{server:Ix}=(or(),ie(Hi)),{watch:Xse,readdir:Zse}=require("fs/promises"),{totalmem:Ox}=require("os"),Dl=L(),wx=ee(),Ys=$(),{randomBytes:eie}=require("crypto"),{_assignPackageExport:tie}=require("../index"),rie=L(),bx=1024*1024,Mi=[],pn=[],nie=50,yA=1e4,sie="restart",Cx="request_thread_info",Dx="resource_report",Lx="thread_info",Mx="added-port",iie="ack",gA;tie("threads",pn);Ui.exports={startWorker:RA,restartWorkers:IA,shutdownWorkers:lie,workers:Mi,setMonitorListener:Sie,onMessageFromWorkers:_ie,onMessageByType:Gx,broadcast:fie,broadcastWithAcknowledgement:hie,setChildListenerByType:uie,getWorkerIndex:Ux,getWorkerCount:Px,getTicketKeys:Bx,setMainIsWorker:aie,setTerminateTimeout:oie,restartNumber:$s?.restartNumber||1};pn.onMessageByType=Gx;pn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=pn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var NA;function oie(e){yA=e}a(oie,"setTerminateTimeout");function Ux(){return $s?$s.workerIndex:NA?0:void 0}a(Ux,"getWorkerIndex");function Px(){return $s?$s.workerCount:NA?1:void 0}a(Px,"getWorkerCount");function aie(e){NA=e}a(aie,"setMainIsWorker");var vx=1,xE;function Bx(){return xE||(xE=bA?eie(48):$s.ticketKeys,xE)}a(Bx,"getTicketKeys");Object.defineProperty(Ix,"workerIndex",{get(){return Ux()}});Object.defineProperty(Ix,"workerCount",{get(){return Px()}});var Hx={[Cx](e,t){mie(t)},[Dx](e,t){pie(t,e)}};function RA(e,t={}){let r=process.constrainedMemory?.()||Ox();r=Math.min(r,Ox(),2e4*bx);let n=wx.get(Dl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/bx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of pn){let _=new Wse;_.existingPort=u,i.push(_),o.push(_.port2)}jse(e)||(e+=".js");let c=new Kse(Jse(e)?e:Nx(zse,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:vx=t.threadCount,name:t.name,restartNumber:Ui.exports.restartNumber,ticketKeys:Bx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Mx,port:u,threadId:c.threadId},[u]);return qE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>RA(e,t),c.on("error",u=>{console.error("Worker error:",u),Ys.error("Worker error:",u)}),c.on("exit",u=>{Mi.splice(Mi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<nie?(t.unexpectedRestarts=c.unexpectedRestarts+1,RA(e,t)):Ys.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{Hx[u.type]?.(u,c)}),Mi.push(c),gie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(RA,"startWorker");var cie=[Dl.THREAD_TYPES.HTTP];async function IA(e=null,t=Math.max(vx>3,1),r=!0){if(bA){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;Ys.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ui.exports.restartNumber,type:Dl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=cie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),yA*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===rie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ys.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");Ys.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}=gf();r&&(e==="http"||!e)&&wx.get(Dl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Es.postMessage({type:sie,workerType:e})}a(IA,"restartWorkers");function uie(e,t){Hx[e]=t}a(uie,"setChildListenerByType");function lie(e){return IA(e,1/0,!1)}a(lie,"shutdownWorkers");var xx=[];function _ie(e){xx.push(e)}a(_ie,"onMessageFromWorkers");var AA=new Map;function Gx(e,t){let r=AA.get(e);r||AA.set(e,r=[]),r.push(t)}a(Gx,"onMessageByType");var die=10;async function fie(e){let t=0;for(let r of pn)try{r.postMessage(e),t++>die&&(t=0,await new Promise(setImmediate))}catch(n){Ys.error("Unable to send message to worker",n)}}a(fie,"broadcast");var GE=new Map,Eie=1;function hie(e){return new Promise(t=>{let r=0;for(let n of pn)try{let s=Eie++,i=a(()=>{GE.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,GE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of GE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ys.error("Unable to send message to worker",s)}r===0&&t()})}a(hie,"broadcastWithAcknowledgement");function mie(e){e.postMessage({type:Lx,workers:qx()})}a(mie,"sendThreadInfo");function qx(){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(qx,"getChildWorkerInfo");function pie(e,t){e.resources=t,e.resources.updated=Date.now()}a(pie,"recordResourceReport");var OA;function Sie(e){OA=e}a(Sie,"setMonitorListener");var Tie=1e3,yx=!1;function gie(){yx||(yx=!0,setInterval(()=>{for(let e of Mi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}OA&&OA()},Tie).unref())}a(gie,"startMonitoring");var Rie=1e3;if(Es){qE(Es);for(let e=0,t=$s.addPorts.length;e<t;e++){let r=$s.addPorts[e];r.threadId=$s.addThreadIds[e],qE(r)}setInterval(()=>{let e=process.memoryUsage();Es.postMessage({type:Dx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Rie).unref(),gA=a(()=>new Promise((e,t)=>{Es.on("message",r),Es.postMessage({type:Cx});function r(n){n.type===Lx&&(Es.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else gA=qx;Ui.exports.getThreadInfo=gA;function qE(e,t){pn.push(e),e.on("message",r=>{if(r.type===Mx)r.port.threadId=r.threadId,qE(r.port);else if(r.type===iie){let n=GE.get(r.id);n&&n()}else{for(let s of xx)s(r,e);let n=AA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ys.error(i)}}}).on("close",()=>{pn.splice(pn.indexOf(e),1)}).on("exit",()=>{pn.splice(pn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(qE,"addPort");if(bA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await Zse(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(Nx(n,i.name));try{for await(let{filename:i}of Xse(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await IA(),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===Dl.ITC_EVENT_TYPES.SHUTDOWN&&(Ui.exports.restartNumber=e.restartNumber,Es.unref(),setTimeout(()=>{Ys.warn("Thread did not voluntarily terminate",Qse),process.exit(0)},yA).unref())})});var DC={};qe(DC,{AUDIT_STORE_OPTIONS:()=>hf,createAuditEntry:()=>m_,openAuditStore:()=>$E,readAuditEntry:()=>Mt,setAuditRetention:()=>Oie,transactionKeyEncoder:()=>zx});function $E(e){let t=e.auditStore=e.openDB(Kx.AUDIT_STORE_NAME,hf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=FE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-wA})){if((_[0]&15)===LA){let l=Mt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Aie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,wA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,VE.getWorkerIndex)()===(0,VE.getWorkerCount)()-1&&s(FE),t}function Oie(e,t=FE){wA=e,FE=t}function m_(e,t,r,n,s,i,o){let c=Jx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?Xa.setFloat64(0,n):Sn.set(fm),u=9),f(0),f(t),d(r),Xa.setFloat64(u,e),u+=8,s?d(s):Sn[u++]=0,Sn[n?8:0]=c;let l=Sn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Za.writeKey)(E,Sn,u);let p=u-h-1;p>127?p>16383?(UA.error("Key or username was too large for audit entry",E),u=h+1,Sn[h]=0):(Sn.copyWithin(h+2,h+1,u),Xa.setUint16(h,p|32768),u++):Sn[h]=p}function f(E){E<128?Sn[u++]=E:E<16384?(Xa.setUint16(u,E|32768),u+=2):E<1056964608?(Xa.setUint32(u,E|3221225472),u+=4):(Sn[u]=255,Xa.setUint32(u+1,E),u+=5)}}function Mt(e){try{let t=e.dataView||(e.dataView=new MA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:Jx[n&7],tableId:i,get recordId(){return Yx(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Yx(e,l,d):void 0},getValue(f,E,h){if(n&CA||n&DA&&!E)return f.decoder.decode(e.subarray(t.position));if(n&DA&&h)return PA(f.getEntry(this.recordId),h,f)}}}catch(t){return UA.error("Reading audit entry error",t,e),{}}}function Yx(e,t,r){let n=e.subarray(t,r);return(0,Za.readKey)(n,0,r-t)}var Za,kE,Kx,Wx,VE,Qx,UA,Sn,Xa,zx,hf,wA,Aie,FE,CA,DA,Fx,LA,kx,Vx,$x,Jx,MA,ei=ge(()=>{Za=require("ordered-binary"),kE=B(ee()),Kx=B(ut()),Wx=B(L()),VE=B(Ke()),Qx=B(Q());wc();UA=B($());YE();(0,kE.initSync)();Sn=Buffer.alloc(1024),Xa=new DataView(Sn.buffer,Sn.byteOffset,1024),zx={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,Za.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,Za.readKey)(e,t,r)}},hf={encoding:"binary",keyEncoder:zx},wA=(0,Qx.convertToMS)((0,kE.get)(Wx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Aie=1e3,FE=1e4;a($E,"openAuditStore");a(Oie,"setAuditRetention");CA=16,DA=32,Fx=1,LA=2,kx=3,Vx=4,$x=5,Jx={put:Fx|CA,[Fx]:"put",delete:LA,[LA]:"delete",message:kx|CA,[kx]:"message",invalidate:Vx,[Vx]:"invalidate",patch:$x|DA,[$x]:"patch"};a(m_,"createAuditEntry");a(Mt,"readAuditEntry");MA=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(Yx,"readKeySafely")});var vA={};qe(vA,{add:()=>KE,applyReverse:()=>jx,getRecordAtTime:()=>PA,rebuildUpdateBefore:()=>WE});function KE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function WE(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,KE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function jx(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=bie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=Xx}}function PA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Mt(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":jx(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===Xx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Mt(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 bie,Xx,YE=ge(()=>{ei();a(KE,"add");KE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};bie={add:KE};a(WE,"rebuildUpdateBefore");a(jx,"applyReverse");Xx={};a(PA,"getRecordAtTime")});function Jr(e){return e[Ct]||(e[Ct]=Object.create(null))}function XE(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[ye])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new Tn.ClientError(`${c} must be a string, attempt to assign ${l}`);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 Tn.ClientError(`${c} must be a string, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new Tn.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new Tn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new Tn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new Tn.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Tn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);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 Tn.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 Tn.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 Tn.ClientError(`${c} must be an object, attempt to assign ${l}`);Jr(this)[c]=l},"set")}_={get(){let l=this[Ct];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=eG(d,o);if(f)return l||(l=this[Ct]=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[Ct];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 Tn.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[Ct],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 eG(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}},XE(r,t)),new r(e)):new QE(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=eG(o,t?.elements)),n[s]=o}return n;default:return e}}function dd(e){let t=e[Ct],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=dd(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[Ct]){let r;if(Zx.call(e,_e)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Mo(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[_e]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=vA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Mo(s);r[n]=s}return r?Object.freeze(r):Zx.call(e,_e)?e[_e]:e}function zE(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(zE(i))return!0}else return!0}}else{let r=e[Ct];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(zE(s))return!0}else return!0}else return!0}}return!1}var Tn,Ct,QE,Zx,Lo,JE,jE,fd=ge(()=>{Nn();Tn=B(ne());YE();Ct=Symbol("own-data");a(Jr,"getChanges");a(XE,"assignTrackedAccessors");a(eG,"trackObject");QE=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}};XE(QE,{});a(dd,"collapseData");Zx=Object.prototype.hasOwnProperty;a(Mo,"deepFreeze");a(zE,"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;jE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Gp={};qe(Gp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Me,IS_COLLECTION:()=>gn,RECORD_PROPERTY:()=>_e,Resource:()=>Ft,snake_case:()=>Nie,transformForSelect:()=>eh});function Nie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function tG(e,t){if(Ll=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Ll=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new HA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Ll=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function jr(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[ye]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[ye]||i):l=i:(l=s,c=l[Me]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[ye]||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 ZE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new ZE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Xr(e,t){let r=new sG.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function BA(e,t,r){let n=e[_e];if(n){let s=e[Ct];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 eh(e,t){let r=t?.propertyResolvers,n=t[ye],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):BA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(BA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(BA(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=eh(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var rG,nG,sG,ye,Me,gn,_e,yie,Ft,ZE,Ll,HA,Nn=ge(()=>{rG=require("crypto");Rc();nG=require("../index"),sG=B(ne());fd();ro();Qf();ye=Symbol.for("context"),Me=Symbol.for("primary-key"),gn=Symbol("is-collection"),_e=Symbol("stored-record"),yie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Ft=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Me]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=jr(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 _=eh(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=jr(function(t,r,n,s){if(Array.isArray(s)&&t[gn]){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):Xr(t,"put")},{hasContent:!0,type:"update"});static patch=jr(function(t,r,n,s){return t.patch?t.patch(s,r):Xr(t,"patch")},{hasContent:!0,type:"update"});static delete=jr(function(t,r,n,s){return t.delete?t.delete(r):Xr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,rG.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),Xe(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):Xr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=jr(function(t,r,n,s){return t.invalidate?t.invalidate(r):Xr(t,"delete")},{hasContent:!1,type:"update"});static post=jr(function(t,r,n,s){return t[Me]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=jr(function(t,r,n,s){return t.connect?t.connect(s,r):Xr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=jr(function(t,r,n,s){return t.subscribe?t.subscribe(r):Xr(t,"subscribe")},{type:"read"});static publish=jr(function(t,r,n,s){return t[Me]!=null&&t.update?.(),t.publish?t.publish(s,r):Xr(t,"publish")},{hasContent:!0,type:"create"});static search=jr(function(t,r,n,s){let i=t.search?t.search(r):Xr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=eh(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=jr(function(t,r,n,s){return t.search?t.search(s,r):Xr(t,"search")},{hasContent:!0,type:"read"});static copy=jr(function(t,r,n,s){return t.copy?t.copy(s,r):Xr(t,"copy")},{type:"create"});static move=jr(function(t,r,n,s){return t.move?t.move(s,r):Xr(t,"move")},{type:"delete"});post(t){if(this[gn])return this.constructor.create(this[Me],t,this[ye]);Xr(this,"post")}static isCollection(t){return t?.[gn]}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&&yie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:tG(t,this),isCollection:Ll}}let i=tG(t,this);return Ll?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[ye],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(_=>_[Me]===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[Me],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[gn]=!0),s}subscribe(t){return new yn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new yn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Me]}getContext(){return this[ye]}};Ft.prototype[ye]=null;(0,nG._assignPackageExport)("Resource",Ft);a(Nie,"snake_case");ZE=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(tG,"pathToId");HA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(jr,"transactional");a(Xr,"missingMethod");a(BA,"selectFromObject");a(eh,"transformForSelect")});function oG(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;ec||((0,th.onMessageByType)(iG,l=>{aG(l.path)}),ec=Object.create(null));let o=ec[s]||(ec[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=ya(t);let u=new GA(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function aG(e,t){if(!ec)return;let r=ec[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Mt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=ya(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,xA.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,p)}catch(p){console.error(p),(0,xA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function cG(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,th.broadcast)({type:iG,path:s}),aG(s,!0)})}}var xA,th,iG,ec,FSe,GA,uG=ge(()=>{xA=B($()),th=B(Ke());Rc();Wu();ei();iG="transaction",FSe=Buffer.alloc(4096);a(oG,"addSubscription");GA=class extends yn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(aG,"notifyFromTransactionData");a(cG,"listenToCommits")});var TR={};qe(TR,{coerceType:()=>rh,makeTable:()=>ih,setServerUtilities:()=>vie,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=[]),cG(i,u);let T=mm(i,n,u),b=0,R,M,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,Le={},Be={},Lt=864e5,zl,Jl,Qs,oO=!1,Ah,Oh,fq=i.getRange({start:!1,end:!1}).constructor,Eq=10,hq=6;h&&uO();class ze extends Ft{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,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),M=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(D=>{let N=this.sources.slice(0,-1);if(N=N.filter(U=>U[D]&&(!U[D].reliesOnPrototype||U.prototype[D])),N.length>0)if(N.length===1){let U=N[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 N){if(U?.source===G)break;x.push(G[D](F,C,U))}return Promise.all(x)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],O=a(D=>{if(y[D]&&(!y[D].reliesOnPrototype||y.prototype[D]))return(N,U,F)=>{if(!N?.source)return y[D](U,F,N)}},"getApplyToCanonicalSource");return Le={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Be={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let D=!1,N=a(async(U,F)=>{let C=U.value,x=U.table?st[c][U.table]:ze;if(c===Vn.SYSTEM_SCHEMA_NAME&&(U.table===Vn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===Vn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(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{N(G,x);continue}if(G.type==="end_txn")continue;let pe=Xe(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ae}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ae of G.attributes)te.find(Ge=>Ge.name===ae.name)||(te.push(ae),Pe=!0);Pe&&(lt({table:s,database:c,attributes:te,origin:"cluster"}),xl.signalSchemaChange(new Gl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(x=G,N(G,G),new Promise(te=>{x.resolve=te})):N(G,G)});D&&(await pe,xl.signalUserChange(new Gl.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,A,I){let y=super.getResource(m,A,I);if(m!=null){oc(m);try{if(y.hasOwnProperty(_e))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let O=!I?.async||i.cache?.get(m),D=On(A),N=D.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return bh(m,A,{transaction:N},O,U=>{if(U?nh(y,U):y[_e]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new Rn.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let F=yh(m,U,A,y);if(F)return D?.disregardReadTxn(),y[qA]=!0,kA(F,C=>(nh(y,C),y))}return y})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(m)),O}}return y}ensureLoaded(){let m=yh(this[Me],this[Zr],this[ye]);if(m)return this[qA]=!0,kA(m,A=>{this[Zr]=A,this[_e]=A.value,this[Bl]=A.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,Lt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(f<0)throw new Error("Expiration can not be negative");Lt=Lt||(f+E)/4,Ih()}static enableAuditing(m=!0){h=m,m&&uO(),ze.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(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));xl.signalSchemaChange(new Gl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[gn])return this.search(m);if(this[Me]===null){if(m?.conditions)return this.search(m);let A=ze.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let I=Xl(m);if(I?.read){if(I.isSuperUser)return!0;let y=I.attribute_permissions,O=A?.select;if(y?.length>0||oO&&O){if(A||(A={}),O){let D=y?.length>0&&FA(y,"read");A.select=O.map(N=>{let U=N.name||N;if(!D||D[U]){let F=Qs[U]?.definition?.tableClass;if(F){if(N.name||(N={name:N}),!F.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else A.select=y.filter(D=>D.read&&!Qs[D.attribute_name]).map(D=>D.attribute_name);return A}else return!0}}allowUpdate(m,A){let I=Xl(m);if(I?.update){let y=I.attribute_permissions;if(y?.length>0){let O=FA(y,"update");for(let D in A)if(!O[D])return!1;for(let D of y){let N=D.attribute_name;!D.update&&!(N in A)&&(A[N]=this.getProperty(N))}}return!0}}allowCreate(m,A){if(this[gn]){let I=Xl(m);if(I?.insert){let y=I.attribute_permissions;if(y?.length>0){let O=FA(y,"insert");for(let D in A)if(!O[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Xl(m)?.delete}update(m,A){if(!On(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[_e]={},this[Ct]=m):(y=this[Ct],y&&(m=Object.assign(y,m)),this[Ct]=y=m)),this._writeUpdate(this[Ct],A),this}addTo(m,A){if(typeof A=="number")this[Ml]===_G?this.set(m,(+this.getProperty(m)||0)+A):(this[Ml]||this.update(),this.set(m,new jE(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let A=this[ye],I=this[Me];oc(I),On(this[ye]).addWrite({key:I,store:i,invalidated:!0,entry:this[Zr],nodeName:this[ye]?.nodeName,before:Le.invalidate?.bind(this,A,I),beforeIntermediate:Be.invalidate?.bind(this,A,I),commit:(O,D)=>{if(D?.version>O)return;let N=null;for(let U in r)N||(N={}),N[U]=this.getProperty(U);T(I,N,this[Zr],O,Ul,h,this[ye],0,"invalidate")}})}static evict(m,A,I){let y=this.Source,O;if(!((M||h)&&(!A||(O=i.getEntry(m),!O||!A)||O.version!==I))){if(M){if(i.hasLock(m,O.version))return;let D;for(let N in r)D||(D={}),D[N]=A[N];if(D)return T(m,D,O,I,Pl,null,null,0,null,!0)}return i.ifVersion(m,I,()=>{jl(m,A,null)}),h?T(m,null,O,I,Pl,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,pG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,I){let y=this[ye],O=On(y),D=this[Me];oc(D);let N=this[Zr];this[Ml]=A?_G:Mie;let U={key:D,store:i,entry:N,nodeName:y?.nodeName,validate:F=>{m||(m=this[Ct]),A||m&&zE(m)?y?.source||(O.checkOverloaded(),this.validate(m,!A),H&&(m[H.name]=H.type==="Date"?new Date(F):H.type==="String"?new Date(F).toISOString():F),A&&(t&&m[t]!==D&&(m[t]=D),k&&(N?.value?m[k.name]=N?.value[k.name]:m[k.name]=k.type==="Date"?new Date(F):k.type==="String"?new Date(F).toISOString():F),m=Mo(m))):O.removeWrite(U)},before:A?Le.put?()=>Le.put(y,D,m):null:Le.patch?()=>Le.patch(y,D,m):Le.put?()=>Le.put(y,D,Mo(this)):null,beforeIntermediate:A?Be.put?()=>Be.put(y,D,m):null:Be.patch?()=>Be.patch(y,D,m):Be.put?()=>Be.put(y,D,Mo(this)):null,commit:(F,C,x)=>{if(x){if(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),this[Zr]=C,C?.value?.[_e])throw new Error("Can not assign a record to a record, check for circular references");A||(this[_e]=C?.value??null)}this[Ct]=m,this[Bl]=F;let G=C?.value,se=m;if(this[Ml]=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=Mt(re);if(Ge=X.version,Ge>F){if(X.type==="patch"){let Oe=X.getValue(i);se=WE(se,Oe)}else if(X.type==="put"||X.type==="delete")return}else if(Ge===F)return;ae=X.previousLocalTime}}else{if(A)return;se=WE(se,G)}let pe;if(A?pe=se:(this[_e]=G,pe=A?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;A||(te=m),jl(D,G,pe);let Pe=A?"put":"patch";T(D,pe,C,F,0,h,y,y.expiresAt||(f?f+Date.now():0),Pe,!1,te)}};O.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[gn]){for await(let A of this.search(m))(await ze.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[_e]?this._writeDelete(m):!1}_writeDelete(m){let A=On(this[ye]),I=this[Me];oc(I);let y=this[ye];return A.addWrite({key:I,store:i,resource:this,nodeName:y?.nodeName,before:Le.delete?.bind(this,y,I),beforeIntermediate:Be.delete?.bind(this,y,I),commit:(O,D,N)=>{let U=D?.value;N&&(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),nh(this,D)),!(D?.version>O)&&(jl(this[Me],U),tt.trace("Write delete entry",I,O),h||p?(T(I,null,this[Zr],O,0,h,this[ye],0,"delete"),h||Ih()):i.remove(this[Me]))}}),!0}search(m){let A=this[ye],I=On(A);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Me]&&(y=[{attribute:null,comparator:"prefix",value:this[Me]}].concat(y));let O,D={};function N(X,Oe){let He;switch(Oe){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');He=!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 "+Oe)}let $n=He&&{},zs;for(let Ye of X){if(Ye.conditions){Ye.conditions=N(Ye.conditions,Ye.operator);continue}let Gt=Ye[0]??Ye.attribute,rn=Gt==null?v:Gs(S,Gt);if(rn){if(He){let Yn=xn(Gt),qt=$n[Yn];qt?(qt.push(Ye),zs=!0):$n[Yn]=[Ye]}(rn.type||Yg[Ye.comparator])&&(Ye[1]===void 0?Ye.value=F(Ye.value,rn):Ye[1]=F(Ye[1],rn))}else if(Gt!=null)throw(0,Rn.handleHDBError)(new Error,`${Gt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(zs)for(let Ye in $n){let Gt=$n[Ye],rn=Gt.length;if(rn>1)for(let Yn=0;Yn<rn;Yn++){let qt=Gt[Yn];if(qt.comparator==="ge"||qt.comparator==="greater_than_equal")for(let Js=0;Js<rn;Js++){let Go=Gt[Js];(Go.comparator==="le"||Go.comparator==="less_than_equal")&&(qt.comparator="between",qt.value=[qt.value,Go.value],X.splice(X.indexOf(Go),1))}if(qt.comparator==="equals"||!qt.comparator){for(let Js=0;Js<rn;Js++)if(Js!==Yn){let Go=Gt[Js];X.splice(X.indexOf(Go),1)}break}}}return X}a(N,"prepareConditions");function U(X,Oe){if(m.enforceExecutionOrder)return X;for(let He of X)He.conditions&&(He.conditions=U(He.conditions,He.operator));return X.length>1&&Oe!=="or"?(0,mG.sortBy)(X,Kf(ze)):X}a(U,"orderConditions");function F(X,Oe){return Array.isArray(X)?X.map(He=>rh(He,Oe)):rh(X,Oe)}a(F,"coerceTypedValues");let C=m.operator;(y.length>0||C)&&(y=N(y,C));let x=typeof m.sort=="object"&&m.sort,G;if(x&&C!=="or"){let X=x.attribute;if(O=y.find(Oe=>xn(Oe.attribute)===xn(X)),!O){if(!Gs(S,X))throw(0,Rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);O={attribute:X,comparator:"sort"},y.push(O)}O.descending=!!x.descending}y=U(y,C),x&&(y[0]===O?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(O&&y.splice(y.indexOf(O),1),G=x));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:C,postOrdering:G,selectApplied:!!se};let pe=I.useReadTxn(),te=Kg(y,C,ze,pe,m,A,(X,Oe)=>aO(X,se,A,pe,Oe),D),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ae=ze.transformEntryForSelect(se,A,pe,D,Pe,!0),Ge=ze.transformToOrderedSelect(te,se,G,pe,A,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 Oe of se)Oe==="*"?X.push(...S.map(He=>He.name)):X.push(Oe.name||Oe);return X}return S.map(X=>X.name)},Ge}static transformToOrderedSelect(m,A,I,y,O,D){let N=new fq;if(I){m=aO(m,A,y,O,null);let U;N.iterate=function(){let C,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=I.dbOrderedAttribute,pe,te,Pe=!0;function ae(re){let X=re.next&&ae(re.next),Oe=re.descending;return(He,$n)=>{let zs=Nh(He,re.attribute,y),Ye=Nh($n,re.attribute,y),Gt=Oe?(0,vo.compareKeys)(Ye,zs):(0,vo.compareKeys)(zs,Ye);return Gt===0?X?.(He,$n)||0:Gt}}a(ae,"createComparator");let Ge=ae(I);return{async next(){let re;if(C)if(re=C.next(),re.done){if(G)return N.onDone&&N.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 N.onDone&&N.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),se){let Oe=Nh(X,se,y);if(Pe)Pe=!1,te=Oe;else if(Oe!==te){te=Oe,pe=X;break}}U.push(X)}while(!0);return I.isGrouped,U.sort(Ge),C=U[Symbol.iterator](),re=C.next(),re.done?(N.onDone&&N.onDone(),re):{value:await D.call(this,re.value)}},return(){N.onDone&&N.onDone(),x.return()},throw(){N.onDone&&N.onDone(),x.throw()}}};let F=a(C=>{if(typeof A=="object"&&Array.isArray(C.attribute))for(let x=0;x<A.length;x++){let G=A[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]&&(A[x]=se={name:G,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&F(C.next)},"applySortingOnSelect");F(I)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(D);return N}static transformEntryForSelect(m,A,I,y,O,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(x=>x?.key??x,"transform");return m===t?C:m.asArray?x=>[C(x)]:x=>({[t]:C(x)})}let N;O&&M&&!m?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(N=!0);let U,F=a(function(C){let x;if(C!=null){if(Ah=C,x=C.value||C.deref?.(),!x&&(C.key===void 0||C.deref)){if(C=bh(C.key??C,A,{transaction:I,lazy:m?.length<4},this.isSync,G=>G),C?.then)return C.then(F.bind(this));x=C?.value}if(N&&(C.metadataFlags&(Ul|Pl)||C.expiresAt&&C.expiresAt<Date.now())){let G=yh(C.key??C,C,A);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,Pe)=>{let ae;typeof te=="object"?ae=te.name:ae=te;let Ge=Qs?.[ae],re;if(Ge){let X=y?.[ae];if(X)if(X.hasMappings){let He=Ge.from?x[Ge.from]:xn(C.key);re=X.get(He),re||(re=[])}else re=X.fromRecord?.(x);else re=Ge(x,A,C);let Oe=a(He=>{if(He&&typeof He=="object"){let $n=Ge.definition?.tableClass||ze;U||(U={});let zs=U[ae]||(U[ae]=$n.transformEntryForSelect(ae===te?null:te.select||(Array.isArray(te)?te:null),A,I,X,O));if(Array.isArray(He)){let Ye=[],Gt=$n.transformToOrderedSelect(He,te.select,typeof te.sort=="object"&&te.sort,A,I,zs)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),rn=a(qt=>{for(;!qt.done;){if(qt?.then)return qt.then(rn);Ye.push(qt.value),qt=Gt.next()}Pe(Ye,ae)},"nextValue"),Yn=rn(Gt.next());Yn&&(G||(G=[]),G.push(Yn));return}else if(He=zs.call(this,He),He?.then){G||(G=[]),G.push(He.then(Ye=>Pe(Ye,ae)));return}}Pe(He,ae)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(Oe))):Oe(re);return}else re=x[ae],re&&typeof re=="object"&&ae!==te&&(re=ze.transformEntryForSelect(te.select||te,A,I,null)({value:re}));Pe(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,Pe)=>{te==="*"?m[Pe]=x:se(te,ae=>pe[Pe]=ae)});else{pe={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ae in x)pe[ae]=x[ae];else se(Pe,(ae,Ge)=>{ae===void 0&&te&&(ae=null),pe[Ge]=ae})}else throw new Rn.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 A=!m.rawEvents,I=oG(ze,this[Me]??null,function(N,U,F,C){try{let x=U.getValue?.(i,A);if(!x&&U.type==="patch"&&A){let G=i.getEntry(N);G?.version===U.version?x=G.value:x=U.getValue?.(i,!0,F),U.type="put"}this.send({id:N,timestamp:F,value:x,version:U.version,type:U.type,beginTxn:C})}catch(x){tt.error(x)}},m.startTime||0,this[gn]);this[gn]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let y=this[Me],O=m.previousCount;O>1e3&&(O=1e3);let D=m.startTime;if(this[gn]){if(D){if(O)throw new Rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:D,exclusiveStart:!0})){let F=Mt(U);if(F.tableId!==n)continue;let C=F.recordId;if(y==null||EG(y,C)){let x=F.getValue(i,A,N);I.send({id:C,timestamp:N,value:x,version:F.version,type:F.type})}I.startTime=N}}else if(O){let N=[];for(let{key:U,value:F}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Mt(F);if(C.tableId!==n)continue;let x=C.recordId;if(y==null||EG(y,x)){let G=C.getValue(i,A,U);if(N.push({id:x,timestamp:U,value:G,version:C.version,type:C.type}),--O<=0)break}}catch(C){tt.error("Error getting history entry",U,C)}for(let U=N.length;U>0;)I.send(N[--U]);N[0]&&(I.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:F,localTime:C}of i.getRange({start:y??!1,end:y==null?void 0:[y,vo.MAXIMUM_KEY],versions:!0}))U&&I.send({id:N,timestamp:C,value:U,version:F,type:"put"})}else{O&&!D&&(D=0);let N=this[Zr]?.localTime;if(N===hm&&(i.cache?.delete(y),this[Zr]=i.getEntry(y),tt.trace("re-retrieved record",N,this[Zr]?.localTime),N=this[Zr]?.localTime),tt.trace("Subscription from",D,"from",y,N),D<N){let U=[],F=N;do{let C=u.get(F);if(C){m.omitCurrent=!0;let x=Mt(C),G=x.getValue(i,A,F);A&&(x.type="put"),U.push({id:y,value:G,timestamp:F,...x}),F=x.previousLocalTime}else break;O&&O--}while(F>D&&O!==0);for(let C=U.length;C>0;)I.send(U[--C]);I.startTime=N}!m.omitCurrent&&this.doesExist()&&I.send({id:y,timestamp:N,value:this,version:this[Bl],type:"put"})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[_e]||this[Ml])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let I=On(this[ye]),y=this[Me]||null;oc(y);let O=this[ye];I.addWrite({key:y,store:i,entry:this[Zr],nodeName:O?.nodeName,validate:()=>{O?.source||(I.checkOverloaded(),this.validate(m))},before:Le.publish?.bind(this,O,y,m),beforeIntermediate:Be.publish?.bind(this,O,y,m),commit:(D,N,U)=>{N===void 0&&p&&!h&&Ih(),T(y,N?.value??null,N,N?.version||D,0,!0,O,N?.expiresAt,"message",!1,m)}})}validate(m,A){let I,y=a((O,D,N)=>{if(D.type&&O!=null)if(A&&O.__op__&&(O=O.value),D.properties){typeof O!="object"&&(I||(I=[])).push(`Value ${kn(O)} in property ${N} 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=y(O[x.name],x,N+"."+x.name);G&&(O[x.name]=G)}if(D.sealed&&O!=null&&typeof O=="object")for(let F in O)U.find(C=>C.name===F)||(I||(I=[])).push(`Property ${F} is not allowed within object in property ${N}`)}else switch(D.type){case"Int":(typeof O!="number"||O>>0!==O)&&(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(U=>typeof U=="string")||(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(D.elements)for(let U=0,F=O.length;U<F;U++){let C=O[U],x=y(C,D.elements,N+"[*]");x&&(O[U]=x)}}else(I||(I=[])).push(`Value ${kn(O)} in property ${N} must be a Buffer or Uint8Array`);break}D.nullable===!1&&O==null&&(I||(I=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let O=0,D=S.length;O<D;O++){let N=S[O];if(!N.relationship&&(!A||N.name in m)){let U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}if(d)for(let O in m)S.find(D=>D.name===O)||(I||(I=[])).push(`Property ${O} is not allowed`);if(I)throw new Rn.ClientError(I.join(". "))}getUpdatedTime(){return this[Bl]}wasLoadedFromSource(){return M?!!this[qA]:void 0}static async addAttributes(m){let A=S.slice(0);for(let I of m){if(!I.name)throw new Rn.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new Rn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(I)}return lt({table:s,database:c,schemaDefined:_,attributes:A}),ze.indexingOperation}static async removeAttributes(m){let A=S.filter(I=>!m.includes(I.name));return lt({table:s,database:c,schemaDefined:_,attributes:A}),ze.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,I=5e3,y=1e3,O;A>I&&!m?.exactCount&&(O=y);let D=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:O}))N!=null&&D++;if(O){let N=D;D=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:O}))Pe!=null&&D++;let U=O*2,F=(D+N)/U,C=Math.pow((D-N+1)/O/2,2)+F*(1-F)/U,x=Math.max(Math.sqrt(C)*A,1),G=Math.round(F*A),se=Math.max(G-1.96*x,0),pe=Math.min(G+1.96*x,A),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(){Qs=this.propertyResolvers={$id:(m,A,I)=>({value:I.key}),$updatedtime:(m,A,I)=>I.version,$record:(m,A,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),oO=!0,A.to)m.elements?.definition?(Qs[m.name]=m.resolve=(I,y,O)=>{let D=I[A.from?A.from:t],N=m.elements.definition.tableClass;return O?Ba({attribute:A.to,value:D},On(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:A.to,value:D}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.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(A.from){let I=m.definition||m.elements?.definition;I?(Qs[m.name]=m.resolve=(y,O,D)=>{let N=y[A.from];if(N!==void 0){if(m.elements){let U,F=N.map(C=>{let x=D?I.tableClass.primaryStore.getEntry(C,{transaction:On(O).getReadTxn()}):I.tableClass.get(C,O);return x?.then&&(U=!0),x});return A.filterMissing?U?Promise.all(F).then(C=>C.filter(hG)):F.filter(hG):U?Promise.all(F):F}return D?I.tableClass.primaryStore.getEntry(N,{transaction:On(O).getReadTxn()}):I.tableClass.get(N,O)}},m.set=(y,O)=>{if(Array.isArray(O)){let D=O.map(N=>N[Me]||N[I.tableClass.primaryKey]);y[A.from]=D}else{let D=O[Me]||O[I.tableClass.primaryKey];y[A.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.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`)}XE(this,this)}static async deleteHistory(m=0){let A;for(let{key:I,value:y}of u.getRange({start:0,end:m}))await vl(),Mt(y).tableId===n&&(A=u.remove(I));await A}static async*getHistory(m=0,A=1/0){for(let{key:I,value:y}of u.getRange({start:m,end:A})){await vl();let O=Mt(y);O.tableId===n&&(yield{id:O.recordId,localTime:I,version:O.version,type:O.type,value:O.getValue(i,!0,I),user:O.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return A;let y=I.localTime;if(!y)throw new Error("The entry does not have a local audit time");let O=0;do{await vl();let D=u.get(y);if(D){let N=Mt(D);A.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(O<1e3&&y);return A.reverse()}static cleanup(){z?.remove()}}ze.updatedAttributes();let mq=ze.prototype;return mq[Lie]=!0,f&&ze.setTTLExpiration(f/1e3),j&&pq(),ze;function jl(K,m,A){let I;for(let y in r){let O=r[y],D=O.isIndexing,N=A?.[y],U=m?.[y];if(N===U&&!D)continue;I=!0;let F=O.indexNulls,C=(0,Hl.getIndexedValues)(N,F),x=(0,Hl.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)&&lG){let se=x.concat(C).map(pe=>({key:pe,value:K}));O.prefetch(se,fG)}for(let se=0,pe=x.length;se<pe;se++)O.remove(x[se],K)}else C?.length>0&&lG&&O.prefetch(C.map(G=>({key:G,value:K})),fG);if(C)for(let G=0,se=C.length;G<se;G++)O.put(C[G],K)}return I}a(jl,"updateIndices");function oc(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>dG)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,Uie,0)>dG)throw new Error("Primary key size is too large: "+K.length);return!0}a(oc,"checkValidId");function bh(K,m,A,I,y){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return y(null,K);let D=i.getEntry(K,A);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),y(D,K)},"whenPrefetched");return I?O():ce>0?(ce--,O()):new Promise((D,N)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),F()})):(J.push(K),me.push(F),J.length>hq&&(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<Eq&&de++}a(U,"prefetch");function F(){try{D(O())}catch(C){N(C)}}a(F,"load")})}a(bh,"loadLocalRecord");function Xl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return Pie;let A=m[c],I,y=A?.tables;if(y)return y[s];if(c==="data"&&(I=m[s])&&!I.tables)return I}a(Xl,"getTablePermissions");function yh(K,m,A,I){if(M){let y;if(A.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Ul|Pl)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,cn(!y,"cache-hit",s)),y){let O=cO(K,m,A).then(D=>(D?.value?.[_e]&&tt.error("Can not assign a record with a record property"),A&&(D?.version>(A.lastModified||0)&&(A.lastModified=D.version),A.lastRefreshed=Date.now()),D));if(A?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,K)){if(O.catch(D=>tt.warn(D)),A?.onlyIfCached&&!I.doesExist())throw new Rn.ServerError("Entry is not cached",504);return}else return O}}}a(yh,"ensureLoadedFromSource");function On(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new to,m.lmdbDb=i,m;m=A}while(!0)}else return new ld}a(On,"txnForContext");function Nh(K,m,A){if(!K)return;Ah=K;let I=K.value||K.deref?.()||(Ah=i.getEntry(K.key))?.value;if(typeof m=="object"){let O=Qs,D=I;for(let N=0,U=m.length;N<U;N++){let F=m[N],C=O?.[F];D=C&&D?C(D,A,!0)?.value:D?.[F],O=C?.definition?.tableClass?.propertyResolvers}return D}let y=Qs[m];return y?y(I,A):I[m]}a(Nh,"getAttributeValue");function aO(K,m,A,I,y){let O=y?.length,D={transaction:I,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(F,C){let x=F?.value;if(!x)return Uo.SKIP;for(let G=0;G<O;G++)if(!N?.includes(G)&&!y[G](x,F))return Uo.SKIP;return C!==void 0&&(F.key=C),F}if(a(U,"processEntry"),O>0||!K.hasEntries){let F=K.map(C=>{if(N=null,typeof C=="object"&&C?.key!==void 0)return O>0?U(C):C;if(C==null)return Uo.SKIP;for(let x=0;x<O;x++){let se=y[x].idFilter;if(se){if(!se(C))return Uo.SKIP;N||(N=[]),N.push(x)}}return bh(C,A,D,!1,U)});return Array.isArray(K)&&(F=F.filter(C=>C!==Uo.SKIP)),F.hasEntries=!0,F}return K}a(aO,"transformToEntries");async function cO(K,m,A){let I=m?.metadataFlags,y=m?.version,O,D;if(!i.attemptLock(K,y,()=>{clearTimeout(D);let C=i.getEntry(K);!C||!C.value||C.metadataFlags&(Ul|Pl)?O(cO(K,i.getEntry(K),A)):O(C)}))return new Promise(C=>{O=C,D=setTimeout(()=>{i.unlock(K,y)},Die)});let N=m?.value,U={requestContext:A,replacingRecord:N,replacingVersion:y,source:null,resourceCache:A?.resourceCache},F=A?.responseHeaders;return new Promise((C,x)=>{let G;kA(Xe(U,async se=>{let pe=performance.now(),te,Pe,ae;try{for(let Oe of ze.sources)if(Oe.get&&(!Oe.get.reliesOnPrototype||Oe.prototype.get)&&(U.source=Oe,te=await Oe.get(K,U),te))break;ae=I&Ul;let re=U.lastModified||ae&&y;Pe=ae||re>y||!N,re||(re=(0,Hl.getNextMonotonicTime)());let X=performance.now()-pe;if(kr(X,"cache-resolution",s),F&&fg(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}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(C({version:y,value:N}),tt.trace(re.message,"(returned stale record)")):x(re),U.transaction.abort();return}if(A?.noCacheStore){U.transaction.abort();return}On(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==y)return;let Oe=jl(K,N,te);te?(Be.put?.(U,K,te),T(K,te,X,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ae)):(Be.delete?.(U,K),h||p?T(K,null,X,re,0,h&&Pe||null,U,0,"delete",!!ae):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&tt.error("Error committing cache update",se)})})}a(cO,"getFromSource");function Ih(){if(Lt!==zl&&(zl=Lt,(0,Po.getWorkerIndex)()===(0,Po.getWorkerCount)()-1)){if(Jl&&clearTimeout(Jl),!Lt)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())/Lt)*Lt+K.getTime(),A=a(I=>{tt.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),Jl=setTimeout(()=>P=P.then(async()=>{if(A(Math.max(I+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Jl);return}let y=50,O=new Array(y),D=0;tt.trace(`Starting cleanup scan for ${s}`);try{let N=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+Cie<Date.now()?G=i.remove(U,C):x&&x+E<Date.now()&&(G=ze.evict(U,F,C),N++),G&&(await O[D],O[D]=G.catch(se=>{tt.error("Cleanup error",se)}),++D>=y&&(D=0)),await vl()}tt.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){tt.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Ih,"scheduleCleanup");function uO(){z=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(uO,"addDeleteRemoval");function pq(){(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 A of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let I of m.getValues(A)){let y=i.getEntry(I);y?.value?y.value[K]<Date.now()&&ze.evict(I,y.value,y.version):i.ifVersion(I,y?.version,()=>m.remove(A,I))}await vl()}}catch(K){tt.error("Error in evicting old records",K)}finally{Oh=!1}}},wie).unref()}a(pq,"runRecordExpirationEviction")}function FA(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function fG(){}function vie(e){pG=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"?(typeof e!="number"&&!Bie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,sh.autoCast)(e):e}function EG(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function kA(e,t,r){return e?.then?e.then(t,r):t(e)}function nh(e,t){e[Zr]=t,e[_e]=t?.value??null,e[Bl]=t?.version}function hG(e){return e!=null}function kn(e){try{return JSON.stringify(e)}catch{return e}}var Vn,Uo,Hl,mG,ql,Rn,xl,Gl,tt,vo,Po,sh,Iie,pG,wie,Cie,lG,Die,Bl,Lie,Zr,Ml,_G,Mie,qA,tc,Ul,Pl,Uie,dG,Pie,iTe,Bie,vl,cE=ge(()=>{Vn=B(L()),Uo=require("lmdb"),Hl=B(Dr()),mG=require("lodash");Nn();oS();ql=B(ee());uG();Rn=B(ne()),xl=B(bs()),Gl=B(Mn());Re();Qf();tt=B($());fd();ro();vo=require("ordered-binary"),Po=B(Ke());ei();sh=B(Q());wc();ws();YE();Qu();Iie=new Uint8Array(9);Iie[8]=192;wie=6e4,Cie=864e5;ql.initSync();lG=ql.get(Vn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Die=1e4,Bl=Symbol.for("version"),Lie=Symbol.for("incremental-update"),Zr=Symbol("entry"),Ml=Symbol("is-saving"),_G=1,Mie=2,qA=Symbol("loaded-from-source"),tc={isNotification:!0,ensureLoaded:!1},Ul=1,Pl=8,Uie=Buffer.allocUnsafeSlow(8192),dG=1978,Pie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},iTe=(0,sh.convertToMS)(ql.get(Vn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(ih,"makeTable");a(FA,"attributesAsObject");a(fG,"noop");a(vie,"setServerUtilities");Bie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(rh,"coerceType");a(EG,"isDescendantId");vl=a(()=>new Promise(setImmediate),"rest");a(kA,"when");a(nh,"updateResource");a(hG,"exists");a(kn,"stringify")});var Fe={};qe(Fe,{database:()=>ru,databases:()=>st,dropDatabase:()=>_S,dropTableMeta:()=>Fie,getDatabases:()=>dr,getDefaultCompression:()=>mf,getTables:()=>Hie,onUpdatedTable:()=>XR,readMetaDb:()=>Fl,resetDatabases:()=>Fu,table:()=>lt,tables:()=>Lr});function Hie(){return lh||dr(),Lr||{}}function dr(){if(lh)return st;lh=!0,sc=new Map;let e=(0,ht.getHdbBasePath)()&&(0,rt.join)((0,ht.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),t=(0,ht.get)(Dt.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)(Dt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,en.existsSync)(e)?e:(0,rt.join)((0,ht.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,en.existsSync)(e))for(let r of(0,en.readdirSync)(e,{withFileTypes:!0})){let n=(0,rt.basename)(r.name,".mdb");r.isFile()&&(0,rt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Fl((0,rt.join)(e,r.name),null,n)}if((0,en.existsSync)((0,nc.getBaseSchemaPath)())){for(let r of(0,en.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,en.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,rt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,rt.join)(s,i.name);Fl((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,en.existsSync)(s))for(let o of(0,en.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,rt.extname)(o.name).toLowerCase()===".mdb"&&Fl((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,en.existsSync)(u)&&Fl(u,o,r,null,!0)}}for(let r in st){let n=sc.get(r);if(n){let s=st[r];r.includes("delete")&&An.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(An.trace(`delete table class ${i}`),delete s[i])}else if(delete st[r],r==="data"){for(let s in Lr)delete Lr[s];delete Lr[dh]}}return sc=null,st}}function Fu(){lh=!1;for(let[,e]of Pi)e.needsDeletion=!0;dr();for(let[e,t]of Pi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Pi.delete(e));return st}function Fl(e,t,r=YA,n,s){let i=new VA.default(e,!1);try{let o=Pi.get(e);o?o.needsDeletion=!1:(o=(0,ah.open)(i),Pi.set(e,o));let c=new Bo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(oh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,en.existsSync)(n)&&(i.path=n,_=(0,ah.open)(i),_.isLegacy=!0):_=$E(o));let l=RG(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){An.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[E],b={},R=[],M,v,P=typeof S.audit=="boolean"?S.audit:(0,ht.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=S.trackDeletes,H=S.expiration,j=S.eviction,z=S.sealed;if(T)b=T.indices,R=T.attributes,T.schemaVersion++;else{M=S.tableId,M?M>=(u.get(rc)||0)&&u.putSync(rc,M+1):(S.tableId=M=u.get(rc),M||(M=1),u.putSync(rc,M+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)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||gG;J.compression.threshold=me}v=p_(o.openDB(S.key,J)),v.rootStore=o,v.tableId=M}for(let J of p){J.attribute=J.name;try{if(!J.is_hash_attribute&&(J.indexed||J.attribute&&!J.name)){if(!b[J.name]){let ce=new Bo.default(!J.is_hash_attribute,J.is_hash_attribute);b[J.name]=o.openDB(J.key,ce),b[J.name].indexNulls=J.indexNulls}let me=R.find(ce=>ce.name===J.name);me?R.splice(R.indexOf(me),1,J):R.push(J)}}catch(me){An.error("Error trying to update attribute",J,R,b,me)}}if(!T){T=AG(l,E,ih({primaryStore:v,auditStore:_,audit:P,sealed:z,expirationMS:H&&H*1e3,evictionMS:j&&j*1e3,trackDeletes:k,tableName:E,tableId:M,primaryKey:S.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:b,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let J of KA)J(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function RG(e){let t=st[e];if(t||(e==="data"?t=st[e]=Lr: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 AG(e,t,r){return e[t]=r,r}function ru({database:e,table:t}){e||(e=YA),dr();let r=RG(e),n=(0,rt.join)((0,ht.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),s=(0,ht.get)(Dt.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)(Dt.CONFIG_PARAMS.STORAGE_PATH)||((0,en.existsSync)(n)?n:(0,rt.join)((0,ht.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME));let o=(0,rt.join)(n,(i?t:e)+".mdb"),c=Pi.get(o);if(!c){let u=new VA.default(o,!1);c=(0,ah.open)(u),Pi.set(o,c)}return c}async function _S(e){if(!st[e])throw new Error("Schema does not exist");let t=st[e];for(let r in t){let s=t[r].primaryStore.rootStore;Pi.delete(s.path),s.status==="open"&&(await s.close(),await _h.remove(s.path))}if(e==="data"){for(let r in Lr)delete Lr[r];delete Lr[dh]}delete st[e]}function lt({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=YA);let d=ru({database:t,table:e}),f=st[t],E=f?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let b=new Bo.default(!1);for(let H of i)H.attribute?(H.name=H.attribute,H.indexed=!0):H.attribute=H.name,H.expiresAt&&(H.indexed=!0);let R,M;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=$E(d)),p=i.find(me=>me.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=mf(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,ht.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),An.trace(`${e} table loading, opening primary store`);let j=new Bo.default(!1,!0);j.compression=p.compression;let z=e+"/",J=p_(d.openDB(z,j));J.rootStore=d,T=d.dbisDb=d.openDB(oh.INTERNAL_DBIS_NAME,b),J.tableId=T.get(rc),J.tableId||(J.tableId=1),T.putSync(rc,J.tableId+1),p.tableId=J.tableId,E=AG(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,R=!0,k(),T.put(z,p)}S=E.indices,T=T||(d.dbisDb=d.openDB(oh.INTERNAL_DBIS_NAME,b)),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(),R=!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),R=!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<kl.workerData?.restartNumber)&&(R=!0,k(),z=T.get(j),(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<kl.workerData?.restartNumber)&&(R=!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&&(R=!0,k(),T.put(j,H))}}finally{M&&M()}if(R&&(E.schemaVersion++,E.updatedAttributes()),An.trace(`${e} table loading, running index`),P.length>0||v.length>0?E.indexingOperation=qie(E,P,v):R&&ch.signalSchemaChange(new uh.SchemaEventMsg(process.pid,"schema-change",E.databaseName,E.tableName)),E.origin=l,R)for(let H of KA)H(E,l!=="cluster");return(r||n||s)&&E.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),An.trace(`${e} table loaded`),E;function k(){M||d.transactionSync(()=>({then(H){M=H}}))}a(k,"startTxn")}async function qie(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,SG.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--,An.error(f)}),kl.workerData&&kl.workerData.restartNumber!==TG.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>xie?await s:u>Gie&&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){An.error("Error in indexing",n)}}function Fie({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 XR(e){KA.push(e)}function mf(){let e=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||gG,n={startingOffset:32};return t&&(n.dictionary=_h.readFileSync(t)),r&&(n.threshold=r),e&&n}var ht,oh,ah,rt,en,nc,Bo,VA,Dt,_h,$A,SG,ch,uh,kl,An,TG,YA,dh,gG,Lr,st,rc,KA,lh,Pi,sc,xie,Gie,Re=ge(()=>{ht=B(ee()),oh=B(ut()),ah=require("lmdb"),rt=require("path"),en=require("fs"),nc=B(Je());cE();Bo=B(Cc()),VA=B(Dc()),Dt=B(L()),_h=B(require("fs-extra")),$A=require("../index"),SG=B(Dr()),ch=B(bs()),uh=B(Mn()),kl=require("worker_threads"),An=B($()),TG=B(Ke());ei();wc();YA="data",dh=Symbol("defined-tables"),gG=((0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,ht.initSync)();Lr=Object.create(null),st=Object.create(null);(0,$A._assignPackageExport)("databases",st);(0,$A._assignPackageExport)("tables",Lr);rc=Symbol.for("next-table-id"),KA=[],Pi=new Map;a(Hie,"getTables");a(dr,"getDatabases");a(Fu,"resetDatabases");a(Fl,"readMetaDb");a(RG,"ensureDB");a(AG,"setTable");a(ru,"database");a(_S,"dropDatabase");a(lt,"table");xie=1e3,Gie=10;a(qie,"runIndexing");a(Fie,"dropTableMeta");a(XR,"onUpdatedTable");a(mf,"getDefaultCompression")});var Q=g((ETe,BG)=>{"use strict";var vi=require("path"),IG=require("fs-extra"),Ir=$(),OG=require("fs-extra"),fh=require("os"),kie=require("net"),Vie=require("recursive-iterator"),ct=L(),$ie=kO(),bG=require("papaparse"),Eh=require("moment"),{inspect:Yie}=require("util"),yG=require("is-number"),fTe=require("lodash"),Kie=require("minimist"),Wie=require("https"),Qie=require("http"),{hdb_errors:hh}=ne(),zie=/^((\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)))$/,wG=require("util").promisify(setTimeout),Jie=100,jie=5,Xie="",Zie=4,NG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};BG.exports={isEmpty:tn,isEmptyOrZeroLength:hs,arrayHasEmptyValues:roe,arrayHasEmptyOrZeroLengthValues:noe,buildFolderPath:soe,isBoolean:CG,errorizeMessage:eoe,stripFileExtension:ooe,autoCast:aoe,autoCastJSON:DG,autoCastJSONDeep:QA,removeDir:coe,compareVersions:uoe,isCompatibleDataVersion:loe,escapeRawValue:_oe,unescapeValue:doe,stringifyProps:foe,timeoutPromise:hoe,isClusterOperation:poe,getClusterUser:Toe,checkGlobalSchemaTable:Soe,getHomeDir:MG,getPropsFilePath:Eoe,promisifyPapaParse:goe,removeBOM:UG,createEventPromise:Roe,checkProcessRunning:Aoe,checkSchemaTableExist:Ooe,checkSchemaExists:PG,checkTableExists:vG,getStartOfTomorrowInSeconds:boe,getLimitKey:yoe,isObject:ioe,isNotEmptyAndHasValue:toe,autoCasterIsNumberCheck:LG,backtickASTSchemaItems:Noe,isPortTaken:moe,createForkArgs:Ioe,autoCastBoolean:woe,async_set_timeout:wG,getTableHashAttribute:Coe,doesSchemaExist:Doe,doesTableExist:Loe,stringifyObj:Moe,ms_to_time:Uoe,changeExtension:Poe,getEnvCliRootPath:zA,noBootFile:voe,httpRequest:Boe,transformReq:Hoe,convertToMS:xoe,PACKAGE_ROOT:ct.PACKAGE_ROOT};function eoe(e){return e instanceof Error?e:new Error(e)}a(eoe,"errorizeMessage");function tn(e){return e==null}a(tn,"isEmpty");function toe(e){return!tn(e)&&(e||e===0||e===""||CG(e))}a(toe,"isNotEmptyAndHasValue");function hs(e){return tn(e)||e.length===0||e.size===0}a(hs,"isEmptyOrZeroLength");function roe(e){if(tn(e))return!0;for(let t=0;t<e.length;t++)if(tn(e[t]))return!0;return!1}a(roe,"arrayHasEmptyValues");function noe(e){if(hs(e))return!0;for(let t=0;t<e.length;t++)if(hs(e[t]))return!0;return!1}a(noe,"arrayHasEmptyOrZeroLengthValues");function soe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(soe,"buildFolderPath");function CG(e){return tn(e)?!1:e===!0||e===!1}a(CG,"isBoolean");function ioe(e){return tn(e)?!1:typeof e=="object"}a(ioe,"isObject");function ooe(e){return hs(e)?Xie:e.slice(0,-Zie)}a(ooe,"stripFileExtension");function aoe(e){return tn(e)||e===""||typeof e!="string"?e:NG[e]!==void 0?NG[e]:LG(e)===!0?Number(e):zie.test(e)?new Date(e):e}a(aoe,"autoCast");function DG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(DG,"autoCastJSON");function QA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=QA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=QA(r);n!==r&&(e[t]=n)}return e}else return DG(e)}a(QA,"autoCastJSONDeep");function LG(e){if(e.startsWith("0.")&&yG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&yG(e))}a(LG,"autoCasterIsNumberCheck");async function coe(e){if(hs(e))throw new Error(`Directory path: ${e} does not exist`);try{await OG.emptyDir(e),await OG.remove(e)}catch(t){throw Ir.error(`Error removing files in ${e} -- ${t}`),t}}a(coe,"removeDir");function uoe(e,t){if(hs(e)){Ir.info("Invalid current version sent as parameter.");return}if(hs(t)){Ir.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(uoe,"compareVersions");function loe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(loe,"isCompatibleDataVersion");function _oe(e){if(tn(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(_oe,"escapeRawValue");function doe(e){if(tn(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(doe,"unescapeValue");function foe(e,t){if(tn(e))return Ir.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{Ir.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(foe,"stringifyProps");function MG(){let e;try{e=fh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(MG,"getHomeDir");function Eoe(){let e=vi.join(MG(),ct.HDB_HOME_DIR_NAME,ct.BOOT_PROPS_FILE_NAME);return IG.existsSync(e)||(e=vi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Eoe,"getPropsFilePath");function hoe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(hoe,"timeoutPromise");async function moe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=kie.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(moe,"isPortTaken");function poe(e){try{return ct.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Ir.error(`Error checking operation against cluster ops ${t}`)}return!1}a(poe,"isClusterOperation");function Soe(e,t){let r=(Re(),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(Soe,"checkGlobalSchemaTable");function Toe(e,t){if(tn(t)){Ir.warn("No CLUSTERING_USER defined, clustering disabled");return}if(tn(e)||hs(e)){Ir.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){Ir.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Ir.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Toe,"getClusterUser");function goe(){bG.parsePromise=function(e,t,r){return new Promise(function(n,s){bG.parse(e,{header:!0,transformHeader:UG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(goe,"promisifyPapaParse");function UG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(UG,"removeBOM");function Roe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Ir.info(`Got cluster status event response: ${Yie(s)}`);try{i.cancel()}catch{Ir.error("Error trying to cancel timeout.")}n(s)})})}a(Roe,"createEventPromise");async function Aoe(e){let t=!0,r=0;do await wG(Jie*r++),(await $ie.findPs(e)).length>0&&(t=!1);while(t&&r<jie);if(t)throw new Error(`process ${e} was not started`)}a(Aoe,"checkProcessRunning");function Ooe(e,t){let r=PG(e);if(r)return r;let n=vG(e,t);if(n)return n}a(Ooe,"checkSchemaTableExist");function PG(e){let{getDatabases:t}=(Re(),ie(Fe));if(!t()[e])return hh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(PG,"checkSchemaExists");function vG(e,t){let{getDatabases:r}=(Re(),ie(Fe));if(!r()[e][t])return hh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(vG,"checkTableExists");function boe(){let e=Eh().utc().add(1,ct.MOMENT_DAYS_TAG).startOf(ct.MOMENT_DAYS_TAG).unix(),t=Eh().utc().unix();return e-t}a(boe,"getStartOfTomorrowInSeconds");function yoe(){return Eh().utc().format("DD-MM-YYYY")}a(yoe,"getLimitKey");function Noe(e){try{let t=new Vie(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){Ir.error("Got an error back ticking items."),Ir.error(t)}}a(Noe,"backtickASTSchemaItems");function Ioe(e){return[e]}a(Ioe,"createForkArgs");function woe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(woe,"autoCastBoolean");function Coe(e,t){let{getDatabases:r}=(Re(),ie(Fe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Coe,"getTableHashAttribute");function Doe(e){let{getDatabases:t}=(Re(),ie(Fe));return t()[e]!==void 0}a(Doe,"doesSchemaExist");function Loe(e,t){let{getDatabases:r}=(Re(),ie(Fe));return r()[e]?.[t]!==void 0}a(Loe,"doesTableExist");function Moe(e){try{return JSON.stringify(e)}catch{return e}}a(Moe,"stringifyObj");function Uoe(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(Uoe,"ms_to_time");function Poe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(Poe,"changeExtension");function zA(){if(process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Kie(process.argv);if(e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(zA,"getEnvCliRootPath");var WA;function voe(){if(WA)return WA;let e=zA();zA()&&IG.pathExistsSync(vi.join(e,ct.HDB_CONFIG_FILE))&&(WA=!0)}a(voe,"noBootFile");function Boe(e,t){let r;return e.protocol==="http:"?r=Qie:r=Wie,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(Boe,"httpRequest");function Hoe(e){if(!e.schema&&!e.database){e.schema=ct.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Hoe,"transformReq");function xoe(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(xoe,"convertToMS")});var ee=g((mTe,FG)=>{"use strict";var JA=require("fs-extra"),Ho=require("path"),HG=require("os"),Goe=require("properties-reader"),$l=$(),Vl=Q(),ue=L(),mh=lr(),qoe="Error initializing environment manager",ph="BOOT_PROPS_FILE_PATH",xG=!1,Foe={[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},Ks={};FG.exports={BOOT_PROPS_FILE_PATH:ph,getHdbBasePath:koe,setHdbBasePath:Voe,get:GG,initSync:Yoe,setProperty:Ue,initTestEnvironment:Woe,setCloneVar:Koe};function koe(){return Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(koe,"getHdbBasePath");function Voe(e){Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Voe,"setHdbBasePath");function GG(e){let t=mh.getConfigValue(e);return t===void 0?Ks[e]:t}a(GG,"get");function Ue(e,t){Foe[e]&&(Ks[e]=t),mh.updateConfigObject(e,t)}a(Ue,"setProperty");function $oe(){let e;try{e=Vl.getPropsFilePath(),JA.accessSync(e,JA.constants.F_OK|JA.constants.R_OK),xG=!0;let t=Goe(e);return Ks[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Ks[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ks[ph]=e,!0}catch{return $l.trace(`Environment manager found no properties file at ${e}`),!1}}a($oe,"doesPropFileExist");function Yoe(e=!1){try{(xG||$oe()||Vl.noBootFile())&&!qG&&(mh.initConfig(e),Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=mh.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){$l.error(qoe),$l.error(t),console.error(t),process.exit(1)}}a(Yoe,"initSync");var qG=!1;function Koe(e){qG=e}a(Koe,"setCloneVar");function Woe(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");Ks[ph]=Ho.join(u,"hdb_boot_properties.file"),Ue(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Ho.join(u,"settings.test")),Ue(ue.HDB_SETTINGS_NAMES.INSTALL_USER,HG.userInfo()?HG.userInfo().username:void 0),Ue(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ue(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Ho.join(u,"envDir","log")),Ue(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Ho.join(u,"envDir")),Ue(ue.CONFIG_PARAMS.STORAGE_PATH,Ho.join(u,"envDir")),s&&(Ue(ue.CONFIG_PARAMS.HTTP_SECUREPORT,GG(ue.CONFIG_PARAMS.HTTP_PORT)),Ue(ue.CONFIG_PARAMS.HTTP_PORT,null)),Ue(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Ue(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ue(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Vl.isEmpty(i)?!1:i),Ue(ue.CONFIG_PARAMS.HTTP_CORS,Vl.isEmpty(i)?!1:i),Ue(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ue(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Ho.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ue(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Vl.isEmpty(c)?!1:c),o&&(Ue("CORS_ACCESSLIST",o),Ue(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Ue(ue.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ue(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ue(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`;$l.fatal(r),$l.error(t)}}a(Woe,"initTestEnvironment")});var KG=g((STe,YG)=>{"use strict";var $G=require("joi"),{string:Yl,boolean:kG,array:Qoe}=$G.types(),VG=L(),zoe=je();YG.exports=Joe;function Joe(e){let t=$G.object({operation:Yl.valid(VG.OPERATIONS_ENUM.ADD_NODE,VG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Yl.required(),subscriptions:Qoe.items({schema:Yl.required(),table:Yl.optional(),hash_attribute:Yl.optional(),subscribe:kG.required(),publish:kG.required()}).min(1).required()});return zoe.validateBySchema(e,t)}a(Joe,"updateRemoteSourceValidator")});var Kl=g((gTe,WG)=>{"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}};WG.exports=jA});var jG=g((ATe,JG)=>{"use strict";var joe=KG(),Ws=$(),XA=ke(),Xoe=L(),ZA=ln(),xo=it(),QG=Tu(),Zoe=ad(),{Node:eae,NodeSubscription:zG}=mi(),eO=Kl(),tO=Q(),tae=ee(),{cloneDeep:rae}=require("lodash"),{broadcast:nae}=Ke();JG.exports=sae;async function sae(e){try{let t=joe(e);if(t)return Ws.error(`Validation error in updateRemoteSource: ${t.message}`),new eO(XA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=rae(await ZA.getNodeRecord(n)),c=!tO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Ws.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!tO.doesSchemaExist(f)){Ws.trace(`updateRemoteSource creating schema: ${f}`);try{await QG.createSchema({operation:"create_schema",schema:f})}catch(h){Ws.error(h)}}if(E&&!tO.doesTableExist(f,E)){let h=new Zoe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Ws.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await QG.createTable(h)}catch(p){Ws.error(p)}}if(Ws.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 zG(f,E,d.publish,d.subscribe))}else i.push(new zG(f,E,d.publish,d.subscribe))}c||(o=new eae(n,i,void 0),Ws.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await ZA.upsertNodeRecord(u),nae({type:"nats_update"}),new eO(XA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${tae.get(Xoe.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await ZA.getSystemInfo())}catch(t){Ws.error(t);let r=t.message?t.message:t;return new eO(XA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(sae,"updateRemoteSource")});var tq=g((bTe,eq)=>{"use strict";var ZG=require("joi"),{string:XG}=ZG.types(),iae=L(),oae=je();eq.exports=aae;function aae(e){let t=ZG.object({operation:XG.valid(iae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:XG.required()});return oae.validateBySchema(e,t)}a(aae,"removeRemoteSourceValidator")});var sq=g((NTe,nq)=>{"use strict";var cae=tq(),Sh=$(),Th=ke(),rO=L(),uae=ln(),lae=Q(),rq=it(),_ae=ee(),gh=Kl(),{NodeSubscription:dae}=mi(),fae=ia(),Eae=ii(),{broadcast:hae}=Ke(),mae=_ae.get(rO.CONFIG_PARAMS.CLUSTERING_NODENAME);nq.exports=pae;async function pae(e){try{let t=cae(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 uae.getNodeRecord(r);if(lae.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 dae(c.schema,c.table,!1,!1);await rq.updateConsumerIterator(c.schema,c.table,r,"stop"),await rq.updateRemoteConsumer(u,r)}let s=new fae(rO.SYSTEM_SCHEMA_NAME,rO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Eae.deleteRecord(s),hae({type:"nats_update"}),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${mae} 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(pae,"removeRemoteSource")});var cq=g((wTe,aq)=>{"use strict";var Rh=$(),Wl=L(),iq=ke(),nO=ee(),Sae=Q(),oq=Kl(),Tae=ln(),gae=Hd(),Rae=vr();aq.exports=Aae;async function Aae(e){try{Rh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Sae.ms_to_time(t),n=new Oae(nO.get(Wl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),nO.get(Wl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??nO.get(Wl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Tae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new gae(Wl.SYSTEM_SCHEMA_NAME,Wl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await Rae.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 oq(iq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){Rh.error(t);let r=t.message?t.message:t;return new oq(iq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Aae,"getRemoteSourceConfig");function Oae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(Oae,"ConfigResponseObject")});var dq=g((DTe,_q)=>{"use strict";var uq=ee();uq.initSync();var lq=it(),Ql=$(),ic=L(),sO=ke(),bae=jG(),yae=sq(),Nae=cq(),Iae=Kl(),{encode:wae,decode:Cae}=require("msgpackr"),Dae=Os(),Lae=As(),Mae=require("util"),Uae=L(),{isMainThread:Pae,parentPort:vae}=require("worker_threads");Ke();var Bae=Mae.promisify(Dae.setSchemaDataToGlobal),iO=uq.get(ic.CONFIG_PARAMS.CLUSTERING_NODENAME);_q.exports=Hae;async function Hae(){try{Ql.notify("Starting reply service."),await Bae();let e=await lq.getConnection(),t=`${iO}.__request__`,r=e.subscribe(t,{queue:iO});await xae(r)}catch(e){Ql.error(e)}}a(Hae,"initialize");async function xae(e){for await(let t of e){let r=Cae(t.data),n;switch(r.operation){case ic.OPERATIONS_ENUM.ADD_NODE:case ic.OPERATIONS_ENUM.UPDATE_NODE:n=await bae(r);break;case ic.OPERATIONS_ENUM.REMOVE_NODE:n=await yae(r);break;case ic.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Nae(r);break;case ic.OPERATIONS_ENUM.DESCRIBE_ALL:n=await Gae();break;default:let s=`node '${iO}' reply service received unrecognized request operation`;Ql.error(s),n=new Iae(sO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Ql.trace(n),t.respond(wae(n))}}a(xae,"handleRequest");async function Gae(){try{return{status:sO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Lae.describeAll()}}catch(e){return Ql.error(e),{status:sO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(Gae,"getRemoteDescribeAll");Pae||vae.on("message",async e=>{let{type:t}=e;t===Uae.ITC_EVENT_TYPES.SHUTDOWN&&lq.closeConnection()})});var qae=dq();(async()=>{try{await qae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|