harperdb 4.3.0 → 4.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +19 -19
- package/bin/lite.js +15 -15
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +15 -15
- package/launchServiceScripts/launchNatsReplyService.js +17 -17
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +15 -15
- package/npm-shrinkwrap.json +23 -23
- package/package.json +1 -1
- package/server/jobs/jobProcess.js +15 -15
- package/server/threads/threadServer.js +14 -14
- 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.08f98c36.js} +2 -2
- package/utility/scripts/restartHdb.js +15 -15
- /package/studio/build-local/static/js/{main.6edd076f.js.LICENSE.txt → main.08f98c36.js.LICENSE.txt} +0 -0
|
@@ -1,22 +1,22 @@
|
|
|
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(Sn,"createLogRecord");function fc(e){mn&&xO(e),Ws&&process.stdout.write(e)}a(fc,"logStdOut");function n_(e){mn&&xO(e),Ws&&process.stderr.write(e)}a(n_,"logStdErr");function xO(e){
|
|
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 mq=Object.create;var oc=Object.defineProperty;var pq=Object.getOwnPropertyDescriptor;var Sq=Object.getOwnPropertyNames;var Tq=Object.getPrototypeOf,gq=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 Sq(t))!gq.call(e,n)&&n!==r&&oc(e,n,{get:()=>t[n],enumerable:!(s=pq(t,n))||s.enumerable});return e};var B=(e,t,r)=>(r=e!=null?mq(Tq(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 Rq=require("fast-glob"),{statSync:wh,existsSync:Ch,readFileSync:Aq,writeFileSync:Oq}=require("fs"),{spawnSync:bq,spawn:yq,execFileSync:Gae}=require("child_process"),{isMainThread:Nq}=require("worker_threads"),{join:Xn,relative:_O}=require("path"),{PACKAGE_ROOT:bs}=L(),{tmpdir:Iq,platform:wq}=require("os");require("source-map-support").install();var Cq=["resources","server","dataLayer","components"],ac="ts-build",Dh,Dq=__filename.endsWith("tsBuild.js");if(Dq){if(Nq){let r;try{wh(Xn(bs,ac)),r=!0}catch{}if(r)for(let s of Rq.sync(Cq.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");wq()==="win32"&&(s+=".cmd");let n=bq(s,{cwd:bs});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=Xn(Iq(),"harperdb-tsc.pid"),o;if(Ch(i))try{process.kill(+Aq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=yq(s,["--watch"],{cwd:bs,detached:!0,stdio:"ignore"});Oq(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"),Lq=require("fs"),{relative:Fae,join:kae}=ss,{existsSync:Mq}=Lq;function Uq(){let e=__dirname;for(;!Mq(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(Uq,"getHDBPackageRoot");var jn=Uq(),EO="js",jl=EO,Pq="harperdb-config.yaml",vq="defaultConfig.yaml",Bq="hdb",hO=`harperdb.${jl}`,mO=`customFunctionsServer.${jl}`,Hq=`restartHdb.${jl}`,Mh="HarperDB",Xl="Custom Functions",Zl="Clustering Hub",e_="Clustering Leaf",xq="Clustering Ingest Service",Gq="Clustering Reply Service",qq="foreground.pid",Fq="hdb.pid",kq="data",Vq={HDB:Mh,CLUSTERING_HUB:Zl,CLUSTERING_LEAF:e_,CLUSTERING_INGEST_SERVICE:xq,CLUSTERING_REPLY_SERVICE:Gq,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"},$q={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Yq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Kq={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"},Wq={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")},Qq={HDB:ss.join(Lh.HDB,hO),CUSTOM_FUNCTIONS:ss.join(Lh.CUSTOM_FUNCTIONS,mO)},zq={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")},Jq={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},pO="support@harperdb.io",Xq="customer-success@harperdb.io",SO=1,jq=4141,TO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",Zq="https://www.harperdb.io/product",eF=`For support, please submit a request at ${TO} or contact ${pO}`,gO=`For license support, please contact ${Xq}`,tF="None of the specified records were found.",rF="hash attribute not found",sF=`Your current license only supports ${SO} role. ${gO}`,nF="Your current license only supports 3 connections to a node.",iF="127.0.0.1",oF=1,aF=/^\.$/,cF=/^\.\.$/,uF="U+002E",lF=/\//g,_F="U+002F",dF=/U\+002F/g,fF=/^U\+002E$/,EF=/^U\+002EU\+002E$/,hF="d",mF=999999,pF="*",SF="--max-old-space-size=",TF="system",gF="__hdb_hash",RF=".harperdb",AF=".hdb",OF="keys",bF="hdb_boot_properties.file",yF=".updateConfig.json",NF="SIGTSTP",IF=24,wF=6e4,CF=448,DF="blob",LF="trash",MF="database",UF="schema",PF="transactions",vF=".count",BF="id",HF="PROCESS_NAME",RO={SETTINGS_PATH_KEY:"settings_path"},AO=require("lodash"),xF={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"},GF={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},qF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},FF={JOB_TABLE_NAME:"hdb_job",NODE_TABLE_NAME:"hdb_nodes",ATTRIBUTE_TABLE_NAME:"hdb_attribute",LICENSE_TABLE_NAME:"hdb_license",ROLE_TABLE_NAME:"hdb_role",SCHEMA_TABLE_NAME:"hdb_schema",TABLE_TABLE_NAME:"hdb_table",USER_TABLE_NAME:"hdb_user",INFO_TABLE_NAME:"hdb_info"},kF={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},wr="hdb_internal:",VF={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"},$F={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"},YF="060493.ks",KF=".license",WF={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"},QF={CSV:".csv",JSON:".json"},zF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},JF={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 XF={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"},jF={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"},ZF=AO.invert(OO),ek={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 tk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},rk={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"},sk={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"},nk={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},ik={VERSION_DEFAULT:"2.2.0"},ok={DEVELOPMENT:8192,DEFAULT:512},ak={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"},ck={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"},uk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},yO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},lk=Symbol("metadata"),_k="__clustering__",dk=Object.values(yO),fk=15984864e5,NO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Ek=AO.invert(NO),hk={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"},mk=111,pk=`\r
|
|
2
|
+
`,Sk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Tk=["*","%"],gk="unauthorized_access",Rk="func_val",Ak={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Ok={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},bk={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"},yk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Nk={HTTP:"http"},Ik={STOPPED:"stopped",ONLINE:"online"},wk="3.x.x",Ck={SUCCESS:"success",FAILURE:"failure"},Dk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};IO.exports={LOCAL_HARPERDB_OPERATIONS:xe,HDB_SUPPORT_ADDRESS:pO,HDB_SUPPORT_URL:TO,HDB_PRICING_URL:Zq,SUPPORT_HELP_MSG:eF,LICENSE_HELP_MSG:gO,HDB_PROC_NAME:hO,HDB_PROC_DESCRIPTOR:Mh,CLUSTERING_LEAF_PROC_DESCRIPTOR:e_,CLUSTERING_HUB_PROC_DESCRIPTOR:Zl,SYSTEM_SCHEMA_NAME:TF,HASH_FOLDER_NAME:gF,HDB_HOME_DIR_NAME:RF,UPDATE_FILE_NAME:yF,LICENSE_KEY_DIR_NAME:OF,BOOT_PROPS_FILE_NAME:bF,JOB_TYPE_ENUM:rk,JOB_STATUS_ENUM:WF,SYSTEM_TABLE_NAMES:FF,SYSTEM_TABLE_HASH_ATTRIBUTES:kF,OPERATIONS_ENUM:Z,VALID_S3_FILE_TYPES:QF,S3_BUCKET_AUTH_KEYS:zF,VALID_SQL_OPS_ENUM:JF,GEO_CONVERSION_ENUM:jF,HDB_SETTINGS_NAMES:OO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:ZF,SERVICE_ACTIONS_ENUM:XF,CLUSTER_MESSAGE_TYPE_ENUM:sk,CLUSTER_CONNECTION_DIRECTION_ENUM:nk,CLUSTER_EVENTS_DEFS_ENUM:ak,PERIOD_REGEX:aF,DOUBLE_PERIOD_REGEX:cF,UNICODE_PERIOD:uF,FORWARD_SLASH_REGEX:lF,UNICODE_FORWARD_SLASH:_F,ESCAPED_FORWARD_SLASH_REGEX:dF,ESCAPED_PERIOD_REGEX:fF,ESCAPED_DOUBLE_PERIOD_REGEX:EF,REG_KEY_FILE_NAME:YF,RESTART_TIMEOUT_MS:wF,HDB_FILE_PERMISSIONS:CF,DATABASES_DIR_NAME:MF,LEGACY_DATABASES_DIR_NAME:UF,TRANSACTIONS_DIR_NAME:PF,LIMIT_COUNT_NAME:vF,ID_ATTRIBUTE_STRING:BF,INSERT_MODULE_ENUM:GF,UPGRADE_JSON_FIELD_NAMES_ENUM:qF,RESTART_CODE:NF,RESTART_CODE_NUM:IF,CLUSTER_OPERATIONS:cc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:$F,HDB_INTERNAL_SC_CHANNEL_PREFIX:wr,INTERNAL_SC_CHANNELS:VF,CLUSTERING_MESSAGE_TYPES:hk,HDB_FILE_SUFFIX:AF,BLOB_FOLDER_NAME:DF,HDB_TRASH_DIR:LF,ORIGINATOR_SET_VALUE:mk,LICENSE_VALUES:ik,RAM_ALLOCATION_ENUM:ok,TIME_STAMP_NAMES_ENUM:yO,TIME_STAMP_NAMES:dk,PERMS_UPDATE_RELEASE_TIMESTAMP:fk,SEARCH_NOT_FOUND_MESSAGE:tF,SEARCH_ATTRIBUTE_NOT_FOUND:rF,LICENSE_ROLE_DENIED_RESPONSE:sF,LICENSE_MAX_CONNS_REACHED:nF,BASIC_LICENSE_MAX_NON_CU_ROLES:SO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:jq,VALUE_SEARCH_COMPARATORS:NO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Ek,LICENSE_FILE_NAME:KF,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:ck,NEW_LINE:pk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:oF,MOMENT_DAYS_TAG:hF,API_TURNOVER_SEC:mF,LOOPBACK:iF,CODE_EXTENSION:jl,WILDCARD_SEARCH_VALUE:pF,NODE_ERROR_CODES:uk,JAVASCRIPT_EXTENSION:EO,PERMS_CRUD_ENUM:Sk,UNAUTHORIZED_PERMISSION_NAME:gk,SEARCH_WILDCARDS:Tk,FUNC_VAL:Rk,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Ak,JWT_ENUM:Ok,CLUSTERING_FLAG:_k,ITC_EVENT_TYPES:bk,CUSTOM_FUNCTION_PROC_NAME:mO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Xl,SERVICES:yk,THREAD_TYPES:Nk,MEM_SETTING_KEY:SF,HDB_RESTART_SCRIPT:Hq,PROCESS_DESCRIPTORS:Vq,SERVICE_SERVERS:Qq,SERVICE_SERVERS_CWD:Lh,PROCESS_DESCRIPTORS_VALIDATE:Kq,LAUNCH_SERVICE_SCRIPTS:zq,LOG_LEVELS:Yq,PROCESS_NAME_ENV_PROP:HF,LOG_NAMES:$q,PM2_PROCESS_STATUSES:Ik,CONFIG_PARAM_MAP:bO,CONFIG_PARAMS:w,HDB_CONFIG_FILE:Pq,HDB_DEFAULT_CONFIG_FILE:vq,ROLE_TYPES_ENUM:Jq,BOOT_PROP_PARAMS:RO,INSTALL_PROMPTS:xF,HDB_ROOT_DIR_NAME:Bq,CLUSTERING_PROCESSES:Wq,FOREGROUND_PID_FILE:qq,PACKAGE_ROOT:jn,PRE_4_0_0_VERSION:wk,DATABASES_PARAM_CONFIG:tk,METADATA_PROPERTY:lk,AUTH_AUDIT_STATUS:Ck,AUTH_AUDIT_TYPES:Dk,HDB_PID_FILE:Fq,DEFAULT_DATABASE_NAME:kq,LEGACY_CONFIG_PARAMS:ek};fO()});var Uh=g((Yae,DO)=>{"use strict";var wO=require("minimist");DO.exports=Lk;function Lk(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=CO(process.env),s=CO(wO(process.argv))):(r=process.env,s=wO(process.argv));let n={};for(let i=0,o=e.length;i<o;i++){let c=e[i];s[c]!==void 0?n[c]=s[c].toString().trim():r[c]!==void 0&&(n[c]=r[c].toString().trim())}return n}a(Lk,"assignCMDENVVariables");function CO(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(CO,"objKeysToLowerCase")});var $=g((Wae,qh)=>{"use strict";var Bi=require("fs-extra"),{workerData:Mk,threadId:Uk}=require("worker_threads"),pn=require("path"),UO=require("yaml"),PO=require("properties-reader"),Ot=L(),LO=Uh(),Pk=require("os"),{PACKAGE_ROOT:vh}=L(),{_assignPackageExport:vk}=require("../index"),lc={};for(let e in console)lc[e]||(lc[e]=console[e]);var nr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},vO={STDOUT:"stdOut",STDERR:"stdErr"},Bk=pn.join(vh,"logs"),Hk=pn.join(vh,"config/yaml/",Ot.HDB_DEFAULT_CONFIG_FILE),xk=1e4,mn,Ws,sr,t_,r_,_c,Fo,uc;uc===void 0&&BO();qh.exports={notify:GO,fatal:qO,error:dc,warn:Gh,info:s_,debug:xh,trace:Hh,setLogLevel:Yk,log_level:sr,loggerWithTag:Gk,suppressLogging:qk,initLogSettings:BO,setupConsoleLogging:HO,logCustomLevel:Vk,closeLogFile:Bh,getLogFilePath:()=>_c,OUTPUTS:vO,AuthAuditLog:Qk};vk("logger",qh.exports);function BO(e=!1){try{if(uc===void 0||e){Bh();let t=$k(),r=LO(["ROOTPATH"]);try{uc=PO(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!Bi.pathExistsSync(pn.join(r.ROOTPATH,Ot.HDB_CONFIG_FILE)))throw s}({level:sr,config_log_path:r_,to_file:mn,to_stream:Ws}=Kk(r.ROOTPATH?pn.join(r.ROOTPATH,Ot.HDB_CONFIG_FILE):uc.get("settings_path"))),t_=Ot.LOG_NAMES.HDB,_c=pn.join(r_,t_)}}catch(t){if(uc=void 0,t.code===Ot.NODE_ERROR_CODES.ENOENT){let r=LO(Object.keys(Ot.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Ot.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Ot.CONFIG_PARAMS.LOGGING_LEVEL){sr=u;continue}if(c===Ot.CONFIG_PARAMS.LOGGING_STDSTREAMS){Ws=u;continue}c===Ot.CONFIG_PARAMS.LOGGING_FILE&&(mn=c)}let{default_level:s,default_to_file:n,default_to_stream:i}=Wk();mn=mn===void 0?n:mn,mn=MO(mn),Ws=Ws===void 0?i:Ws,Ws=MO(Ws),sr=sr===void 0?s:sr,r_=Bk,t_=Ot.LOG_NAMES.INSTALL,_c=pn.join(r_,t_);return}throw dc("Error initializing log settings"),dc(t),t}process.env.DEV_MODE&&(Ws=!0),HO()}a(BO,"initLogSettings");var Ph=!0;function HO(){qo("error",dc),qo("warn",Gh),qo("log",s_),qo("info",s_),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 lc[e](...r)}}a(qo,"logConsole");function Gk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(GO),fatal:r(qO),error:r(dc),warn:r(Gh),info:r(s_),debug:r(xh),trace:r(Hh)};function r(s){return function(...n){return s(t,...n)}}}a(Gk,"loggerWithTag");function qk(e){try{Ph=!1,e()}finally{Ph=!0}}a(qk,"suppressLogging");var Fk=Mk?.name?.replace(/ /g,"-")||"main";function Sn(e,t){let r=new Date(Date.now()).toISOString(),s="",n=t.length,i=n-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||Fk+"/"+Uk);c<n;c++){let _=t[c];_ instanceof Error&&_.stack?s+=_.stack:typeof _=="object"?s+=JSON.stringify(_):s+=_,c<i&&(s+=" ")}return`${r} [${o.join("] [")}]: ${s}
|
|
3
|
+
`}a(Sn,"createLogRecord");function fc(e){mn&&xO(e),Ws&&process.stdout.write(e)}a(fc,"logStdOut");function n_(e){mn&&xO(e),Ws&&process.stderr.write(e)}a(n_,"logStdErr");function xO(e){kk(),Fo?Bi.appendFileSync(Fo,e):lc.log(e)}a(xO,"logToFile");function Bh(){try{Bi.closeSync(Fo)}catch{}Fo=null}a(Bh,"closeLogFile");function kk(){if(!Fo){try{if(!_c)debugger;Fo=Bi.openSync(_c,"a")}catch(e){lc.error(e)}setTimeout(()=>{Bh()},xk).unref()}}a(kk,"openLogFile");function s_(...e){nr[sr]<=nr.info&&fc(Sn("info",e))}a(s_,"info");function Hh(...e){nr[sr]<=nr.trace&&fc(Sn("trace",e))}a(Hh,"trace");function dc(...e){nr[sr]<=nr.error&&n_(Sn("error",e))}a(dc,"error");function xh(...e){nr[sr]<=nr.debug&&fc(Sn("debug",e))}a(xh,"debug");function GO(...e){nr[sr]<=nr.notify&&fc(Sn("notify",e))}a(GO,"notify");function qO(...e){nr[sr]<=nr.fatal&&n_(Sn("fatal",e))}a(qO,"fatal");function Gh(...e){nr[sr]<=nr.warn&&n_(Sn("warn",e))}a(Gh,"warn");function Vk(e,t,...r){t===vO.STDERR?n_(Sn(e,r)):fc(Sn(e,r))}a(Vk,"logCustomLevel");function $k(){let e;try{e=Pk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=pn.join(e,Ot.HDB_HOME_DIR_NAME,Ot.BOOT_PROPS_FILE_NAME);return Bi.existsSync(t)||(t=pn.join(vh,"utility/hdb_boot_properties.file")),t}a($k,"getPropsFilePath");function Yk(e){sr=e}a(Yk,"setLogLevel");function MO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(MO,"autoCastBoolean");function Kk(e){try{if(e.includes("config/settings.js")){let o=PO(e);return{level:o.get(Ot.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:pn.dirname(o.get(Ot.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Ot.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Ot.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=UO.parseDocument(Bi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),s=t.getIn(["logging","root"]),n=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:s,to_file:n,to_stream:i}}catch(t){if(t.code===Ot.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Kk,"getLogConfig");function Wk(){try{let e=UO.parseDocument(Bi.readFileSync(Hk,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),s=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:s}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(Wk,"getDefaultConfig");function Qk(e,t,r,s,n,i){this.username=e,this.status=t,this.type=r,this.originating_ip=s,this.request_method=n,this.path=i}a(Qk,"AuthAuditLog")});var kO=g((zae,FO)=>{"use strict";var zk=require("util"),Jk=require("path"),Xk=require("child_process"),jk=zk.promisify(Xk.execFile),Zk=1e3*1e3*10;FO.exports={findPs:eV};async function eV(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await jk("ps",["wwxo",`pid,${r}`],{maxBuffer:Zk});for(let n of s.trim().split(`
|
|
4
|
+
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,s])=>({pid:Number.parseInt(r,10),name:Jk.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(eV,"findPs")});var ut=g((Xae,$O)=>{"use strict";var tV="__dbis__",rV="__txns__",sV="__environment_name__",nV="__dbi_defintion__",iV={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"},oV=["__createdtime__","__updatedtime__"],aV="\uFFFF",VO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},cV=Object.values(VO);$O.exports={AUDIT_STORE_NAME:rV,INTERNAL_DBIS_NAME:tV,DBI_DEFINITION_NAME:nV,SEARCH_TYPES:iV,TIMESTAMP_NAMES:oV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:sV,TRANSACTIONS_DBI_NAMES_ENUM:VO,TRANSACTIONS_DBIS:cV,OVERFLOW_MARKER:aV}});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"},uV=zO[WO.INTERNAL_SERVER_ERROR],lV={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.`},_V={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},dV={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"},fV={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"},EV={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"},hV={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."},mV={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`},pV={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"},SV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},TV={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}`},gV={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."},RV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},AV={...JO,...dV,...lV,...hV,...mV,...pV,...SV,...TV,...EV,...XO,...jO,...gV,...RV,..._V};ZO.exports={CHECK_LOGS_WRAPPER:QO,HDB_ERROR_MSGS:AV,DEFAULT_ERROR_MSGS:zO,DEFAULT_ERROR_RESP:uV,HTTP_STATUS_CODES:WO,LMDB_ERRORS_ENUM:fV,AUTHENTICATION_ERROR_MSGS:JO,VALIDATION_ERROR_MSGS:XO,ITC_ERRORS:jO}});var se=g((ece,rb)=>{"use strict";var ko=Cr(),OV=$(),bV=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&&OV[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=bV.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(),yV=Q(),ir=ee(),Tc=require("path"),NV=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 IV(e,t){let r=ir.get(Zn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Tc.join(ab(),e.toString())}a(IV,"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 wV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,NV(process.argv));let s=r[Zn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!yV.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(wV,"initSystemSchemaPaths");function CV(){hc=void 0,mc=void 0,pc=void 0}a(CV,"resetPaths");ub.exports={getBaseSchemaPath:ib,getSystemSchemaPath:ob,getTransactionAuditStorePath:IV,getTransactionAuditStoreBasePath:ab,getSchemaPath:cb,initSystemSchemaPaths:wV,resetPaths:CV}});var Dr=g((oce,Eb)=>{"use strict";var DV=Cr().LMDB_ERRORS_ENUM,nce=require("lmdb"),LV=ut(),ice=require("buffer").Buffer,{OVERFLOW_MARKER:lb,MAX_SEARCH_KEY_LENGTH:a_}=LV,_b=["number","string","symbol","boolean","bigint"];function MV(e){if(e=e?.primaryStore||e,!e)throw new Error(DV.ENV_REQUIRED)}a(MV,"validateEnv");function UV(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(UV,"stringifyData");function PV(e){return e instanceof Date?e.valueOf():e}a(PV,"convertKeyValueToWrite");function vV(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(vV,"getIndexedValues");var c_=0,db=0;function fb(){db=Date.now()-performance.now()}a(fb,"adjustStartTime");fb();var BV=6e4;setInterval(fb,BV).unref();function HV(){let e=performance.now()+db;return e>c_?(c_=e,e):(c_+=488e-6,c_)}a(HV,"getNextMonotonicTime");Eb.exports={validateEnv:MV,stringifyData:UV,convertKeyValueToWrite:PV,getNextMonotonicTime:HV,getIndexedValues:vV}});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 Hi={};qe(Hi,{server:()=>st});var mb,st,or=ge(()=>{mb=require("../index"),st={};(0,mb._assignPackageExport)("server",st)});var Kh={};qe(Kh,{loadGQLSchema:()=>qV,start:()=>Yh,startOnMainThread:()=>GV});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 v=function(P){if(P.kind==="NonNullType"){let X=v(P.type);return X.nullable=!1,X}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 X={};for(let z of H.arguments)X[z.name.value]=z.value.value;k.relationship=X}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 X=k.authorizedRoles=[];for(let z of H.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):xV.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,xV,GV,qV,Sb=ge(()=>{$h=require("path");Re();pb=B(Ke()),xV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Yh,"start");GV=Yh,qV=Yh({ensureTable:lt}).handleFile});async function u_(e){return FV?(Rc||(Rc=kV($V)),(await(await Rc).import(e)).namespace):import(e)}async function kV(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:VV,...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 VV(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 $V(){return{Resource:Ft,tables:Lr}}var Tb,gb,FV,Rc,Wh=ge(()=>{Ns();Re();Tb=require("fs/promises"),gb=require("path"),FV=!1;a(u_,"secureImport");a(kV,"getCompartment");a(VV,"secureOnlyFetch");a($V,"getGlobalVars")});var zh={};qe(zh,{handleFile:()=>YV});async function YV(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(YV,"handleFile")});var Xh={};qe(Xh,{start:()=>KV});function KV({resources:e}){e.set("login",Jh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Jh,Ob=ge(()=>{Ns();a(KV,"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:()=>xi});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 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 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)+":"+xi(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Zh(e){return zV.test(e)?WV.parse(e):JSON.parse(e)}var Nb,Ib,WV,QV,wb,jh,zV,em=ge(()=>{Nb=require("stream"),Ib=B(require("json-bigint-fixes")),WV=(0,Ib.default)({useNativeBigInt:!0}),QV=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 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>QV?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(xi,"stringify");a(Cb,"jsStringify");zV=/[[,:]\s*-?\d{16,}/;a(Zh,"parse")});var Vb=g((Ace,kb)=>{"use strict";var tm=require("recursive-iterator"),JV=require("alasql"),rm=require("clone"),Lb=Q(),{handleHDBError:Mb,hdb_errors:XV}=se(),{HDB_ERROR_MSGS:Ub,HTTP_STATUS_CODES:Pb}=XV,{getDatabases:jV}=(Re(),ie(Fe)),ZV=["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=jV();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 JV.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&&ZV.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:()=>e$,METADATA:()=>bc,NO_TIMESTAMP:()=>um,PENDING_LOCAL_TIME:()=>hm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>fm,RecordEncoder:()=>dm,TIMESTAMP_ASSIGN_LAST:()=>r$,TIMESTAMP_ASSIGN_NEW:()=>zb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Jb,TIMESTAMP_PLACEHOLDER:()=>__,TIMESTAMP_RECORD_PREVIOUS:()=>lm,getUpdateRecord:()=>mm,handleLocalTimeForGets:()=>h_});function n$(){return yc[0]=yc[0]^64,t$.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,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(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 b=i?.localTime,R=r.get(b);if(R){let M=Mt(R).previousLocalTime;return r.put(b,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,e$,bc,yc,t$,um,zb,r$,Jb,lm,Em,hm,s$,d_,Vo,f_,_m,dm,Gi,Ic=ge(()=>{Qb=require("msgpackr");ei();cm=B($()),__=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]),e$=Symbol("local-timestamp"),bc=Symbol("metadata"),yc=new Uint8Array(8),t$=new DataView(yc.buffer,0,8),um=0,zb=0,r$=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 _=s$=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=n$(),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(n$,"getTimestamp");a(h_,"handleLocalTimeForGets");Gi=[];setInterval(()=>{for(let e=0;e<Gi.length;e++){let t=Gi[e].deref();!t||t.isDone||t.isCommitted?Gi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(cm.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):cm.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(mm,"getUpdateRecord")});var wc=g((Lce,Zb)=>{"use strict";var jb=ee(),i$=L(),{RecordEncoder:o$}=(Ic(),ie(Xb)),Dce=require("fs");jb.initSync();var a$=jb.get(i$.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=a$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:o$})}};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:c$,resetDatabases:u$}=(Re(),ie(Fe)),ry=ee(),ws=ti.INTERNAL_DBIS_NAME,iy=ti.DBI_DEFINITION_NAME,l$="data.mdb",_$="lock.mdb",Dc=".mdb",d$="-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,l$),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 f$(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(f$,"createEnvironment");async function E$(e,t,r,s=!0){T_(e,t),t=t.toString();let n=Ur.join(e,t);return c$({table:t,database:Ur.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(E$,"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 h$(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+d$:Ur.join(Ur.dirname(n),_$))}a(h$,"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 m$(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(m$,"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 p$(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(p$,"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=p$(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 S$(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(S$,"statDBI");async function T$(e,t){try{let r=Ur.join(e,t+Dc);return(await Is.stat(r)).size}catch{throw new Error(ar.INVALID_ENVIRONMENT)}}a(T$,"environmentDataSize");function g$(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(g$,"dropDBI");function R$(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&&u$()}a(R$,"initializeDBIs");ly.exports={openDBI:is,openEnvironment:oy,createEnvironment:f$,listDBIs:cy,listDBIDefinitions:m$,createDBI:uy,dropDBI:g$,statDBI:S$,deleteEnvironment:h$,initializeDBIs:R$,TransactionCursor:Sm,environmentDataSize:T$,copyEnvironment:E$,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 A$=We(),O$=dy(),b$=Ey(),y$=my(),Qs=Dr(),Lc=Cr().LMDB_ERRORS_ENUM,N$=ut(),Tn=L(),I$=Q(),w$=require("uuid"),Vce=require("lmdb"),{handleHDBError:C$,hdb_errors:D$}=se(),{OVERFLOW_MARKER:$ce,MAX_SEARCH_KEY_LENGTH:Yce}=N$,py=ee();py.initSync();var R_=py.get(Tn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Nm=Tn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=Tn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function L$(e,t,r,s,n=Qs.getNextMonotonicTime()){Dm(e,t,r,s),Im(e,t,r);let i=new O$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];Sy(_,!0,n);let l=M$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return wm(o,c,s,i,n)}a(L$,"insertRecords");function M$(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[qi])})}a(M$,"insertRecord");function U$(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(U$,"removeSkippedRecords");function Sy(e,t,r){let s=r>0;(s||!Number.isInteger(e[qi]))&&(e[qi]=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),A$.initializeDBIs(e,t,r)}a(Im,"initializeTransaction");async function P$(e,t,r,s,n=Qs.getNextMonotonicTime()){Dm(e,t,r,s),Im(e,t,r);let i=new b$,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(P$,"updateRecords");async function v$(e,t,r,s,n=Qs.getNextMonotonicTime()){try{Dm(e,t,r,s)}catch(u){throw C$(u,u.message,D$.HTTP_STATUS_CODES.BAD_REQUEST)}Im(e,t,r);let i=new y$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;I$.isEmpty(_[t])?(l=w$.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(v$,"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(),U$(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[qi])&&_[qi]>r[qi])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 b=Qs.getIndexedValues(T);if(b){R_&&S.prefetch(b.map(R=>({key:R,value:s})),A_);for(let R=0,M=b.length;R<M;R++)S.remove(b[R],s)}if(b=Qs.getIndexedValues(p),b){R_&&S.prefetch(b.map(R=>({key:R,value:s})),A_);for(let R=0,M=b.length;R<M;R++)S.put(b[R],s)}}let E=Object.assign({},_,r);c.put(s,E,E[qi])},"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 B$(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(B$,"validateBasic");function Dm(e,t,r,s){if(B$(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:L$,updateRecords:P$,upsertRecords:v$}});var Fi=g((Qce,H$)=>{H$.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"}},x$=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(),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()),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()).required();function F$(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(F$,"checkValidTable");function k$(e,t){return Ry.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(k$,"validateSchemaExists");function V$(e,t){let r=t.state.ancestors[0].schema;return Ry.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(V$,"validateTableExists");function $$(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($$,"validateSchemaName");Ay.exports={common_validators:ri,schema_regex:Yo,hdb_schema_table:x$,validateSchemaExists:k$,validateTableExists:V$,validateSchemaName:$$,checkValidTable:F$,hdb_database:G$,hdb_table:q$}});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:Y$,validateObjectAsync:K$,validateBySchema:W$};function Y$(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(Y$,"validateObject");async function K$(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(K$,"validateObjectAsync");function W$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(W$,"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 Q$(e){return e=Pc(e),mt.table.presence=!1,mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(Q$,"schema_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$,"table_object");function J$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence=!1,Uc.validateObject(e,mt)}a(J$,"create_table_object");function X$(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(X$,"attribute_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$,"describe_table");function Z$(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(Z$,"validateTableResidence");by.exports={schema_object:Q$,create_table_object:J$,table_object:z$,attribute_object:X$,describe_table:j$,validateTableResidence:Z$}});var Ny=g((tue,yy)=>{"use strict";var e1=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||e1.v4(),this.schema_table=`${this.schema}.${this.table}`}};yy.exports=Lm});var b_=g((sue,Iy)=>{"use strict";var t1=Ny(),Mm=class extends t1{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=s1;var r1="inserted";function s1(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===r1?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(s1,"returnObject")});var y_=g((aue,Py)=>{"use strict";var n1=L(),Um=We(),i1=$o(),{getSystemSchemaPath:o1,getSchemaPath:a1}=Je(),c1=Fi(),u1=O_(),l1=b_(),_1=Cy(),{handleHDBError:Dy,hdb_errors:My}=se(),Ly=Q(),{HTTP_STATUS_CODES:d1}=My,Pm=c1.hdb_attribute,Uy=[];for(let e=0;e<Pm.attributes.length;e++)Uy.push(Pm.attributes[e].attribute);var f1="inserted";Py.exports=E1;async function E1(e){let t=u1.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,d1.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 l1(e.schema,e.table,e.attribute,e.id);try{let i=await Um.openEnvironment(a1(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(o1(),n1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await i1.insertRecords(o,Pm.hash_attribute,Uy,[n]);return _1(f1,c,{records:[n]},u)}catch(i){throw i}}a(E1,"lmdbCreateAttribute")});var Bm=g((uue,By)=>{var{hdb_table:h1,hdb_database:vy}=Js(),m1=Xe(),vm=require("joi"),p1={undefined:"undefined",null:"null"},S1=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||p1[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"),T1=vm.object({database:vy,schema:vy,table:h1,records:vm.array().items(vm.object().custom(S1)).required()});By.exports=function(e){return m1.validateBySchema(e,T1)}});var vc=g((due,xy)=>{"use strict";var gn=Q(),Hy=$(),_ue=Bm(),{getDatabases:g1}=(Re(),ie(Fe)),{ClientError:ki}=se();xy.exports=R1;function R1(e){if(gn.isEmpty(e))throw new ki("invalid update parameters defined.");if(gn.isEmptyOrZeroLength(e.schema))throw new ki("invalid schema specified.");if(gn.isEmptyOrZeroLength(e.table))throw new ki("invalid table specified.");if(!Array.isArray(e.records))throw new ki("records must be an array");let t=g1()[e.schema]?.[e.table];if(gn.isEmpty(t))throw new ki(`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 ki("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 ki(`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(R1,"insertUpdateValidate")});var Bc=g((Eue,Gy)=>{"use strict";var A1=L().OPERATIONS_ENUM,Hm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=A1.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=$(),O1=require("uuid"),{handleHDBError:I_,hdb_errors:b1}=se(),{HDB_ERROR_MSGS:w_,HTTP_STATUS_CODES:C_}=b1;Fy.exports=y1;function y1(e,t,r){for(let n=0;n<t.length;n++)N1(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];I1(i,r,e.operation)}}a(y1,"processRows");function N1(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(N1,"validateAttribute");function I1(e,t,r){if(!e.hasOwnProperty(t)||xm.isEmptyOrZeroLength(e[t])){if(r===N_.OPERATIONS_ENUM.INSERT||r===N_.OPERATIONS_ENUM.UPSERT){e[t]=O1.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(I1,"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(),w1=$(),$y=Cr().LMDB_ERRORS_ENUM;Yy.exports=C1;async function C1(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){w1.error(t)}}a(C1,"cleanLMDBMap")});var Rn=g((Oue,Jy)=>{"use strict";var xc=require("crypto"),D1=ee(),{CONFIG_PARAMS:L1}=L(),Qy="aes-256-cbc",M1=32,U1=16,Fm=64,zy=32,P1=Fm+zy,Wy=new Map;Jy.exports={encrypt:v1,decrypt:B1,createNatsTableStreamName:H1};function v1(e){let t=xc.randomBytes(M1),r=xc.randomBytes(U1),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(v1,"encrypt");function B1(e){let t=e.substr(0,Fm),r=e.substr(Fm,zy),s=e.substr(P1,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(B1,"decrypt");function H1(e,t){let r=D1.get(L1.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(H1,"createNatsTableStreamName")});var An=g((Nue,jy)=>{"use strict";var yue=Pr(),D_=$(),Xy=O_(),x1=Rn(),L_=Q(),{handleHDBError:M_,hdb_errors:G1}=se(),{HDB_ERROR_MSGS:U_,HTTP_STATUS_CODES:km}=G1,q1=ee();q1.initSync();var{getDatabases:Vm}=(Re(),ie(Fe));jy.exports={describeAll:F1,describeTable:P_,describeSchema:k1};async function F1(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(F1,"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=x1.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 k1(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(k1,"describeSchema")});var On=g((Due,sN)=>{var V1=Fi(),{callbackify:eN,promisify:$1}=require("util"),{getDatabases:tN}=(Re(),ie(Fe));sN.exports={setSchemaDataToGlobal:Zy,getTableSchema:Y1,getSystemSchema:K1,setSchemaDataToGlobalAsync:$1(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 Y1(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(Y1,"getTableSchema");function K1(){return V1}a(K1,"getSystemSchema")});var vr=g((Mue,aN)=>{"use strict";var B_=Bm(),kt=Q(),W1=require("util"),H_=Cs(),Q1=On(),nN=$(),{handleHDBError:Vi,hdb_errors:z1}=se(),{HTTP_STATUS_CODES:$i}=z1,J1=W1.promisify(Q1.getTableSchema),X1="updated",iN="inserted",oN="upserted";aN.exports={insert:Z1,update:eY,upsert:tY,validation:j1,flush:rY};async function j1(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 J1(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(j1,"validation");async function Z1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=B_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.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(Z1,"insertData");async function eY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=B_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let s=await H_.updateRecords(e);return kt.isEmpty(s.existing_rows)?v_(X1,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(eY,"updateData");async function tY(e){if(e.operation!=="upsert")throw Vi(new Error,"invalid operation, must be upsert",$i.INTERNAL_SERVER_ERROR);let t=B_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let s=await H_.upsertRecords(e);return v_(oN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(tY,"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 rY(e){return kt.transformReq(e),H_.flush(e.schema,e.table)}a(rY,"flush")});var Ym=g((Pue,lN)=>{var sY=Xe(),$m=require("joi"),{hdb_table:nY,hdb_database:cN}=Js(),uN={schema:cN,database:cN,table:nY},iY={date:$m.date().iso().required()},oY={timestamp:$m.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};lN.exports=function(e,t){let r=t==="timestamp"?{...uN,...oY}:{...uN,...iY},s=$m.object(r);return sY.validateBySchema(e,s)}});var fN=g((vue,dN)=>{var aY=Xe(),Km=require("joi"),{hdb_table:cY,hdb_database:_N}=Js(),uY=Km.object({schema:_N,database:_N,table:cY,hash_values:Km.array().required(),ids:Km.array()});dN.exports=function(e){return aY.validateBySchema(e,uY)}});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(),lY=fN(),Yi=Q(),mN=require("moment"),SN=$(),{promisify:_Y,callbackify:dY}=require("util"),Ki=L(),fY=On(),Jm=_Y(fY.getTableSchema),Xm=Cs(),{DeleteResponseObject:EY}=hN(),{handleHDBError:si,hdb_errors:hY}=se(),{HDB_ERROR_MSGS:x_,HTTP_STATUS_CODES:ni}=hY,mY="records successfully deleted",pY=dY(TN);gN.exports={delete:pY,deleteRecord:TN,deleteFilesBefore:SY,deleteAuditLogsBefore:TY};async function SY(e){let t=pN(e,"date");if(t)throw si(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!mN(e.date,mN.ISO_8601).isValid())throw si(new Error,x_.INVALID_DATE,ni.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,x_.INVALID_DATE,!0);let s=Yi.checkSchemaTableExist(e.schema,e.table);if(s)throw si(new Error,s,ni.NOT_FOUND,Ki.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(SY,"deleteFilesBefore");async function TY(e){let t=pN(e,"timestamp");if(t)throw si(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),isNaN(e.timestamp))throw si(new Error,x_.INVALID_VALUE("Timestamp"),ni.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,x_.INVALID_VALUE("Timestamp"),!0);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ni.NOT_FOUND,Ki.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(TY,"deleteAuditLogsBefore");async function TN(e){e.ids&&(e.hash_values=e.ids);let t=lY(e);if(t)throw si(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);Yi.transformReq(e);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ni.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);try{await Jm(e.schema,e.table);let s=await Xm.deleteRecords(e);return Yi.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${mY}`),s}catch(s){if(s.message===Ki.SEARCH_NOT_FOUND_MESSAGE){let n=new EY;return n.message=Ki.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 gY=require("crypto"),RN=9;function RY(e){let t=OY(RN),r=AN(e+t);return t+r}a(RY,"createHash");function AY(e,t){let r=e?.substr(0,RN),s=r+AN(t+r);return e===s}a(AY,"validateHash");function OY(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(OY,"generateSalt");function AN(e){return gY.createHash("md5").update(e).digest("hex")}a(AN,"md5");ON.exports={hash:RY,validate:AY}});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 bY(e){return Qt.password.presence=!0,Qt.username.presence=!0,Qt.role.presence=!0,Qt.active.presence=!0,jm.validateObject(e,Qt)}a(bY,"addUserValidation");function yY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,jm.validateObject(e,Qt)}a(yY,"alterUserValidation");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,"dropUserValidation");bN.exports={addUserValidation:bY,alterUserValidation:yY,dropUserValidation:NY}});var ke=g((Yue,IN)=>{"use strict";var{platform:$ue}=require("os"),IY="nats-server.zip",Zm="nats-server",wY=process.platform==="win32"?`${Zm}.exe`:Zm,CY=/^[^\s.,*>]+$/,NN="__request__",DY=a(e=>`${e}.${NN}`,"REQUEST_SUBJECT"),LY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},MY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},UY={HUB:"hub.pid",LEAF:"leaf.pid"},PY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},vY={SUCCESS:"success",ERROR:"error"},BY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},HY={TXN:"txn",MSGID:"msgid"},Ko={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},xY={[Ko.ERR]:1,[Ko.WRN]:2,[Ko.INF]:3,[Ko.DBG]:4,[Ko.TRC]:5},GY={debug:"-D",trace:"-DVV"};IN.exports={NATS_SERVER_ZIP:IY,NATS_SERVER_NAME:Zm,NATS_BINARY_NAME:wY,PID_FILES:UY,NATS_CONFIG_FILES:MY,SERVER_SUFFIX:PY,NATS_TERM_CONSTRAINTS_RX:CY,REQUEST_SUFFIX:NN,UPDATE_REMOTE_RESPONSE_STATUSES:vY,CLUSTER_STATUS_STATUSES:BY,REQUEST_SUBJECT:DY,SUBJECT_PREFIXES:HY,MSG_HEADERS:LY,LOG_LEVELS:Ko,LOG_LEVEL_FLAGS:GY,LOG_LEVEL_HIERARCHY:xY}});var CN=g((Wue,wN)=>{"use strict";var qY={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
|
+
`)},FY="certificate.pem",kY="privateKey.pem",VY="ca.pem";wN.exports={CERTIFICATE_VALUES:qY,CERTIFICATE_PEM_NAME:FY,PRIVATEKEY_PEM_NAME:kY,CA_PEM_NAME:VY}});var tp=g((zue,PN)=>{"use strict";var UN=require("fs-extra"),oe=require("joi"),$Y=require("os"),{boolean:be,string:zt,number:Ze,array:ep}=oe.types(),{totalmem:DN}=require("os"),Wi=require("path"),YY=$(),q_=Q(),Que=CN(),LN=L(),KY=Xe(),MN="log",WY="components",QY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",zY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",JY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",XY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",jY="rootPath config parameter is undefined",ZY="clustering.enabled config parameter is undefined",Qi=Ze.min(0).required(),F_=ep.items({host:zt.required(),port:Qi}).empty(null),js;PN.exports={configValidator:eK,routesValidator:oK,route_constraints:F_};function eK(e){if(js=e.rootPath,q_.isEmpty(js))throw jY;let t=be.required(),r=Ze.min(0).max(1e3).empty(null).default(iK),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(rK).empty(null).default(Gc),u=e.clustering?.enabled;if(q_.isEmpty(u))throw ZY;let _;return u===!0?_=oe.object({enabled:t,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:Qi,routes:F_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:Qi}).required()}).required(),network:oe.object({port:Qi}).required()}).required(),leafServer:oe.object({network:oe.object({port:Qi,routes:F_}).required(),streams:oe.object({maxAge:Ze.min(120).allow(null).optional(),maxBytes:Ze.min(1).allow(null).optional(),maxMsgs:Ze.min(1).allow(null).optional(),path: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(nK).optional().empty(null),maxSize:zt.custom(sK).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:Qi,securePort:Qi,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(eK,"configValidator");function tK(e){return UN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(tK,"doesPathExist");function rK(e,t){oe.assert(e,zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=tK(e);if(r)return t.message(r)}a(rK,"validatePath");function sK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(QY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(JY):e}a(sK,"validateRotationMaxSize");function nK(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(zY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(XY):e}a(nK,"validateRotationInterval");function iK(e,t){let r=t.state.path.join("."),s=$Y.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),YY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(iK,"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 Wi.join(js,WY);case"logging.root":return Wi.join(js,MN);case"clustering.leafServer.streams.path":return Wi.join(js,"clustering","leaf");case"storage.path":let s=Wi.join(js,LN.LEGACY_DATABASES_DIR_NAME);return UN.existsSync(s)?s:Wi.join(js,LN.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(js,MN);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(js,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Gc,"setDefaultRoot");function oK(e){let t=oe.object({routes:F_});return KY.validateBySchema({routes:e},t)}a(oK,"routesValidator")});var lr=g((jue,VN)=>{"use strict";var Hr=L(),Ut=Q(),bt=$(),{configValidator:aK,routesValidator:vN}=tp(),ur=require("fs-extra"),cK=require("yaml"),Ds=require("path"),uK=require("is-number"),HN=require("properties-reader"),lK=require("lodash"),{handleHDBError:_K}=se(),{HTTP_STATUS_CODES:dK,HDB_ERROR_MSGS:k_}=Cr(),Xue=require("minimist"),{server:fK}=(or(),ie(Hi)),{DATABASES_PARAM_CONFIG:qc,CONFIG_PARAMS:Br,CONFIG_PARAM_MAP:Ls}=Hr,EK="Unable to get config value because config is uninitialized",hK="Config successfully initialized",mK="Error backing up config file",pK="Empty parameter sent to getConfigValue",xN=Ds.join(Hr.PACKAGE_ROOT,"config","yaml",Hr.HDB_DEFAULT_CONFIG_FILE),SK="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:TK,getDefaultConfig:gK,getConfigValue:qN,initConfig:sp,flattenConfig:Wo,updateConfigValue:FN,updateConfigObject:AK,getConfiguration:yK,setConfiguration:NK,readConfigFile:ip,getClusteringRoutes:IK,initOldConfig:kN,getConfigFromFile:wK,getConfigFilePath:zi,addConfig:CK,deleteConfigFromFile:DK,getConfigObj:LK};function TK(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(TK,"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 gK(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(gK,"getDefaultConfig");function qN(e){if(e==null){bt.error(pK);return}if(yt===void 0){bt.trace(EK);return}let t=Ls[e.toLowerCase()];if(t!==void 0)return yt[t.toLowerCase()]}a(qN,"getConfigValue");function zi(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(zi,"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=zi(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}`)}RK(s,r),np(s);let n=s.toJSON();if(fK.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(hK)}}a(sp,"initConfig");function RK(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(RK,"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=aK(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 AK(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(AK,"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&&OK(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 OK(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(mK),bt.error(r)}}a(OK,"backupConfigFile");var bK=["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])&&!bK.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(uK(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 yK(){let e=Ut.getPropsFilePath(),t=zi(e);return oi(t).toJSON()}a(yK,"getConfiguration");async function NK(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return FN(void 0,void 0,n,!0),SK}catch(i){throw typeof i=="string"||i instanceof String?_K(i,i,dK.BAD_REQUEST,void 0,void 0,!0):i}}a(NK,"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=zi(e);return oi(t).toJSON()}a(ip,"readConfigFile");function oi(e){return cK.parseDocument(ur.readFileSync(e,"utf8"),{simpleKeys:!0})}a(oi,"parseYamlDoc");function IK(){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(IK,"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 wK(e){let t=ip();return lK.get(t,e.replaceAll("_","."))}a(wK,"getConfigFromFile");async function CK(e,t){let r=oi(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await ur.writeFile(zi(),String(r))}a(CK,"addConfig");function DK(e){let t=zi(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(DK,"deleteConfigFromFile");function LK(){return $_||(sp(),$_)}a(LK,"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 Ji=g((rle,XN)=>{"use strict";var zo=require("fs-extra"),WN=G_(),QN=require("crypto"),MK=require("moment"),UK=require("uuid").v4,Jt=$(),cp=require("path"),PK=Q(),ai=L(),{totalmem:KN}=require("os"),vK=YN().ExtendedLicense,Qo="invalid license key format",BK="061183",HK="mofi25",xK="aes-256-cbc",GK=16,qK=32,zN=ee();zN.initSync();var ap;XN.exports={validateLicense:JN,generateFingerPrint:kK,licenseSearch:_p,getLicense:YK,checkMemoryLimit:KK};function up(){return cp.join(zN.getHdbBasePath(),ai.LICENSE_KEY_DIR_NAME,ai.LICENSE_FILE_NAME)}a(up,"getLicenseDirPath");function FK(){let e=up();return cp.join(e,ai.LICENSE_FILE_NAME)}a(FK,"getLicenseFilePath");function lp(){let e=up();return cp.join(e,ai.REG_KEY_FILE_NAME)}a(lp,"getFingerPrintFilePath");async function kK(){let e=lp();try{return await zo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await VK();throw Jt.error(`Error writing fingerprint file to ${e}`),Jt.error(t),new Error("There was an error generating the fingerprint")}}a(kK,"generateFingerPrint");async function VK(){let e=UK(),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(VK,"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(HK),c=o[1];c=Buffer.concat([Buffer.from(c)],GK);let u=Buffer.concat([Buffer.from(i)],qK),_=QN.createDecipheriv(xK,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=$K(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<MK().valueOf()&&(r.valid_date=!1),WN.validate(o[1],`${BK}${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 $K(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($K,"checkOldLicense");function _p(){let e=new vK,t=[];try{t=zo.readFileSync(FK(),"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(PK.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 YK(){return ap||await _p(),ap}a(YK,"getLicense");function KK(){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(KK,"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:tW,alterUser:rW,dropUser:nW,getSuperUser:cW,userInfo:iW,listUsers:Q_,listUsersExternal:oW,setUsersToGlobal:Xo,findAndValidateUser:_I,getClusterUser:uW,USERNAME_REQUIRED:tI,ALTERUSER_NOTHING_TO_UPDATE:rI,EMPTY_PASSWORD:sI,EMPTY_ROLE:nI,ACTIVE_BOOLEAN:iI};var oI=vr(),WK=ii(),Ep=G_(),aI=yN(),cI=Pr(),hp=bn(),xr=Q(),uI=require("validate.js"),Ae=$(),{promisify:QK}=require("util"),mp=Rn(),jN=L(),ZN=ke(),zK=lr(),nle=ee(),ile=Ji(),JK=Fi(),{table:ole}=(Re(),ie(Fe)),{handleHDBError:Zs,hdb_errors:XK}=se(),{HTTP_STATUS_CODES:en,AUTHENTICATION_ERROR_MSGS:dp,HDB_ERROR_MSGS:Jo}=XK,{UserEventMsg:pp}=Ms(),fp=require("lodash"),{server:Sp}=(or(),ie(Hi)),jK=$();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,ZK=cI.searchByHash,eW=QK(WK.delete);async function tW(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(tW,"addUser");async function rW(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=sW(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(rW,"alterUser");function sW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(sW,"isClusterUser");async function nW(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 eW(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(nW,"dropUser");async function iW(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 ZK(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(iW,"userInfo");async function oW(){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(oW,"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],aW(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 aW(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(JK)){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(aW,"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 cW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(cW,"getSuperUser");async function uW(){let e=await Q_(),t=zK.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(uW,"getClusterUser");var dI=[];Sp.invalidateUser=function(e){for(let t of dI)try{t(e)}catch(r){jK.error("Error invalidating user",r)}};Sp.onInvalidatedUser=function(e){dI.push(e)}});var kc=g((_le,pI)=>{"use strict";var Xi=$(),Gr=L(),lW=Ky(),ule=On(),lle=An(),_W=os(),{validateEvent:EI}=Ms(),Fc=Cs(),dW=require("process"),{resetDatabases:fW}=(Re(),ie(Fe)),EW={[Gr.ITC_EVENT_TYPES.SCHEMA]:hW,[Gr.ITC_EVENT_TYPES.USER]:mI};async function hW(e){let t=EI(e);if(t){Xi.error(t);return}Xi.trace("ITC schemaHandler received schema event:",e),await lW(e.message),await mW(e.message)}a(hW,"schemaHandler");async function mW(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=fW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Xi.error(t)}}a(mW,"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){Xi.warn(r)}let t=EI(e);if(t){Xi.error(t);return}Xi.trace(`ITC userHandler ${Gr.HDB_ITC_CLIENT_PREFIX}${dW.pid} received user event:`,e),await _W.setUsersToGlobal();for(let r of hI)r()}catch(t){Xi.error(t)}}a(mI,"userHandler");mI.addListener=function(e){hI.push(e)};pI.exports=EW});var Ms=g((ple,TI)=>{"use strict";var fle=$(),Tp=Q(),pW=L(),{ITC_ERRORS:Vc}=Cr(),{parentPort:Ele,threadId:SW,isMainThread:TW,workerData:hle}=require("worker_threads"),{onMessageFromWorkers:gW,broadcast:mle,broadcastWithAcknowledgement:RW}=Ke();TI.exports={sendItcEvent:AW,validateEvent:SI,SchemaEventMsg:OW,UserEventMsg:bW};var z_;gW(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 AW(e){return!TW&&e.message&&(e.message.originator=SW),RW(e)}a(AW,"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(pW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Vc.INVALID_EVENT(e.type)}a(SI,"validateEvent");function OW(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(OW,"SchemaEventMsg");function bW(e){this.originator=e}a(bW,"UserEventMsg")});var bn=g((gle,OI)=>{"use strict";var gI=L(),Tle=Q(),J_=$(),RI=Vy(),jo,{sendItcEvent:AI}=Ms();function yW(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(yW,"signalSchemaChange");function NW(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(NW,"signalUserChange");OI.exports={signalSchemaChange:yW,signalUserChange:NW}});var X_=g((Ale,yI)=>{"use strict";var bI=Q(),IW=L(),wW=$(),CW=y_(),DW=b_(),LW=bn(),{SchemaEventMsg:MW}=Ms(),UW="already exists in";yI.exports=PW;async function PW(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 vW(e,t.schema,t.name,i)})),n}a(PW,"lmdbCheckForNewAttributes");async function vW(e,t,r,s){let n=new DW(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await BW(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(UW))wW.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(vW,"createNewAttribute");async function BW(e){let t;return t=await CW(e),LW.signalSchemaChange(new MW(process.pid,IW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(BW,"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 HW=Zo(),xW=L().OPERATIONS_ENUM,Rp=class extends HW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(xW.INSERT,r,s,n,i),this.records=t}};II.exports=Rp});var DI=g((wle,CI)=>{"use strict";var GW=Zo(),qW=L().OPERATIONS_ENUM,Ap=class extends GW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(qW.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};CI.exports=Ap});var MI=g((Dle,LI)=>{"use strict";var FW=Zo(),kW=L().OPERATIONS_ENUM,Op=class extends FW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(kW.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};LI.exports=Op});var PI=g((Mle,UI)=>{"use strict";var VW=Zo(),$W=L().OPERATIONS_ENUM,bp=class extends VW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super($W.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(),YW=wI(),KW=DI(),WW=MI(),QW=PI(),ea=ut(),BI=Q(),{CONFIG_PARAMS:zW}=L(),HI=ee();HI.initSync();var j_=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:JW}=Je();xI.exports=XW;async function XW(e,t){if(HI.get(zW.LOGGING_AUDITLOG)===!1)return;let r=JW(e.schema,e.table),s=await vI.openEnvironment(r,e.table,!0),n=jW(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(XW,"writeTransaction");function jW(e,t){let r=BI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===j_.INSERT)return new YW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.UPDATE)return new KW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.UPSERT)return new WW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.DELETE)return new QW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(jW,"createTransactionObject")});var yp=g((xle,GI)=>{"use strict";var ZW=vc(),Hle=Bc(),Yc=L(),eQ=Hc(),tQ=$o().insertRecords,rQ=We(),sQ=$(),nQ=X_(),{getSchemaPath:iQ}=Je(),oQ=$c();GI.exports=aQ;async function aQ(e){try{let{schema_table:t,attributes:r}=ZW(e);eQ(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 nQ(e.hdb_auth_header,t,r),n=iQ(e.schema,e.table),i=await rQ.openEnvironment(n,e.table),o=await tQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await oQ(e,o)}catch(c){sQ.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(aQ,"lmdbCreateRecords")});var kI=g((qle,FI)=>{"use strict";var qI=L(),cQ=yp(),uQ=Bc(),lQ=require("fs-extra"),{getSchemaPath:_Q}=Je();FI.exports=dQ;async function dQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new uQ(qI.SYSTEM_SCHEMA_NAME,qI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await cQ(r),await lQ.mkdirp(_Q(e.schema))}a(dQ,"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,fQ=ut(),KI=$(),$le=Q(),EQ=require("lmdb"),hQ=$I(),mQ=L(),{OVERFLOW_MARKER:Yle,MAX_SEARCH_KEY_LENGTH:Kle}=fQ,pQ=mQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function SQ(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 hQ,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[pQ]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,EQ.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 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{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(SQ,"deleteRecords");WI.exports={deleteRecords:SQ}});var Kc=g((zle,JI)=>{"use strict";var ta=Q(),TQ=QI(),gQ=We(),{getSchemaPath:RQ}=Je(),AQ=$c(),OQ=$();JI.exports=bQ;async function bQ(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=RQ(e.schema,e.table),i=await gQ.openEnvironment(n,e.table),o=await TQ.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await AQ(e,o)}catch(c){OQ.error(`unable to write transaction due to ${c.message}`)}return zI(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(bQ,"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 yQ=L(),Xle=Dr();function Cp(e,t){let r=Object.create(null);if(t.length===1&&yQ.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 NQ(e,t,r,s){let n=Cp(r,e);s.push(n)}a(NQ,"searchAll");function IQ(e,t,r,s){let n=Cp(r,e);s[t]=n}a(IQ,"searchAllToMap");function wQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(wQ,"iterateDBI");function ji(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(ji,"pushResults");function CQ(e,t,r,s,n,i){t.toString().endsWith(e)&&ji(t,r,s,n,i)}a(CQ,"endsWith");function DQ(e,t,r,s,n,i){t.toString().includes(e)&&ji(t,r,s,n,i)}a(DQ,"contains");function LQ(e,t,r,s,n,i){t>e&&ji(t,r,s,n,i)}a(LQ,"greaterThanCompare");function MQ(e,t,r,s,n,i){t>=e&&ji(t,r,s,n,i)}a(MQ,"greaterThanEqualCompare");function UQ(e,t,r,s,n,i){t<e&&ji(t,r,s,n,i)}a(UQ,"lessThanCompare");function PQ(e,t,r,s,n,i){t<=e&&ji(t,r,s,n,i)}a(PQ,"lessThanEqualCompare");XI.exports={parseRow:Cp,searchAll:NQ,searchAllToMap:IQ,iterateDBI:wQ,endsWith:CQ,contains:DQ,greaterThanCompare:LQ,greaterThanEqualCompare:MQ,lessThanCompare:UQ,lessThanEqualCompare:PQ,pushResults:ji}});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(),vQ=L(),ed=Dp(),{parseRow:BQ}=ed,r_e=require("lmdb"),{OVERFLOW_MARKER:jI,MAX_SEARCH_KEY_LENGTH:HQ}=Z_;function ZI(e,t,r,s=!1,n=void 0,i=void 0){return Zi(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 Zi(e,t,r,(l,d,f,E)=>{let b={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?(b.values=!1,d.getRange(b).map(R=>({value:R}))):d.getRange(b)})}a(Wc,"iterateRangeBetween");function Zi(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(Zi,"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 xQ(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 Zi(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(_=>BQ(_.value,r))))}a(xQ,"searchAll");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);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(GQ,"searchAllToMap");function qQ(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(qQ,"iterateDBI");function FQ(e,t){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return ci.statDBI(e,t).entryCount}a(FQ,"countAll");function kQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ui(e,r,s),Zi(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(kQ,"equals");function VQ(e,t,r){return ui(e,t,r),ci.openDBI(e,t).getValuesCount(r)}a(VQ,"count");function $Q(e,t,r,s,n=!1,i=void 0,o=void 0){return ui(e,r,s),Zi(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($Q,"startsWith");function YQ(e,t,r,s,n=!1,i=void 0,o=void 0){return tw(e,t,r,s,n,i,o,!0)}a(YQ,"endsWith");function tw(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return ui(e,r,s),Zi(e,null,r,(u,_,l,d)=>{let f=ew(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end: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 KQ(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(KQ,"greaterThan");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,!1,!1)}a(WQ,"greaterThanEqual");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="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Wc(e,t,r,u,s,n,i,o,!1,!0)}a(QQ,"lessThan");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,!1)}a(zQ,"lessThanEqual");function JQ(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(JQ,"between");function XQ(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(XQ,"searchByHash");function jQ(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(jQ,"checkHashExists");function ZQ(e,t,r,s,n=[]){return sw(e,t,r,s,n),rw(e,t,r,s,n).map(i=>i[1])}a(ZQ,"batchSearchByHash");function ez(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(ez,"batchSearchByHashToMap");function rw(e,t,r,s,n=[]){return Zi(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>HQ)throw new Error(_t.SEARCH_VALUE_TOO_LARGE)}a(ui,"validateComparisonFunctions");function Qc(e,t){return t.length===1&&vQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ci.listDBIs(e)),t}a(Qc,"setGetWholeRowAttributes");nw.exports={searchAll:xQ,searchAllToMap:GQ,count:VQ,countAll:FQ,equals:kQ,startsWith:$Q,endsWith:YQ,contains:tw,searchByHash:XQ,setGetWholeRowAttributes:Qc,batchSearchByHash:ZQ,batchSearchByHashToMap:ez,checkHashExists:jQ,iterateDBI:qQ,greaterThan:KQ,greaterThanEqual:WQ,lessThan:QQ,lessThanEqual:zQ,between:JQ}});var sa=g((i_e,uw)=>{var iw=require("lodash"),ow=Xe(),fe=require("joi"),tz=Q(),{hdb_schema_table:zc,checkValidTable:aw,hdb_table:cw,hdb_database:rd}=Js(),{handleHDBError:rz,hdb_errors:sz}=se(),{getDatabases:nz}=(Re(),ie(Fe)),{HTTP_STATUS_CODES:iz}=sz,oz=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)}),az=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,oz);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,az);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=tz.checkGlobalSchemaTable(e.schema,e.table);if(n)return rz(new Error,n,iz.NOT_FOUND);let o=nz()[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 cz=We(),uz=sa(),{getSchemaPath:lz}=Je();lw.exports=_z;function _z(e){let t=uz(e,"hashes");if(t)throw t;let r=lz(e.schema,e.table);return cz.openEnvironment(r,e.table)}a(_z,"initialize")});var Mp=g((u_e,_w)=>{"use strict";var dz=ra(),fz=Lp();_w.exports=Ez;async function Ez(e){let t=await fz(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return dz.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(Ez,"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(),hz=ra(),mz=Lp();fw.exports=pz;async function pz(e){let t=await mz(e),r=global.hdb_schema[e.schema][e.table];return hz.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(pz,"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(),Sz=We(),Tz=Q(),Ee=ut(),eo=L(),gz=Fi(),mw=Cr().LMDB_ERRORS_ENUM,{getSchemaPath:Rz}=Je(),yn=eo.SEARCH_WILDCARDS;async function Az(e,t,r){let s;e.schema===eo.SYSTEM_SCHEMA_NAME?s=gz[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(Az,"prepSearch");async function Sw(e,t,r,s){let n=Rz(e.schema,e.table),i=await Sz.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(Oz(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 Oz(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(Oz,"checkToFetchMore");function gw(e,t,r,s){if(Tz.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 eo.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case eo.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case eo.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case eo.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case eo.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(mw.UNKNOWN_SEARCH_TYPE)}}a(gw,"createSearchTypeFromSearchObject");Rw.exports={executeSearch:Sw,createSearchTypeFromSearchObject:gw,prepSearch:Az,searchByType:Tw}});var Ow=g((R_e,Aw)=>{"use strict";var g_e=tn(),bz=sa(),yz=Q(),Nz=L(),Iz=sd();Aw.exports=wz;function wz(e,t){if(!yz.isEmpty(t)&&Nz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=bz(e,"value");if(s)throw s;return Iz.prepSearch(e,t,!0)}a(wz,"lmdbGetDataByValue")});var Jc=g((b_e,bw)=>{"use strict";var O_e=tn(),Cz=sa(),Dz=Q(),Lz=L(),Mz=sd();bw.exports=Uz;async function Uz(e,t){if(!Dz.isEmpty(t)&&Lz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=Cz(e,"value");if(s)throw s;return Mz.prepSearch(e,t,!1)}a(Uz,"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,Pz=tn(),vz=sa(),xp=ra(),nd=ut(),{Resource:D_e}=(Ns(),ie(Gp)),Cw=sd(),Bz=Dp(),Hz=require("lodash"),{getSchemaPath:xz}=Je(),Iw=We(),{handleHDBError:Gz,hdb_errors:qz}=se(),{HTTP_STATUS_CODES:Fz}=qz,kz=1e8;Dw.exports=Vz;async function Vz(e){let t=vz(e,"conditions");if(t)throw Gz(t,t.message,Fz.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=xz(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=Hz.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=kz}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=>Bz.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(Vz,"lmdbSearchByConditions");async function ww(e,t,r,s){let n=new Pz(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 $z=L().OPERATIONS_ENUM,qp=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=$z.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:Yz,getSchemaPath:Kz}=Je(),vw=$();qw.exports=Wz;async function Wz(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 Qz(e),await zz(e);let t=Kz(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=Yz(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(Wz,"lmdbDropTable");async function Qz(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(Qz,"deleteAttributesFromSystem");async function zz(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(zz,"dropTableFromSystem")});var kw=g((H_e,Fw)=>{"use strict";var Jz=require("fs-extra"),Xz=tn(),jz=na(),Zz=ia(),e2=Fp(),t2=Kc(),r2=Mp(),s2=Jc(),Nn=L(),{getSchemaPath:n2}=Je(),{handleHDBError:i2,hdb_errors:o2}=se(),{HDB_ERROR_MSGS:a2,HTTP_STATUS_CODES:c2}=o2;Fw.exports=u2;async function u2(e){let t;try{t=await l2(e.schema);let r=new Xz(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 s2(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await e2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new Zz(Nn.SYSTEM_SCHEMA_NAME,Nn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await t2(n);let i=n2(t);await Jz.remove(i)}catch(r){throw r}}a(u2,"lmdbDropSchema");async function l2(e){let t=new jz(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 r2(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw i2(new Error,a2.SCHEMA_NOT_FOUND(e),c2.NOT_FOUND,void 0,void 0,!0);return s}a(l2,"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 _2=require("fs-extra"),od=We(),{getTransactionAuditStorePath:d2}=Je(),Vp=ut(),F_e=id();$w.exports=f2;async function f2(e){let t;try{let r=d2(e.schema,e.table);await _2.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(f2,"createTransactionsAuditEnvironment")});var zw=g(($_e,Qw)=>{"use strict";var $p=L(),Kw=We(),E2=$o(),{getSystemSchemaPath:h2,getSchemaPath:m2}=Je(),p2=Fi(),S2=y_(),Yp=b_(),T2=$(),g2=Yw(),Wp=p2.hdb_table,Ww=[];for(let e=0;e<Wp.attributes.length;e++)Ww.push(Wp.attributes[e].attribute);Qw.exports=R2;async function R2(e,t){let r=m2(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(h2(),$p.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await E2.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 g2(t)}catch(o){throw o}}a(R2,"lmdbCreateTable");async function Kp(e){try{await S2(e)}catch(t){T2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Kp,"createAttribute")});var Xw=g((K_e,Jw)=>{"use strict";var A2=vc(),O2=Hc(),b2=X_(),Xc=L(),y2=$o().updateRecords,N2=We(),{getSchemaPath:I2}=Je(),w2=$c(),C2=$();Jw.exports=D2;async function D2(e){try{let{schema_table:t,attributes:r}=A2(e);O2(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 b2(e.hdb_auth_header,t,r),n=I2(e.schema,e.table),i=await N2.openEnvironment(n,e.table),o=await y2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await w2(e,o)}catch(c){C2.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(D2,"lmdbUpdateRecords")});var Zw=g((Q_e,jw)=>{"use strict";var L2=L().OPERATIONS_ENUM,Qp=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=L2.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(),M2=vc(),U2=Hc(),P2=X_(),jc=L(),v2=$o().upsertRecords,B2=We(),{getSchemaPath:H2}=Je(),x2=$c(),G2=$(),{handleHDBError:q2,hdb_errors:F2}=se();eC.exports=k2;async function k2(e){let t;try{t=M2(e)}catch(u){throw q2(u,u.message,F2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;U2(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 P2(e.hdb_auth_header,r,s),i=H2(e.schema,e.table),o=await B2.openEnvironment(i,e.table),c=await v2(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await x2(e,c)}catch(u){G2.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(k2,"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:V2}=Je(),sde=sC(),Zc=ut(),$2=Q(),oC=iC(),Y2=require("util").promisify,K2=Y2(setTimeout),W2=1e4,Q2=100;aC.exports=z2;async function z2(e){let t=V2(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 J2(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 K2(Q2);while(n.transactions_deleted>0);return i}a(z2,"deleteAuditLogsBefore");async function J2(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];$2.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>W2)break}return await n,r}catch(s){throw s}}a(J2,"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 X2=tn(),j2=ia(),cde=lC(),rn=L(),Z2=Q(),Zp=We(),eJ=Fi(),tJ=Jc(),rJ=Kc(),{getSchemaPath:sJ}=Je();_C.exports=nJ;async function nJ(e,t=!0){let r;e.schema===rn.SYSTEM_SCHEMA_NAME?r=eJ[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await oJ(e),n=sJ(e.schema,e.table),i=await Zp.openEnvironment(n,e.table);return t===!0&&await iJ(e,i,r.hash_attribute),Zp.dropDBI(i,e.attribute),s}a(nJ,"lmdbDropAttribute");async function iJ(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(iJ,"removeAttributeFromAllObjects");async function oJ(e){let t=new X2(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 tJ(t)).filter(o=>o[rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(Z2.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 j2(rn.SYSTEM_SCHEMA_NAME,rn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return rJ(i)}a(oJ,"dropAttributeFromSystem")});var SC=g((dde,pC)=>{"use strict";var eS=We(),oa=ut(),_de=Dr(),tS=L(),fC=Q(),{getTransactionAuditStorePath:aJ}=Je(),cJ=ra(),ad=Zo(),uJ=$();pC.exports=lJ;async function lJ(e){let t=aJ(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,dJ(r,e.search_values,n);case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return _J(r,e.search_values);default:return EC(r)}}a(lJ,"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 _J(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(_J,"searchTransactionsByUsername");function dJ(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=cJ.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(dJ,"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){uJ.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:fJ}=(Re(),ie(Fe));TC.exports={writeTransaction:EJ};async function EJ(e,t,r){return fJ({database:e,table:t}).transaction(r)}a(EJ,"writeTransaction")});var bC=g((Sde,OC)=>{"use strict";var{getSchemaPath:RC}=Je(),AC=We();OC.exports={flush:hJ,resetReadTxn:mJ};async function hJ(e,t){return(await AC.openEnvironment(RC(e,t),t.toString())).flushed}a(hJ,"flush");async function mJ(e,t){try{(await AC.openEnvironment(RC(e,t),t.toString())).resetReadTxn()}catch{}}a(mJ,"resetReadTxn")});var wC=g((gde,IC)=>{"use strict";var{Readable:pJ}=require("stream"),{getDatabases:SJ}=(Re(),ie(Fe)),{readSync:TJ,openSync:gJ,createReadStream:yC}=require("fs"),{open:RJ}=require("lmdb"),NC=wc(),AJ=Cc(),{AUDIT_STORE_OPTIONS:OJ}=(ei(),ie(CC)),{INTERNAL_DBIS_NAME:bJ,AUDIT_STORE_NAME:yJ}=ut();IC.exports=IJ;var rS=32768,NJ=100;async function IJ(e){let t=e.database||e.schema||"data",r=SJ()[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=RJ({noSync:!0,maxDbs:AJ.MAX_DBS}),f,E=d.openDB(bJ,new NC(!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++%NJ===0&&(await new Promise(X=>setTimeout(X,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:b,value:R}of l.getRange({transaction:h,start:!1}))if(n.some(M=>b.startsWith?.(M+"/"))){E.put(b,R);let[,M]=b.split("/"),v=!M,P=new NC(!v,v);await S(b,P)}e.include_audit&&await S(yJ,Object.assign({},OJ)),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=gJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(rS);TJ(c,_,0,rS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=yC(null,{fd:c,start:rS}),f=new pJ.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(IJ,"getBackup")});var MC=g((Ade,LC)=>{"use strict";var wJ=$(),{handleHDBError:CJ}=se(),DJ=Yb(),LJ=y_(),MJ=yp(),UJ=kI(),PJ=Kc(),vJ=Mp(),BJ=Ew(),HJ=Ow(),xJ=Jc(),GJ=Lw(),qJ=kw(),FJ=zw(),kJ=Xw(),VJ=tC(),$J=cC(),YJ=Fp(),KJ=dC(),WJ=SC(),QJ=gC(),DC=bC(),zJ=wC(),sS=class extends DJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return GJ(t)}async getDataByHash(t){return await vJ(t)}async searchByHash(t){return await BJ(t)}async getDataByValue(t,r){return await HJ(t,r)}async searchByValue(t){return await xJ(t)}async createSchema(t){return await UJ(t)}async dropSchema(t){return await qJ(t)}async createTable(t,r){return await FJ(t,r)}async dropTable(t){return await YJ(t)}async createAttribute(t){return await LJ(t)}async createRecords(t){return await MJ(t)}async updateRecords(t){return await kJ(t)}async upsertRecords(t){try{return await VJ(t)}catch(r){throw CJ(r,null,null,wJ.ERR,r)}}async deleteRecords(t){return await PJ(t)}async dropAttribute(t){return await KJ(t)}async deleteAuditLogsBefore(t){return await $J(t)}async readAuditLog(t){return await WJ(t)}writeTransaction(t,r,s){return QJ.writeTransaction(t,r,s)}flush(t,r){return DC.flush(t,r)}resetReadTxn(t,r){return DC.resetReadTxn(t,r)}getBackup(t){return zJ(t)}};LC.exports=sS});function e4(){ZJ=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},jJ).unref()}var iS,PC,vC,JJ,nS,XJ,eu,UC,to,cd,jJ,ZJ,oS=ge(()=>{iS=B(Dr()),PC=B(se()),vC=B($());Ns();JJ=100,nS=new Set,XJ=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),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>XJ)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<JJ>>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 to{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,iS.getNextMonotonicTime)())}getReadTxn(){}},jJ=3e4;a(e4,"startMonitoringTxns");e4()});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 to;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,ro=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||r4,r=dr()[t];if(!r)throw(0,Us.handleHDBError)(new Error,t4.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,t4,r4,s4,n4,HC,uS,KC=ge(()=>{"use strict";FC=B(MC()),ud=B(sa()),Us=B(se());Re();kC=B(vc()),VC=B(Hc()),Ps=B(L()),aS=B(bn()),cS=B(Ms()),$C=B(Q());ro();_d();({HDB_ERROR_MSGS:t4}=Us.hdb_errors),r4="data",s4=1e4,n4=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)(n4),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%s4===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:i4}=(KC(),ie(YC)),o4=ee();o4.initSync();var dd;function a4(){return dd||(dd=new i4,dd)}a(a4,"getBridge");WC.exports=a4()});var XC=g((Gde,JC)=>{"use strict";var QC=require("lodash"),ru=require("mathjs"),c4=require("jsonata"),zC=Q();JC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?QC.uniqWith(e,QC.isEqual):e,searchJSON:u4,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 u4(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=c4(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(u4,"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 l4=require("@turf/area"),_4=require("@turf/length"),d4=require("@turf/circle"),f4=require("@turf/difference"),E4=require("@turf/distance"),h4=require("@turf/boolean-contains"),m4=require("@turf/boolean-equal"),p4=require("@turf/boolean-disjoint"),S4=require("@turf/helpers"),eD=L(),Se=Q(),In=$();rD.exports={geoArea:T4,geoLength:g4,geoCircle:R4,geoDifference:A4,geoDistance:tD,geoNear:O4,geoContains:b4,geoEqual:y4,geoCrosses:N4,geoConvert:I4};function T4(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return l4.default(e)}catch(t){return In.trace(t,e),NaN}}a(T4,"geoArea");function g4(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return _4.default(e,{units:t||"kilometers"})}catch(r){return In.trace(r,e),NaN}}a(g4,"geoLength");function R4(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return d4.default(e,t,{units:r||"kilometers"})}catch(s){return In.trace(s,e,t),NaN}}a(R4,"geoCircle");function A4(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 f4(e,t)}catch(r){return In.trace(r,e,t),NaN}}a(A4,"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 E4.default(e,t,{units:r||"kilometers"})}catch(s){return In.trace(s,e,t),NaN}}a(tD,"geoDistance");function O4(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(O4,"geoNear");function b4(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 h4.default(e,t)}catch(r){return In.trace(r,e,t),!1}}a(b4,"geoContains");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,"geoEqual");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,"geoCrosses");function I4(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)),S4[t](e,r)}a(I4,"geoConvert")});var fd=g(($de,nD)=>{var so=XC(),Fr=ZC(),nn=sD();nD.exports=e=>{e.aggr.mad=e.aggr.MAD=so.mad,e.aggr.mean=e.aggr.MEAN=so.mean,e.aggr.mode=e.aggr.MODE=so.mode,e.aggr.prod=e.aggr.PROD=so.prod,e.aggr.median=e.aggr.MEDIAN=so.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=so.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=so.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 w4=fd(),iD=require("clone"),Ed=require("recursive-iterator"),le=$(),Ce=Q(),aa=Cs(),C4=L(),{hdb_errors:D4}=se(),{getDatabases:oD}=(Re(),ie(Fe)),L4="IS NULL",vs="There was a problem performing this search. Please check the logs and try again.";w4(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(C4.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(L4)>-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 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 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(D4.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 M4=Vb();uD.exports={searchByConditions:P4,searchByHash:v4,searchByValue:B4,search:H4};var ES=Cs(),{transformReq:hS}=Q(),U4=cD();async function P4(e){return hS(e),ES.searchByConditions(e)}a(P4,"searchByConditions");async function v4(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(v4,"searchByHash");async function B4(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(B4,"searchByValue");function H4(e,t){try{let r=new M4(e);r.validate(),new U4(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(H4,"search")});var hd=g((zde,lD)=>{"use strict";var x4=Cs();lD.exports={writeTransaction:G4};function G4(e,t,r){return x4.writeTransaction(e,t,r)}a(G4,"writeTransaction")});var ED=g((jde,fD)=>{"use strict";var q4=Pr(),F4=On(),_D=$(),k4=vr(),Xde=hd(),V4=require("clone"),pS=require("alasql"),$4=fd(),dD=require("util"),Y4=dD.promisify(F4.getTableSchema),K4=dD.promisify(q4.search),W4=L(),mS=Q();$4(pS);fD.exports={update:z4};var Q4="There was a problem performing this update. Please check the logs and try again.";async function z4({statement:e,hdb_user:t}){let r=await Y4(e.table.databaseid,e.table.tableid),s=J4(e.columns);mS.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=V4(n),c=mS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=pS.parse(u).statements[0],l=await K4(_),d=X4(s,l);return j4(o,d,t)}a(z4,"update");function J4(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 [${W4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw _D.error(t),new Error(Q4)}}a(J4,"createUpdateRecord");function X4(e,t){return mS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(X4,"buildUpdateRecords");async function j4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await k4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){_D.error(`Error delete new_attributes from update response: ${i}`)}return n}a(j4,"updateRecords")});var mD=g((rfe,hD)=>{var Z4=require("alasql"),e3=Pr(),t3=$(),r3=Cs(),TS=require("util"),SS=Q(),s3=L(),n3=On(),efe=hd(),tfe=vr(),i3="record",o3="successfully deleted",a3=TS.callbackify(_3),c3=TS.promisify(e3.search),u3=TS.promisify(n3.getTableSchema);hD.exports={convertDelete:a3};function l3(e){return`${e.deleted_hashes.length} ${i3}${e.deleted_hashes.length===1?"":"s"} ${o3}`}a(l3,"generateReturnMessage");async function _3({statement:e,hdb_user:t}){let r=await u3(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=Z4.parse(o).statements[0],u={operation:s3.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await c3(c);let _=await r3.deleteRecords(u);return SS.isEmptyOrZeroLength(_.message)&&(_.message=l3(_)),delete _.txn_time,_}catch(_){throw t3.error(_),_.hdb_code?_.message:_}}a(_3,"convertDelete")});var RD=g((nfe,gD)=>{"use strict";var d3=An(),{hdb_errors:pD}=se(),{getDatabases:SD}=(Re(),ie(Fe));gD.exports={checkSchemaExists:TD,checkSchemaTableExists:f3,schema_describe:d3};async function TD(e){if(!SD()[e])return pD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(TD,"checkSchemaExists");async function f3(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(f3,"checkSchemaTableExists")});var iu=g((ofe,E3)=>{E3.exports={name:"harperdb",version:"4.3.1",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:()=>h3});function h3(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||m3()}function as(e,t,r,s,n){kr(!!e,t,r,s,n)}function uu(e){UD.push(e)}function m3(){md=performance.now(),setTimeout(async()=>{let e=performance.now()-md;md=0;let t=[],r={time:Date.now(),period:e,threadId:no.threadId,metrics:t};for(let[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:no.threadId,byThread:!0,...s});for(let n of UD)n(t);Sd=new Map,no.parentPort?no.parentPort.postMessage({type:MD,report:r}):xD({report:r})},LD).unref()}async function p3(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:b}=S;for(let R of T||[]){let{path:M,method:v,type:P,metric:k,count:H,total:X,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,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[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 vD()}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(X=>X);for(let X in H){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 b=T.count-1,R=[],M=0,v=0,P;for(let Be of PD){let Lt=b*Be;for(;M<Lt;)P=S[v++],M+=P.count,v===1&&M--;let Wl=S[v>1?v-2:0];P||(P=S[0]),R.push(P.value-(P.value-Wl.value)*(M-Lt)/P.count)}let[k,H,X,z,J,me,ce,de,Le]=R;Object.assign(T,{p1:k,p10:H,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 g3(){HD=!0;let e=(0,cu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await p3(LD,e),await bD(AS(),S3),await bD(BD(),T3)},Math.min(e/2,2147483647)).unref()}function xD(e,t){let r=e.report;r.threadId=t?.threadId||no.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||g3(),R3&&(GD=O3(r))}async function O3(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>A3){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 no,CD,ou,au,gS,pd,cu,RS,Sd,DD,md,LD,MD,UD,PD,AD,OD,vD,S3,T3,yD,ND,HD,ID,wD,R3,GD,li,A3,wn=ge(()=>{no=require("worker_threads"),CD=B(Ke());Re();ou=B($()),au=require("path"),gS=require("fs/promises"),pd=B(Dr()),cu=B(ee()),RS=B(L());or();(0,cu.initSync)();Sd=new Map,DD=(0,cu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(h3,"setAnalyticsEnabled");a(kr,"recordAction");st.recordAnalytics=kr;a(as,"recordActionBinary");md=0,LD=1e3,MD="analytics-report",UD=[];a(uu,"addAnalyticsListener");PD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(m3,"sendAnalytics");a(p3,"aggregation");AD=0,OD=0,vD=a(()=>new Promise(setImmediate),"rest");a(bD,"cleanup");S3=36e5,T3=31536e6;a(AS,"getRawAnalyticsTable");a(BD,"getAnalyticsTable");(0,CD.setChildListenerByType)(MD,xD);a(g3,"startScheduledTasks");ID=0,wD=new Map,R3=!1;a(xD,"recordAnalytics");A3=1e6;a(O3,"logAnalytics")});var wS=g((Tfe,zD)=>{"use strict";var{decode:b3}=require("msgpackr"),{isMainThread:mfe,parentPort:pfe,threadId:Sfe}=require("worker_threads"),_u=it(),ca=ke(),yS=L(),jt=$(),bS=ee(),y3=L(),{onMessageByType:N3}=Ke(),kD=Rn(),{recordAction:I3,recordActionBinary:w3}=(wn(),ie(lu)),{publishToStream:C3}=_u,{ConsumerEvents:qD}=require("nats"),D3=Pr(),{promisify:L3}=require("util"),VD=L3(setTimeout),Rd=1e4,Ad,gd,M3,U3,$D,du=new Map,ua=new Map;zD.exports={initialize:NS,ingestConsumer:IS,setSubscription:P3,setIgnoreOrigin:H3,getDatabaseSubscriptions:B3,updateConsumer:YD};async function NS(){N3(yS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async s=>{await YD(s)}),$D=!0,jt.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await _u.getNATSReferences();Ad=e,gd=e.info.server_name,M3=t,U3=r}a(NS,"initialize");async function YD(e){if(e.status==="start"){let{js:t,jsm:r}=await KD(e.node_domain_name);IS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=du.get(e.stream_name+e.node_domain_name);t&&(jt.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),du.set(e.stream_name+e.node_domain_name,"close")),ua.get(e.node_domain_name)==="failed"&&ua.set(e.node_domain_name,"close")}}a(YD,"updateConsumer");var Od=new Map;function P3(e,t,r){let s=Od.get(e);s||Od.set(e,s=new Map),s.set(t,r),$D||NS().then(v3)}a(P3,"setSubscription");async function v3(){let e=await D3.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,s,n;for(let i of t.subscriptions)if(i.subscribe===!0){if(!s&&({js:s,jsm:n}=await KD(r),!s))break;let{schema:o,table:c}=i,u=kD.createNatsTableStreamName(o,c);IS(u,s,n,r)}}}a(v3,"accessConsumers");async function KD(e){let t,r,s=1;for(;!r;)try{t=await Ad.jetstream({domain:e}),r=await Ad.jetstreamManager({domain:e,checkAPI:!1})}catch(n){if(ua.get(e)==="close")break;ua.set(e,"failed"),s%10===1&&jt.warn("Nats ingest attempting to connect to:",e,"Nats error:",n.message);let i=s++*100<Rd?s++*100:Rd;await VD(i)}return{js:t,jsm:r}}a(KD,"connectToRemoteJS");function B3(){return Od}a(B3,"getDatabaseSubscriptions");var WD;function H3(e){WD=e}a(H3,"setIgnoreOrigin");var QD=100,FD=new Array(QD),Td=0;async function IS(e,t,r,s){let{connection:n}=await _u.getNATSReferences();Ad=n,gd=n.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,gd),jt.notify("Initializing ingest consumer for node:",s,"stream:",e)}catch(_){if(ua.get(s)==="close")break;o%10===1&&jt.warn("Nats ingest error getting consumer:",s,"stream:",e,"Nats error:",_.message),_.code==="404"&&(jt.notify("Nats ingest creating consumer for node:",s,"stream:",e),i=await _u.createConsumer(r,e,gd,new Date(Date.now()).toISOString()));let l=o++*100<Rd?o++*100:Rd;await VD(l)}let c=!1,u;for(;!c;){if(du.get(e+s)==="close"||ua.get(s)==="close"){du.delete(e+s),c=!0;continue}u=await i.consume({max_messages:bS.get(yS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100}),du.set(e+s,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===qD.ConsumerDeleted&&(await u.close(),c=!0),l.type===qD.HeartbeatsMissed){let d=l.data;jt.trace(`${d} clustering ingest consumer heartbeats missed, node: ${s} stream: ${u.consumer.stream}`),d===2&&(jt.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${s} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await FD[Td],FD[Td]=x3(l).catch(d=>{jt.error(d)}),++Td>=QD&&(Td=0)}catch(l){l.message==="consumer deleted"?(jt.notify("Nats consumer deleted, closing messages for node:",s,"stream:",u.consumer.stream),await u.close(),c=!0):jt.error("Error consuming clustering ingest, restarting consumer",l)}_u.clearClientCache(),!c&&_&&await NS()}}a(IS,"ingestConsumer");async function x3(e){let t=b3(e.data);I3(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),jt.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,s=!1,n=bS.get(yS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(ca.MSG_HEADERS.TRANSACTED_NODES)&&r.values(ca.MSG_HEADERS.TRANSACTED_NODES).indexOf(n)>-1&&(s=!0);let i=r.get(ca.MSG_HEADERS.ORIGIN);if(s||(s=i===n&&!WD),w3(s,"echo",e.subject,t.operation,"ingest"),s){e.ack();return}r.append(ca.MSG_HEADERS.TRANSACTED_NODES,n);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;jt.trace("processing message:",o,c,_,(l?"records: "+l.map(M=>M?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),jt.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=Od.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(y3.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&C3(e.subject.split(".").slice(0,-1).join("."),kD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){jt.error(o)}e.ack()}a(x3,"messageProcessor");function OS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(OS,"convertOperation")});var it=g((Nfe,dL)=>{"use strict";var Pt=ee();Pt.initSync();var G3=require("fs-extra"),q3=require("semver"),hu=require("path"),{monotonicFactory:F3}=require("ulidx"),XD=F3(),k3=require("util"),jD=require("child_process"),V3=k3.promisify(jD.exec),$3=jD.spawn,Vt=ke(),De=L(),bd=Q(),Bs=$(),yd=Rn(),Y3=hd(),fu=lr(),{broadcast:K3,onMessageByType:W3,getWorkerIndex:Q3}=Ke(),{isMainThread:ZD}=require("worker_threads"),{Encoder:z3,decode:MS}=require("msgpackr"),eL=new z3,{isEmpty:co}=bd,tL=os(),Rfe=48*36e11;ZD&&W3(De.ITC_EVENT_TYPES.RESTART,()=>{Er=void 0,ao=void 0});var{connect:J3,StorageType:X3,RetentionPolicy:j3,AckPolicy:US,DeliverPolicy:PS,DiscardPolicy:Z3,NatsConnection:Afe,JetStreamManager:Ofe,JetStreamClient:bfe,StringCodec:yfe,JSONCodec:eX,createInbox:vS,headers:tX,ErrorCode:JD}=require("nats"),{PACKAGE_ROOT:rX}=L(),sX=iu(),{recordAction:nX}=(wn(),ie(lu)),rL=eX(),iX="clustering",oX=sX.engines[Vt.NATS_SERVER_NAME],aX=hu.join(rX,"dependencies"),LS=hu.join(aX,`${process.platform}-${process.arch}`,Vt.NATS_BINARY_NAME),CS,DS,Eu,io,oo;dL.exports={runCommand:sL,checkNATSServerInstalled:cX,createConnection:BS,getConnection:Nd,getJetStreamManager:mu,getJetStream:iL,getNATSReferences:Hs,getServerList:lX,createLocalStream:HS,listStreams:oL,deleteLocalStream:_X,getServerConfig:pu,listRemoteStreams:dX,viewStream:fX,viewStreamIterator:EX,publishToStream:hX,request:SX,reloadNATS:xS,reloadNATSHub:TX,reloadNATSLeaf:gX,extractServerName:pX,requestErrorHandler:RX,createLocalTableStream:lL,createTableStreams:bX,purgeTableStream:_L,purgeSchemaTableStreams:yX,getStreamInfo:NX,updateLocalStreams:wX,closeConnection:uX,getJsmServerName:Id,addNatsMsgHeader:aL,clearClientCache:nL,updateRemoteConsumer:AX,createConsumer:cL,updateConsumerIterator:OX};async function sL(e,t=void 0){let{stdout:r,stderr:s}=await V3(e,{cwd:t});if(s)throw new Error(s.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 cX(){try{await G3.access(LS)}catch{return!1}let e=await sL(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return q3.eq(t,oX)}a(cX,"checkNATSServerInstalled");async function BS(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await tL.getClusterUser();if(co(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 J3({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,io=void 0,oo=void 0,ao=void 0}a(nL,"clearClientCache");async function uX(){Er&&(await Er.drain(),Er=void 0,io=void 0,oo=void 0,ao=void 0)}a(uX,"closeConnection");var Er,ao;async function Nd(){return ao||(ao=BS(Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Er=await ao),Er||ao}a(Nd,"getConnection");async function mu(){if(io)return io;co(Er)&&await Nd();let{domain:e}=pu(De.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(mu,"getJetStreamManager");async function iL(){if(oo)return oo;co(Er)&&await Nd();let{domain:e}=pu(De.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(iL,"getJetStream");async function Hs(){let e=Er||await Nd(),t=io||await mu(),r=oo||await iL();return{connection:e,jsm:t,js:r}}a(Hs,"getNATSReferences");async function lX(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(lX,"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:X3.File,retention:j3.Limits,subjects:t,discard:Z3.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 _X(e){let{jsm:t}=await Hs();await t.streams.delete(e)}a(_X,"deleteLocalStream");async function dX(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(dX,"listRemoteStreams");async function fX(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(fX,"viewStream");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[];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(EX,"viewStreamIterator");async function hX(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}`),nX(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(hX,"publishToStream");function aL(e,t){t===void 0&&(t=tX());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),iX);if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(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 co(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 mX(e,t,r){await e.consumers.delete(t,r)}a(mX,"removeConsumer");function pX(e){return e.split(".")[1]}a(pX,"extractServerName");async function SX(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(SX,"request");function xS(e){return new Promise(async(t,r)=>{let s=$3(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 TX(){let{pid_file_path:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await xS(e)}a(TX,"reloadNATSHub");async function gX(){let{pid_file_path:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await xS(e)}a(gX,"reloadNATSLeaf");function RX(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(RX,"requestErrorHandler");async function AX(e,t){let r=t+Vt.SERVER_SUFFIX.LEAF,{connection:s}=await Hs(),{jsm:n}=await DX(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 mX(n,c,s.info.server_name)}catch(_){Bs.trace(_)}})}a(AX,"updateRemoteConsumer");async function OX(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&&Q3()<Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=wS();await c(o)}await K3(o),s==="stop"&&await bd.async_set_timeout(1e3)}a(OX,"updateConsumerIterator");function uL(e){return Y3.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=IX(e,t,s);await HS(r,[n])}a(lL,"createLocalTableStream");async function bX(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(bX,"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 yX(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(yX,"purgeSchemaTableStreams");async function NX(e){return(await mu()).streams.info(e)}a(NX,"getStreamInfo");function IX(e,t,r){return`${Vt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(IX,"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 wX(){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=CX(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(wX,"updateLocalStreams");function CX(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(CX,"updateStreamLimits");async function DX(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(DX,"connectToRemoteJS")});var Su=g((Cfe,mL)=>{"use strict";var la=O_(),_a=RD(),LX=$(),MX=require("uuid").v4,wfe=require("clone"),Cd=bn(),da=L(),UX=require("util"),_i=Cs(),{handleHDBError:hr,hdb_errors:PX}=se(),{HDB_ERROR_MSGS:wd,HTTP_STATUS_CODES:mr}=PX,{SchemaEventMsg:Dd}=Ms(),fL=it(),{getDatabases:vX}=(Re(),ie(Fe)),{transformReq:fa}=Q();mL.exports={createSchema:BX,createSchemaStructure:EL,createTable:HX,createTableStructure:hL,createAttribute:kX,dropSchema:xX,dropTable:GX,dropAttribute:qX,getBackup:VX};async function BX(e){let t=await EL(e);return Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),t}a(BX,"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 HX(e){return fa(e),e.hash_attribute=e.primary_key??e.hash_attribute,await hL(e)}a(HX,"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:MX(),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 xX(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(xX,"dropSchema");async function GX(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(GX,"dropTable");async function qX(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),FX(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw LX.error(`Got an error deleting attribute ${UX.inspect(e)}.`),s}}a(qX,"dropAttribute");function FX(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(FX,"dropAttributeFromGlobal");async function kX(e){fa(e);let t=vX()[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(kX,"createAttribute");function VX(e){return _i.getBackup(e)}a(VX,"getBackup")});var SL=g((Lfe,pL)=>{"use strict";var{OPERATIONS_ENUM:$X}=L(),GS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=$X.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 YX=Cs(),Ufe=SL(),Ld=Q(),Md=L(),KX=ee(),{handleHDBError:TL,hdb_errors:WX}=se(),{HDB_ERROR_MSGS:gL,HTTP_STATUS_CODES:RL}=WX,QX=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=zX;async function zX(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(!KX.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)&&QX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await YX.readAuditLog(e)}a(zX,"readAuditLog")});var yL=g((Bfe,bL)=>{"use strict";var{OPERATIONS_ENUM:JX}=L(),FS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=JX.GET_BACKUP,this.schema=t,this.table=r}};bL.exports=FS});var wL=g((qfe,IL)=>{"use strict";var XX=Cs(),xfe=yL(),kS=Q(),jX=L(),Gfe=ee(),{handleHDBError:ZX,hdb_errors:ej}=se(),{HDB_ERROR_MSGS:NL,HTTP_STATUS_CODES:tj}=ej;IL.exports=rj;async function rj(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 ZX(new Error,t,tj.NOT_FOUND,jX.LOG_LEVELS.ERROR,t,!0);return await XX.getBackup(read_audit_log_object)}a(rj,"getBackup")});var PL=g((kfe,UL)=>{var di=require("validate.js"),DL=Xe(),Ea=L(),{handleHDBError:sj,hdb_errors:nj}=se(),{HDB_ERROR_MSGS:dt,HTTP_STATUS_CODES:ij}=nj,VS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),oj={STRUCTURE_USER:"structure_user"},CL=Object.values(Ea.ROLE_TYPES_ENUM),aj="attribute_permissions",cj="attribute_name",{PERMS_CRUD_ENUM:ha}=Ea,uj=[aj,...Object.values(ha)],LL=[ha.READ,ha.INSERT,ha.UPDATE],lj=[cj,...LL];function _j(e){let t=VS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,ML(e,t)}a(_j,"addRoleValidation");function dj(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,ML(e,t)}a(dj,"alterRoleValidation");function fj(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,DL.validateObject(e,t)}a(fj,"dropRoleValidation");var Ej=["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++)Ej.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=hj(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===oj.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=>{uj.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=>{!lj.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 mj(r)}a(ML,"customValidate");UL.exports={addRoleValidation:_j,alterRoleValidation:dj,dropRoleValidation:fj};function hj(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(hj,"validateNoSUPerms");function mj(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 sj(new Error,s,ij.BAD_REQUEST)}else return null}a(mj,"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(),pj=ii(),YS=PL(),KS=bn(),Sj=require("uuid").v4,Tj=require("util"),Ud=L(),gj=Q(),WS=BL.searchByValue,Rj=BL.searchByHash,Aj=Tj.promisify(pj.delete),Oj=tn(),bj=na(),{hdb_errors:yj,handleHDBError:uo}=se(),{HDB_ERROR_MSGS:HL,HTTP_STATUS_CODES:Tu}=yj,{UserEventMsg:QS}=Ms();xL.exports={addRole:Nj,alterRole:Ij,dropRole:wj,listRoles:Cj};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 Nj(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 uo(i)}if(s&&s.length>0)throw uo(new Error,HL.ROLE_ALREADY_EXISTS(e.role),Tu.CONFLICT,void 0,void 0,!0);e.id||(e.id=Sj());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(Nj,"addRole");async function Ij(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 uo(n)}if(s&&s?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",Tu.BAD_REQUEST,void 0,void 0,!0);return await KS.signalUserChange(new QS(process.pid)),e}a(Ij,"alterRole");async function wj(e){let t=YS.dropRoleValidation(e);if(t)throw uo(new Error,t,Tu.BAD_REQUEST,void 0,void 0,!0);let r=new bj(Ud.SYSTEM_SCHEMA_NAME,Ud.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await Rj(r));if(s.length===0)throw uo(new Error,HL.ROLE_NOT_FOUND,Tu.NOT_FOUND,void 0,void 0,!0);let n=new Oj(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(gj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`,Tu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Aj(c),KS.signalUserChange(new QS(process.pid)),`${s[0].role} successfully deleted`}a(wj,"dropRole");async function Cj(){return WS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Cj,"listRoles")});var kL=g((Kfe,FL)=>{"use strict";var Dj=ee(),fi=require("joi"),Lj=Xe(),GL=require("moment"),Mj=require("fs-extra"),JS=require("path"),Uj=require("lodash"),gu=L(),{LOG_LEVELS:lo}=L(),Pj="YYYY-MM-DD hh:mm:ss",vj=JS.resolve(__dirname,"../logs");FL.exports=function(e){return Lj.validateBySchema(e,Bj)};var Bj=fi.object({from:fi.custom(qL),until:fi.custom(qL),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(Hj)});function qL(e,t){if(GL(e,GL.ISO_8601).format(Pj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(qL,"validateDatetime");function Hj(e,t){if(Uj.invert(gu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=Dj.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(vj,gu.LOG_NAMES.INSTALL):JS.join(s,n);return Mj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Hj,"validateReadLogPath")});var jS=g((Qfe,$L)=>{"use strict";var Pd=L(),xj=$(),Gj=ee(),qj=kL(),XS=require("path"),VL=require("fs-extra"),{once:Fj}=require("events"),{handleHDBError:kj,hdb_errors:Vj}=se(),{PACKAGE_ROOT:$j}=L(),Yj=XS.join($j,"logs"),Kj=1e3,Wj=200;$L.exports=Qj;async function Qj(e){let t=qj(e);if(t)throw kj(t,t.message,Vj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Gj.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(Yj,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?Kj: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)*Wj,0));let S=VL.createReadStream(n,{start:p});S.on("error",P=>{xj.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,X;for(;(X=k.exec(P))&&!S.destroyed;){M&&(M.message=P.slice(H,X.index),v(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:""},H=X.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,X;switch(!0){case(i&&c&&_):k=new Date(P.timestamp),H=new Date(u),X=new Date(l),P.level===o&&k>=H&&k<=X&&T<E?T++:P.level===o&&k>=H&&k<=X&&(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),X=new Date(l),P.level===o&&k<=X&&T<E?T++:P.level===o&&k<=X&&(Ei(P,f,b),T++,T===h&&S.destroy());break;case(c&&_):k=new Date(P.timestamp),H=new Date(u),X=new Date(l),k>=H&&k<=X&&T<E?T++:k>=H&&k<=X&&(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),X=new Date(l),k<=X&&T<E?T++:k<=X&&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 Fj(S,"close"),b}a(Qj,"readLog");function Ei(e,t,r){t==="desc"?zj(e,r):t==="asc"?Jj(e,r):r.push(e)}a(Ei,"pushLineToResult");function zj(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(zj,"insertDescending");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,"insertAscending")});var vd=g((Zfe,QL)=>{"use strict";var ZS=require("joi"),{string:Ru,boolean:YL,date:Xj}=ZS.types(),jj=Xe(),{validateSchemaExists:Jfe,validateTableExists:Xfe,validateSchemaName:jfe}=Js(),Zj=L(),eZ=ke(),KL=ee();KL.initSync();var tZ=Ru.invalid(KL.get(Zj.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(eZ.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:tZ,subscriptions:ZS.array().items({table:Ru.optional(),schema:Ru.optional(),database:Ru.optional(),subscribe:YL.required(),publish:YL.required().custom(sZ),start_time:Xj.iso()}).min(1).required()};function rZ(e){return jj.validateBySchema(e,ZS.object(WL))}a(rZ,"addUpdateNodeValidator");function sZ(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(sZ,"checkForFalsy");QL.exports={addUpdateNodeValidator:rZ,validation_schema:WL}});var JL=g((tEe,zL)=>{var nZ=Xe(),iZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};zL.exports=function(e){return nZ.validateObject(e,iZ)}});var Bd=g((rEe,XL)=>{"use strict";var oZ=L().OPERATIONS_ENUM,eT=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=oZ.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};XL.exports=eT});var ZL=g((nEe,jL)=>{"use strict";var aZ={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:aZ,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:cZ}=se(),{HTTP_STATUS_CODES:Sr,AUTHENTICATION_ERROR_MSGS:Tr}=cZ,Au=$(),eM=G_(),aT=os(),uZ=vr().update,lZ=Bd(),_Z=bn(),{UserEventMsg:dZ}=Ms(),hi=ee();hi.initSync();var iT=require("path"),{JWTTokens:fZ,JWTRSAKeys:EZ,TOKEN_TYPE_ENUM:Hd}=ZL(),hZ=hi.get(cs.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?hi.get(cs.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",mZ=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:pZ,validateOperationToken:TZ,refreshOperationToken:SZ,validateRefreshToken:rM};async function pZ(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:mZ,algorithm:xd,subject:Hd.REFRESH}),u=eM.hash(c),_=new lZ(cs.SYSTEM_SCHEMA_NAME,cs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await uZ(_)}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 _Z.signalUserChange(new dZ(process.pid)),new fZ(o,c)}a(pZ,"createTokens");async function tM(e,t,r){return await Ou.sign(e,{key:t,passphrase:r},{expiresIn:hZ,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 EZ(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 SZ(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(SZ,"refreshOperationToken");async function TZ(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(TZ,"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 gZ=JL(),ma=require("passport"),RZ=require("passport-local").Strategy,AZ=require("passport-http").BasicStrategy,OZ=require("util"),bZ=os(),iM=OZ.callbackify(bZ.findAndValidateUser),cEe=Cr(),yZ=L(),nM=bu();ma.use(new RZ(function(e,t,r){iM(e,t,r)}));ma.use(new AZ(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 NZ(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===yZ.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(NZ,"authorize");function IZ(e,t){let r=gZ(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(IZ,"checkPermissions");oM.exports={authorize:NZ,checkPermissions:IZ}});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 wZ=L().OPERATIONS_ENUM,_T=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=wZ.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 CZ=dM(),TEe=ut(),fM=We(),DZ=$(),{getSchemaPath:gEe,getTransactionAuditStorePath:REe}=Je(),{getDatabases:LZ}=(Re(),ie(Fe));EM.exports=MZ;async function MZ(e){let t=new CZ;try{let r=LZ()[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){DZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(MZ,"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 UZ=require("fs-extra"),PZ=require("path"),Zt=require("systeminformation"),pi=$(),SM=it(),NEe=ke(),Fd=L(),vZ=hM(),BZ=An(),{getThreadInfo:TM}=Ke(),yT=ee();yT.initSync();var HZ=pM(),{openEnvironment:IEe}=We(),{getSchemaPath:wEe}=Je(),{database:xZ,databases:gM}=(Re(),ie(Fe)),qd;AM.exports={getHDBProcessInfo:TT,getNetworkInfo:RT,getDiskInfo:gT,getMemoryInfo:ST,getCPUInfo:pT,getTimeInfo:mT,getSystemInformation:AT,systemInformation:GZ,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,...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:X,...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: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 UZ.readFile(PZ.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 BZ.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await vZ(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=xZ({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 GZ(e){let t=new HZ;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(GZ,"systemInformation")});var Vd=g((LEe,OM)=>{"use strict";OM.exports={version:qZ,printVersion:FZ};var kd=iu();function qZ(){if(kd)return kd.version}a(qZ,"version");function FZ(){kd&&console.log(`HarperDB Version ${kd.version}`)}a(FZ,"printVersion")});var us=g((vEe,IM)=>{"use strict";var kZ=vr(),NT=Q(),VZ=require("util"),_o=L(),bM=ee();bM.initSync();var $Z=cT(),yM=Pr(),{Node:UEe,NodeSubscription:PEe}=mi(),YZ=na(),KZ=uM(),{RemotePayloadObject:WZ,RemotePayloadSubscription:QZ}=yu(),{handleHDBError:zZ,hdb_errors:JZ}=se(),{HTTP_STATUS_CODES:XZ,HDB_ERROR_MSGS:jZ}=JZ,ZZ=tn(),e5=pa(),t5=Vd(),{getDatabases:r5}=(Re(),ie(Fe)),s5=VZ.promisify($Z.authorize),n5=yM.searchByHash,i5=yM.searchByValue;IM.exports={authHeaderToUser:o5,isEmpty:a5,getNodeRecord:c5,upsertNodeRecord:u5,buildNodePayloads:l5,checkClusteringEnabled:_5,getAllNodeRecords:d5,getSystemInfo:f5,reverseSubscription:NM};async function o5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await s5(t,null),e}a(o5,"authHeaderToUser");function a5(e){return e==null}a(a5,"isEmpty");async function c5(e){let t=new YZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return n5(t)}a(c5,"getNodeRecord");async function u5(e){let t=new KZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return kZ.upsert(t)}a(u5,"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 l5(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=r5()[u]?.[_],h=new QZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new WZ(r,t,n,s)}a(l5,"buildNodePayloads");function _5(){if(!bM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw zZ(new Error,jZ.CLUSTERING_NOT_ENABLED,XZ.BAD_REQUEST,void 0,void 0,!0)}a(_5,"checkClusteringEnabled");async function d5(){let e=new ZZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await i5(e))}a(d5,"getAllNodeRecords");async function f5(){let e=await e5.getSystemInformation();return{hdb_version:t5.version(),node_version:e.node_version,platform:e.platform}}a(f5,"getSystemInfo")});var IT=g((HEe,vM)=>{"use strict";var $d=it(),wM=Q(),CM=ke(),DM=L(),Yd=$(),LM=Su(),E5=id(),{RemotePayloadObject:h5}=yu(),{handleHDBError:MM,hdb_errors:m5}=se(),{HTTP_STATUS_CODES:UM}=m5,{NodeSubscription:PM}=mi();vM.exports=p5;async function p5(e,t){let r;try{r=await $d.request(`${t}.${CM.REQUEST_SUFFIX}`,new h5(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 E5(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(p5,"reviewSubscriptions")});var zd=g((GEe,xM)=>{"use strict";var{handleHDBError:Kd,hdb_errors:S5}=se(),{HTTP_STATUS_CODES:Wd}=S5,{addUpdateNodeValidator:T5}=vd(),Qd=$(),HM=L(),BM=ke(),g5=Q(),Nu=it(),Iu=us(),R5=ee(),A5=IT(),{Node:O5,NodeSubscription:b5}=mi(),{broadcast:y5}=Ke(),N5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",I5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",w5=R5.get(HM.CONFIG_PARAMS.CLUSTERING_NODENAME);xM.exports=C5;async function C5(e,t=!1){Qd.trace("addNode called with:",e),Iu.checkClusteringEnabled();let r=T5(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(!g5.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 A5(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=N5,o;let c=Iu.buildNodePayloads(n,w5,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 b5(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 O5(s,u,_.system_info);return await Iu.upsertNodeRecord(l),y5({type:"nats_update"}),i.length>0?o.message=I5:o.message=`Successfully added '${s}' to manifest`,o}a(C5,"addNode")});var DT=g((kEe,FM)=>{"use strict";var{handleHDBError:wT,hdb_errors:D5}=se(),{HTTP_STATUS_CODES:CT}=D5,{addUpdateNodeValidator:L5}=vd(),wu=$(),qM=L(),GM=ke(),FEe=Q(),Cu=it(),Du=us(),M5=ee(),{cloneDeep:U5}=require("lodash"),P5=IT(),{Node:v5,NodeSubscription:B5}=mi(),{broadcast:H5}=Ke(),x5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",G5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",q5=M5.get(qM.CONFIG_PARAMS.CLUSTERING_NODENAME);FM.exports=F5;async function F5(e){wu.trace("updateNode called with:",e),Du.checkClusteringEnabled();let t=L5(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=U5(n));let{added:i,skipped:o}=await P5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=x5,c;let u=Du.buildNodePayloads(i,q5,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 v5(r,[],_.system_info)]),await k5(s[0],i,_.system_info),o.length>0?c.message=G5:c.message=`Successfully updated '${r}'`,c}a(F5,"updateNode");async function k5(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 B5(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Du.upsertNodeRecord(s),H5({type:"nats_update"})}a(k5,"updateNodeTable")});var KM=g(($Ee,YM)=>{"use strict";var $M=require("joi"),{string:kM}=$M.types(),V5=Xe(),VM=L(),$5=ee(),Y5=ke();YM.exports=K5;function K5(e){let t=kM.invalid($5.get(VM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Y5.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 V5.validateBySchema(e,r)}a(K5,"removeNodeValidator")});var Xd=g((KEe,XM)=>{"use strict";var{handleHDBError:WM,hdb_errors:W5}=se(),{HTTP_STATUS_CODES:QM}=W5,Q5=KM(),Lu=$(),zM=us(),z5=Q(),Jd=L(),JM=ke(),LT=it(),J5=ee(),{RemotePayloadObject:X5}=yu(),{NodeSubscription:j5}=mi(),Z5=ia(),e8=ii(),{broadcast:t8}=Ke(),r8=J5.get(Jd.CONFIG_PARAMS.CLUSTERING_NODENAME);XM.exports=s8;async function s8(e){Lu.trace("removeNode called with:",e),zM.checkClusteringEnabled();let t=Q5(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(z5.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 X5(Jd.OPERATIONS_ENUM.REMOVE_NODE,r8,[]),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 j5(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 Z5(Jd.SYSTEM_SCHEMA_NAME,Jd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await e8.deleteRecord(c),t8({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(s8,"removeNode")});var eU=g((QEe,ZM)=>{"use strict";var jM=require("joi"),{string:n8,array:i8}=jM.types(),o8=Xe(),a8=vd();ZM.exports=c8;function c8(e){let t=jM.object({operation:n8.valid("configure_cluster").required(),connections:i8.items(a8.validation_schema).required()});return o8.validateBySchema(e,t)}a(c8,"configureClusterValidator")});var MT=g((JEe,iU)=>{"use strict";var u8=L(),jd=$(),l8=Q(),_8=Xd(),d8=zd(),tU=us(),f8=eU(),{handleHDBError:rU,hdb_errors:E8}=se(),{HTTP_STATUS_CODES:sU}=E8,h8="Configure cluster complete.",m8="Failed to configure the cluster. Check the logs for more details.",p8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";iU.exports=S8;async function S8(e){jd.trace("configure cluster called with:",e),tU.checkClusteringEnabled();let t=f8(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(_8,{operation:u8.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(d8,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(l8.isEmptyOrZeroLength(o))return{message:h8,connections:c};if(u)return{message:p8,failed_nodes:o,connections:c};throw rU(new Error,m8,sU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(S8,"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"),T8=Xe(),{validateSchemaExists:oU,validateTableExists:g8,validateSchemaName:aU}=Js(),R8=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(g8).required()});function A8(e){return T8.validateBySchema(e,R8)}a(A8,"purgeStreamValidator");cU.exports=A8});var UT=g((ehe,lU)=>{"use strict";var{handleHDBError:O8,hdb_errors:b8}=se(),{HTTP_STATUS_CODES:y8}=b8,N8=uU(),I8=it(),w8=us();lU.exports=C8;async function C8(e){e.schema=e.schema??e.database;let t=N8(e);if(t)throw O8(t,t.message,y8.BAD_REQUEST,void 0,void 0,!0);w8.checkClusteringEnabled();let{schema:r,table:s,options:n}=e;return await I8.purgeTableStream(r,s,n),`Successfully purged table '${r}.${s}'`}a(C8,"purgeStream")});var BT=g((rhe,mU)=>{"use strict";var vT=us(),D8=it(),fU=ee(),Zd=L(),fo=ke(),L8=Q(),PT=$(),{RemotePayloadObject:M8}=yu(),{ErrorCode:_U}=require("nats"),dU=fU.get(Zd.CONFIG_PARAMS.CLUSTERING_ENABLED),EU=fU.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);mU.exports={clusterStatus:U8,buildNodeStatus:hU};async function U8(){let e={node_name:EU,is_enabled:dU,connections:[]};if(!dU)return e;let t=await vT.getAllNodeRecords();if(L8.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(U8,"clusterStatus");async function hU(e,t){let r=e.name,s=new M8(Zd.OPERATIONS_ENUM.CLUSTER_STATUS,EU,void 0,await vT.getSystemInfo()),n,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await D8.request(fo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.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=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===_U.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new P8(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 P8(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(P8,"NodeStatusObject")});var xT=g((nhe,pU)=>{"use strict";var{handleHDBError:v8,hdb_errors:B8}=se(),{HTTP_STATUS_CODES:H8}=B8,x8=it(),G8=us(),HT=Q(),ef=require("joi"),q8=Xe(),F8=2e3,k8=ef.object({timeout:ef.number().min(1),connected_nodes:ef.boolean(),routes:ef.boolean()});pU.exports=V8;async function V8(e){G8.checkClusteringEnabled();let t=q8.validateBySchema(e,k8);if(t)throw v8(t,t.message,H8.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 x8.getServerList(r??F8),_={};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(V8,"clusterNetwork")});var RU=g((ohe,gU)=>{"use strict";var GT=require("joi"),SU=Xe(),{route_constraints:TU}=tp();gU.exports={setRoutesValidator:$8,deleteRoutesValidator:Y8};function $8(e){let t=GT.object({server:GT.valid("hub","leaf").required(),routes:TU.required()});return SU.validateBySchema(e,t)}a($8,"setRoutesValidator");function Y8(e){let t=GT.object({routes:TU.required()});return SU.validateBySchema(e,t)}a(Y8,"deleteRoutesValidator")});var FT=g((che,yU)=>{"use strict";var Eo=lr(),qT=Q(),tf=L(),AU=RU(),{handleHDBError:OU,hdb_errors:K8}=se(),{HTTP_STATUS_CODES:bU}=K8,W8="cluster routes successfully set",Q8="cluster routes successfully deleted";yU.exports={setRoutes:z8,getRoutes:J8,deleteRoutes:X8};function z8(e){let t=AU.setRoutesValidator(e);if(t)throw OU(t,t.message,bU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=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"?Eo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Eo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:W8,set:o,skipped:i}}a(z8,"setRoutes");function J8(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(J8,"getRoutes");function X8(e){let t=AU.deleteRoutesValidator(e);if(t)throw OU(t,t.message,bU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=s.length;E<h;E++){let p=s[E];if(d.host===p.host&&d.port===p.port){s.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=n.length;h<p;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(s=qT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=qT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:Q8,deleted:i,skipped:o}}a(X8,"deleteRoutes")});var IU=g((lhe,NU)=>{"use strict";var Uu=require("alasql"),ho=require("recursive-iterator"),xs=$(),j8=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,e6(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=Z8(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 Z8(e){return e.filter(t=>t[Pu.PERMS_CRUD_ENUM.READ])}a(Z8,"filterReadRestrictedAttrs");function e6(e,t,r,s,n){t6(e,t,r,s,n)}a(e6,"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 t6(e,t,r,s,n){if(!e){xs.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Uu.yy.Insert?i6(e,t,r):e instanceof Uu.yy.Select?r6(e,t,r,s,n):e instanceof Uu.yy.Update?s6(e,t,r):e instanceof Uu.yy.Delete?n6(e,t,r):xs.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(t6,"getRecordAttributesAST");function r6(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(j8.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 ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{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 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{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 ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=n.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{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 ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{xs.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(r6,"getSelectAttributes");function s6(e,t,r){if(!e){xs.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new ho(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(s6,"getUpdateAttributes");function n6(e,t,r){if(!e){xs.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new ho(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(n6,"getDeleteAttributes");function i6(e,t,r){if(!e){xs.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new ho(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(i6,"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=Ji(),wU=require("chalk"),Vr=$(),CU=require("prompt"),{promisify:o6}=require("util"),$T=L(),a6=require("fs-extra"),c6=require("path"),u6=Q(),l6=Vd(),DU=ee();DU.initSync();var _6=require("moment"),d6=o6(CU.get),f6=c6.join(DU.getHdbBasePath(),$T.LICENSE_KEY_DIR_NAME,$T.LICENSE_FILE_NAME,$T.LICENSE_FILE_NAME);LU.exports={getFingerprint:h6,setLicense:E6,parseLicense:YT,register:m6,getRegistrationInfo:S6};async function E6(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(E6,"setLicense");async function h6(){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(h6,"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 a6.writeFile(f6,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 m6(){let e=await p6();return YT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(m6,"register");async function p6(){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 d6(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(p6,"promptForRegistration");async function S6(){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(u6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=l6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=_6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(S6,"getRegistrationInfo")});var UU=g((Ehe,MU)=>{"use strict";var T6=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+T6.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 g6=ke(),JT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+g6.SERVER_SUFFIX.ADMIN,this.password=r}};GU.exports=JT});var ZT=g((Ahe,VU)=>{"use strict";var Sa=require("path"),of=require("fs-extra"),R6=UU(),A6=BU(),O6=xU(),b6=qU(),XT=os(),ga=Q(),gr=lr(),nf=L(),Bu=ke(),{CONFIG_PARAMS:ft}=nf,Ra=$(),Hu=ee(),FU=Rn(),jT=it(),Ta="clustering",y6=1e4,kU=50;VU.exports={generateNatsConfig:I6,removeNatsConfig:w6,getHubConfigPath:N6};function N6(){let e=Hu.get(ft.ROOTPATH);return Sa.join(e,Ta,Bu.NATS_CONFIG_FILES.HUB_SERVER)}a(N6,"getHubConfigPath");async function I6(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 b=[],R=[];for(let[z,J]of p.entries())J.role.role===nf.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(b.push(new b6(J.username,FU.decrypt(J.hash))),R.push(new O6(J.username,FU.decrypt(J.hash))));let M=[],{hub_routes:v}=gr.getClusteringRoutes();if(!ga.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 R6(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,b,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}`,H=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,X=new A6(gr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[k],[H],b,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(I6,"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 w6(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(y6),u=Sa.join(Hu.get(ft.ROOTPATH),Ta,r);await of.writeFile(u,c),await of.remove(u),Ra.notify(e,"started.")}a(w6,"removeNatsConfig")});var zU=g((bhe,QU)=>{"use strict";var $r=ee(),C6=Ji(),he=L(),xu=ke(),Cn=require("path"),{PACKAGE_ROOT:uf}=L(),$U=ee(),cf=Q(),Aa="/dev/null",D6=Cn.join(uf,"launchServiceScripts"),YU=Cn.join(uf,"utility/scripts"),L6=Cn.join(YU,he.HDB_RESTART_SCRIPT),KU=Cn.resolve(uf,"dependencies",`${process.platform}-${process.arch}`,xu.NATS_BINARY_NAME);function WU(){let t=C6.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 M6=9930;function U6(){$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!==M6?"-"+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(U6,"generateNatsHubServerConfig");var P6=9940;function v6(){$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!==P6?"-"+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(v6,"generateNatsLeafServerConfig");function B6(){$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:D6,autorestart:!1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Aa,t.error_file=Aa),t}a(B6,"generateClusteringUpgradeV4ServiceConfig");function H6(){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:L6}}a(H6,"generateRestart");function x6(){return{apps:[WU()]}}a(x6,"generateAllServiceConfigs");QU.exports={generateAllServiceConfigs:x6,generateMainServerConfig:WU,generateRestart:H6,generateNatsHubServerConfig:U6,generateNatsLeafServerConfig:v6,generateClusteringUpgradeV4ServiceConfig:B6}});var uP=g((Ihe,cP)=>{"use strict";var ve=L(),G6=Q(),Ln=ZT(),lf=it(),Dn=ke(),Si=zU(),_f=ee(),Ti=$(),q6=us(),{startWorker:JU,onMessageFromWorkers:F6}=Ke(),k6=pa(),Nhe=require("util"),V6=require("child_process"),$6=require("fs"),{execFile:Y6}=V6,Ne;cP.exports={enterPM2Mode:K6,start:gi,stop:eg,reload:jU,restart:ZU,list:tg,describe:tP,connect:Mn,kill:X6,startAllServices:j6,startService:rg,getUniqueServicesList:rP,restartAllServices:Z6,isServiceRegistered:sP,reloadStopStart:nP,restartHdb:eP,deleteProcess:z6,startClusteringProcesses:oP,startClusteringThreads:aP,isHdbRestartRunning:J6,isClusteringRunning:t9,stopClustering:e9,reloadClustering:r9};var Gu=!1;F6(e=>{e.type==="restart"&&_f.initSync(!0)});function K6(){Gu=!0}a(K6,"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,W6=10,XU;function gi(e,t=!1){if(Gu)return Q6(e);let r=Y6(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<W6&&($6.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 Q6(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(Q6,"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 z6(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(z6,"deleteProcess");async function eP(){await gi(Si.generateRestart())}a(eP,"restartHdb");async function J6(){let e=await tg();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(J6,"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 X6(){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(X6,"kill");async function j6(){try{await oP(),await aP(),await gi(Si.generateAllServiceConfigs())}catch(e){throw Ne?.disconnect(),e}}a(j6,"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 Z6(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(Z6,"restartAllServices");async function sP(e){if(Rr?.find(r=>r.name===e))return!0;let t=await k6.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=G6.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 q6.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 e9(){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(e9,"stopClustering");async function t9(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await sP(t)===!1)return!1}return!0}a(t9,"isClusteringRunning");async function r9(){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(r9,"reloadClustering")});var mP={};qe(mP,{compactOnStart:()=>s9,copyDb:()=>hP});async function s9(){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,mo.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,mo.move)(i,n,{overwrite:!0}),await(0,mo.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,mo.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}.
|
|
11
11
|
Total record count before compaction: ${i}, total after: ${c}.
|
|
12
|
-
Database backup has not been removed and can be found here: ${n}`;Fu.error(u),console.error(u)}(0,sg.get)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",n),await(0,
|
|
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(`
|
|
12
|
+
Database backup has not been removed and can be found here: ${n}`;Fu.error(u),console.error(u)}(0,sg.get)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",n),await(0,mo.remove)(n))}(0,ng.updateConfigValue)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function lP(e){let t=await(0,EP.describeSchema)({database:e}),r=0;for(let s in t)r+=t[s].record_count;return r}async function hP(e,t){console.log("copyDb start");let r=dr()[e],s;for(let f in r){s=r[f].primaryStore.rootStore;break}let n=s.dbisDb,i=s.auditStore,o=(0,_P.open)(new dP.default(t)),c=o.openDB(ff.INTERNAL_DBIS_NAME),u,_=0;for(let{key:f,value:E}of n.getRange({})){let h=E.is_hash_attribute||E.isPrimaryKey,p,S;if(h&&(p=E.compression,S=hf(),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 fP.default(!h,h);T.encoding="binary",T.compression=p;let b=s.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=s.openDB(ff.AUDIT_STORE_NAME,Ef);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 _P,df,mo,sg,dP,fP,ff,Ri,EP,ng,Fu,pP=ge(()=>{Re();_P=require("lmdb"),df=require("path"),mo=require("fs-extra"),sg=B(ee()),dP=B(Cc()),fP=B(wc()),ff=B(ut()),Ri=B(L());ei();EP=B(An()),ng=B(lr()),Fu=B($());a(s9,"compactOnStart");a(lP,"getTotalDBRecordCount");a(hP,"copyDb")});var Tf=g((Uhe,bP)=>{"use strict";var n9=require("minimist"),{isMainThread:og,parentPort:gP}=require("worker_threads"),et=L(),{PROCESS_DESCRIPTORS_VALIDATE:ku}=et,on=$(),ag=Q(),pf=ZT(),mf=it(),Mhe=ke(),RP=lr(),an=uP(),SP=pa(),{compactOnStart:i9}=(pP(),ie(mP)),o9=Uh(),{restartWorkers:Sf,onMessageByType:a9}=Ke(),{handleHDBError:c9,hdb_errors:u9}=se(),{HTTP_STATUS_CODES:l9}=u9,$u=ee();$u.initSync();var Vu=`Restarting HarperDB. This may take up to ${et.RESTART_TIMEOUT_MS/1e3} seconds.`,_9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",TP="Clustering is not enabled so cannot be restarted",d9="Invalid service",Oa,ls;bP.exports={restart:AP,restartService:cg};og&&a9(et.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?cg({service:e.workerType}):AP({operation:"restart"})});async function AP(e){ls=Object.keys(e).length===0,Oa=await an.isServiceRegistered(et.HDB_PROC_DESCRIPTOR);let t=n9(process.argv);if(t.service){await cg(t);return}if(ls&&!Oa){console.error(_9);return}if(ls&&console.log(Vu),Oa){an.enterPM2Mode(),on.notify(Vu);let r=o9(Object.keys(et.CONFIG_PARAM_MAP),!0);return ag.isEmptyOrZeroLength(Object.keys(r))||RP.updateConfigValue(void 0,void 0,r,!0,!0),f9(),Vu}return og?(on.notify(Vu),$u.get(et.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await i9(),setTimeout(()=>{Sf()},50)):gP.postMessage({type:et.ITC_EVENT_TYPES.RESTART}),Vu}a(AP,"restart");async function cg(e){let{service:t}=e;if(et.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw c9(new Error,d9,l9.BAD_REQUEST,void 0,void 0,!0);if(Oa=await an.isServiceRegistered(et.HDB_PROC_DESCRIPTOR),!og)return gP.postMessage({type:et.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case ku.clustering:if(!$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=TP;break}ls&&console.log("Restarting clustering"),on.notify("Restarting clustering"),await OP();break;case ku.clustering_config:case ku["clustering config"]:if(!$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=TP;break}ls&&console.log("Restarting clustering_config"),on.notify("Restarting clustering_config"),await an.reloadClustering();break;case"custom_functions":case"custom functions":case ku.harperdb:case ku.http_workers:if(ls&&!Oa){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}ls&&console.log("Restarting http_workers"),on.notify("Restarting http_workers"),ls?await an.restart(et.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Sf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(on.error(r),ls&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(cg,"restartService");async function f9(){await OP(),await an.restart(et.HDB_PROC_DESCRIPTOR),await ag.async_set_timeout(2e3),$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await ig(),ls&&(await mf.closeConnection(),process.exit(0))}a(f9,"restartPM2Mode");async function OP(){if(!RP.getConfigFromFile(et.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await SP.getHDBProcessInfo()).clustering.length===0)on.trace("Clustering not running, restart will start clustering services"),await pf.generateNatsConfig(!0),await an.startClusteringProcesses(),await an.startClusteringThreads(),await ig(),ls&&await mf.closeConnection();else{await pf.generateNatsConfig(!0),Oa?(on.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await an.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await an.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await SP.getHDBProcessInfo()).clustering.forEach(n=>{on.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await ag.async_set_timeout(3e3),await ig(),await mf.updateLocalStreams(),ls&&await mf.closeConnection(),on.trace("Restart clustering restarting ingest and reply service threads");let t=Sf(et.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Sf(et.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(OP,"restartClustering");async function ig(){await pf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await pf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(ig,"removeNatsConfig")});var vP=g((Bhe,PP)=>{"use strict";var vhe=require("lodash"),Ar=L(),{handleHDBError:yP,hdb_errors:E9}=se(),{HDB_ERROR_MSGS:h9,HTTP_STATUS_CODES:m9}=E9,ug=$();PP.exports={getRolePermissions:S9};var po=Object.create(null),p9=a(e=>({key:e,perms:{}}),"perms_template_obj"),CP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),DP=a((e=!1,t=!1,r=!1,s=!1)=>({[Ar.PERMS_CRUD_ENUM.READ]:e,[Ar.PERMS_CRUD_ENUM.INSERT]:t,[Ar.PERMS_CRUD_ENUM.UPDATE]:r,[Ar.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),lg=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...DP(t,r,s,n)}),"table_perms_template"),NP=a((e,t=DP())=>({attribute_name:e,describe:UP(t),[Yu]:t[Yu],[_g]:t[_g],[dg]:t[dg]}),"attr_perms_template"),IP=a((e,t=!1)=>({attribute_name:e,describe:t,[Yu]:t}),"timestamp_attr_perms_template"),{READ:Yu,INSERT:_g,UPDATE:dg}=Ar.PERMS_CRUD_ENUM,LP=Object.values(Ar.PERMS_CRUD_ENUM),MP=[Yu,_g,dg];function S9(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 s=JSON.stringify([e.__updatedtime__,r]);if(po[t]&&po[t].key===s)return po[t].perms;let n=T9(e,r);return po[t]?po[t].key=s:po[t]=p9(s),po[t].perms=n,n}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 s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw ug.error(s),ug.debug(r),yP(new Error,h9.OUTDATED_PERMS_TRANSLATION_ERROR,m9.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
13
|
+
${r.stack}`;throw ug.error(s),yP(new Error)}}}a(S9,"getRolePermissions");function T9(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]=g9(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],_=R9(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(T9,"translateRolePermissions");function g9(e){let t=CP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=lg(!0,!0,!0,!0,!0)}),t}a(g9,"createStructureUserPermissions");function R9(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||A9(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(R9,"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 A9(e,t){MP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(A9,"checkForHashPerms")});var BP={};qe(BP,{Resources:()=>gf,keyArrayToString:()=>ba,resetResources:()=>O9,resources:()=>Ai});function O9(){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(()=>{ro();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(O9,"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:()=>D9,login:()=>M9,logout:()=>U9,start:()=>L9});function D9(){$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?I9?N9:[]:y9?b9:[];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=So.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 C9&&(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(s,d),w9&&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 L9({server:e,port:t}){e.request(YP,{port:t||"all"}),qP||(qP=!0,setInterval(()=>{So=new Map},_s.get(vt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),VP.user.addListener(()=>{So=new Map}))}async function M9(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 U9(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,b9,y9,N9,I9,GP,Rf,$P,w9,C9,So,qP,Of=ge(()=>{FP=B(os());or();Ku();Af=B(bu());Re();kP=require("uuid"),_s=B(ee()),vt=B(L()),ya=B($()),VP=B(kc());Wu();Na();xP=(0,ya.loggerWithTag)("auth-event");_s.initSync();b9=_s.get(vt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),y9=_s.get(vt.CONFIG_PARAMS.HTTP_CORS),N9=_s.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),I9=_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,w9=_s.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,C9=_s.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,So=new Map;st.onInvalidatedUser(()=>{So=new Map});a(D9,"bypassAuth");a(YP,"authentication");a(L9,"start");a(M9,"login");a(U9,"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:P9}=se(),{HDB_ERROR_MSGS:er}=P9,Un=/^[a-zA-Z0-9-_]+$/;XP.exports={getDropCustomFunctionValidator:B9,setCustomFunctionValidator:H9,addComponentValidator:F9,dropCustomFunctionProjectValidator:k9,packageComponentValidator:V9,deployComponentValidator:$9,setComponentFileValidator:x9,getComponentFileValidator:q9,dropComponentFileValidator:G9};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 v9(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(v9,"checkFileExists");function B9(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(v9.bind(null,e.project,e.type)).custom(zu).required().messages({"string.pattern.base":er.BAD_FILE_NAME})});return Pn.validateBySchema(e,t)}a(B9,"getDropCustomFunctionValidator");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().custom(zu).required(),function_content:Ie.string().required()});return Pn.validateBySchema(e,t)}a(H9,"setCustomFunctionValidator");function x9(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(x9,"setComponentFileValidator");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).optional()});return Pn.validateBySchema(e,t)}a(G9,"dropComponentFileValidator");function q9(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(q9,"getComponentFileValidator");function F9(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(F9,"addComponentValidator");function k9(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(k9,"dropCustomFunctionProjectValidator");function V9(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(V9,"packageComponentValidator");function $9(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($9,"deployComponentValidator")});var wf=g((zhe,iv)=>{"use strict";var yf=require("joi"),Nf=require("path"),ZP=require("fs-extra"),{exec:Y9}=require("child_process"),K9=require("util"),ev=K9.promisify(Y9),Ju=L(),{handleHDBError:Ia,hdb_errors:W9}=se(),{HTTP_STATUS_CODES:wa}=W9,Xu=ee(),Q9=Xe(),Ca=$();Xu.initSync();var Eg=Xu.get(Ju.CONFIG_PARAMS.COMPONENTSROOT),tv="npm install --omit=dev --json",z9=`${tv} --dry-run`;iv.exports={installModules:Z9,auditModules:e7,installAllRootModules:J9,uninstallRootModule:X9,linkHarperdb:j9};async function J9(e=!1){await If(),await ju(e?"npm install --ignore-scripts":"npm install",Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(J9,"installAllRootModules");async function X9(e){await ju(`npm uninstall ${e}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(X9,"uninstallRootModule");async function j9(){await If(),await ju(`npm link ${Ju.PACKAGE_ROOT}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(j9,"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
14
|
`,""))}return s&&!s.includes("Debugger listening")&&Ca.error("Error running NPM command:",e,s),Ca.trace(r,s),r?.replace(`
|
|
15
|
-
`,"")}a(ju,"runCommand");async function
|
|
15
|
+
`,"")}a(ju,"runCommand");async function Z9(e){Ca.info(`starting installModules for request: ${e}`);let t=nv(e);if(t)throw Ia(t,t.message,wa.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?z9:tv;await If(),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 _=Nf.join(Eg,u),l,d=null;try{let{stdout:f,stderr:E}=await ev(n,{cwd:_});l=f?f.replace(`
|
|
16
16
|
`,""):null,d=E?E.replace(`
|
|
17
|
-
`,""):null}catch(f){f.stderr?i[u].npm_error=rv(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 Ca.info(`finished installModules with response ${i}`),i}a(
|
|
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+`
|
|
17
|
+
`,""):null}catch(f){f.stderr?i[u].npm_error=rv(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 Ca.info(`finished installModules with response ${i}`),i}a(Z9,"installModules");function rv(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
|
|
18
|
+
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(rv,"parseNPMStdErr");async function e7(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(e7,"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 Q9.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(),t7=lr();lv.exports=r7;async function r7(){let e=s7(),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(r7,"installComponents");function s7(){let e=t7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(s7,"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(),n7=Q(),{PACKAGE_ROOT:i7}=L(),{handleHDBError:Bt,hdb_errors:o7}=se(),{basename:a7}=require("path"),c7=mg(),fv=ee(),u7=L(),{Readable:l7}=require("stream"),{isMainThread:_7}=require("worker_threads"),{HDB_ERROR_MSGS:To,HTTP_STATUS_CODES:Ht}=o7,d7=Te.join(i7,"application-template"),_v=Te.join(Tt.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function f7(){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,To.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,t)}return e}a(f7,"customFunctionsStatus");function E7(){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,To.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,r)}return e}a(E7,"getCustomFunctions");function h7(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,To.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(h7,"getCustomFunction");function m7(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,To.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(m7,"setCustomFunction");function p7(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,To.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,o)}}a(p7,"dropCustomFunction");function S7(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(d7,n),`Successfully added project: ${s}`}catch(n){throw Bt(new Error,To.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,n)}}a(S7,"addComponent");function T7(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(!n7.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,To.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,i)}}a(T7,"dropCustomFunctionProject");async function g7(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(g7,"packageComponent");async function R7(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=l7.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 c7();let f=fv.get(u7.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",s)}if(_7)return;let c=new Map;c.isWorker=!0;let u=(Mf(),ie(Lf)),_;u.setErrorReporter(f=>_=f);let l=a7(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(R7,"deployComponent");async function A7(){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(A7,"getComponents");async function O7(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(O7,"getComponentFile");async function b7(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(b7,"setComponentFile");async function y7(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(y7,"dropComponent");Ev.exports={customFunctionsStatus:f7,getCustomFunctions:E7,getCustomFunction:h7,setCustomFunction:m7,dropCustomFunction:p7,addComponent:S7,dropCustomFunctionProject:T7,packageComponent:g7,deployComponent:R7,getComponents:A7,getComponentFile:O7,setComponentFile:b7,dropComponent:y7}});var gg=g((rme,mv)=>{"use strict";var un=require("joi"),hv=Xe();mv.exports={readTransactionLogValidator:N7,deleteTransactionLogsBeforeValidator:I7};function N7(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(N7,"readTransactionLogValidator");function I7(e){let t=un.object({schema:un.string().required(),table:un.string().required(),timestamp:un.date().timestamp().required()});return hv.validateBySchema(e,t)}a(I7,"deleteTransactionLogsBeforeValidator")});var Pf=g((nme,Rv)=>{"use strict";var Rg=L(),Uf=it(),pv=Q(),Sv=ee(),Tv=Rn(),{handleHDBError:La,hdb_errors:w7}=se(),{HTTP_STATUS_CODES:Ma}=w7,{readTransactionLogValidator:C7,deleteTransactionLogsBeforeValidator:D7}=gg(),gv="This operation relies on clustering and cannot run with it disable.",L7="Logs successfully deleted from transaction log.",M7="All logs successfully deleted from transaction log.";Rv.exports={readTransactionLog:U7,deleteTransactionLogsBefore:P7};async function*U7(e){let t=C7(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(U7,"readTransactionLog");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,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=L7,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=M7):d=(await Uf.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(P7,"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(),v7=yv(),{HDB_ERROR_MSGS:B7}=Cr(),bg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=B7.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 v7(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(),H7=qS(),x7=wL(),sl=os(),Bf=zS(),It=$(),G7=jS(),q7=zd(),F7=DT(),k7=Xd(),V7=MT(),$7=UT(),Y7=BT(),K7=xT(),wg=FT(),vn=Q(),W7=IU(),Cg=KT(),Dv=Tf(),ds=L(),Lv=vP(),Q7=pa(),Mv=bu(),Uv=(Of(),ie(Qu)),Pv=lr(),Yr=Tg(),z7=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",go="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},J7="catchup",X7="handleGetJob",j7="handleGetJobsByStartDate",Hf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},Z7=[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,[go]));V.set(Ng.upsert.name,new W(!1,[yi,go]));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(G7.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(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(Y7.clusterStatus.name,new W(!0,[]));V.set(K7.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(H7.name,new W(!0,[]));V.set(x7.name,new W(!0,[Bn]));V.set(Q7.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(X7,new W(!1,[]));V.set(j7,new W(!0,[]));V.set(J7,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(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,[go]));Vv.exports={verifyPerms:tee,verifyPermsAst:eee,verifyBulkLoadAttributePerms:see};function eee(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 W7(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 z7.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(eee,"verifyPermsAst");function tee(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(Z7.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(b=>b[ds.PERMS_CRUD_ENUM.READ]).forEach(b=>{p.push(b.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let E=ree(e),h=Lg(e.hdb_user.role.permission,n,i);return Dg(E,h,r,i,n,c,s),c.getPermsResponse()}a(tee,"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 ree(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(ree,"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 see(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(see,"verifyBulkLoadAttributePerms")});var qf=g((Eme,Qv)=>{"use strict";Qv.exports={evaluateSQL:mee,processAST:Wv,convertSQLToAST:Kv,checkASTPermissions:Yv};var nee=vr(),$v=require("util"),iee=$v.callbackify(nee.insert),oee=Pr().search,aee=ED().update,cee=$v.callbackify(aee),uee=mD().convertDelete,Ni=require("alasql"),lee=xf(),Gf=$(),_ee=fd(),dee=Q(),nl=L(),{hdb_errors:fee,handleHDBError:Mg}=se(),{HTTP_STATUS_CODES:Ug}=fee;_ee(Ni);var Eee=403,hee="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 mee(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)&&dee.isEmptyOrZeroLength(s))return t("No schema specified",null)}Wv(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(mee,"evaluateSQL");function Yv(e,t){let r;try{r=lee.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=pee;if(!e.bypass_auth&&!t.permissions_checked){let i=Yv(e,t);if(i&&i.length>0)return r(Eee,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case nl.VALID_SQL_OPS_ENUM.SELECT:s=oee,n=t.ast.statements[0];break;case nl.VALID_SQL_OPS_ENUM.INSERT:s=See;break;case nl.VALID_SQL_OPS_ENUM.UPDATE:s=cee;break;case nl.VALID_SQL_OPS_ENUM.DELETE:s=uee;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 pee(e,t){Gf.info(e),t("unknown sql statement")}a(pee,"nullFunction");function See({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=Tee(i,e.values)}catch(o){return r(o)}iee(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(See,"convertInsert");function Tee(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(hee)}}a(Tee,"createDataObjects")});var vg=g((mme,Jv)=>{"use strict";var{S3:gee,GetObjectCommand:Ree}=require("@aws-sdk/client-s3");Jv.exports={getFileStreamFromS3:Aee,getS3AuthObj:zv};async function Aee(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 Ree(r))).Body}a(Aee,"getFileStreamFromS3");function zv(e,t,r){return new gee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(zv,"getS3AuthObj")});var Ff=g((Sme,i0)=>{"use strict";var Hg=Pr(),Oee=qf(),bee=vg(),{AsyncParser:yee,Transform:Nee}=require("json2csv"),ol=require("stream"),Kr=Q(),Bg=require("fs-extra"),Iee=require("path"),hs=$(),{promisify:Zv}=require("util"),il=Q(),{handleHDBError:gt,hdb_errors:wee}=se(),{HDB_ERROR_MSGS:br,HTTP_STATUS_CODES:Rt}=wee,{streamAsJSON:Cee}=(em(),ie(Db)),{Upload:Dee}=require("@aws-sdk/lib-storage"),Xv=["search_by_value","search_by_hash","sql","search_by_conditions"],jv=["json","csv"],e0="json",t0="csv",Lee="Successfully exported JSON locally.",Mee="Successfully exported CSV locally.",Uee=1e3,Pee=Hg.searchByHash,vee=Hg.searchByValue,Bee=Zv(Oee.evaluateSQL),Hee=Zv(ol.finished);i0.exports={export_to_s3:Fee,export_local:xee,toCsvStream:r0};async function xee(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(Iee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Kr.buildFolderPath(e.path,r);await Gee(e.path);let n=await n0(e);return await qee(s,e.format,n)}a(xee,"export_local");async function Gee(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(Gee,"confirmPath");async function qee(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 Cee(r).pipe(s),await Hee(s),{message:Lee,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 yee(i,c).fromInput(n).toOutput(s).promise(!1),{message:Mee,path:e}}throw gt(new Error,br.INVALID_VALUE("format"),Rt.BAD_REQUEST)}a(qee,"saveToLocal");async function Fee(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 bee.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%Uee===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 Dee({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Fee,"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 Nee(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=vee;break;case"search_by_hash":t=Pee;break;case"search_by_conditions":t=Hg.searchByConditions;break;case"sql":t=Bee;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:()=>Ao,registerContentHandlers:()=>Vg,serialize:()=>$f,serializeMessage:()=>bi});function kee(e){try{return e?.[0]===123?Fg(e):e}catch{return e}}function Vg(e){e.register($ee,{serializers:[{regex:/^application\/json$/,serializer:Ac},{regex:/^application\/cbor$/,serializer:function(t){return new Ro.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,Ro.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 Yee(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function Ao(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=xt.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=xt.get(e)?.deserialize||c0(e,s);return o=>Yee(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 Kee(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,Ro,Hn,kf,u0,Gg,qg,l0,_0,al,Fg,cl,xt,kg,o0,d0,Vee,$ee,a0,Na=ge(()=>{em();xg=B(Ff()),ln=require("msgpackr"),Ro=require("cbor-x"),Hn=require("zlib"),kf=require("stream");or();u0=require("../index"),Gg=B(ee()),qg=B(L()),l0=B(require("yaml")),_0=Gg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,al=_0?xi: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 Ro.Encoder(cl);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ro.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(Kee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
20
20
|
`),e.data){let r=e.data;typeof r=="object"&&(r=al(r)),t+="data: "+r+`
|
|
21
21
|
`}return e.id&&(t+="id: "+e.id+`
|
|
22
22
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
@@ -25,8 +25,8 @@ Database backup has not been removed and can be found here: ${n}`;Fu.error(u),co
|
|
|
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,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:kee,q:.8};xt.set("*/*",d0);xt.set("",d0);a(kee,"tryJSONParse");a(Vg,"registerContentHandlers");Vee=require("fastify-plugin"),$ee=Vee(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(Yee,"streamToBuffer");a(Ao,"getDeserializer");a(c0,"deserializerUnknownType");a(Kee,"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 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=tte(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 b=o[0],R=Gn(s.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=va({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,M,n,v);if(R.relationship.to){i[o[0]]=v;let k=!!Gn(M.attributes,R.relationship.to)?.elements;P=Xee(P,R,M.primaryStore,k,v)}if(R.relationship.from){let k=a(H=>va({attribute:R.relationship.from,value:H},t,r,s,n,v),"searchEntry");R.elements?(i[o[0]]=v,P=jee(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]=_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 b=_;_=l,l=b,b=!f,f=!d,d=b}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 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):s.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 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 Xee(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 jee(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((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,_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(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=va(e,r.transaction.getReadTxn(),!1,t).map(Gs),P=new Set(v);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=zee*xn(e.primaryStore)+1:s==="between"?r.estimated_count=Qee*xn(e.primaryStore)+1:s==="sort"?r.estimated_count=xn(e.primaryStore)+1:r.estimated_count=Wee*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,Zee.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=Jee[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?ete: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 tte(e,t,r){return t*r/xn(e)}var Wr,$g,_n,Ii,Wee,Qee,zee,Jee,Yg,Wg,Zee,Ua,ete,yr,wi,Pa,Qf=ge(()=>{Wr=B(se()),$g=B(ut()),_n=require("ordered-binary"),Ii=require("lmdb"),Wee=.3,Qee=.1,zee=.05,Jee={"<":"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(Xee,"joinTo");a(jee,"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");Zee=/[()[\]|!<>.]|(=\w*=)/,Ua=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,ete=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/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(tte,"intersectionEstimate")});function A0(e){let t={openapi:rte,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: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 X={};H.properties.forEach(z=>{X[z.name]=new jg(zg[z.type],z.type)}),t.components.schemas[H.type]=new g0(X)}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 jg(zg[v.type],v.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",b="/"+n+"/";h&&(t.paths[b]={},t.paths[b].post=new ste(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 Xg({$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 T0(l,r,"delete all the records that match the provided query",{204:new S0})),b="/"+n+"/{"+c+"}",S&&(t.paths[b]={},t.paths[b].get=new Jg([f],r,{200:new Xg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[b]||(t.paths[b]={}),t.paths[b].put=new nte([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 T0([f],r,"delete a record with the given primary key",{204:new S0})),S&&E.schema.enum.length>0&&(b="/"+n+"/{"+c+"}.{property}",t.paths[b]={},t.paths[b].get=new Jg([f,E],r,{200:new Xg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function ste(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 nte(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,rte,zg,Ci,eR,O0=ge(()=>{R0=B(Vd()),rte="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(ste,"Post");a(Jg,"Get");a(Xg,"Response200");a(S0,"Response204");a(nte,"Put");a(T0,"Delete");a(g0,"ResourceSchema");a(jg,"Type");a(Zg,"Parameter")});var Jf={};qe(Jf,{start:()=>ate});async function ote(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=Ao(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){ite[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?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"),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 ate(e){tR=e,!y0&&(y0=!0,zf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return ote(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,Oo.warn(l)});let o;t.on("message",a(function(d){o||(o=Ao(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 Oo,Ba,Yt,ite,tR,b0,y0,zf,N0,_l,I0=ge(()=>{Na();wn();Oo=B($()),Ba=B(se());Qf();gc();ro();Wu();O0();Yt=new Uint8Array(8),ite=new Float64Array(Yt.buffer,0,1),tR={},b0="openapi";a(ote,"http");_l=0;a(ate,"start")});var rR=g((Bme,w0)=>{var{recordAction:Xf,recordActionBinary:cte}=(wn(),ie(lu)),ute=require("fastify-plugin"),lte=200;w0.exports=ute(function(e,t,r){e.addHook("onResponse",async(s,n)=>{let i=n.elapsedTime}),e.addHook("onSend",async(s,n,i)=>{let o=n.elapsedTime,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),cte(n.raw.statusCode<400,"success",_,d,l);let f=lte;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(),_te=Q(),Zf=L(),Hme=$(),sR=require("fs"),iR=require("joi"),{string:eE}=iR.types(),{hdb_errors:dte,handleHDBError:jf}=se(),{HDB_ERROR_MSGS:xme,HTTP_STATUS_CODES:nR}=dte,{common_validators:Ha}=Js(),C0=" is required",fte=["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:fte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Ete={schema:eE.required(),table:eE.required(),action:eE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:hte,AWS_SECRET:mte,AWS_BUCKET:pte,AWS_FILE_KEY:Ste,REGION:Tte}=Zf.S3_BUCKET_AUTH_KEYS,gte={s3:{presence:!0},[`s3.${hte}`]:{presence:!0,type:"String"},[`s3.${mte}`]:{presence:!0,type:"String"},[`s3.${pte}`]:{presence:!0,type:"String"},[`s3.${Ste}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Tte}`]:{presence:!0,type:"String"}},D0=tE(oR);D0.data.presence={message:C0};var L0=tE(oR);L0.file_path.presence={message:C0};var Rte=Object.assign(tE(oR),gte),aR=tE(Ete);aR.csv_url=eE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();aR.passthrough_headers=iR.object();function Ate(e){let t=rE.validateObject(e,D0);return sE(e,t)}a(Ate,"dataObject");function Ote(e){let t=rE.validateBySchema(e,iR.object(aR));return sE(e,t)}a(Ote,"urlObject");function bte(e){let t=rE.validateObject(e,L0);return sE(e,t)}a(bte,"fileObject");function yte(e){let t=rE.validateObject(e,Rte);return sE(e,t)}a(yte,"s3FileObject");function sE(e,t){if(!t){let r=_te.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:Ate,urlObject:Ote,fileObject:bte,s3FileObject:yte}});var uR=g((Fme,U0)=>{"use strict";var dl=$(),nE=L();async function Nte(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(Nte,"callOperationFunctionAsAwait");U0.exports={callOperationFunctionAsAwait:Nte}});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(),Ite=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:yo}=K0,Ga=$(),fR=require("papaparse");xa.promisifyPapaParse();var Fs=require("fs-extra"),wte=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"),Cte=ee(),W0=uR(),Dte=vg(),{BulkLoadFileObject:hR,BulkLoadDataObject:Lte}=v0(),mR=yg(),{verifyBulkLoadAttributePerms:Q0}=xf(),Qme=H0(),zme=it(),Jme=Rn(),{databases:Mte}=(Re(),ie(Fe)),{coerceType:Ute}=(cE(),ie(TR)),V0="No records parsed from csv file.",bo=`${Cte.get("HDB_ROOT")}/tmp`,{schema_regex:Pte}=Js(),$0=1024*1024*2,Y0=5e3,vte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};eB.exports={csvDataLoad:Bte,csvURLLoad:Hte,csvFileLoad:xte,importFromS3:Gte};async function Bte(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 Lte(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 No(n)}}a(Bte,"csvDataLoad");async function Hte(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=`${bo}/${r}`;try{await qte(e,r)}catch(n){throw Ga.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+n),ot(n,yo(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),No(n)}}a(Hte,"csvURLLoad");async function xte(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 No(s)}}a(xte,"csvFileLoad");async function Gte(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=wte.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${bo}/${n}`;let i=new hR(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await Fte(n,e);let o=await pR(i);return await oE(r),o}catch(s){throw await oE(r),No(s)}}a(Gte,"importFromS3");async function qte(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Ite("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)}Vte(r,e.csv_url),await kte(t,r.raw)}a(qte,"downloadCSVFile");async function Fte(e,t){try{let r=`${bo}/${e}`;await Fs.mkdirp(bo),await Fs.writeFile(`${bo}/${e}`,"",{flag:"a+"});let s=await Fs.createWriteStream(r),n=await Dte.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,yo(wt.S3_DOWNLOAD_ERR))}}a(Fte,"downloadFileFromS3");async function kte(e,t){try{await Fs.mkdirp(bo),await Fs.writeFile(`${bo}/${e}`,t)}catch(r){throw Ga.error(wt.WRITE_TEMP_FILE_ERR),ot(r,yo(wt.DEFAULT_BULK_LOAD_ERR))}}a(kte,"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 Vte(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(!vte[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(Vte,"validateURLResponse");async function pR(e){try{let t;switch(e.file_type){case qs.VALID_S3_FILE_TYPES.CSV:t=await $te(e);break;case qs.VALID_S3_FILE_TYPES.JSON:t=await Yte(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 No(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,yo(wt.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(J0,"insertChunk");async function $te(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,yo(wt.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+s)}}a($te,"callPapaParse");function X0(e,t){let r=Mte[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>Ute(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 Yte(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,yo(wt.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+s)}}a(Yte,"insertJson");async function j0(e){let t={};try{e.data&&e.data.length>0&&Kte(e.data[0])?t=await Wte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ga.info(t.message))}catch(r){throw No(r)}return t}a(j0,"callBulkFileLoad");function Kte(e){let t=Object.keys(e);for(let r of t)if(!Pte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Kte,"validateColumnNames");async function Wte(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 No(o)}}a(Wte,"bulkFileLoad");function Z0(e,t){return`successfully loaded ${t} of ${e} records`}a(Z0,"buildResponseMsg");function No(e){return ot(e,yo(wt.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,qs.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(No,"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 Qte=L(),sB=require("moment"),zte=require("uuid").v4,RR=class{static{a(this,"JobObject")}constructor(){this.id=zte(),this.type=void 0,this.start_datetime=sB().valueOf(),this.created_datetime=sB().valueOf(),this.end_datetime=void 0,this.status=Qte.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 Jte=require("uuid").v4,cB=vr(),uB=Pr(),Xte=tn(),jte=na(),Zte=rB(),at=L(),ere=iB(),tre=Bd(),ms=$(),rre=Bc(),qa=Q(),{promisify:sre}=require("util"),Io=require("moment"),nre=qf(),uE=cR(),oB=Ym(),{deleteTransactionLogsBeforeValidator:ire}=gg(),{handleHDBError:ore,hdb_errors:are}=se(),{HTTP_STATUS_CODES:cre}=are,aB=uB.searchByValue,ure=uB.searchByHash,lre=cB.insert,_re=sre(nre.evaluateSQL),dre=cB.update;_B.exports={addJob:hre,updateJob:pre,handleGetJob:fre,handleGetJobsByStartDate:Ere,getJobById:lB};async function fre(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(fre,"handleGetJob");async function Ere(e){try{let t=await mre(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=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 ms.error(r),new Error(r)}}a(Ere,"handleGetJobsByStartDate");async function hre(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=ire(e);break;default:break}if(s)throw ore(s,s.message,cre.BAD_REQUEST,void 0,void 0,!0);let n=new ere;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 Xte(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=Jte();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 rre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await lre(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(hre,"addJob");async function mre(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 s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new Zte(s,e.hdb_user);try{return await _re(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(mre,"getJobsInDateRange");async function lB(e){if(qa.isEmptyOrZeroLength(e))return qa.errorizeMessage("Invalid job ID specified.");let t=new jte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await ure(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 pre(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=Io().valueOf());let t=new tre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await dre(t),r}a(pre,"updateJob")});var pB=g((ipe,mB)=>{"use strict";var dB=Q(),Nr=L(),Sre=require("moment"),lE=SR(),_E=$(),fB=AR(),EB=Ff(),hB=ii(),Tre=Ke(),gre=Pf(),OR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Rre(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,gre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Rre,"parseMessage");async function qn(e,t){try{e.job.status=Nr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Sre().valueOf(),await fB.updateJob(e.job),await Are(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 Are(e){_E.trace("launching job thread:",e),Tre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Are,"launchJobThread");mB.exports={parseMessage:Rre,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(),Ore=qS(),fl=os(),EE=zS(),Wt=Tg(),hE=$(),bre=jS(),yre=zd(),gB=DT(),Nre=Xd(),Ire=MT(),wre=UT(),Cre=BT(),Dre=xT(),yR=FT(),RB=Ff(),Lre=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(),Mre=On(),Ure=pa(),bB=pB(),yB=bu(),NB=(Of(),ie(Qu)),IB=lr(),wB=Pf(),CB=wf(),{setServerUtilities:Pre}=(cE(),ie(TR)),{CONTEXT:vre}=(Ns(),ie(Gp)),{_assignPackageExport:Bre}=require("../index"),{transformReq:Hre}=Q(),{server:xre}=(or(),ie(Hi)),tr=hE.loggerWithTag("operation"),Gre=uR(),DB=mE.searchByHash,qre=mE.searchByValue,Fre=MB.promisify(mE.search),kre=MB.promisify(IR.evaluateSQL),Vre={[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 Gre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Vre[e.body.operation]&&Mre.setSchemaDataToGlobal(s=>{s&&tr.error(s)}),r}a(UB,"processLocalTransaction");var LB=Yre();DR.exports={chooseOperation:PB,getOperationFunction:vB,operation:CR,processLocalTransaction:UB};Pre(DR.exports);xre.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=Lre.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");Bre("operation",CR);function CR(e,t){e.hdb_user=this[vre]?.user,e.bypass_auth=!t;let r=PB(e);return UB({body:e},r)}a(CR,"operation");async function $re(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($re,"catchup");async function dn(e){Hre(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 Yre(){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(qre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(Fre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(kre)),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(bre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(yre)),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(Nre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Ire)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(wre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(IB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Cre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Dre)),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($re)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Ure.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(Ore)),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(Yre,"initializeOperationFunctionMap")});var SE=g((_pe,GB)=>{"use strict";var LR=L(),Kre=Q(),pl=$(),{handleHDBError:MR,hdb_errors:pE}=se(),{isMainThread:Wre}=require("worker_threads"),{Readable:Qre}=require("stream"),HB=require("os"),zre=require("util"),Jre=cT(),Xre=zre.promisify(Jre.authorize),xB=BB(),{createGzip:jre,constants:Zre}=require("zlib");function ese(e){let t=`Found an uncaught exception with message: ${e.message}. ${HB.EOL}Stack: ${e.stack} ${HB.EOL}Terminating ${Wre?"HDB":"thread"}.`;console.error(t),pl.fatal(t),process.exit(1)}a(ese,"handleServerUncaughtException");function tse(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(tse,"serverErrorHandler");function rse(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(Kre.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(rse,"reqBodyValidationHandler");function sse(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?Xre(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(sse,"authHandler");async function nse(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 Qre&&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(jre({level:Zre.Z_BEST_SPEED})))}return n}catch(n){throw pl.error(n),n}}a(nse,"handlePostRequest");GB.exports={authHandler:sse,handlePostRequest:nse,handleServerUncaughtException:ese,serverErrorHandler:tse,reqBodyValidationHandler:rse}});var VB=g((fpe,kB)=>{"use strict";var ise=require("fastify-plugin"),{handlePostRequest:qB,authHandler:ose,reqBodyValidationHandler:ase}=SE();async function cse(e){e.decorate("hdbCore",{preValidation:[ase,ose],request:t=>FB(qB(t,response)),requestWithoutAuthentication:(t,r)=>FB(qB(t,r,!0))})}a(cse,"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=ise(cse)});var KB=g((mpe,YB)=>{"use strict";var hpe=require("fs"),UR=ee();UR.initSync();var{CONFIG_PARAMS:$B}=L(),use=1024*1024*1024;function lse(e){let t=UR.get($B.HTTP_TIMEOUT),r=UR.get($B.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:use,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(lse,"getServerOptions");YB.exports=lse});var zB=g((Spe,QB)=>{"use strict";var PR=ee();PR.initSync();var{CONFIG_PARAMS:WB}=L();function _se(){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(_se,"getCORSOptions");QB.exports=_se});var jB=g((gpe,XB)=>{"use strict";var JB=ee();JB.initSync();var dse=L();function fse(){return JB.get(dse.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(fse,"getHeaderTimeoutConfig");XB.exports=fse});var BR={};qe(BR,{customFunctionsServer:()=>mse,ready:()=>fH,start:()=>hse});function hse(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(Sse(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 mse(){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 pse();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 pse(){try{$e.info("Custom Functions starting configuration."),await aH.setUsersToGlobal(),$e.info("Custom Functions completed configuration.")}catch(e){$e.error(e)}}function Sse(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(Ese),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,Ese,aH,cH,uH,lH,_H,kn,ZB,EH=ge(()=>{vR=require("path"),eH=require("fs"),tH=B(require("fastify")),rH=B(require("@fastify/cors")),sH=B(rR()),nH=B(require("@fastify/autoload")),iH=B(ee()),oH=B(L()),$e=B($()),Ese=B(VB()),aH=B(os()),cH=B(KB()),uH=B(zB()),lH=B(jB()),_H=B(SE());Na();or();ZB=new Set;a(hse,"start");a(mse,"customFunctionsServer");a(pse,"setUp");a(Sse,"buildRouteFolder");a(dH,"buildServer");a(fH,"ready")});var HR={};qe(HR,{start:()=>Tse});function Tse(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=B(require("send")),SH=require("fs"),TH=B(require("serve-static")),hH=new Map;a(Tse,"start")});function Ase(e,t=1,r){if(xR++,(0,wo.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)});Rse.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,wo.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=Ose:r=bse(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"),Ase(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});wse(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 Ose(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 bse(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 Nse(){TE=0;for(let e of ka)e.expectedIdle=e.recentELU.idle+yse,e.requests=1;ka.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function wse(e,t,r){let s=Ise++;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 wo,$a,RE,qR,AE,OH,gse,ka,Va,bH,RH,xR,Rse,GR,TE,AH,Ya,yse,gE,Ise,NH=ge(()=>{wo=B(Ke()),$a=require("net"),RE=B(L()),qR=B($()),AE=require("fs");wn();OH=require("worker_threads"),gse=B(Ji()),ka=[],Va=[],bH=[],xR=0,Rse=[];OH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Ase,"startHTTPWorker");a(yH,"startSocketServer");TE=0;a(FR,"findMostIdleWorker");AH=36e5,Ya=new Map;a(Ose,"findByRemoteAddressAffinity");a(bse,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ya)r.lastUsed+AH<e&&Ya.delete(t)},AH).unref();yse=1e3;a(Nse,"updateWorkerIdleness");(0,wo.setMonitorListener)(Nse);gE=new Map,Ise=1;a(wse,"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 Cse=require("cluster"),Co=ee();Co.initSync();var CH=L(),Dpe=require("util"),Vn=$(),Lpe=require("fs"),Dse=require("fastify"),Mpe=iu(),Lse=require("@fastify/cors"),Mse=require("@fastify/compress"),Use=require("@fastify/static"),Pse=rR(),vse=require("path"),{PACKAGE_ROOT:Bse}=L(),Hse=On(),xse=Q(),Gse=os(),qse=Ji(),{server:Fse}=(or(),ie(Hi)),{node_request_key:Upe}=(bE(),ie(YR)),{authHandler:kse,handlePostRequest:Vse,serverErrorHandler:$se,reqBodyValidationHandler:Yse}=SE(),Ppe=require("net"),{registerContentHandlers:Kse}=(Na(),ie(f0)),Wse=6e4,Qse=1024*1024*1024,zse="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=Cse.isMaster,await Jse();let t=e.securePort>0;Ka=Xse(t),await Ka.ready(),e||(e={}),e.isOperationsServer=!0;try{Fse.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 Jse(){Vn.trace("Configuring HarperDB process."),Hse.setSchemaDataToGlobal(),await Gse.setUsersToGlobal(),await qse.getLicense()}a(Jse,"setUp");function Xse(e){Vn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=jse(e),r=Dse(t);r.server.headersTimeout=ene(),r.setErrorHandler($se);let s=Zse();s&&r.register(Lse,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Pse),r.register(Mse),r.register(Use,{root:vse.join(Bse,"studio/build-local")}),Kse(r);let n=Co.get(CH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!xse.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Yse,kse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Vse(i,o)}),r.get("/health",()=>"HarperDB is running."),Vn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Xse,"buildServer");function jse(e){let t=Co.get(Sl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Co.get(Sl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Qse,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(jse,"getServerOptions");function Zse(){let e=Co.get(Sl.OPERATIONSAPI_NETWORK_CORS),t=Co.get(Sl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===zse)&&(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(Zse,"getCORSOpts");function ene(){return Co.get(Sl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Wse}a(ene,"getHeaderTimeoutConfig")});var XR={};qe(XR,{disableNATS:()=>rne,publishToStream:()=>IE,setNATSReplicator:()=>KR,setPublishToStream:()=>sne,setSubscription:()=>JR,start:()=>tne});function tne(){Tl.default.get(gl.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&ine()}function rne(e=!0){BH=e}function sne(e,t){IE=e,JR=t}function ine(){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)??nne)}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,nne,HH,MH,yE,WR,GH=ge(()=>{Re();Ns();UH=B(it()),QR=B(ke()),zR=B(Rn());gc();PH=B(wS()),vH=B(Dr()),Tl=B(ee()),gl=B(L()),NE=B($());a(tne,"start");a(rne,"disableNATS");IE=UH.publishToStream,JR=PH.setSubscription;a(sne,"setPublishToStream");nne=2;a(ine,"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(Do=>{"use strict";var{isMainThread:YH,parentPort:Al,threadId:wE}=require("worker_threads"),{Socket:one,createServer:ane}=require("net"),{createServer:cne,IncomingMessage:une}=require("http"),{createServer:lne}=require("https"),{readFileSync:Wa,unlinkSync:qH,existsSync:_ne}=require("fs"),rr=$(),we=ee(),Et=L(),{server:ME}=(or(),ie(Hi)),{WebSocketServer:dne}=require("ws"),{createServer:fne}=require("tls"),{getTicketKeys:Ene,restartNumber:hne,getWorkerIndex:DE}=Ke(),{Headers:KH,appendHeader:mne}=(Wu(),ie(HP)),{recordAction:Rl,recordActionBinary:pne}=(wn(),ie(lu)),{Request:WH,createReuseportFd:FH}=(bE(),ie(YR)),{checkMemoryLimit:Sne}=Ji(),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){hne<=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:Tne}=Et;we.initSync();var gne=we.get(Tne.HTTP_SESSIONAFFINITY),fn={};Do.registerServer=sA;Do.httpServer=nA;Do.deliverSocket=rA;Do.startServers=JH;Do.when_components_loaded=null;ME.http=nA;ME.request=bne;ME.socket=yne;ME.ws=Nne;var ZR={},CE={},Rne,Di={},LE={},Ane=[],eA=[];function JH(){return Do.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)One(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
|
|
29
29
|
Connection: close\r
|
|
30
30
|
\r
|
|
31
|
-
`))}},25).unref()}o.close?.(()=>{if(we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&DE()==0)try{qH(we.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(zH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){rr.info("Could not close debugger",i)}}}).ref();let e=[];if(FH&&!
|
|
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(we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&DE()==0)try{qH(we.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(zH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){rr.info("Could not close debugger",i)}}}).ref();let e=[];if(FH&&!gne)for(let t in fn){let r=fn[t];if(isNaN(t)&&DE()==0){_ne(t)&&qH(t),e.push(new Promise((n,i)=>{r.listen({path:t},()=>{n(),rr.info("Domain socket listening on "+t)}).on("error",i)}));continue}let s;try{s=FH(+t,"::")}catch(n){console.error(`Unable to bind to port ${t}`,n);continue}e.push(new Promise((n,i)=>{r.listen({fd:s},()=>{n(),rr.trace("Listening on port "+t,wE)}).on("error",i)}))}Promise.all(e).then(()=>{Al?.postMessage({type:Et.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(JH,"startServers");YH||JH();function rA(e,t,r){let s=e?.read?e:new one({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),n=fn[t];if(n.isSecure&&(s.startTime=performance.now()),n)typeof n=="function"?n(s):n.emit("connection",s),r&&s.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=fn[t];c?(typeof c=="function"?c(s):c.emit("connection",s),r&&s.emit("data",r)):o<5?i(o+1):(rr.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(rA,"deliverSocket");var VH=new Map;function One(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=VH.get(n),r){case"connection":i=rA(void 0,t),VH.set(n,i),i.write=(c,u,_)=>(Al.postMessage({requestId:n,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Al.postMessage({requestId:n,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Al.postMessage({requestId:n,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(s,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(One,"proxyRequest");function sA(e,t,r=!0){!+t&&t!==we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(we.get(Et.CONFIG_PARAMS.HTTP_PORT),10));let s=fn[t];if(s){let n=s.lastServer||s;if(n===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!n.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);n.off("unhandled",$H),n.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(s.cantCleanupProperly=!0),e.emit("request",i,o)}),s.lastServer=e}else fn[t]=e;e.on("unhandled",$H)}a(sA,"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=[],we.get(Et.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:we.get(Et.CONFIG_PARAMS.HTTP_PORT),secure:we.get(Et.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),we.get(Et.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:we.get(Et.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(XH,"getPorts");function nA(e,t){for(let{port:r,secure:s}of XH(t))jH(r,s,t?.isOperationsServer),typeof e=="function"?eA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=s,sA(e,r,!1)),LE[r]=tA(eA,r),Rne=tA(Ane,r)}a(nA,"httpServer");function jH(e,t,r){if(!Di[e]){let s=r?"operationsApi_network":"http",n={keepAliveTimeout:we.get(s+"_keepAliveTimeout"),headersTimeout:we.get(s+"_headersTimeout"),requestTimeout:we.get(s+"_timeout")},i=we.get(s+"_mtls"),o=we.get(s+"_mtls_required");if(t){s=r?"operationsApi_":"";let u=we.get(s+"tls_privateKey"),_=we.get(s+"tls_certificate"),l=we.get(s+"tls_certificateAuthority");Object.assign(n,{allowHTTP1:!0,key:Wa(u),ciphers:we.get("tls_ciphers"),cert:Wa(_),ca:l&&Wa(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:Ene(),maxHeaderSize:we.get(Et.CONFIG_PARAMS.HTTP_MAXHEADERSIZE)})}let c=Sne();Di[e]=(t?lne:cne)(n,async(u,_)=>{try{let d=performance.now(),f=new WH(u,_);r&&(f.isOperationsServer=!0);let E=await LE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=ZH(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 KH;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"),mne(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(Rl(S,"duration",R,M,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),pne(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",()=>{Rl(performance.now()-p,"transfer",R,M),Rl(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&&Rl(performance.now()-u._parent.startTime,"tls-handshake",e),Rl(u.isSessionReused(),"tls-reused",e)}),Di[e].isSecure=!0),sA(Di[e],e)}return Di[e]}a(jH,"getHTTPServer");function tA(e,t){let r=ZH;for(let s=e.length;s>0;){let{listener:n,port:i}=e[--s];if(i===t||i==="all"){let o=r;r=a(c=>n(c,o),"next_callback")}}return r}a(tA,"makeCallbackChain");function ZH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new KH}}a(ZH,"unhandled");function bne(e,t){nA(e,{requestOnly:!0,...t})}a(bne,"onRequest");function yne(e,t){let r;if(t.securePort){let s=we.get("tls_privateKey"),n=we.get("tls_certificate"),i=t.mtls?.certificateAuthority||we.get("tls_certificateAuthority");r=fne({ciphers:we.get("tls_ciphers"),key:Wa(s),cert:Wa(n),ca:i&&Wa(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),fn[t.securePort]=r}return t.port&&(r=ane(e),fn[t.port]=r),r}a(yne,"onSocket");Object.defineProperty(une.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 Nne(e,t){let r;for(let{port:s,secure:n}of XH(t)){CE[s]||(CE[s]=new dne({server:r=jH(s,n)}),CE[s].on("connection",async(c,u)=>{try{let _=new WH(u);_.isWebSocket=!0;let l=LE[s](_),d=u.headers["sec-websocket-protocol"]||"",f=ZR[s];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[s].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=ZR[s];o||(o=ZR[s]=[]),o.push({listener:e,protocol:i}),LE[s]=tA(eA,s)}return r}a(Nne,"onWebSocket");function $H(e,t){t.writeHead(404),t.end(`Not found
|
|
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=B(Dr()),Li=B($());ro();rx=B(Ke()),sx=B(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 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(s&&R)throw new Error("Filters can not be combined");let M=!0;b[b.length-1]==="#"&&(b.length--,M=!1),R&&(s=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 je(f,async()=>{let T=this.createContext();T.topic=n,T.retainHandling=i;let b=await p.subscribe(f,T);if(!b)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!b[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);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"||s&&!s(R))continue;r?(R.topic=n,M=this.needsAcknowledge(R)):(R.acknowledge?.(),M=aA());let v=R.id;Array.isArray(v)&&(v=ba(v)),v==null&&(v=""),this.listener(h+"/"+v,R.value,M,t)}catch(M){(0,Li.warn)(M)}})(),b});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:()=>Ine,start:()=>wne});function Ine(){ux=!0}function wne({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=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=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,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(),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(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),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=B(os());Na();wn();or();bl=B(ee()),zr=B(L()),_A=B($()),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(Ine,"bypassAuth");a(wne,"start");vE=0;a(ax,"onSocket")});var Lf={};qe(Lf,{component_errors:()=>za,loadComponent:()=>HE,loadComponentDirectories:()=>Tx,setErrorReporter:()=>Mne});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 Mne(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 b=e,R;for(;!(0,ks.existsSync)(R=(0,At.join)(b,"node_modules",l));)if(b=(0,At.dirname)(b),b.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=Lne[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(Qa.isMainThread&&(f=await f.startOnMainThread?.({server:st,ensureTable:h,port:T,securePort:S,resources:t,...d})||f,s&&p))for(let b of[T,S])try{if(+b&&!_x.includes(b)){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(b),yH(b,R))}}catch(R){console.error("Error listening on socket",b,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 b=(0,At.join)(e,d.files).replace(/\\/g,"/"),R=b.indexOf("/*");if(R>-1&&d.files!==mA[l]?.files&&!(0,ks.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,At.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,At.join)(e,z)}else(H=b.indexOf("/*"))>-1&&(k=b.slice(0,H+1),P=(0,At.relative)(e,k));let X=!1;if(Qa.isMainThread&&f.setupDirectory&&(X=await f.setupDirectory?.(v,k,t)),t.isWorker&&f.handleDirectory&&(X=await f.handleDirectory?.(v,k,t)),X)continue;for(let z of await(0,Ex.default)(b,{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=v+(v.endsWith("/")?"":"/")+ce;try{if(me.isFile()){let Le=await Dne(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,Cne,px,Dne,fA,hA,Sx,EA,za,Lne,mA,_x,dx,Nl,Il,Mf=ge(()=>{ks=require("fs"),At=require("path"),Qa=require("worker_threads"),fx=require("yaml"),pA=B(ee()),SA=B(L());Sb();Ab();Ob();I0();EH();gH();Ex=B(require("fast-glob")),Ja=B(Ke()),yl=B($());Wh();or();hx=B(se());Ns();Re();NH();mx=B(ee()),Cne=B(LH());Of();GH();lx();px=B(lr());bE();({readFile:Dne}=ks.promises),fA=pA.get(SA.CONFIG_PARAMS.COMPONENTSROOT),hA=new Map,za=new Map;a(Tx,"loadComponentDirectories");Lne={REST:Jf,rest:Jf,graphqlSchema:Kh,jsResource:zh,fastifyRoutes:BR,login:Xh,static:HR,operationsApi:Cne,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(Mne,"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:Une}=(Re(),ie(Fe)),{loadComponentDirectories:Pne,loadComponent:vne}=(Mf(),ie(Lf)),{resetResources:Bne}=(Ku(),ie(BP)),Hne=mg(),xne=lr(),{dirname:Gne}=require("path"),{getConnection:qne}=it(),Fne=ee(),kne=L(),TA=new Map;async function Vne(e=!1){!gx&&Fne.get(kne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&qne();try{gx&&await Hne()}catch(s){console.error(s)}let t=Bne();Une(),t.isWorker=e,await vne(Gne(xne.getConfigFilePath()),t,"hdb",!0,TA),await Pne(TA,t);let r=[];for(let[s]of TA)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(Vne,"loadRootComponents");Rx.exports.loadRootComponents=Vne});var Ke=g((mSe,Ui)=>{"use strict";var{Worker:$ne,MessageChannel:Yne,parentPort:En,isMainThread:bA,threadId:Kne,workerData:$n}=require("worker_threads"),{PACKAGE_ROOT:Wne}=L(),{join:yx,isAbsolute:Qne,extname:zne}=require("path"),{server:Nx}=(or(),ie(Hi)),{watch:Jne,readdir:Xne}=require("fs/promises"),{totalmem:Ax}=require("os"),wl=L(),Ix=ee(),Yn=$(),{randomBytes:jne}=require("crypto"),{_assignPackageExport:Zne}=require("../index"),eie=L(),Ox=1024*1024,Mi=[],ps=[],tie=50,yA=1e4,rie="restart",wx="request_thread_info",Cx="resource_report",Dx="thread_info",Lx="added-port",sie="ack",gA;Zne("threads",ps);Ui.exports={startWorker:RA,restartWorkers:IA,shutdownWorkers:cie,workers:Mi,setMonitorListener:mie,onMessageFromWorkers:uie,onMessageByType:xx,broadcast:_ie,broadcastWithAcknowledgement:fie,setChildListenerByType:aie,getWorkerIndex:Mx,getWorkerCount:Ux,getTicketKeys:vx,setMainIsWorker:iie,setTerminateTimeout:nie,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 nie(e){yA=e}a(nie,"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 iie(e){NA=e}a(iie,"setMainIsWorker");var Px=1,xE;function vx(){return xE||(xE=bA?jne(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){Eie(t)},[Cx](e,t){hie(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 Yne;_.existingPort=u,i.push(_),o.push(_.port2)}zne(e)||(e+=".js");let c=new $ne(Qne(e)?e:yx(Wne,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<tie?(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),Sie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(RA,"startWorker");var oie=[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=oie.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===eie.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:rie,workerType:e})}a(IA,"restartWorkers");function aie(e,t){Bx[e]=t}a(aie,"setChildListenerByType");function cie(e){return IA(e,1/0,!1)}a(cie,"shutdownWorkers");var Hx=[];function uie(e){Hx.push(e)}a(uie,"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 lie=10;async function _ie(e){let t=0;for(let r of ps)try{r.postMessage(e),t++>lie&&(t=0,await new Promise(setImmediate))}catch(s){Yn.error("Unable to send message to worker",s)}}a(_ie,"broadcast");var GE=new Map,die=1;function fie(e){return new Promise(t=>{let r=0;for(let s of ps)try{let n=die++,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(fie,"broadcastWithAcknowledgement");function Eie(e){e.postMessage({type:Dx,workers:Gx()})}a(Eie,"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 hie(e,t){e.resources=t,e.resources.updated=Date.now()}a(hie,"recordResourceReport");var OA;function mie(e){OA=e}a(mie,"setMonitorListener");var pie=1e3,bx=!1;function Sie(){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()},pie).unref())}a(Sie,"startMonitoring");var Tie=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})},Tie).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===sie){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 Xne(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(yx(s,i.name));try{for await(let{filename:i}of Jne(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",Kne),process.exit(0)},yA).unref())})});var CC={};qe(CC,{AUDIT_STORE_OPTIONS:()=>Ef,createAuditEntry:()=>E_,openAuditStore:()=>$E,readAuditEntry:()=>Mt,setAuditRetention:()=>Rie,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>=gie){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 Rie(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,gie,FE,CA,DA,qx,LA,Fx,kx,Vx,zx,MA,ei=ge(()=>{ja=require("ordered-binary"),kE=B(ee()),Yx=B(ut()),Kx=B(L()),VE=B(Ke()),Wx=B(Q());Ic();UA=B($());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,gie=1e3,FE=1e4;a($E,"openAuditStore");a(Rie,"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=Aie[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 Aie,Xx,YE=ge(()=>{ei();a(KE,"add");KE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Aie={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 Mo(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=Mo(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=Mo(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[Lo]||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,Lo,JE,XE,_d=ge(()=>{Ns();Ts=B(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(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;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:()=>bie,transformForSelect:()=>eh});function bie(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,Oie,Ft,ZE,Cl,HA,Ns=ge(()=>{tG=require("crypto");gc();rG=require("../index"),sG=B(se());_d();ro();Qf();ye=Symbol.for("context"),Me=Symbol.for("primary-key"),gs=Symbol("is-collection"),_e=Symbol("stored-record"),Oie={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&&Oie[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(bie,"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=B($()),th=B(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:()=>Uie,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),b=0,R,M,v={},P=Promise.resolve(),k,H,X;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(H=K),K.expiresAt&&(X=K),K.isPrimaryKey&&(v=K);let z,J=[],me=[],ce=1,de=2,Le={},Be={},Lt=864e5,Wl,Ql,Qn,oO=!1,Ah,Oh,_q=i.getRange({start:!1,end:!1}).constructor,dq=10,fq=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=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?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[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,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,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=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?(x=G,N(G,G),new Promise(te=>{x.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,A,I){let y=super.getResource(m,A,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 O=!I?.async||i.cache?.get(m),D=Os(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?sh(y,U):y[_e]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new Rs.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=>(sh(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[Pl]=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 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 A=ze.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.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,A){let I=Jl(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=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 A.select=y.filter(D=>D.read&&!Qn[D.attribute_name]).map(D=>D.attribute_name);return A}else return!0}}allowUpdate(m,A){let I=Jl(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[gs]){let I=Jl(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 Jl(m)?.delete}update(m,A){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&&(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[Dl]===lG?this.set(m,(+this.getProperty(m)||0)+A):(this[Dl]||this.update(),this.set(m,new XE(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];ic(I),Os(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,Ll,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,Ml,null,null,0,null,!0)}return i.ifVersion(m,I,()=>{zl(m,A,null)}),h?T(m,null,O,I,Ml,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=n,m.schema||=c,mG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,I){let y=this[ye],O=Os(y),D=this[Me];ic(D);let N=this[Zr];this[Dl]=A?lG:Die;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[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(A)return;ne=WE(ne,G)}let pe;if(A?pe=ne:(this[_e]=G,pe=A?ne:Mo(this,ne)),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),zl(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[gs]){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=Os(this[ye]),I=this[Me];ic(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),sh(this,D)),!(D?.version>O)&&(zl(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=Os(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(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?v: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 x=typeof m.sort=="object"&&m.sort,G;if(x&&C!=="or"){let j=x.attribute;if(O=y.find(Oe=>Gs(Oe.attribute)===Gs(j)),!O){if(!Gn(S,j))throw(0,Rs.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);O={attribute:j,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 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,A,(j,Oe)=>aO(j,ne,A,pe,Oe),D),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ae=ze.transformEntryForSelect(ne,A,pe,D,Pe,!0),Ge=ze.transformToOrderedSelect(te,ne,G,pe,A,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,A,I,y,O,D){let N=new _q;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,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,vo.compareKeys)(Ye,zn):(0,vo.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 x.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(),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],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]&&(A[x]=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,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&(Ll|Ml)||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,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?x[Ge.from]:Gs(C.key);re=j.get(He),re||(re=[])}else re=j.fromRecord?.(x);else re=Ge(x,A,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),A,I,j,O));if(Array.isArray(He)){let Ye=[],Gt=Ys.transformToOrderedSelect(He,te.select,typeof te.sort=="object"&&te.sort,A,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=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")ne(m,te=>{pe=te});else if(Array.isArray(m))if(m.asArray)pe=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=x:ne(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 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 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:n,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let A=!m.rawEvents,I=iG(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[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],O=m.previousCount;O>1e3&&(O=1e3);let D=m.startTime;if(this[gs]){if(D){if(O)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 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!==s)continue;let x=C.recordId;if(y==null||fG(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[Pl],type:"put"})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[_e]||this[Dl])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let I=Os(this[ye]),y=this[Me]||null;ic(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 ${Vs(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 ${Vs(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 ${Vs(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(I||(I=[])).push(`Value ${Vs(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 ${Vs(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(I||(I=[])).push(`Value ${Vs(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(I||(I=[])).push(`Value ${Vs(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 ${Vs(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 ${Vs(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(I||(I=[])).push(`Value ${Vs(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 ${Vs(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 Rs.ClientError(I.join(". "))}getUpdatedTime(){return this[Pl]}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 Rs.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new Rs.ClientError("Attribute names cannot include backticks or forward slashes");A.push(I)}return lt({table:n,database:c,schemaDefined:_,attributes:A}),ze.indexingOperation}static async removeAttributes(m){let A=S.filter(I=>!m.includes(I.name));return lt({table:n,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),ne=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(ne),Math.round(pe)]}}return{recordCount:D}}static updatedAttributes(){Qn=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?(Qn[m.name]=m.resolve=(I,y,O)=>{let D=I[A.from?A.from:t],N=m.elements.definition.tableClass;return O?va({attribute:A.to,value:D},Os(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 "${n}" must have an array type referencing a table as the elements`);else if(A.from){let I=m.definition||m.elements?.definition;I?(Qn[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:Os(O).getReadTxn()}):I.tableClass.get(C,O);return x?.then&&(U=!0),x});return A.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(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 "${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 A;for(let{key:I,value:y}of u.getRange({start:0,end:m}))await Ul(),Mt(y).tableId===s&&(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 Ul();let O=Mt(y);O.tableId===s&&(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 Ul();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 Eq=ze.prototype;return Eq[Cie]=!0,f&&ze.setTTLExpiration(f/1e3),X&&hq(),ze;function zl(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,vl.getIndexedValues)(N,F),x=(0,vl.getIndexedValues)(U,F);if(x?.length>0){let G=new Set(x);if(C=C?C.filter(ne=>{if(G.has(ne))G.delete(ne);else return!0}):[],x=Array.from(G),(x.length>0||C.length>0)&&uG){let ne=x.concat(C).map(pe=>({key:pe,value:K}));O.prefetch(ne,dG)}for(let ne=0,pe=x.length;ne<pe;ne++)O.remove(x[ne],K)}else C?.length>0&&uG&&O.prefetch(C.map(G=>({key:G,value:K})),dG);if(C)for(let G=0,ne=C.length;G<ne;G++)O.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,vo.writeKey)(K,Lie,0)>_G)throw new Error("Primary key size is too large: "+K.length);return!0}a(ic,"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>fq&&(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<dq&&de++}a(U,"prefetch");function F(){try{D(O())}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 Mie;let A=m[c],I,y=A?.tables;if(y)return y[n];if(c==="data"&&(I=m[n])&&!I.tables)return I}a(Jl,"getTablePermissions");function yh(K,m,A,I){if(M){let y;if(A.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 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 Rs.ServerError("Entry is not cached",504);return}else return O}}}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 A=m.next;if(!A)return m=m.next=new to,m.lmdbDb=i,m;m=A}while(!0)}else return new cd}a(Os,"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=Qn,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=Qn[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 ne=y[x].idFilter;if(ne){if(!ne(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&(Ll|Ml)?O(cO(K,i.getEntry(K),A)):O(C)}))return new Promise(C=>{O=C,D=setTimeout(()=>{i.unlock(K,y)},wie)});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(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")&&!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}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,Po.getWorkerIndex)()===(0,Po.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(),A=a(I=>{tt.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),Ql=setTimeout(()=>P=P.then(async()=>{if(A(Math.max(I+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Ql);return}let y=50,O=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:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;F===null&&!h&&C+Iie<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(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");A(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 hq(){(0,Po.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 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 Ul()}}catch(K){tt.error("Error in evicting old records",K)}finally{Oh=!1}}},Nie).unref()}a(hq,"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 Uie(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"&&!Pie.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,Uo,vl,hG,xl,Rs,Bl,Hl,tt,vo,Po,nh,yie,mG,Nie,Iie,uG,wie,Pl,Cie,Zr,Dl,lG,Die,qA,ec,Ll,Ml,Lie,_G,Mie,rTe,Pie,Ul,cE=ge(()=>{$s=B(L()),Uo=require("lmdb"),vl=B(Dr()),hG=require("lodash");Ns();oS();xl=B(ee());cG();Rs=B(se()),Bl=B(bn()),Hl=B(Ms());Re();Qf();tt=B($());_d();ro();vo=require("ordered-binary"),Po=B(Ke());ei();nh=B(Q());Ic();wn();YE();Wu();yie=new Uint8Array(9);yie[8]=192;Nie=6e4,Iie=864e5;xl.initSync();uG=xl.get($s.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),wie=1e4,Pl=Symbol.for("version"),Cie=Symbol.for("incremental-update"),Zr=Symbol("entry"),Dl=Symbol("is-saving"),lG=1,Die=2,qA=Symbol("loaded-from-source"),ec={isNotification:!0,ensureLoaded:!1},Ll=1,Ml=8,Lie=Buffer.allocUnsafeSlow(8192),_G=1978,Mie={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(Uie,"setServerUtilities");Pie=/[+-][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:()=>Gie,getDatabases:()=>dr,getDefaultCompression:()=>hf,getTables:()=>vie,onUpdatedTable:()=>jR,readMetaDb:()=>Gl,resetDatabases:()=>qu,table:()=>lt,tables:()=>Lr});function vie(){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 Bo.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],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,X=S.eviction,z=S.sealed;if(T)b=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 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)||TG;J.compression.threshold=me}v=h_(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){As.error("Error trying to update attribute",J,R,b,me)}}if(!T){T=RG(l,E,ih({primaryStore:v,auditStore:_,audit:P,sealed:z,expirationMS:H&&H*1e3,evictionMS:X&&X*1e3,trackDeletes:k,tableName:E,tableId:M,primaryKey:S.name,databasePath:n?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 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 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=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 Bo.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,b),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:H,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,b)),E.dbisDB=T;let v=[];for(let{key:H,value:X}of T.getRange({start:!0})){let[z,J]=H.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(H);let ce=E.indices[z];ce&&v.push(ce)}}let P=[];try{for(let H of i||[]){if(H.relationship)continue;let X=e+"/"+(H.name||"");Object.defineProperty(H,"key",{value:X,configurable:!0});let z=T.get(X);if(H.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!==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(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,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(X,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(X,H))}}finally{M&&M()}if(R&&(E.schemaVersion++,E.updatedAttributes()),As.trace(`${e} table loading, running index`),P.length>0||v.length>0?E.indexingOperation=xie(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||s||n)&&E.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),As.trace(`${e} table loaded`),E;function k(){M||d.transactionSync(()=>({then(H){M=H}}))}a(k,"startTxn")}async function xie(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>Bie?await n:u>Hie&&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 Gie({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,Bo,VA,Dt,_h,$A,pG,ch,uh,ql,As,SG,YA,dh,TG,Lr,nt,tc,KA,lh,Pi,sc,Bie,Hie,Re=ge(()=>{ht=B(ee()),oh=B(ut()),ah=require("lmdb"),rt=require("path"),es=require("fs"),rc=B(Je());cE();Bo=B(wc()),VA=B(Cc()),Dt=B(L()),_h=B(require("fs-extra")),$A=require("../index"),pG=B(Dr()),ch=B(bn()),uh=B(Ms()),ql=require("worker_threads"),As=B($()),SG=B(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(vie,"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");Bie=1e3,Hie=10;a(xie,"runIndexing");a(Gie,"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"),qie=require("net"),Fie=require("recursive-iterator"),ct=L(),kie=kO(),OG=require("papaparse"),Eh=require("moment"),{inspect:Vie}=require("util"),bG=require("is-number"),lTe=require("lodash"),$ie=require("minimist"),Yie=require("https"),Kie=require("http"),{hdb_errors:hh}=se(),Wie=/^((\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),Qie=100,zie=5,Jie="",Xie=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:eoe,arrayHasEmptyOrZeroLengthValues:toe,buildFolderPath:roe,isBoolean:wG,errorizeMessage:jie,stripFileExtension:noe,autoCast:ioe,autoCastJSON:CG,autoCastJSONDeep:QA,removeDir:ooe,compareVersions:aoe,isCompatibleDataVersion:coe,escapeRawValue:uoe,unescapeValue:loe,stringifyProps:_oe,timeoutPromise:foe,isClusterOperation:hoe,getClusterUser:poe,checkGlobalSchemaTable:moe,getHomeDir:LG,getPropsFilePath:doe,promisifyPapaParse:Soe,removeBOM:MG,createEventPromise:Toe,checkProcessRunning:goe,checkSchemaTableExist:Roe,checkSchemaExists:UG,checkTableExists:PG,getStartOfTomorrowInSeconds:Aoe,getLimitKey:Ooe,isObject:soe,isNotEmptyAndHasValue:Zie,autoCasterIsNumberCheck:DG,backtickASTSchemaItems:boe,isPortTaken:Eoe,createForkArgs:yoe,autoCastBoolean:Noe,async_set_timeout:IG,getTableHashAttribute:Ioe,doesSchemaExist:woe,doesTableExist:Coe,stringifyObj:Doe,ms_to_time:Loe,changeExtension:Moe,getEnvCliRootPath:zA,noBootFile:Uoe,httpRequest:Poe,transformReq:voe,convertToMS:Boe,PACKAGE_ROOT:ct.PACKAGE_ROOT};function jie(e){return e instanceof Error?e:new Error(e)}a(jie,"errorizeMessage");function ts(e){return e==null}a(ts,"isEmpty");function Zie(e){return!ts(e)&&(e||e===0||e===""||wG(e))}a(Zie,"isNotEmptyAndHasValue");function hn(e){return ts(e)||e.length===0||e.size===0}a(hn,"isEmptyOrZeroLength");function eoe(e){if(ts(e))return!0;for(let t=0;t<e.length;t++)if(ts(e[t]))return!0;return!1}a(eoe,"arrayHasEmptyValues");function toe(e){if(hn(e))return!0;for(let t=0;t<e.length;t++)if(hn(e[t]))return!0;return!1}a(toe,"arrayHasEmptyOrZeroLengthValues");function roe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(roe,"buildFolderPath");function wG(e){return ts(e)?!1:e===!0||e===!1}a(wG,"isBoolean");function soe(e){return ts(e)?!1:typeof e=="object"}a(soe,"isObject");function noe(e){return hn(e)?Jie:e.slice(0,-Xie)}a(noe,"stripFileExtension");function ioe(e){return ts(e)||e===""||typeof e!="string"?e:yG[e]!==void 0?yG[e]:DG(e)===!0?Number(e):Wie.test(e)?new Date(e):e}a(ioe,"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 ooe(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(ooe,"removeDir");function aoe(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(aoe,"compareVersions");function coe(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(coe,"isCompatibleDataVersion");function uoe(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(uoe,"escapeRawValue");function loe(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(loe,"unescapeValue");function _oe(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(_oe,"stringifyProps");function LG(){let e;try{e=fh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(LG,"getHomeDir");function doe(){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(doe,"getPropsFilePath");function foe(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(foe,"timeoutPromise");async function Eoe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=qie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(Eoe,"isPortTaken");function hoe(e){try{return ct.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Ir.error(`Error checking operation against cluster ops ${t}`)}return!1}a(hoe,"isClusterOperation");function moe(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(moe,"checkGlobalSchemaTable");function poe(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(poe,"getClusterUser");function Soe(){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(Soe,"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 Toe(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Ir.info(`Got cluster status event response: ${Vie(n)}`);try{i.cancel()}catch{Ir.error("Error trying to cancel timeout.")}s(n)})})}a(Toe,"createEventPromise");async function goe(e){let t=!0,r=0;do await IG(Qie*r++),(await kie.findPs(e)).length>0&&(t=!1);while(t&&r<zie);if(t)throw new Error(`process ${e} was not started`)}a(goe,"checkProcessRunning");function Roe(e,t){let r=UG(e);if(r)return r;let s=PG(e,t);if(s)return s}a(Roe,"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 Aoe(){let e=Eh().utc().add(1,ct.MOMENT_DAYS_TAG).startOf(ct.MOMENT_DAYS_TAG).unix(),t=Eh().utc().unix();return e-t}a(Aoe,"getStartOfTomorrowInSeconds");function Ooe(){return Eh().utc().format("DD-MM-YYYY")}a(Ooe,"getLimitKey");function boe(e){try{let t=new Fie(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(boe,"backtickASTSchemaItems");function yoe(e){return[e]}a(yoe,"createForkArgs");function Noe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Noe,"autoCastBoolean");function Ioe(e,t){let{getDatabases:r}=(Re(),ie(Fe)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(Ioe,"getTableHashAttribute");function woe(e){let{getDatabases:t}=(Re(),ie(Fe));return t()[e]!==void 0}a(woe,"doesSchemaExist");function Coe(e,t){let{getDatabases:r}=(Re(),ie(Fe));return r()[e]?.[t]!==void 0}a(Coe,"doesTableExist");function Doe(e){try{return JSON.stringify(e)}catch{return e}}a(Doe,"stringifyObj");function Loe(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(Loe,"ms_to_time");function Moe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(Moe,"changeExtension");function zA(){if(process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=$ie(process.argv);if(e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(zA,"getEnvCliRootPath");var WA;function Uoe(){if(WA)return WA;let e=zA();zA()&&NG.pathExistsSync(vi.join(e,ct.HDB_CONFIG_FILE))&&(WA=!0)}a(Uoe,"noBootFile");function Poe(e,t){let r;return e.protocol==="http:"?r=Kie:r=Yie,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(Poe,"httpRequest");function voe(e){if(!e.schema&&!e.database){e.schema=ct.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(voe,"transformReq");function Boe(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(Boe,"convertToMS")});var ee=g((fTe,GG)=>{"use strict";var JA=require("fs-extra"),Ho=require("path"),BG=require("os"),Hoe=require("properties-reader"),kl=$(),Fl=Q(),ue=L(),mh=lr(),xoe="Error initializing environment manager",ph="BOOT_PROPS_FILE_PATH",HG=!1,Goe={[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:qoe,setHdbBasePath:Foe,get:xG,initSync:Voe,setProperty:Ue,initTestEnvironment:$oe};function qoe(){return Kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(qoe,"getHdbBasePath");function Foe(e){Kn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Foe,"setHdbBasePath");function xG(e){let t=mh.getConfigValue(e);return t===void 0?Kn[e]:t}a(xG,"get");function Ue(e,t){Goe[e]&&(Kn[e]=t),mh.updateConfigObject(e,t)}a(Ue,"setProperty");function koe(){let e;try{e=Fl.getPropsFilePath(),JA.accessSync(e,JA.constants.F_OK|JA.constants.R_OK),HG=!0;let t=Hoe(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(koe,"doesPropFileExist");function Voe(e=!1){try{(HG||koe()||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(xoe),kl.error(t),console.error(t),process.exit(1)}}a(Voe,"initSync");function $oe(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=Ho.join(__dirname,"../../","unitTests");Kn[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,BG.userInfo()?BG.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")),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,Ho.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($oe,"initTestEnvironment")});var $G=g((hTe,VG)=>{"use strict";var kG=require("joi"),{string:Vl,boolean:qG,array:Yoe}=kG.types(),FG=L(),Koe=Xe();VG.exports=Woe;function Woe(e){let t=kG.object({operation:Vl.valid(FG.OPERATIONS_ENUM.ADD_NODE,FG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Vl.required(),subscriptions:Yoe.items({schema:Vl.required(),table:Vl.optional(),hash_attribute:Vl.optional(),subscribe:qG.required(),publish:qG.required()}).min(1).required()});return Koe.validateBySchema(e,t)}a(Woe,"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 zG=g((TTe,QG)=>{"use strict";var Qoe=$G(),Wn=$(),jA=ke(),zoe=L(),ZA=us(),xo=it(),KG=Su(),Joe=id(),{Node:Xoe,NodeSubscription:WG}=mi(),eO=$l(),tO=Q(),joe=ee(),{cloneDeep:Zoe}=require("lodash"),{broadcast:eae}=Ke();QG.exports=tae;async function tae(e){try{let t=Qoe(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 KG.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 KG.createTable(h)}catch(p){Wn.error(p)}}if(Wn.trace(`Creating local stream for ${f}.${E}`),await xo.createLocalTableStream(f,E),c?(await xo.updateConsumerIterator(f,E,s,"stop"),await xo.updateRemoteConsumer(d,s),d.subscribe===!0&&await xo.updateConsumerIterator(f,E,s,"start")):(await xo.updateRemoteConsumer(d,s),d.subscribe===!0?await xo.updateConsumerIterator(f,E,s,"start"):await xo.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 WG(f,E,d.publish,d.subscribe))}else i.push(new WG(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(zoe.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 ZG=g((RTe,jG)=>{"use strict";var XG=require("joi"),{string:JG}=XG.types(),rae=L(),sae=Xe();jG.exports=nae;function nae(e){let t=XG.object({operation:JG.valid(rae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:JG.required()});return sae.validateBySchema(e,t)}a(nae,"removeRemoteSourceValidator")});var rq=g((OTe,tq)=>{"use strict";var iae=ZG(),Sh=$(),Th=ke(),rO=L(),oae=us(),aae=Q(),eq=it(),cae=ee(),gh=$l(),{NodeSubscription:uae}=mi(),lae=ia(),_ae=ii(),{broadcast:dae}=Ke(),fae=cae.get(rO.CONFIG_PARAMS.CLUSTERING_NODENAME);tq.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 eq.updateConsumerIterator(c.schema,c.table,r,"stop"),await eq.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 oq=g((yTe,iq)=>{"use strict";var Rh=$(),Yl=L(),sq=ke(),sO=ee(),hae=Q(),nq=$l(),mae=us(),pae=Bd(),Sae=vr();iq.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 nq(sq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){Rh.error(t);let r=t.message?t.message:t;return new nq(sq.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 lq=g((ITe,uq)=>{"use strict";var aq=ee();aq.initSync();var cq=it(),Kl=$(),nc=L(),nO=ke(),Rae=zG(),Aae=rq(),Oae=oq(),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=aq.get(nc.CONFIG_PARAMS.CLUSTERING_NODENAME);uq.exports=Pae;async function Pae(){try{Kl.notify("Starting reply service."),await Uae();let e=await cq.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&&cq.closeConnection()})});var Hae=lq();(async()=>{try{await Hae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|