harperdb 4.2.0-alpha.11 → 4.2.0-alpha.13
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 +32 -32
- package/bin/lite.js +19 -19
- package/index.js +0 -1
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +16 -16
- package/launchServiceScripts/launchNatsReplyService.js +16 -16
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +16 -16
- package/package.json +6 -6
- package/resources/analytics.d.ts +9 -0
- package/resources/databases.d.ts +7 -0
- package/server/jobs/jobProcess.js +16 -16
- package/server/threads/threadServer.js +19 -19
- package/utility/scripts/restartHdb.js +16 -16
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
"use strict";var QB=Object.create;var Wo=Object.defineProperty;var zB=Object.getOwnPropertyDescriptor;var JB=Object.getOwnPropertyNames;var XB=Object.getPrototypeOf,ZB=Object.prototype.hasOwnProperty;var a=(e,t)=>Wo(e,"name",{value:t,configurable:!0});var pe=(e,t)=>()=>(e&&(t=e(e=0)),t);var m=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ze=(e,t)=>{for(var r in t)Wo(e,r,{get:t[r],enumerable:!0})},fR=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of JB(t))!ZB.call(e,n)&&n!==r&&Wo(e,n,{get:()=>t[n],enumerable:!(s=zB(t,n))||s.enumerable});return e};var D=(e,t,r)=>(r=e!=null?QB(XB(e)):{},fR(t||!e||!e.__esModule?Wo(r,"default",{value:e,enumerable:!0}):r,e)),te=e=>fR(Wo({},"__esModule",{value:!0}),e);var SR=m((zte,mR)=>{var jB=require("fast-glob"),{statSync:SE,existsSync:pE,readFileSync:eH,writeFileSync:tH}=require("fs"),{spawnSync:rH,spawn:sH}=require("child_process"),{isMainThread:nH}=require("worker_threads"),{join:Ns,relative:hR}=require("path"),{PACKAGE_ROOT:mr}=g(),{tmpdir:iH}=require("os");require("source-map-support").install();var oH=["resources","server","dataLayer"],Qo="ts-build",TE,aH=__filename.endsWith("tsBuild.js");if(aH){if(nH){let r;try{SE(Ns(mr,Qo)),r=!0}catch{}if(r)for(let s of jB.sync(oH.map(n=>n+"/**/*.ts"),{cwd:mr})){let n=0,i=0;try{n=SE(Ns(mr,s)).mtimeMs-5e3,i=SE(Ns(mr,Qo,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."),TE=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),TE=!0;if(TE){let s=rH(process.argv[0],[Ns(mr,"node_modules/.bin/tsc")],{cwd:mr});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let n=Ns(iH(),"harperdb-tsc.pid"),i;if(pE(n))try{process.kill(+eH(n,{encoding:"utf8"}),0),i=!0}catch{}if(!i){console.log("starting tsc background process");let o=sH(process.argv[0],[Ns(mr,"node_modules/.bin/tsc"),"--watch"],{cwd:mr,detached:!0,stdio:"ignore"});tH(n,o.pid.toString()),o.unref()}}}}let e=mR.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(mr)&&!s[0].includes("node_modules")){let i=hR(mr,s[0]),o;i.startsWith(Qo)?o=Ns(mr,hR(Qo,i)):o=Ns(mr,Qo,i);let c=Ns(o,r),u=c+".js";if(pE(u))return u;if(c.includes(".")&&pE(c))return c}return t(r,s,n)}}});var g=m((Zte,DR)=>{"use strict";var Sr=require("path"),cH=require("fs"),{relative:Jte,join:Xte}=Sr,{existsSync:uH}=cH;function lH(){let e=__dirname;for(;!uH(Sr.join(e,"package.json"));){let t=Sr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(lH,"getHDBPackageRoot");var an=lH(),pR="js",_u=pR,_H="harperdb-config.yaml",dH="defaultConfig.yaml",EH="hdb",TR=`harperdb.${_u}`,RR=`customFunctionsServer.${_u}`,fH=`restartHdb.${_u}`,gE="HarperDB",lu="Custom Functions",du="Clustering Hub",Eu="Clustering Leaf",hH="Clustering Ingest Service",mH="Clustering Reply Service",SH="foreground.pid",pH="hdb.pid",TH="data",RH={HDB:gE,CLUSTERING_HUB:du,CLUSTERING_LEAF:Eu,CLUSTERING_INGEST_SERVICE:hH,CLUSTERING_REPLY_SERVICE:mH,CUSTOM_FUNCTIONS:lu,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"},gH={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},AH={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},OH={harperdb:gE,"clustering hub":du,"clustering leaf":Eu,"custom functions":lu,custom_functions:lu,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},NH={CLUSTERING_HUB_PROC_DESCRIPTOR:du,CLUSTERING_LEAF_PROC_DESCRIPTOR:Eu},RE={HDB:Sr.join(an,"server/harperdb"),CUSTOM_FUNCTIONS:Sr.join(an,"server/customFunctions"),CLUSTERING_HUB:Sr.join(an,"server/nats"),CLUSTERING_LEAF:Sr.join(an,"server/nats")},bH={HDB:Sr.join(RE.HDB,TR),CUSTOM_FUNCTIONS:Sr.join(RE.CUSTOM_FUNCTIONS,RR)},yH={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Sr.join(an,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Sr.join(an,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Sr.join(an,"launchServiceScripts/launchUpdateNodes4-0-0.js")},IH={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},gR="support@harperdb.io",wH="customer-success@harperdb.io",AR=1,CH=4141,OR="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",UH="https://www.harperdb.io/product",DH=`For support, please submit a request at ${OR} or contact ${gR}`,NR=`For license support, please contact ${wH}`,LH="None of the specified records were found.",MH="hash attribute not found",PH=`Your current license only supports ${AR} role. ${NR}`,vH="Your current license only supports 3 connections to a node.",BH="127.0.0.1",HH=1,qH=/^\.$/,FH=/^\.\.$/,GH="U+002E",xH=/\//g,kH="U+002F",VH=/U\+002F/g,$H=/^U\+002E$/,YH=/^U\+002EU\+002E$/,KH="d",WH=999999,QH="*",zH="--max-old-space-size=",JH="system",XH="__hdb_hash",ZH=".harperdb",jH=".hdb",e0="keys",t0="hdb_boot_properties.file",r0=".updateConfig.json",s0="SIGTSTP",n0=24,i0=6e4,o0=448,a0="blob",c0="trash",u0="database",l0="schema",_0="transactions",d0=".count",E0="id",f0="PROCESS_NAME",bR={SETTINGS_PATH_KEY:"settings_path"},yR=require("lodash"),h0={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",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},m0={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},S0={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},p0={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"},T0={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"},tr="hdb_internal:",R0={CREATE_SCHEMA:tr+"create_schema",CREATE_TABLE:tr+"create_table",CREATE_ATTRIBUTE:tr+"create_attribute",ADD_USER:tr+"add_user",ALTER_USER:tr+"alter_user",DROP_USER:tr+"drop_user",HDB_NODES:tr+"hdb_nodes",HDB_USERS:tr+"hdb_users",HDB_WORKERS:tr+"hdb_workers",CATCHUP:tr+"catchup",SCHEMA_CATCHUP:tr+"schema_catchup",WORKER_ROOM:tr+"cluster_workers"},g0={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"},A0="060493.ks",O0=".license",N0={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},$={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",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"},b0={CSV:".csv",JSON:".json"},y0={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},I0={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},zo={};zo[$.INSERT]=$.INSERT;zo[$.UPDATE]=$.UPDATE;zo[$.UPSERT]=$.UPSERT;zo[$.DELETE]=$.DELETE;var Ae=Object.create(null);Ae[$.DESCRIBE_ALL]=$.DESCRIBE_ALL;Ae[$.DESCRIBE_TABLE]=$.DESCRIBE_TABLE;Ae[$.DESCRIBE_SCHEMA]=$.DESCRIBE_SCHEMA;Ae[$.READ_LOG]=$.READ_LOG;Ae[$.ADD_NODE]=$.ADD_NODE;Ae[$.LIST_USERS]=$.LIST_USERS;Ae[$.LIST_ROLES]=$.LIST_ROLES;Ae[$.USER_INFO]=$.USER_INFO;Ae[$.SQL]=$.SQL;Ae[$.GET_JOB]=$.GET_JOB;Ae[$.SEARCH_JOBS_BY_START_DATE]=$.SEARCH_JOBS_BY_START_DATE;Ae[$.DELETE_FILES_BEFORE]=$.DELETE_FILES_BEFORE;Ae[$.EXPORT_LOCAL]=$.EXPORT_LOCAL;Ae[$.EXPORT_TO_S3]=$.EXPORT_TO_S3;Ae[$.CLUSTER_STATUS]=$.CLUSTER_STATUS;Ae[$.REMOVE_NODE]=$.REMOVE_NODE;Ae[$.RESTART]=$.RESTART;Ae[$.CUSTOM_FUNCTIONS_STATUS]=$.CUSTOM_FUNCTIONS_STATUS;Ae[$.GET_CUSTOM_FUNCTIONS]=$.GET_CUSTOM_FUNCTIONS;Ae[$.GET_CUSTOM_FUNCTION]=$.GET_CUSTOM_FUNCTION;Ae[$.SET_CUSTOM_FUNCTION]=$.SET_CUSTOM_FUNCTION;Ae[$.DROP_CUSTOM_FUNCTION]=$.DROP_CUSTOM_FUNCTION;Ae[$.ADD_CUSTOM_FUNCTION_PROJECT]=$.ADD_CUSTOM_FUNCTION_PROJECT;Ae[$.DROP_CUSTOM_FUNCTION_PROJECT]=$.DROP_CUSTOM_FUNCTION_PROJECT;Ae[$.PACKAGE_CUSTOM_FUNCTION_PROJECT]=$.PACKAGE_CUSTOM_FUNCTION_PROJECT;Ae[$.DEPLOY_CUSTOM_FUNCTION_PROJECT]=$.DEPLOY_CUSTOM_FUNCTION_PROJECT;var w0={DEBUG:"debug",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status"},C0={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},IR={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"},U0=yR.invert(IR),R={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_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",HTTP_THREADS:"http_threads",HTTP_SESSION_AFFINITY:"http_sessionAffinity",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_AUTHENTICATION_OPERATIONTOKENTIMEOUT:"operationsApi_authentication_operationTokenTimeout",OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT:"operationsApi_authentication_refreshTokenTimeout",OPERATIONSAPI_FOREGROUND:"operationsApi_foreground",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",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_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERT_AUTH:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",OPERATIONSAPI_NODEENV:"operationsApi_nodeEnv",ROOTPATH:"rootPath",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",SCHEMAS:"schemas",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication"},wR={settings_path:bR.SETTINGS_PATH_KEY,hdb_root_key:R.ROOTPATH,hdb_root:R.ROOTPATH,server_port_key:R.OPERATIONSAPI_NETWORK_PORT,server_port:R.OPERATIONSAPI_NETWORK_PORT,cert_key:R.OPERATIONSAPI_TLS_CERTIFICATE,certificate:R.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:R.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:R.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:R.OPERATIONSAPI_NETWORK_HTTPS,https_on:R.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:R.OPERATIONSAPI_NETWORK_CORS,cors_on:R.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:R.LOGGING_LEVEL,log_level:R.LOGGING_LEVEL,log_path_key:R.LOGGING_ROOT,log_path:R.LOGGING_ROOT,props_env_key:R.OPERATIONSAPI_NODEENV,node_env:R.OPERATIONSAPI_NODEENV,clustering_node_name_key:R.CLUSTERING_NODENAME,node_name:R.CLUSTERING_NODENAME,clustering_enabled_key:R.CLUSTERING_ENABLED,clustering:R.CLUSTERING_ENABLED,max_http_threads:R.HTTP_THREADS,max_hdb_processes:R.HTTP_THREADS,server_timeout_key:R.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:R.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:R.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:R.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:R.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:R.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:R.LOGGING_AUDITLOG,disable_transaction_log:R.LOGGING_AUDITLOG,operation_token_timeout_key:R.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:R.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:R.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:R.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_enabled_key:R.CUSTOMFUNCTIONS_ENABLED,custom_functions:R.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:R.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:R.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:R.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:R.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:R.HTTP_THREADS,log_to_file:R.LOGGING_FILE,log_to_stdstreams:R.LOGGING_STDSTREAMS,run_in_foreground:R.OPERATIONSAPI_FOREGROUND,local_studio_on:R.LOCALSTUDIO_ENABLED,clustering_port:R.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:R.CLUSTERING_USER,clustering_enabled:R.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:R.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:R.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:R.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:R.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:R.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:R.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:R.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:R.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:R.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:R.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:R.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:R.CLUSTERING_NODENAME,clustering_tls_certificate:R.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:R.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:R.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:R.CLUSTERING_TLS_INSECURE,clustering_tls_verify:R.CLUSTERING_TLS_VERIFY,clustering_loglevel:R.CLUSTERING_LOGLEVEL,clustering_republishmessages:R.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:R.CLUSTERING_DATABASELEVEL,customfunctions_enabled:R.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:R.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:R.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:R.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:R.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:R.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:R.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:R.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:R.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:R.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:R.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:R.CUSTOMFUNCTIONS_NODEENV,http_threads:R.HTTP_THREADS,http_session_affinity:R.HTTP_SESSION_AFFINITY,customfunctions_processes:R.HTTP_THREADS,customfunctions_root:R.CUSTOMFUNCTIONS_ROOT,localstudio_enabled:R.LOCALSTUDIO_ENABLED,logging_file:R.LOGGING_FILE,logging_level:R.LOGGING_LEVEL,logging_root:R.LOGGING_ROOT,logging_rotation_enabled:R.LOGGING_ROTATION_ENABLED,logging_rotation_compress:R.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:R.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:R.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:R.LOGGING_ROTATION_PATH,logging_stdstreams:R.LOGGING_STDSTREAMS,logging_auditlog:R.LOGGING_AUDITLOG,logging_auditretention:R.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:R.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:R.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:R.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:R.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:R.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:R.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:R.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:R.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:R.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:R.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:R.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:R.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:R.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:R.OPERATIONSAPI_TLS_CERT_AUTH,operationsapi_network_timeout:R.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:R.OPERATIONSAPI_NODEENV,operationsapi_root:R.ROOTPATH,schemas:R.SCHEMAS,storage_path:R.STORAGE_PATH,ignorescripts:R.IGNORE_SCRIPTS,mqtt_network_port:R.MQTT_NETWORK_PORT,mqtt_websocket:R.MQTT_WEBSOCKET,mqtt_network_secureport:R.MQTT_NETWORK_SECUREPORT,mqtt_requireauthentication:R.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:R.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:R.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:R.AUTHENTICATION_CACHETTL,authentication_enablesessions:R.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:R.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:R.AUTHENTICATION_REFRESHTOKENTIMEOUT};for(let e in R){let t=R[e];wR[t.toLowerCase()]=t}var D0={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},L0={csv_file_load:"csv_file_load",csv_data_load:$.CSV_DATA_LOAD,csv_url_load:$.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"},M0={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"},P0={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},v0={VERSION_DEFAULT:"2.2.0"},B0={DEVELOPMENT:8192,DEFAULT:512},H0={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"},q0={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"},F0={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},CR={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},G0=Symbol("metadata"),x0="__clustering__",k0=Object.values(CR),V0=15984864e5,UR={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},$0=yR.invert(UR),Y0={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"},K0=111,W0=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
4
|
-
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,s])=>({pid:Number.parseInt(r,10),name:yq.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(Uq,"findPs")});var xe=m((ore,QR)=>{"use strict";var Dq="__dbis__",Lq="__txns__",Mq="__environment_name__",Pq="__dbi_defintion__",vq={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"},Bq=["__createdtime__","__updatedtime__"],Hq="\uFFFF",WR={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},qq=Object.values(WR);QR.exports={AUDIT_STORE_NAME:Lq,INTERNAL_DBIS_NAME:Dq,DBI_DEFINITION_NAME:Pq,SEARCH_TYPES:vq,TIMESTAMP_NAMES:Bq,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Mq,TRANSACTIONS_DBI_NAMES_ENUM:WR,TRANSACTIONS_DBIS:qq,OVERFLOW_MARKER:Hq}});var rr=m((are,sg)=>{"use strict";var zR=g(),JR=xe(),XR={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},ZR=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),jR={500:ZR("There was an error processing your request."),400:"Invalid request"},Fq=jR[XR.INTERNAL_SERVER_ERROR],Gq={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.`},xq={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},kq={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"},Vq={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 ${JR.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${JR.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"},$q={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${zR.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 ${zR.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"},eg={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"},Yq={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."},Kq={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`},Wq={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"},Qq={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},zq={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`},tg={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.`},rg={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}`},Jq={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."},Xq={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},Zq={...eg,...kq,...Gq,...Yq,...Kq,...Wq,...Qq,...zq,...$q,...tg,...rg,...Jq,...Xq,...xq};sg.exports={CHECK_LOGS_WRAPPER:ZR,HDB_ERROR_MSGS:Zq,DEFAULT_ERROR_MSGS:jR,DEFAULT_ERROR_RESP:Fq,HTTP_STATUS_CODES:XR,LMDB_ERRORS_ENUM:Vq,AUTHENTICATION_ERROR_MSGS:eg,VALIDATION_ERROR_MSGS:tg,ITC_ERRORS:rg}});var W=m((ure,og)=>{"use strict";var Hi=rr(),jq=F(),eF=g(),pu=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,ng),this.http_resp_code=s||Hi.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Hi.DEFAULT_ERROR_MSGS[s]?Hi.DEFAULT_ERROR_MSGS[s]:Hi.DEFAULT_ERROR_MSGS[Hi.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&&jq[n](i)}},UE=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.http_resp_code=r||400,t;super(t),this.http_resp_code=r||400}},DE=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.http_resp_code=r||500}};function ng(e,t,r,s=eF.LOG_LEVELS.ERROR,n=null,i=!1){if(ig(e))return e;let o=new pu(e,t,r,s,n);return i&&delete o.stack,o}a(ng,"handleHDBError");function ig(e){return e.__proto__.constructor.name===pu.name}a(ig,"isHDBError");og.exports={isHDBError:ig,handleHDBError:ng,ClientError:UE,ServerError:DE,hdb_errors:Hi}});var we=m((_re,Eg)=>{"use strict";var ia=g(),tF=x(),Pt=Q(),oa=require("path"),rF=require("minimist"),ag=require("fs-extra"),cg=require("lodash");Pt.initSync();var{CONFIG_PARAMS:cn,SCHEMAS_PARAM_CONFIG:ta,SYSTEM_SCHEMA_NAME:Tu}=ia,ra,sa,na;function ug(){if(ra!==void 0)return ra;if(Pt.getHdbBasePath()!==void 0)return ra=Pt.get(cn.STORAGE_PATH)||oa.join(Pt.getHdbBasePath(),ia.DATABASES_DIR_NAME),ra}a(ug,"getBaseSchemaPath");function lg(){if(sa!==void 0)return sa;if(Pt.getHdbBasePath()!==void 0)return sa=dg(Tu),sa}a(lg,"getSystemSchemaPath");function _g(){if(na!==void 0)return na;if(Pt.getHdbBasePath()!==void 0)return na=Pt.get(ia.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||oa.join(Pt.getHdbBasePath(),ia.TRANSACTIONS_DIR_NAME),na}a(_g,"getTransactionAuditStoreBasePath");function sF(e,t){let r=Pt.get(cn.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||oa.join(_g(),e.toString())}a(sF,"getTransactionAuditStorePath");function dg(e,t){e=e.toString(),t=t&&t.toString();let r=Pt.get(ia.CONFIG_PARAMS.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.path||r?.path||oa.join(ug(),e)}a(dg,"getSchemaPath");function nF(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,rF(process.argv));let s=r[cn.SCHEMAS.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!tF.isObject(s))throw o;i=s}for(let o of i){let c=o[Tu];if(!c)continue;let u=Pt.get(cn.SCHEMAS);u=u??{};let l=c?.tables?.[t]?.[ta.PATH];if(l)return cg.set(u,[Tu,ta.TABLES,t,ta.PATH],l),Pt.setProperty(cn.SCHEMAS,u),l;let _=c?.[ta.PATH];if(_)return cg.set(u,[Tu,ta.PATH],_),Pt.setProperty(cn.SCHEMAS,u),_}}let n=r[cn.STORAGE_PATH.toUpperCase()];if(n){if(!ag.pathExistsSync(n))throw new Error(n+" does not exist");let i=oa.join(n,e);return ag.mkdirsSync(i),Pt.setProperty(cn.STORAGE_PATH,n),i}return lg()}a(nF,"initSystemSchemaPaths");function iF(){ra=void 0,sa=void 0,na=void 0}a(iF,"resetPaths");Eg.exports={getBaseSchemaPath:ug,getSystemSchemaPath:lg,getTransactionAuditStorePath:sF,getTransactionAuditStoreBasePath:_g,getSchemaPath:dg,initSystemSchemaPaths:nF,resetPaths:iF}});var vt=m((hre,pg)=>{"use strict";var oF=rr().LMDB_ERRORS_ENUM,Ere=require("lmdb"),aF=xe(),fre=require("buffer").Buffer,{OVERFLOW_MARKER:fg,MAX_SEARCH_KEY_LENGTH:Ru}=aF,hg=["number","string","symbol","boolean","bigint"];function cF(e){if(e=e?.primaryStore||e,!e)throw new Error(oF.ENV_REQUIRED)}a(cF,"validateEnv");function uF(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(uF,"stringifyData");function lF(e){return e instanceof Date?e.valueOf():e}a(lF,"convertKeyValueToWrite");function _F(e){if(e==null)return;if(hg.includes(typeof e))return e.length>Ru?[e.slice(0,Ru)+fg]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];if(hg.includes(typeof n))n.length>Ru?t.push(n.slice(0,Ru)+fg):t.push(n);else if(n instanceof Date)return t.push(n.getTime())}}else if(e instanceof Date)return[e.getTime()];return t}a(_F,"getIndexedValues");var gu=0,mg=0;function Sg(){mg=Date.now()-performance.now()}a(Sg,"adjustStartTime");Sg();var dF=6e4;setInterval(Sg,dF).unref();function EF(){let e=performance.now()+mg;return e>gu?(gu=e,e):(gu+=488e-6,gu)}a(EF,"getNextMonotonicTime");pg.exports={validateEnv:cF,stringifyData:uF,convertKeyValueToWrite:lF,getNextMonotonicTime:EF,getIndexedValues:_F}});var Tg,Jr,LE,aa=pe(()=>{Tg=require("events"),Jr=class extends Tg.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new LE;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)}},LE=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function ca(e){return e[Et]||(e[Et]=Object.create(null))}function yu(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u={get(){let l=this[Et];if(l&&c in l)return l[c];let _=this[ce]?.[c];if(_&&typeof _=="object"){let d=Rg(_,o);if(d)return l||(l=this[Et]=Object.create(null)),l[c]=d}return _},set(l){ca(this)[c]=l},enumerable:!0,configurable:!0};switch(u.get.isAttribute=!0,o.type){case"String":u.set=function(l){if(typeof l!="string")throw(0,Au.ClientError)(`${c} must be a string, attempt to assign ${l}`);ca(this)[c]=l};break;case"Int":u.set=function(l){if(typeof l!="number")throw(0,Au.ClientError)(`${c} must be a string, attempt to assign ${l}`);ca(this)[c]=l};break}s[c]=u,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,u)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Et];return u?.[o]!==void 0?u[o]:this[ce]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Au.ClientError("Can not add a property to a sealed table schema");ca(this)[o]=c}),i("deleteProperty",function(o){ca(this)[o]=void 0}),i("toJSON",function(){let o=this[Et],c;for(let l in o)c||(c=Object.assign({},this[ce])),c[l]=o[l];return Object.keys(this).length>0&&(c||(c=Object.assign({},this[ce])),Object.assign(c,this)),c||this[ce]}),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 Rg(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){this[ce]=n}},yu(r,t)),new r(e)):new Ou(e);case Array:let s=new bu(e.length);s[ce]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=Rg(o,t?.elements)),s[n]=o}return s}}function Iu(e){let t=e[Et],r;for(let n in t){r||(r=Object.assign({},e[ce]));let i=t[n];i&&typeof i=="object"&&(i=Iu(i)),r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[ce])),Object.assign(r,e)),r||e[ce]}function ua(e){let t;if(e[ce]&&e.constructor===Array&&!Object.isFrozen(e)){t=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=ua(i);o!==i&&t===e&&(t=e.slice(0)),i=o}t[s]=i}return Object.freeze(t)}let r=e[Et];for(let s in r){t||(t=Object.assign({},e[ce]));let n=r[s];n&&typeof n=="object"&&(n=ua(n)),t[s]=n}return t?Object.freeze(t):e[ce]||Object.freeze(e)}function Nu(e){let t=e[ce];if(!t)return!0;if(e.constructor===Array){if(e[kn]||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?.[ce]===n){if(Nu(i))return!0}else return!0}}else{let r=e[Et];for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[ce]===i){if(Nu(n))return!0}else return!0}else return!0}}return!1}var Au,Et,Ou,kn,bu,wu=pe(()=>{Xr();Au=D(W()),Et=Symbol("own-data");a(ca,"getChanges");a(yu,"assignTrackedAccessors");a(Rg,"trackObject");Ou=class{static{a(this,"GenericTrackedObject")}constructor(t){this[ce]=t}};yu(Ou,{});a(Iu,"collapseData");a(ua,"deepFreeze");a(Nu,"hasChanges");kn=Symbol.for("has-array-changes"),bu=class extends Array{static{a(this,"TrackedArray")}[kn];constructor(t){super(t)}splice(...t){return this[kn]=!0,super.splice(...t)}push(...t){return this[kn]=!0,super.push(...t)}pop(){return this[kn]=!0,super.pop()}unshift(...t){return this[kn]=!0,super.unshift(...t)}shift(){return this[kn]=!0,super.shift()}};bu.prototype.constructor=Array});function Ye(e,t){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let r=e.transaction=new ME;e.timestamp&&(r.timestamp=e.timestamp),r[Oe]=e,e.resourceCache=[];let s;try{if(s=t(r),s?.then)return s.then(n,i)}catch(o){i(o)}return n(s);function n(o){let c=r.commit();return c.then?c.then(()=>(e.transaction=null,o)):(e.transaction=null,o)}function i(o){throw r.abort(),e.transaction=null,o}}var gg,Ag,ME,Vn=pe(()=>{gg=D(vt()),Ag=require("../../index");Xr();a(Ye,"transaction");(0,Ag._assignPackageExport)("transaction",Ye);Ye.commit=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ye.abort=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()};ME=class extends Array{static{a(this,"TransactionSet")}commit(t=!0){let r=[],s=this.length;for(let n=0;n<s;n++)this[n].validate?.();this.timestamp||(this.timestamp=(0,gg.getNextMonotonicTime)());for(let n=0;n<s;n++){let o=this[n].commit(this.timestamp,t);o?.then&&r.push(o)}return r.length>0?Promise.all(r).then(()=>(this.splice(0,s),this.commit(t))):this.length>s?(this.splice(0,s),this.commit(t)):(this.length=0,{txnTime:this.timestamp})}abort(){for(let t of this)t.abort?.()}doneReading(){for(let t of this)t.doneReading?.()}}});function BE(e,t,r,s,n){let i=e[0]??e.attribute,o,c,u,l,_=e[1]??e.value;_ instanceof Date&&(_=_.getTime());let d=e.comparator,E;switch(hF[d]||d){case"lt":o=!0,c=_;break;case"le":o=!0,c=_,u=!0;break;case"gt":o=_,l=!0;break;case"ge":o=_;break;case"prefix":o=_,c=_.slice(0),c[c.length-1]=jr.MAXIMUM_KEY;break;case"starts_with":o=_.toString(),c=_+String.fromCharCode(65535);break;case"between":o=_[0],o instanceof Date&&(o=o.getTime()),c=_[1],c instanceof Date&&(c=c.getTime()),u=!0;break;case lt.SEARCH_TYPES.EQUALS:case void 0:o=_,c=_,u=!0;break;case"ne":case"contains":case"ends_with":E=!0;break}if(r){let S=o;o=c,c=S,S=!l,l=!u,u=S}let f=i===s.primaryKey||i==null,h=f?s.primaryStore:s.indices[i];if(!h||h.isIndexing||E){if(!n)throw new PE.ClientError(`"${i}" is not indexed${h?.isIndexing?" yet":""}, can not search for this attribute`,404);let S=HE(e);if(!S)throw new PE.ClientError(`Unknown search operator ${e.comparator}`);return s.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:y,value:O})=>new Promise(H=>setImmediate(()=>H(S(O)?y:Ng.SKIP))))}let T={start:o,end:c,inclusiveEnd:u,exclusiveStart:l,values:!f,transaction:t,reverse:r};return f?h.getRange(T):h.getRange(T).map(({value:S})=>S)}function HE(e){let t=e.comparator,r=e[0]??e.attribute,s=e[1]??e.value;switch(s instanceof Date&&(s=s.getTime()),t){case lt.SEARCH_TYPES.EQUALS:case void 0:return Zr(r,n=>n===s);case lt.SEARCH_TYPES.CONTAINS:return Zr(r,n=>n?.toString().includes(s));case lt.SEARCH_TYPES.ENDS_WITH:case lt.SEARCH_TYPES._ENDS_WITH:return Zr(r,n=>n?.toString().endsWith(s));case lt.SEARCH_TYPES.STARTS_WITH:case lt.SEARCH_TYPES._STARTS_WITH:return Zr(r,n=>typeof n=="string"&&n.startsWith(s));case lt.SEARCH_TYPES.BETWEEN:return s[0]instanceof Date&&(s[0]=s[0].getTime()),s[1]instanceof Date&&(s[1]=s[1].getTime()),Zr(r,n=>(0,jr.compareKeys)(n,s[0])>=0&&(0,jr.compareKeys)(n,s[1])<=0);case"gt":case lt.SEARCH_TYPES.GREATER_THAN:case lt.SEARCH_TYPES._GREATER_THAN:return Zr(r,n=>(0,jr.compareKeys)(n,s)>0);case"ge":case lt.SEARCH_TYPES.GREATER_THAN_EQUAL:case lt.SEARCH_TYPES._GREATER_THAN_EQUAL:return Zr(r,n=>(0,jr.compareKeys)(n,s)>=0);case lt.SEARCH_TYPES.LESS_THAN:case"lt":case lt.SEARCH_TYPES._LESS_THAN:return Zr(r,n=>(0,jr.compareKeys)(n,s)<0);case"le":case lt.SEARCH_TYPES.LESS_THAN_EQUAL:case lt.SEARCH_TYPES._LESS_THAN_EQUAL:return Zr(r,n=>(0,jr.compareKeys)(n,s)<=0);case"ne":return Zr(r,n=>(0,jr.compareKeys)(n,s)!==0);default:return}}function Zr(e,t){return r=>{let s=r[e];return typeof s!="object"||!s?t(s):Array.isArray(s)?s.some(t):s instanceof Date?t(s.getTime()):!1}}function Cu(e){if(!e)return;let t=new vE,r,s,n,i,o;for(;r=Og.exec(e);){i=Og.lastIndex;let[,c,u]=r;switch(u){case")":switch(o){case"limit":if(c.indexOf(",")>-1){let[l,_]=c.split(",");t.offset=+l,t.limit=_-t.offset}else t.limit=+c;break;case"select":if(c[0]==="["){if(c[c.length-1]!=="]")throw new Error("Unmatched brackets");t.select=c.slice(1,-1).split(","),t.select.asArray=!0}else c.indexOf(",")>-1?t.select=(c.endsWith(",")?c.slice(0,-1):c).split(","):t.select=c;break;case"group-by":throw new Error("Group by is not implemented yet");case"sort":t.sort=c.split(",").map(l=>{switch(l[0]){case"-":return{attribute:l.slice(1),descending:!0};case"+":return{attribute:l.slice(1),descending:!1};default:return{attribute:l,descending:!1}}});break;default:throw new Error(`Unknown query function call ${o}`)}break;case"(":o=c;break;case"=":s?c.length<=2&&(n=c):(n="equals",s=decodeURIComponent(c));break;case"!=":case"<":case"<=":case">":case">=":n=fF[u],s=decodeURIComponent(c);break;case"=*":n="ends_with",s=decodeURIComponent(c);break;case"*":case"*&":t.conditions.push({comparator:n==="ends_with"?"contains":"starts_with",attribute:s,value:decodeURIComponent(c)}),s=null;break;case"":case void 0:case"&":case"|":if(!s)throw new Error(`Unable to parse query, no part before ${u} at ${i} in ${e}`);t.conditions.push({comparator:n,attribute:s,value:decodeURIComponent(c)}),s=void 0;break;default:throw new Error(`Unknown operator ${u} in query ${e}`)}}if(i!==e.length)throw new Error(`Unable to parse query, unexpected end in ${e}`);return t}var PE,lt,jr,Ng,Og,fF,hF,vE,Uu=pe(()=>{PE=D(W()),lt=D(xe()),jr=require("ordered-binary"),Ng=require("lmdb"),Og=/([^?&|=<>!()*]+)([&|=<>!()*]*)/g,fF={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne"};a(BE,"idsForCondition");hF={greater_than:"gt",greater_than_equal:"ge",less_than:"lt",less_than_equal:"le",not_equal:"ne",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(HE,"filterByType");a(Zr,"attributeComparator");a(Cu,"parseQuery");vE=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}}}});var GE={};Ze(GE,{CONTEXT:()=>Oe,ID_PROPERTY:()=>ie,IS_COLLECTION:()=>Cs,RECORD_PROPERTY:()=>ce,Resource:()=>ft,SAVE_UPDATES_PROPERTY:()=>Ug,snake_case:()=>SF});function SF(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function bg(e,t){if(e=e.slice(1),e.indexOf("/")===-1)return e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e));let r=e.split("/"),s=new FE(r.length);for(let n=0;n<r.length;n++)s[n]=t.coerceId(decodeURIComponent(r[n]));return s}function Lr(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[Oe]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Oe]||i):l=i:(l=n,c=l[ie]??l[this.primaryKey]??null):i?o=i[Oe]||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=[];for(let d of n){if(typeof d=="object"&&d)break;c.push(d)}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)))}else{if(typeof(c=n.url)=="string"){let d=c.indexOf("?");if(d>-1){let f=this.parseQuery(c.slice(d+1));u?u=Object.assign(f,u):u=f,c=c.slice(0,d)}let E=this.parsePath(c,o,u);E?.query?(u=E.query,c=E.id):c=E}c===void 0&&(c=n.id??null)}else c=n??null;if(o||(o={}),t.allowInvalidated&&(o.allowInvalidated=!0),o.transaction){let d=this.getResource(c,o,t);return d.then?d.then(_):_(d)}else return Ye(o,()=>{let d=this.getResource(c,o,t);return d.then?d.then(_):_(d)});function _(d){if(t.type==="read"&&(d[Ug]=!1),o.authorize){o.authorize=!1;let E=t.type==="read"?d.allowRead(o.user,o):t.type==="update"?d.doesExist?.()===!1?d.allowCreate(o.user,o):d.allowUpdate(o.user,o):t.type==="create"?d.allowCreate(o.user,o):d.allowDelete(o.user,o);if(E?.then)return E.then(f=>{if(!f)throw new Du(o.user);return typeof l?.then=="function"?l.then(h=>e(d,u,o,h)):e(d,u,o,l)});if(!E)throw new Du(o.user)}return typeof l?.then=="function"?l.then(E=>e(d,u,o,E)):e(d,u,o,l)}a(_,"authorizeActionOnResource")}}function Mr(e,t){let r=new Cg.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 qE(e){let t=e[ce];if(t){let r=e[Et];return s=>{let n;return e.hasOwnProperty(s)&&typeof(n=e[s])!="function"?n:r&&s in r?r[s]:t[s]}}else return r=>e[r]}function yg(e){if(typeof e=="string")return t=>qE(t)(e);if(typeof e=="object"){if(e.asArray)return r=>{let s=[],n=qE(r);for(let i of e)s.push(n(i));return s};let t=e.forceNulls;return r=>{let s={},n=qE(r);for(let i of e){let o=n(i);o===void 0&&t&&(o=null),s[i]=o}return s}}else throw new Error("Invalid select argument type "+typeof e)}var Ig,wg,Cg,Oe,ie,Cs,Ug,ce,mF,ft,Du,FE,Xr=pe(()=>{Ig=require("crypto");aa();wg=require("../../index"),Cg=D(W());wu();Vn();Uu();Oe=Symbol.for("context"),ie=Symbol.for("primary-key"),Cs=Symbol("is-collection"),Ug=Symbol("save-updates"),ce=Symbol("stored-record"),mF={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},ft=class{static{a(this,"Resource")}[Oe];[ie];static transactions;constructor(t,r){this[ie]=t;let s=r?.[Oe];this[Oe]=s!==void 0?s:r||null}updateModificationTime(t=Date.now()){t>this[LAST_MODIFICATION_PROPERTY]&&(this[LAST_MODIFICATION_PROPERTY]=t)}static get=Lr(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){let l=yg(u);return typeof c?.map=="function"?c.map(l):l(c)}return c}},{type:"read"});static put=Lr(function(t,r,s,n){if(Array.isArray(n)&&t[Cs]){let i=[],o=s.authorize;for(let c of n)o&&(s.authorize=!0),i.push(this.put(t,r,s,c));return i}return t.put?t.put(n,r):Mr(t,"put")},{hasContent:!0,type:"update"});static delete=Lr(function(t,r,s,n){return t.delete?t.delete(r):Mr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,Ig.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),Ye(s,()=>{let i=new this(n,s),o=i.put?i.put(r):Mr(i,"put");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static post=Lr(function(t,r,s,n){return t[ie]!=null&&t.update(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Lr(function(t,r,s,n){return t.connect?t.connect(r):Mr(t,"connect")},{type:"read"});static subscribe=Lr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Mr(t,"subscribe")},{type:"read"});static publish=Lr(function(t,r,s,n){return t[ie]!=null&&t.update(),t.publish?t.publish(n,r):Mr(t,"publish")},{hasContent:!0,type:"create"});static search=Lr(function(t,r,s,n){let i=t.search?t.search(s):Mr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null){let c=yg(o);return i.map(c)}return i},{type:"read"});static query=Lr(function(t,r,s,n){return t.search?t.search(n,r):Mr(t,"search")},{hasContent:!0,type:"read"});static copy=Lr(function(t,r,s,n){return t.copy?t.copy(s.headers?.destination,r):Mr(t,"copy")},{type:"create"});static move=Lr(function(t,r,s,n){return t.move?t.move(s.headers?.destination,r):Mr(t,"move")},{type:"delete"});post(t){if(this[Cs])return this.constructor.create(this[ie],t,this[Oe]);Mr(this,"post")}static isCollection(t){return t?.[Cs]}static coerceId(t){return t}static parseQuery(t){return Cu(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let i=t.slice(n+1);t=t.slice(0,n);let o=r?.headers&&mF[i];if(o)r.headers.accept=o;else if(s)s.property=i;else return{query:{property:i},id:bg(t,this)}}return bg(t,this)}static getResource(t,r,s){let n,i=r[Oe],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=t==null||Array.isArray(t)&&t[t.length-1]==null;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 l=u.asMap.get(t);if(n=l?.find(_=>_.constructor===c),n)return n;l||u.asMap.set(t,l=[]),l.push(n=new c(t,i))}else{if(n=u.find(l=>l[ie]===t&&l.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let l=new Map;for(let _ of u){let d=_[ie],E=l.get(d);E?E.push(_):l.set(d,[_])}i.resourceCache.length=0,i.resourceCache.asMap=l}}}else n=new c(t,i);return o&&(n[Cs]=!0),n}connect(t){let r=new Jr;if(t?.subscribe!==!1){let s={listener:i=>{r.send(i)}},n=this.subscribe?.(s);r.on("close",()=>n?.end())}return r}update(t){throw new Error("Not implemented")}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[ie]}getContext(){return this[Oe]}};ft.prototype[Oe]=null;(0,wg._assignPackageExport)("Resource",ft);a(SF,"snake_case");Du=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.http_resp_code=403):(super("Must login"),this.http_resp_code=401)}};a(bg,"pathToId");FE=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Lr,"transactional");a(Mr,"missingMethod");a(qE,"selectFromObject");a(yg,"transformForSelect")});var Lu={};Ze(Lu,{server:()=>ht});var Dg,ht,Us=pe(()=>{Dg=require("../../index"),ht={};(0,Dg._assignPackageExport)("server",ht)});var VE={};Ze(VE,{loadGQLSchema:()=>TF,start:()=>kE,startOnMainThread:()=>pF});function kE({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:l,StringValueNode:_}=await import("graphql"),d=o(new c(r.toString(),n)),E=new Map,f=[],h;for(let T of d.definitions)switch(T.kind){case u.OBJECT_TYPE_DEFINITION:let Y=function(A){if(A.kind==="NonNullType"){let G=Y(A.type);return G.nullable=!0,G}return A.kind==="ListType"?{type:"array",elements:Y(A.type)}:{type:A.name?.value}};a(Y,"getProperty");let S=T.name.value,y=[],O={table:null,database:null,properties:y};E.set(S,O);for(let A of T.directives){if(A.name.value==="table"){for(let w of A.arguments)O[w.name.value]=w.value.value;O.schema&&(O.database=O.schema),O.table||(O.table=S),O.audit&&(O.audit=O.audit!=="false"),O.attributes=O.properties,f.push(O)}if(A.name.value==="sealed"&&(O.sealed=!0),A.name.value==="export"){O.export=!0;for(let w of A.arguments)w.name.value==="name"&&(O.export={name:w.value.value})}}let H=!1;for(let A of T.fields){let w=Y(A.type);w.name=A.name.value,y.push(w);for(let G of A.directives)if(G.name.value==="primaryKey")H?console.warn("Can not define two attributes as a primary key"):(w.isPrimaryKey=!0,H=!0);else if(G.name.value==="indexed")w.indexed=!0;else if(G.name.value==="createdTime")w.assignCreatedTime=!0;else if(G.name.value==="updatedTime")w.assignUpdatedTime=!0;else if(G.name.value==="expiresAt")w.expiresAt=!0;else if(G.name.value==="allow"){let k=w.authorizedRoles=[];for(let X of G.arguments)X.name.value==="role"&&k.push(X.value.value)}}O.typeName=S,S==="Query"&&(h=O)}for(let[T,S]of E)for(let y of S.properties){let O=E.get(y.type);O&&(y.properties=O.properties)}for(let T of f)T.tableClass=e(T),T.export&&i.set((0,xE.dirname)(s)+"/"+(T.export.name||T.typeName),T.tableClass);if(h)for(let T of h.properties){let S=E.get(T.type);if(!S)throw new Error(`${T.type} was not found as a Query export`);i.set((0,xE.dirname)(s)+"/"+T.name,S.tableClass)}}}var xE,pF,TF,Lg=pe(()=>{xE=require("path");de();a(kE,"start");pF=kE,TF=kE({ensureTable:et}).handleFile});async function Mu(e){return RF?(la||(la=gF(OF)),(await(await la).import(e)).namespace):import(e)}async function gF(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),la=new Compartment({console,Math,Date,fetch:AF,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,Pg.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:sr,databases:Pe})}};let s=await(0,Mg.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),la}function AF(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 OF(){return{Resource:ft,tables:sr}}var Mg,Pg,RF,la,$E=pe(()=>{Xr();de();Mg=require("fs/promises"),Pg=require("path"),RF=!1;a(Mu,"secureImport");a(gF,"getCompartment");a(AF,"secureOnlyFetch");a(OF,"getGlobalVars")});var KE={};Ze(KE,{handleFile:()=>NF});async function NF(e,t,r,s){let n=new Map,i=(0,vg.pathToFileURL)(r).toString(),o=await Mu(i);u(o.default)&&s.set((0,YE.dirname)(t),o.default),c(o,(0,YE.dirname)(t));function c(l,_){for(let d in l){let E=l[d];u(E)?s.set(_+"/"+d,E):typeof E=="object"&&c(E,_+"/"+d)}}a(c,"recurseForResources");function u(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return a(u,"isResource"),n}var vg,YE,Bg=pe(()=>{vg=require("url");$E();YE=require("path");a(NF,"handleFile")});var QE={};Ze(QE,{start:()=>bF});function bF({resources:e}){e.set("login",WE),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var WE,Hg=pe(()=>{Xr();a(bF,"start");WE=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 JE=m((Vre,Gg)=>{"use strict";var{Readable:yF}=require("stream"),IF=1e4;Gg.exports={streamAsJSON(e){return new zE({value:e})}};var zE=class extends yF{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0)}*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](),o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){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),qg)}catch(n){yield qg(n)}else yield JSON.stringify(t)}else yield JSON.stringify(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Fg(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>IF?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 Fg(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}}};function qg(e){return console.error(e),JSON.stringify(e.toString())}a(qg,"handleError");function Fg(e,t,r){return e&&e.then?r?e.then(t,r):e.then(t):t(e)}a(Fg,"when")});var jg=m((Kre,Zg)=>{"use strict";var XE=require("recursive-iterator"),wF=require("alasql"),ZE=require("clone"),xg=x(),{handleHDBError:kg,hdb_errors:CF}=W(),{HDB_ERROR_MSGS:Vg,HTTP_STATUS_CODES:$g}=CF,{getDatabases:UF}=(de(),te(Ne)),DF=["DISTINCT_ARRAY"],Yg=Symbol("validateTables"),jE=Symbol("validateTable"),Yre=Symbol("getAllColumns"),Kg=Symbol("validateAllColumns"),Pu=Symbol("findColumn"),Wg=Symbol("validateOrderBy"),_a=Symbol("validateSegment"),ef=Symbol("validateColumn"),Qg=Symbol("setColumnsForTable"),zg=Symbol("checkColumnsForAsterisk"),Jg=Symbol("validateGroupBy"),Xg=Symbol("hasColumns"),tf=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Yg](),this[zg](),this[Kg]()}[Yg](){if(this[Xg]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[jE](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[jE](t.table)})}}[Xg](){let t=!1,r=new XE(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[jE](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=UF();if(!r[t.databaseid])throw kg(new Error,Vg.SCHEMA_NOT_FOUND(t.databaseid),$g.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw kg(new Error,Vg.TABLE_NOT_FOUND(t.databaseid,t.tableid),$g.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=ZE(n);i.table=ZE(t),this.attributes.push(i)})}[Pu](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)}[zg](){let t=new XE(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[Qg](r.tableid)}[Qg](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new wF.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Kg](){this[_a](this.statement.columns,!1),this[_a](this.statement.joins,!1),this[_a](this.statement.where,!1),this[Jg](this.statement.group,!1),this[_a](this.statement.order,!0)}[_a](t,r){if(!t)return;let s=new XE(t),n=[];for(let{node:i,path:o}of s)!xg.isEmpty(i)&&!xg.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Wg](i):n.push(this[ef](i)));return n}[Jg](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&DF.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=ZE(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Pu](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[Pu](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`}[Wg](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[ef](t)}[ef](t){let r=this[Pu](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]}};Zg.exports=tf});var tA=m((Qre,eA)=>{"use strict";var rf=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")}};eA.exports=rf});var sA=m((Jre,rA)=>{"use strict";var sf=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};rA.exports=sf});var vu=m((Zre,nA)=>{"use strict";var of=Q(),af=g();of.initSync();var LF=of.get(af.CONFIG_PARAMS.STORAGE_COMPRESSION),MF=of.get(af.CONFIG_PARAMS.STORAGE_CACHING)!==!1,PF=af.UPDATES_PROPERTY,nf=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=LF&&r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=MF&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.alwaysLazyProperty=s=>s===PF)}};nA.exports=nf});var Hu=m((ese,oA)=>{"use strict";var qi=Q(),da=g();qi.initSync();var vF=qi.get(da.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||qi.get(da.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||qi.get(da.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",iA=qi.get(da.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),BF=qi.get(da.CONFIG_PARAMS.STORAGE_NOREADAHEAD),Bu=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=vF,this.noFSAccess=!0,iA!==void 0&&(this.overlappingSync=iA),this.noReadAhead=BF}};oA.exports=Bu;Bu.MAX_DBS=1e4});var ye=m((rse,mA)=>{"use strict";var uf=require("lmdb"),Pr=require("fs-extra"),nr=require("path"),qu=vt(),uA=F(),Bt=rr().LMDB_ERRORS_ENUM,Fu=sA(),lf=vu(),lA=Hu(),un=xe(),aA=g(),{table:HF,resetDatabases:qF}=(de(),te(Ne)),cA=Q(),vr=un.INTERNAL_DBIS_NAME,_A=un.DBI_DEFINITION_NAME,FF="data.mdb",GF="lock.mdb",Ea=".mdb",xF="-lock",cf=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=pr(t,r),this.key_type=this.dbi[un.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[un.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new uf.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function Gu(e,t){if(e===void 0)throw new Error(Bt.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Bt.ENV_NAME_REQUIRED)}a(Gu,"pathEnvNameValidation");async function _f(e,t,r=!0){try{await Pr.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Bt.INVALID_BASE_PATH):s}try{let s=nr.join(e,t+Ea);return await Pr.access(s,Pr.constants.R_OK|Pr.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Pr.access(nr.join(e,t,FF),Pr.constants.R_OK|Pr.constants.F_OK),nr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Bt.INVALID_ENVIRONMENT)}else throw new Error(Bt.INVALID_ENVIRONMENT);throw s}}a(_f,"validateEnvironmentPath");function xu(e,t){if(qu.validateEnv(e),t===void 0)throw new Error(Bt.DBI_NAME_REQUIRED)}a(xu,"validateEnvDBIName");async function kF(e,t,r=!1,s=!1){Gu(e,t);let n=nr.basename(e);t=t.toString();let i=cA.get(aA.CONFIG_PARAMS.SCHEMAS);i||cA.setProperty(aA.CONFIG_PARAMS.SCHEMAS,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await _f(e,t,s),dA(e,t,r)}catch(o){if(o.message===Bt.INVALID_ENVIRONMENT){let c=nr.join(e,t);await Pr.mkdirp(s?c:e);let u=new lA(s?c:c+Ea,!1),l=uf.open(u);l.dbis=Object.create(null);let _=new lf(!1);l.openDB(vr,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=df(e,t,r);return l[un.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=l,l}throw o}}a(kF,"createEnvironment");async function VF(e,t,r,s=!0){Gu(e,t),t=t.toString();let n=nr.join(e,t);return HF({table:t,database:nr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(VF,"copyEnvironment");async function dA(e,t,r=!1){Gu(e,t),t=t.toString();let s=df(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 _f(e,t),i=nr.join(e,t+Ea),o=n!=i,c=new lA(n,o),u=uf.open(c);u.dbis=Object.create(null);let l=fA(u);for(let _=0;_<l.length;_++)pr(u,l[_]);return u[un.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(dA,"openEnvironment");async function $F(e,t,r=!1){Gu(e,t),t=t.toString();let s=nr.join(e,t+Ea),n=await _f(e,t);if(global.lmdb_map!==void 0){let i=df(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await EA(o),delete global.lmdb_map[i]}}await Pr.remove(n),await Pr.remove(n===s?n+xF:nr.join(nr.dirname(n),GF))}a($F,"deleteEnvironment");async function EA(e){qu.validateEnv(e);let t=e[un.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(EA,"closeEnvironment");function df(e,t,r=!1){let n=`${nr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(df,"getCachedEnvironmentName");function YF(e){qu.validateEnv(e);let t=Object.create(null),r=pr(e,vr);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==vr)try{t[s]=Object.assign(new Fu,n)}catch{uA.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(YF,"listDBIDefinitions");function fA(e){qu.validateEnv(e);let t=[],r=pr(e,vr);for(let{key:s}of r.getRange({start:!1}))s!==vr&&t.push(s);return t}a(fA,"listDBIs");function KF(e,t){let s=pr(e,vr).getEntry(t),n=new Fu;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{uA.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(KF,"getDBIDefinition");function hA(e,t,r,s=!r){if(xu(e,t),t=t.toString(),t===vr)throw new Error(Bt.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return pr(e,t)}catch(n){if(n.message===Bt.DBI_DOES_NOT_EXIST){let i=new lf(r,s===!0),o=e.openDB(t,i),c=new Fu(r===!0,s);return o[_A]=c,pr(e,vr).putSync(t,c),e.dbis[t]=o,o}throw n}}a(hA,"createDBI");function pr(e,t){if(xu(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==vr?r=KF(e,t):r=new Fu,r===void 0)throw new Error(Bt.DBI_DOES_NOT_EXIST);let s;try{let n=new lf(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(Bt.DBI_DOES_NOT_EXIST):n}return s[_A]=r,e.dbis[t]=s,s}a(pr,"openDBI");function WF(e,t){xu(e,t),t=t.toString();let r=pr(e,t),s=r.getStats();return r[un.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(WF,"statDBI");async function QF(e,t){try{let r=nr.join(e,t+Ea);return(await Pr.stat(r)).size}catch{throw new Error(Bt.INVALID_ENVIRONMENT)}}a(QF,"environmentDataSize");function zF(e,t){if(xu(e,t),t=t.toString(),t===vr)throw new Error(Bt.CANNOT_DROP_INTERNAL_DBIS_NAME);pr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],pr(e,vr).removeSync(t)}a(zF,"dropDBI");function JF(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{pr(e,i)}catch(o){if(o.message===Bt.DBI_DOES_NOT_EXIST)hA(e,i,i!==t,i===t),s=!0;else throw o}}s&&qF()}a(JF,"initializeDBIs");mA.exports={openDBI:pr,openEnvironment:dA,createEnvironment:kF,listDBIs:fA,listDBIDefinitions:YF,createDBI:hA,dropDBI:zF,statDBI:WF,deleteEnvironment:$F,initializeDBIs:JF,TransactionCursor:cf,environmentDataSize:QF,copyEnvironment:VF,closeEnvironment:EA}});var pA=m((nse,SA)=>{"use strict";var Ef=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};SA.exports=Ef});var RA=m((ose,TA)=>{"use strict";var ff=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}};TA.exports=ff});var AA=m((cse,gA)=>{"use strict";var hf=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};gA.exports=hf});var Fi=m((Ese,bA)=>{"use strict";var XF=ye(),ZF=pA(),jF=RA(),eG=AA(),es=vt(),fa=rr().LMDB_ERRORS_ENUM,tG=xe(),Ds=g(),rG=x(),sG=require("uuid"),lse=require("lmdb"),{handleHDBError:nG,hdb_errors:iG}=W(),{OVERFLOW_MARKER:_se,MAX_SEARCH_KEY_LENGTH:dse}=tG,OA=Q();OA.initSync();var ku=OA.get(Ds.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),mf=Ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME,$n=Ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function oG(e,t,r,s,n=es.getNextMonotonicTime()){Rf(e,t,r,s),Sf(e,t,r);let i=new ZF,o=[],c=[];for(let u=0;u<s.length;u++){let l=s[u];NA(l,!0,n);let _=aG(e,t,r,l),d=l[t];o.push(_),c.push(d)}return pf(o,c,s,i,n)}a(oG,"insertRecords");function aG(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 _=c([[{}]]);Array.isArray(_)&&(c=_[0][Ds.FUNC_VAL],s[o]=c)}let u=es.getIndexedValues(c),l=e.dbis[o];if(u){ku&&l.prefetch(u.map(_=>({key:_,value:n})),Vu);for(let _=0,d=u.length;_<d;_++)l.put(u[_],n)}}ku&&e.dbis[t].prefetch([n],Vu),e.dbis[t].put(n,s,s[$n])})}a(aG,"insertRecord");function cG(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(cG,"removeSkippedRecords");function NA(e,t,r){let s=r>0;(s||!Number.isInteger(e[$n]))&&(e[$n]=r||(r=es.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[mf]))&&(e[mf]=r||es.getNextMonotonicTime()):delete e[mf]}a(NA,"setTimestamps");function Sf(e,t,r){r.indexOf(Ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),XF.initializeDBIs(e,t,r)}a(Sf,"initializeTransaction");async function uG(e,t,r,s,n=es.getNextMonotonicTime()){Rf(e,t,r,s),Sf(e,t,r);let i=new jF,o=[],c=[],u=[];for(let l=0;l<s.length;l++){let _=s[l],d=_[t],E;try{E=Tf(e,t,_,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(l);continue}c.push(E),u.push(d)}return pf(c,u,s,i,n,o)}a(uG,"updateRecords");async function lG(e,t,r,s,n=es.getNextMonotonicTime()){try{Rf(e,t,r,s)}catch(u){throw nG(u,u.message,iG.HTTP_STATUS_CODES.BAD_REQUEST)}Sf(e,t,r);let i=new eG,o=[],c=[];for(let u=0;u<s.length;u++){let l=s[u],_;rG.isEmpty(l[t])?(_=sG.v4(),l[t]=_):_=l[t];let d=Tf(e,t,l,_,i,!1,n);o.push(d),c.push(_)}return pf(o,c,s,i,n)}a(lG,"upsertRecords");async function pf(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||es.getNextMonotonicTime(),cG(r,i),s}a(pf,"finalizeWrite");function Tf(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),l=u?.value,_=l;if(!l){if(i)return!1;l={}}if(NA(r,!_,o),Number.isInteger(r[$n])&&l[$n]>r[$n])return!1;_&&n.original_records.push(l);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let T=r[h],S=e.dbis[h];if(S===void 0)continue;let y=l[h];if(typeof T=="function"){let H=T([[l]]);Array.isArray(H)&&(T=H[0][Ds.FUNC_VAL],r[h]=T)}if(T===y)continue;let O=es.getIndexedValues(y);if(O){ku&&S.prefetch(O.map(H=>({key:H,value:s})),Vu);for(let H=0,Y=O.length;H<Y;H++)S.remove(O[H],s)}if(O=es.getIndexedValues(T),O){ku&&S.prefetch(O.map(H=>({key:H,value:s})),Vu);for(let H=0,Y=O.length;H<Y;H++)S.put(O[H],s)}}let f=Object.assign({},l,r);c.put(s,f,f[$n])},"do_put");return u?d=c.ifVersion(s,u.version,E):d=c.ifNoExists(s,E),d.then(f=>f?!0:Tf(e,t,r,s,n,i,o))}a(Tf,"updateUpsertRecord");function _G(e,t,r){if(es.validateEnv(e),t===void 0)throw new Error(fa.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(fa.WRITE_ATTRIBUTES_REQUIRED):new Error(fa.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(_G,"validateBasic");function Rf(e,t,r,s){if(_G(e,t,r),!Array.isArray(s))throw s===void 0?new Error(fa.RECORDS_REQUIRED):new Error(fa.RECORDS_MUST_BE_ARRAY)}a(Rf,"validateWrite");function Vu(){}a(Vu,"noop");bA.exports={insertRecords:oG,updateRecords:uG,upsertRecords:lG}});var Yn=m((hse,dG)=>{dG.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",attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var ts=m((mse,wA)=>{"use strict";var IA=x(),yA=g(),Gi=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Ls=require("joi"),ln={schema_format:{pattern:Gi,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},EG=Ls.alternatives(Ls.string().min(1).max(ln.schema_length.maximum).pattern(Gi).messages({"string.pattern.base":"{:#label} "+ln.schema_format.message}),Ls.number()).required(),fG=Ls.alternatives(Ls.string().min(1).max(ln.schema_length.maximum).pattern(Gi).messages({"string.pattern.base":"{:#label} "+ln.schema_format.message}),Ls.number()),hG=Ls.alternatives(Ls.string().min(1).max(ln.schema_length.maximum).pattern(Gi).messages({"string.pattern.base":"{:#label} "+ln.schema_format.message}),Ls.number()).required();function mG(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ln.schema_length.maximum?`'${e}' maximum of 250 characters`:Gi.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(mG,"checkValidTable");function SG(e,t){return IA.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(SG,"validateSchemaExists");function pG(e,t){let r=t.state.ancestors[0].schema;return IA.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(pG,"validateTableExists");function TG(e,t){return e.toLowerCase()===yA.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${yA.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(TG,"validateSchemaName");wA.exports={common_validators:ln,schema_regex:Gi,hdb_schema_table:EG,validateSchemaExists:SG,validateTableExists:pG,validateSchemaName:TG,checkValidTable:mG,hdb_database:fG,hdb_table:hG}});var ve=m((pse,CA)=>{"use strict";var Ht=require("validate.js");Ht.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||Ht.validators.type.checks[t](e)?null:` must be a '${t}' value`};Ht.validators.type.checks={Object:function(e){return Ht.isObject(e)&&!Ht.isArray(e)},Array:Ht.isArray,Integer:Ht.isInteger,Number:Ht.isNumber,String:Ht.isString,Date:Ht.isDate,Boolean:function(e){return typeof e=="boolean"}};Ht.validators.hasValidFileExt=function(e,t){return Ht.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};CA.exports={validateObject:RG,validateObjectAsync:gG,validateBySchema:AG};function RG(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=Ht(e,t,{format:"flat"});return r?new Error(r):null}a(RG,"validateObject");async function gG(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await Ht.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(gG,"validateObjectAsync");function AG(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(AG,"validateBySchema")});var $u=m((Rse,UA)=>{var{common_validators:rs}=ts(),ma=ve(),ha="is required",Ke={database:{presence:!1,format:rs.schema_format,length:rs.schema_length},schema:{presence:!1,format:rs.schema_format,length:rs.schema_length},table:{presence:!0,format:rs.schema_format,length:rs.schema_length},attribute:{presence:!0,format:rs.schema_format,length:rs.schema_length},hash_attribute:{presence:!0,format:rs.schema_format,length:rs.schema_length}};function Sa(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(Sa,"makeAttributesStrings");function OG(e){return e=Sa(e),Ke.table.presence=!1,Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,ma.validateObject(e,Ke)}a(OG,"schema_object");function NG(e){return e=Sa(e),Ke.table.presence={message:ha},Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,ma.validateObject(e,Ke)}a(NG,"table_object");function bG(e){return e=Sa(e),Ke.table.presence={message:ha},Ke.attribute.presence=!1,ma.validateObject(e,Ke)}a(bG,"create_table_object");function yG(e){return e=Sa(e),Ke.table.presence={message:ha},Ke.attribute.presence={message:ha},Ke.hash_attribute.presence=!1,ma.validateObject(e,Ke)}a(yG,"attribute_object");function IG(e){return e=Sa(e),Ke.table.presence={message:ha},Ke.attribute.presence=!1,Ke.hash_attribute.presence=!1,ma.validateObject(e,Ke)}a(IG,"describe_table");function wG(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(wG,"validateTableResidence");UA.exports={schema_object:OG,create_table_object:bG,table_object:NG,attribute_object:yG,describe_table:IG,validateTableResidence:wG}});var LA=m((Ase,DA)=>{"use strict";var CG=require("uuid"),gf=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||CG.v4(),this.schema_table=`${this.schema}.${this.table}`}};DA.exports=gf});var Yu=m((Nse,MA)=>{"use strict";var UG=LA(),Af=class extends UG{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}};MA.exports=Af});var vA=m((yse,PA)=>{"use strict";PA.exports=LG;var DG="inserted";function LG(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===DG?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(LG,"returnObject")});var Ku=m((wse,GA)=>{"use strict";var MG=g(),Of=ye(),PG=Fi(),{getSystemSchemaPath:vG,getSchemaPath:BG}=we(),HG=Yn(),qG=$u(),FG=Yu(),GG=vA(),{handleHDBError:BA,hdb_errors:qA}=W(),HA=x(),{HTTP_STATUS_CODES:xG}=qA,Nf=HG.hdb_attribute,FA=[];for(let e=0;e<Nf.attributes.length;e++)FA.push(Nf.attributes[e].attribute);var kG="inserted";GA.exports=VG;async function VG(e){let t=qG.attribute_object(e);if(t)throw BA(new Error,t.message,qA.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&HA.checkGlobalSchemaTable(e.schema,e.table);if(r)throw BA(new Error,r,xG.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=HA.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 FG(e.schema,e.table,e.attribute,e.id);try{let i=await Of.openEnvironment(BG(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}`);Of.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Of.openEnvironment(vG(),MG.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await PG.insertRecords(o,Nf.hash_attribute,FA,[n]);return GG(kG,c,{records:[n]},u)}catch(i){throw i}}a(VG,"lmdbCreateAttribute")});var yf=m((Use,kA)=>{var{hdb_table:$G,hdb_database:xA}=ts(),YG=ve(),bf=require("joi"),KG={undefined:"undefined",null:"null"},WG=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||KG[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"),QG=bf.object({database:xA,schema:xA,table:$G,records:bf.array().items(bf.object().custom(WG)).required()});kA.exports=function(e){return YG.validateBySchema(e,QG)}});var pa=m((Mse,$A)=>{"use strict";var Ms=x(),VA=F(),Lse=yf(),{getDatabases:zG}=(de(),te(Ne)),{ClientError:Kn}=W();$A.exports=JG;function JG(e){if(Ms.isEmpty(e))throw new Kn("invalid update parameters defined.");if(Ms.isEmptyOrZeroLength(e.schema))throw new Kn("invalid schema specified.");if(Ms.isEmptyOrZeroLength(e.table))throw new Kn("invalid table specified.");if(!Array.isArray(e.records))throw new Kn("records must be an array");let t=zG()[e.schema]?.[e.table];if(Ms.isEmpty(t))throw new Kn(`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&&Ms.isEmptyOrZeroLength(o[r]))throw VA.error("a valid hash attribute must be provided with update record:",o),new Kn("a valid hash attribute must be provided with update record, check log for more info");if(!Ms.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw VA.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Kn(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Ms.isEmpty(o[r])&&o[r]!==""&&s.has(Ms.autoCast(o[r]))&&(o.skip=!0),s.add(Ms.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(JG,"insertUpdateValidate")});var Ta=m((vse,YA)=>{"use strict";var XG=g().OPERATIONS_ENUM,If=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=XG.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};YA.exports=If});var Oa=m((qse,KA)=>{"use strict";var Hse=Ta(),Wu=g(),Cf=x(),wf=F(),ZG=require("uuid"),{handleHDBError:Ra,hdb_errors:jG}=W(),{HDB_ERROR_MSGS:ga,HTTP_STATUS_CODES:Aa}=jG;KA.exports=ex;function ex(e,t,r){for(let n=0;n<t.length;n++)tx(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];rx(i,r,e.operation)}}a(ex,"processRows");function tx(e){if(Buffer.byteLength(String(e))>Wu.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Ra(new Error,ga.ATTR_NAME_LENGTH_ERR(e),Aa.BAD_REQUEST,void 0,void 0,!0);if(Cf.isEmptyOrZeroLength(e)||Cf.isEmpty(e.trim()))throw Ra(new Error,ga.ATTR_NAME_NULLISH_ERR,Aa.BAD_REQUEST,void 0,void 0,!0)}a(tx,"validateAttribute");function rx(e,t,r){if(!e.hasOwnProperty(t)||Cf.isEmptyOrZeroLength(e[t])){if(r===Wu.OPERATIONS_ENUM.INSERT||r===Wu.OPERATIONS_ENUM.UPSERT){e[t]=ZG.v4();return}throw wf.error("Update transaction aborted due to record with no hash value:",e),Ra(new Error,ga.RECORD_MISSING_HASH_ERR,Aa.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>Wu.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw wf.error(e),Ra(new Error,ga.HASH_VAL_LENGTH_ERR,Aa.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw wf.error(e),Ra(new Error,ga.INVALID_FORWARD_SLASH_IN_HASH_ERR,Aa.BAD_REQUEST,void 0,void 0,!0)}a(rx,"validateHash")});var QA=m((Gse,WA)=>{"use strict";var Uf=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};WA.exports=Uf});var XA=m((kse,JA)=>{"use strict";var Df=ye(),sx=F(),zA=rr().LMDB_ERRORS_ENUM;JA.exports=nx;async function nx(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 Df.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==zA.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Df.closeEnvironment(global.lmdb_map[s]),await Df.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==zA.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){sx.error(t)}}a(nx,"cleanLMDBMap")});var Ps=m(($se,tO)=>{"use strict";var Na=require("crypto"),ix=Q(),{CONFIG_PARAMS:ox}=g(),jA="aes-256-cbc",ax=32,cx=16,Lf=64,eO=32,ux=Lf+eO,ZA=new Map;tO.exports={encrypt:lx,decrypt:_x,createNatsTableStreamName:dx};function lx(e){let t=Na.randomBytes(ax),r=Na.randomBytes(cx),s=Na.createCipheriv(jA,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(lx,"encrypt");function _x(e){let t=e.substr(0,Lf),r=e.substr(Lf,eO),s=e.substr(ux,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Na.createDecipheriv(jA,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(_x,"decrypt");function dx(e,t){let r=ix.get(ox.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=ZA.get(r);return s||(s=Na.createHash("md5").update(r).digest("hex"),ZA.set(r,s)),s}a(dx,"createNatsTableStreamName")});var Wn=m((Wse,sO)=>{"use strict";var Kse=Tr(),Qu=F(),rO=$u(),Ex=Ps(),zu=x(),{handleHDBError:Ju,hdb_errors:fx}=W(),{HDB_ERROR_MSGS:Xu,HTTP_STATUS_CODES:Mf}=fx,hx=Q();hx.initSync();var{getDatabases:Pf}=(de(),te(Ne));sO.exports={describeAll:mx,describeTable:Zu,describeSchema:Sx};async function mx(e){try{let t=zu.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=Pf(),i={},o={},c=[];for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let _=n[l];for(let d in _)try{let E;if(t||s)E=await Zu({schema:l,table:d});else if(r&&r[l].describe&&r[l].tables[d].describe){let f=r[l].tables[d].attribute_permissions;E=await Zu({schema:l,table:d},f)}E&&c.push(E)}catch(E){Qu.error(E)}}let u={};for(let l in c)t||s?(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?u[l]={}:o[l]&&(u[l]={});return u}catch(t){return Qu.error("Got an error in describeAll"),Qu.error(t),Ju(new Error,Xu.DESCRIBE_ALL_ERR)}}a(mx,"describeAll");async function Zu(e,t){zu.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=rO.describe_table(e);if(i)throw i;let c=Pf()[r];if(!c)throw Ju(new Error,Xu.SCHEMA_NOT_FOUND(e.schema),Mf.NOT_FOUND);let u=c[s];if(!u)throw Ju(new Error,Xu.TABLE_NOT_FOUND(e.schema,e.table),Mf.NOT_FOUND);let l=[];if(n){let d={};n.forEach(E=>{E.describe&&(d[E.attribute_name]=!0)}),u.attributes.forEach(E=>{d[E.name]&&l.push(E)})}else l=u.attributes;let _={schema:r,name:u.tableName,attributes:l,hash_attribute:u.attributes.find(d=>d.isPrimaryKey||d.is_hash_attribute)?.name};_.clustering_stream_name=Ex.createNatsTableStreamName(_.schema,_.name);try{_.record_count=u.getRecordCount();let d=u.auditStore;if(d)for(let E of d.getKeys({reverse:!0,limit:1}))_.last_updated_record=E[0];if(!_.last_updated_record&&u.indices.__updatedtime__)for(let E of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))_.last_updated_record=E}catch(d){Qu.warn(`unable to stat table dbi due to ${d}`)}return _}a(Zu,"descTable");async function Sx(e){zu.transformReq(e);let t=rO.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=Pf()[s];if(!i)throw Ju(new Error,Xu.SCHEMA_NOT_FOUND(e.schema),Mf.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),zu.isEmpty(u)||u.describe){let l=await Zu({schema:e.schema,table:c},u?u.attribute_permissions:null);l&&(o[l.name]=l)}}return o}a(Sx,"describeSchema")});var _n=m((Xse,cO)=>{var px=Yn(),{callbackify:iO,promisify:Tx}=require("util"),{getDatabases:oO}=(de(),te(Ne));cO.exports={setSchemaDataToGlobal:nO,getTableSchema:Rx,getSystemSchema:gx,setSchemaDataToGlobalAsync:Tx(nO)};var aO=Wn(),zse=iO(aO.describeAll),Jse=iO(aO.describeTable);function nO(e){global.hdb_schema=oO(),e&&e()}a(nO,"setSchemaDataToGlobal");function Rx(e,t,r){let s=oO()[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(Rx,"getTableSchema");function gx(){return px}a(gx,"getSystemSchema")});var Rr=m((jse,dO)=>{"use strict";var el=yf(),mt=x(),Ax=require("util"),tl=Br(),Ox=_n(),uO=F(),{handleHDBError:Qn,hdb_errors:Nx}=W(),{HTTP_STATUS_CODES:zn}=Nx,bx=Ax.promisify(Ox.getTableSchema),yx="updated",lO="inserted",_O="upserted";dO.exports={insert:wx,update:Cx,upsert:Ux,validation:Ix,flush:Dx};async function Ix(e){if(mt.isEmpty(e))throw new Error("invalid update parameters defined.");if(mt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(mt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await bx(e.schema,e.table),r=el(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&&mt.isEmptyOrZeroLength(c[s]))throw uO.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(!mt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw uO.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!mt.isEmpty(c[s])&&c[s]!==""&&n.has(mt.autoCast(c[s]))&&(c.skip=!0),n.add(mt.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(Ix,"validation");async function wx(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=el(e);if(t)throw Qn(new Error,t.message,zn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qn(new Error,r,zn.BAD_REQUEST);let s=await tl.createRecords(e);return ju(lO,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(wx,"insertData");async function Cx(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=el(e);if(t)throw Qn(new Error,t.message,zn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qn(new Error,r,zn.BAD_REQUEST);let s=await tl.updateRecords(e);return mt.isEmpty(s.existing_rows)?ju(yx,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):ju(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(Cx,"updateData");async function Ux(e){if(e.operation!=="upsert")throw Qn(new Error,"invalid operation, must be upsert",zn.INTERNAL_SERVER_ERROR);let t=el(e);if(t)throw Qn(new Error,t.message,zn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qn(new Error,r,zn.BAD_REQUEST);let s=await tl.upsertRecords(e);return ju(_O,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(Ux,"upsertData");function ju(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===lO?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===_O?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(ju,"returnObject");function Dx(e){return mt.transformReq(e),tl.flush(e.schema,e.table)}a(Dx,"flush")});var Bf=m((tne,hO)=>{var Lx=ve(),vf=require("joi"),{hdb_table:Mx,hdb_database:EO}=ts(),fO={schema:EO,database:EO,table:Mx},Px={date:vf.date().iso().required()},vx={timestamp:vf.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};hO.exports=function(e,t){let r=t==="timestamp"?{...fO,...vx}:{...fO,...Px},s=vf.object(r);return Lx.validateBySchema(e,s)}});var pO=m((rne,SO)=>{var Bx=ve(),Hf=require("joi"),{hdb_table:Hx,hdb_database:mO}=ts(),qx=Hf.object({schema:mO,database:mO,table:Hx,hash_values:Hf.array().required(),ids:Hf.array()});SO.exports=function(e){return Bx.validateBySchema(e,qx)}});var RO=m((sne,TO)=>{"use strict";var qf=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}},Ff=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}},Gf=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};TO.exports={InsertObject:qf,NoSQLSeachObject:Ff,DeleteResponseObject:Gf}});var Zn=m((ine,bO)=>{"use strict";var AO=Bf(),Fx=pO(),Jn=x(),gO=require("moment"),OO=F(),{promisify:Gx,callbackify:xx}=require("util"),Xn=g(),kx=_n(),xf=Gx(kx.getTableSchema),kf=Br(),{DeleteResponseObject:Vx}=RO(),{handleHDBError:dn,hdb_errors:$x}=W(),{HDB_ERROR_MSGS:rl,HTTP_STATUS_CODES:En}=$x,Yx="records successfully deleted",Kx=xx(NO);bO.exports={delete:Kx,deleteRecord:NO,deleteFilesBefore:Wx,deleteAuditLogsBefore:Qx};async function Wx(e){let t=AO(e,"date");if(t)throw dn(t,t.message,En.BAD_REQUEST,void 0,void 0,!0);if(Jn.transformReq(e),!gO(e.date,gO.ISO_8601).isValid())throw dn(new Error,rl.INVALID_DATE,En.BAD_REQUEST,Xn.LOG_LEVELS.ERROR,rl.INVALID_DATE,!0);let s=Jn.checkSchemaTableExist(e.schema,e.table);if(s)throw dn(new Error,s,En.NOT_FOUND,Xn.LOG_LEVELS.ERROR,s,!0);let n=await kf.deleteRecordsBefore(e);if(await xf(e.schema,e.table),OO.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(Wx,"deleteFilesBefore");async function Qx(e){let t=AO(e,"timestamp");if(t)throw dn(t,t.message,En.BAD_REQUEST,void 0,void 0,!0);if(Jn.transformReq(e),isNaN(e.timestamp))throw dn(new Error,rl.INVALID_VALUE("Timestamp"),En.BAD_REQUEST,Xn.LOG_LEVELS.ERROR,rl.INVALID_VALUE("Timestamp"),!0);let r=Jn.checkSchemaTableExist(e.schema,e.table);if(r)throw dn(new Error,r,En.NOT_FOUND,Xn.LOG_LEVELS.ERROR,r,!0);let s=await kf.deleteAuditLogsBefore(e);return await xf(e.schema,e.table),OO.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(Qx,"deleteAuditLogsBefore");async function NO(e){e.ids&&(e.hash_values=e.ids);let t=Fx(e);if(t)throw dn(t,t.message,En.BAD_REQUEST,void 0,void 0,!0);Jn.transformReq(e);let r=Jn.checkSchemaTableExist(e.schema,e.table);if(r)throw dn(new Error,r,En.NOT_FOUND,Xn.LOG_LEVELS.ERROR,r,!0);try{await xf(e.schema,e.table);let s=await kf.deleteRecords(e);return Jn.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${Yx}`),s}catch(s){if(s.message===Xn.SEARCH_NOT_FOUND_MESSAGE){let n=new Vx;return n.message=Xn.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(NO,"deleteRecord")});var sl=m((ane,wO)=>{var zx=require("crypto"),yO=9;function Jx(e){let t=Zx(yO),r=IO(e+t);return t+r}a(Jx,"createHash");function Xx(e,t){let r=e.substr(0,yO),s=r+IO(t+r);return e===s}a(Xx,"validateHash");function Zx(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(Zx,"generateSalt");function IO(e){return zx.createHash("md5").update(e).digest("hex")}a(IO,"md5");wO.exports={hash:Jx,validate:Xx}});var UO=m((une,CO)=>{var Vf=ve(),It={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 jx(e){return It.password.presence=!0,It.username.presence=!0,It.role.presence=!0,It.active.presence=!0,Vf.validateObject(e,It)}a(jx,"addUserValidation");function ek(e){return It.password.presence=!1,It.username.presence=!0,It.role.presence=!1,It.active.presence=!1,Vf.validateObject(e,It)}a(ek,"alterUserValidation");function tk(e){return It.password.presence=!1,It.username.presence=!0,It.role.presence=!1,It.active.presence=!1,Vf.validateObject(e,It)}a(tk,"dropUserValidation");CO.exports={addUserValidation:jx,alterUserValidation:ek,dropUserValidation:tk}});var Be=m((dne,LO)=>{"use strict";var{platform:_ne}=require("os"),rk="nats-server.zip",$f="nats-server",sk=process.platform==="win32"?`${$f}.exe`:$f,Yf="HDB",nk=/^[^\s.,*>]+$/,DO="__request__",ik=a(e=>`${e}.${DO}`,"REQUEST_SUBJECT"),ok={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin"},ak={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},ck={HUB:"hub.pid",LEAF:"leaf.pid"},uk={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},lk={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Yf,deliver_subject:"__HDB__.WORKQUEUE"},_k={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Yf,deliver_subject:"HDB.SCHEMAQUEUE"},dk={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Yf,deliver_subject:"HDB.USERQUEUE"},Ek={SUCCESS:"success",ERROR:"error"},fk={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},hk={TXN:"txn",MSGID:"msgid"},xi={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},mk={[xi.ERR]:1,[xi.WRN]:2,[xi.INF]:3,[xi.DBG]:4,[xi.TRC]:5},Sk={debug:"-D",trace:"-DVV"};LO.exports={NATS_SERVER_ZIP:rk,NATS_SERVER_NAME:$f,NATS_BINARY_NAME:sk,PID_FILES:ck,NATS_CONFIG_FILES:ak,SERVER_SUFFIX:uk,WORK_QUEUE_CONSUMER_NAMES:lk,SCHEMA_QUEUE_CONSUMER_NAMES:_k,USER_QUEUE_CONSUMER_NAMES:dk,NATS_TERM_CONSTRAINTS_RX:nk,REQUEST_SUFFIX:DO,UPDATE_REMOTE_RESPONSE_STATUSES:Ek,CLUSTER_STATUS_STATUSES:fk,REQUEST_SUBJECT:ik,SUBJECT_PREFIXES:hk,MSG_HEADERS:ok,LOG_LEVELS:xi,LOG_LEVEL_FLAGS:Sk,LOG_LEVEL_HIERARCHY:mk}});var PO=m((fne,MO)=>{"use strict";var pk={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,String.fromCharCode(13,10)),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,String.fromCharCode(13,10))},Tk="certificate.pem",Rk="privateKey.pem",gk="ca.pem";MO.exports={CERTIFICATE_VALUES:pk,CERTIFICATE_PEM_NAME:Tk,PRIVATEKEY_PEM_NAME:Rk,CA_PEM_NAME:gk}});var Wf=m((mne,GO)=>{"use strict";var qO=require("fs-extra"),j=require("joi"),Ak=require("os"),{boolean:Se,string:Bs,number:ir,array:Kf}=j.types(),{totalmem:vO}=require("os"),ki=require("path"),Ok=F(),il=x(),hne=PO(),BO=g(),Nk=ve(),HO="log",bk="components",yk="Invalid logging.rotation.maxSize unit. Available units are G, M or K",Ik="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",wk="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",Ck="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",Uk="rootPath config parameter is undefined",Dk="clustering.enabled config parameter is undefined",vs=ir.min(0).required(),ol=Kf.items({host:Bs.required(),port:vs}).empty(null),Hs;GO.exports={configValidator:Lk,routesValidator:qk,route_constraints:ol};function Lk(e){if(Hs=e.rootPath,il.isEmpty(Hs))throw Uk;let t=Se.required(),r=j.valid("production","development").required(),s=ir.min(0).max(1e3).empty(null).default(Hk),n=Bs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(nl),i=j.custom(Mk).messages({"any.custom":"{:#label} {:#error}"}),o=Bs.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=j.string().empty(null).default(nl),u=j.custom(Pk).empty(null).default(nl),l=e.clustering?.enabled;if(il.isEmpty(l))throw Dk;let _;return l===!0?_=j.object({enabled:t,hubServer:j.object({cluster:j.object({name:j.required().empty(null),network:j.object({port:vs,routes:ol}).required()}).required(),leafNodes:j.object({network:j.object({port:vs}).required()}).required(),network:j.object({port:vs}).required()}).required(),leafServer:j.object({network:j.object({port:vs,routes:ol}).required(),streams:j.object({maxAge:ir.min(120).allow(null).optional(),maxBytes:ir.min(1).allow(null).optional(),maxMsgs:ir.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:j.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:Se.optional(),databaseLevel:Se.optional(),tls:j.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:Se.required(),verify:Se.optional()}),user:Bs.optional().empty(null)}).required():_=j.object({enabled:t,tls:j.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:Se.required()})}).required(),j.object({authentication:j.object({authorizeLocal:Se,cacheTTL:ir.required(),enableSessions:Se,operationTokenTimeout:j.required(),refreshTokenTimeout:j.required()}),analytics:j.object({aggregatePeriod:ir}),clustering:_,customFunctions:j.object({enabled:t,network:j.object({cors:Se.required(),corsAccessList:Kf.required(),headersTimeout:ir.min(1).required(),https:Se.required(),keepAliveTimeout:ir.min(1).required(),port:vs,timeout:ir.min(1).required()}),nodeEnv:r,root:n,tls:j.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),localStudio:j.object({enabled:t}).required(),logging:j.object({auditAuthEvents:j.object({logFailed:Se,logSuccessful:Se}),file:Se.required(),level:j.valid("notify","fatal","error","warn","info","debug","trace"),rotation:j.object({enabled:Se.optional(),compress:Se.optional(),interval:Bs.custom(Bk).optional().empty(null),maxSize:Bs.custom(vk).optional().empty(null),path:Bs.optional().empty(null).default(nl)}).required(),root:n,stdStreams:Se.required(),auditLog:Se.required()}).required(),operationsApi:j.object({foreground:Se.required(),network:j.object({cors:Se.required(),corsAccessList:Kf.required(),headersTimeout:ir.min(1).required(),https:Se.required(),keepAliveTimeout:ir.min(1).required(),port:vs,timeout:ir.min(1).required()}).required(),nodeEnv:r,tls:j.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Bs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:j.object({network:j.object({port:vs,securePort:vs}).required(),webSocket:Se.optional(),requireAuthentication:Se.optional()}),http:j.object({threads:s}).required(),storage:j.object({writeAsync:Se.required(),overlappingSync:Se.optional(),caching:Se.optional(),compression:Se.optional(),noReadAhead:Se.optional(),path:u,prefetchWrites:Se.optional()}).required(),ignoreScripts:Se.optional()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Lk,"configValidator");function FO(e){return qO.existsSync(e)?null:`Specified path ${e} does not exist.`}a(FO,"doesPathExist");function Mk(e,t){if(e===null)return;let r=FO(e);return r?t.message(r):e}a(Mk,"validatePemFile");function Pk(e,t){j.assert(e,Bs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=FO(e);if(r)return t.message(r)}a(Pk,"validatePath");function vk(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(yk);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(wk):e}a(vk,"validateRotationMaxSize");function Bk(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(Ik);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(Ck):e}a(Bk,"validateRotationInterval");function Hk(e,t){let r=t.state.path.join("."),s=Ak.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||vO();return i=Math.round(Math.min(i,vO())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),Ok.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(Hk,"setDefaultThreads");function nl(e,t){if(!il.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(il.isEmpty(Hs))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return ki.join(Hs,bk);case"logging.root":return ki.join(Hs,HO);case"clustering.leafServer.streams.path":return ki.join(Hs,"clustering","leaf");case"storage.path":let s=ki.join(Hs,BO.LEGACY_DATABASES_DIR_NAME);return qO.existsSync(s)?s:ki.join(Hs,BO.DATABASES_DIR_NAME);case"logging.rotation.path":return ki.join(Hs,HO);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(nl,"setDefaultRoot");function qk(e){let t=j.object({routes:ol});return Nk.validateBySchema({routes:e},t)}a(qk,"routesValidator")});var Ar=m((Tne,JO)=>{"use strict";var gr=g(),_t=x(),tt=F(),{configValidator:Fk,routesValidator:xO}=Wf(),qt=require("fs-extra"),Gk=require("yaml"),Hr=require("path"),xk=require("is-number"),VO=require("properties-reader"),kk=require("lodash"),{handleHDBError:Vk}=W(),{HTTP_STATUS_CODES:$k,HDB_ERROR_MSGS:al}=rr(),pne=require("minimist"),{SCHEMAS_PARAM_CONFIG:ba,CONFIG_PARAMS:fn,CONFIG_PARAM_MAP:qs}=gr,Yk="Unable to get config value because config is uninitialized",Kk="Config successfully initialized",Wk="Error backing up config file",Qk="Empty parameter sent to getConfigValue",$O=Hr.join(gr.PACKAGE_ROOT,"config","yaml",gr.HDB_DEFAULT_CONFIG_FILE),zk="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",kO={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"},cl,St;JO.exports={createConfigFile:Jk,getDefaultConfig:Xk,getConfigValue:KO,initConfig:WO,flattenConfig:ei,updateConfigValue:QO,updateConfigObject:jk,getConfiguration:rV,setConfiguration:sV,readConfigFile:Jf,getClusteringRoutes:nV,initOldConfig:zO,getConfigFromFile:iV,getConfigFilePath:jn,addConfig:oV,deleteConfigFromFile:aV};function Jk(e){let t=hn($O);cl=ei(t.toJSON());let r;for(let o in e){let c=qs[o.toLowerCase()];if(c===fn.SCHEMAS){r=e[o];continue}if(c!==void 0){let u=c.split("_"),l=Qf(c,e[o]);c==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{t.setIn([...u],l)}catch(_){tt.error(_)}}}r&&YO(t,r),zf(t);let s=t.toJSON();St=ei(s);let n=t.getIn(["rootPath"]),i=Hr.join(n,gr.HDB_CONFIG_FILE);qt.createFileSync(i),qt.writeFileSync(i,String(t)),tt.trace(`Config file written to ${i}`)}a(Jk,"createConfigFile");function YO(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!_t.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(ba.TABLES))for(let i in s[n][ba.TABLES])for(let o in s[n][ba.TABLES][i]){let c=s[n][ba.TABLES][i][o],u=[fn.SCHEMAS,n,ba.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=[fn.SCHEMAS,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){tt.error("Error parsing schemas CLI/env config arguments",s)}}a(YO,"setSchemasConfig");function Xk(e){if(cl===void 0){let r=hn($O);cl=ei(r.toJSON())}let t=qs[e.toLowerCase()];if(t!==void 0)return cl[t.toLowerCase()]}a(Xk,"getDefaultConfig");function KO(e){if(e==null){tt.error(Qk);return}if(St===void 0){tt.trace(Yk);return}let t=qs[e.toLowerCase()];if(t!==void 0)return St[t.toLowerCase()]}a(KO,"getConfigValue");function jn(e=_t.getPropsFilePath()){let t=_t.getEnvCliRootPath();return t?Hr.join(t,gr.HDB_CONFIG_FILE):VO(e).get(gr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(jn,"getConfigFilePath");function WO(e=!1){if(St===void 0||e){let t;if(!_t.noBootFile()){t=_t.getPropsFilePath();try{qt.accessSync(t,qt.constants.F_OK|qt.constants.R_OK)}catch(i){throw tt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=jn(t),s;if(r.includes("config/settings.js"))try{zO(r);return}catch(i){if(i.code!==gr.NODE_ERROR_CODES.ENOENT)throw i}try{s=hn(r)}catch(i){if(i.code===gr.NODE_ERROR_CODES.ENOENT){tt.trace(`HarperDB config file not found at ${r}.
|
|
5
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw tt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}Zk(s,r),zf(s);let n=s.toJSON();if(St=ei(n),St.logging_rotation_rotate)for(let i in kO)St[i]&&tt.error(`Config ${kO[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);tt.trace(Kk)}}a(WO,"initConfig");function Zk(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Hr.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Hr.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Hr.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(tt.trace("Updating config file with missing config params"),qt.writeFileSync(t,String(e)))}a(Zk,"checkForUpdatedConfig");function zf(e){let t=e.toJSON(),r=Fk(t);if(r.error)throw al.CONFIG_VALIDATION(r.error.message);e.setIn(["http","threads"],r.value.http.threads),e.setIn(["customFunctions","root"],r.value.customFunctions.root),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)}a(zf,"validateConfig");function jk(e,t){St===void 0&&(St={});let r=qs[e.toLowerCase()];if(r===void 0){tt.trace(`Unable to update config object because config param '${e}' does not exist`);return}St[r.toLowerCase()]=t}a(jk,"updateConfigObject");function QO(e,t,r=void 0,s=!1,n=!1,i=!1){St===void 0&&WO();let o=KO(qs.hdb_root),c=Hr.join(o,gr.HDB_CONFIG_FILE),u=hn(c),l;if(r===void 0&&e.toLowerCase()===fn.SCHEMAS)l=t;else if(r===void 0){let E;if(i)E=e;else if(E=qs[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=Qf(E,t);u.setIn([...f],h)}else for(let E in r){let f=qs[E.toLowerCase()];if(f===fn.SCHEMAS){l=r[E];continue}if(f!==void 0){let h=f.split("_"),T=Qf(f,r[E]);f==="rootPath"&&T?.endsWith("/")&&(T=T.slice(0,-1));try{u.setIn([...h],T)}catch(S){tt.error(S)}}}l&&YO(u,l),zf(u);let _=u.getIn(["rootPath"]),d=Hr.join(_,gr.HDB_CONFIG_FILE);s===!0&&eV(c,_),qt.writeFileSync(d,String(u)),n&&(St=ei(u.toJSON())),tt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(QO,"updateConfigValue");function eV(e,t){try{let r=Hr.join(t,"backup",`${gr.HDB_CONFIG_FILE}.bak`);qt.copySync(e,r),tt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){tt.error(Wk),tt.error(r)}}a(eV,"backupConfigFile");var tV=["schemas"];function ei(e){let t={};for(let r in e)if(e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])&&!tV.includes(r)){let s=ei(e[r]);for(let n in s)s.hasOwnProperty(n)&&(t[r.toLowerCase()+"_"+n]=s[n])}else t[r.toLowerCase()]=e[r];return t}a(ei,"flattenConfig");function Qf(e,t){if(e===fn.CLUSTERING_NODENAME||e===fn.CLUSTERING_USER){if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(xk(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||_t.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 _t.autoCast(t)}a(Qf,"castConfigValue");function rV(){let e=_t.getPropsFilePath(),t=jn(e);return hn(t).toJSON()}a(rV,"getConfiguration");async function sV(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return QO(void 0,void 0,n,!0),zk}catch(i){throw typeof i=="string"||i instanceof String?Vk(i,i,$k.BAD_REQUEST,void 0,void 0,!0):i}}a(sV,"setConfiguration");function Jf(){let e=_t.getPropsFilePath();try{qt.accessSync(e,qt.constants.F_OK|qt.constants.R_OK)}catch(s){if(!_t.noBootFile())throw tt.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=jn(e);return hn(t).toJSON()}a(Jf,"readConfigFile");function hn(e){return Gk.parseDocument(qt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(hn,"parseYamlDoc");function nV(){let e=Jf(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=_t.isEmptyOrZeroLength(t)?[]:t;let r=xO(t);if(r)throw al.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=_t.isEmptyOrZeroLength(s)?[]:s;let n=xO(s);if(n)throw al.CONFIG_VALIDATION(n.message);if(!_t.isEmptyOrZeroLength(s)&&!_t.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!_t.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw al.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(nV,"getClusteringRoutes");function zO(e){let t=VO(e);St={};for(let r in qs){let s=t.get(r.toUpperCase());if(_t.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=qs[r].toLowerCase();n===fn.LOGGING_ROOT?St[n]=Hr.dirname(s):St[n]=s}return St}a(zO,"initOldConfig");function iV(e){let t=Jf();return kk.get(t,e.replaceAll("_","."))}a(iV,"getConfigFromFile");async function oV(e,t){let r=hn(jn());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await qt.writeFile(jn(),String(r))}a(oV,"addConfig");function aV(e){let t=jn(_t.getPropsFilePath()),r=hn(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Hr.join(s,gr.HDB_CONFIG_FILE);qt.writeFileSync(n,String(r))}a(aV,"deleteConfigFromFile")});var ZO=m((gne,XO)=>{"use strict";var ul=g(),ll=class{static{a(this,"BaseLicense")}constructor(t=0,r=ul.RAM_ALLOCATION_ENUM.DEFAULT,s=ul.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},Xf=class extends ll{static{a(this,"ExtendedLicense")}constructor(t=0,r=ul.RAM_ALLOCATION_ENUM.DEFAULT,s=ul.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};XO.exports={BaseLicense:ll,ExtendedLicense:Xf}});var ya=m((One,nN)=>{"use strict";var $i=require("fs-extra"),jO=sl(),eN=require("crypto"),cV=require("moment"),uV=require("uuid").v4,wt=F(),jf=require("path"),lV=x(),mn=g(),_V=ZO().ExtendedLicense,Vi="invalid license key format",dV="061183",EV="mofi25",fV="aes-256-cbc",hV=16,mV=32,tN=Q();tN.initSync();var Zf;nN.exports={validateLicense:rN,generateFingerPrint:pV,licenseSearch:sN,getLicense:gV};function eh(){return jf.join(tN.getHdbBasePath(),mn.LICENSE_KEY_DIR_NAME,mn.LICENSE_FILE_NAME)}a(eh,"getLicenseDirPath");function SV(){let e=eh();return jf.join(e,mn.LICENSE_FILE_NAME)}a(SV,"getLicenseFilePath");function th(){let e=eh();return jf.join(e,mn.REG_KEY_FILE_NAME)}a(th,"getFingerPrintFilePath");async function pV(){let e=th();try{return await $i.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await TV();throw wt.error(`Error writing fingerprint file to ${e}`),wt.error(t),new Error("There was an error generating the fingerprint")}}a(pV,"generateFingerPrint");async function TV(){let e=uV(),t=jO.hash(e),r=th();try{await $i.mkdirp(eh()),await $i.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw wt.error(`Error writing fingerprint file to ${r}`),wt.error(s),new Error("There was an error generating the fingerprint")}return t}a(TV,"writeFingerprint");function rN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:mn.RAM_ALLOCATION_ENUM.DEFAULT,version:mn.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return wt.error("empty license key passed to validate."),r;let s=th(),n=!1;try{n=$i.statSync(s)}catch(i){wt.error(i)}if(n){let i;try{i=$i.readFileSync(s,"utf8")}catch{wt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(EV),c=o[1];c=Buffer.concat([Buffer.from(c)],hV);let u=Buffer.concat([Buffer.from(i)],mV),l=eN.createDecipheriv(fV,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let _=null;try{_=l.update(o[0],"hex","utf8"),_.trim(),_+=l.final("utf8")}catch{let f=RV(o[0],i);if(f)_=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Vi),wt.error(Vi),new Error(Vi)}let d;if(isNaN(_))try{d=JSON.parse(_),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(Vi),wt.error(Vi),new Error(Vi)}else r.exp_date=_;r.exp_date<cV().valueOf()&&(r.valid_date=!1),jO.validate(o[1],`${dV}${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||wt.error("Invalid licence"),r}a(rN,"validateLicense");function RV(e,t){try{let r=eN.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{wt.warn("Check old license failed")}}a(RV,"checkOldLicense");function sN(){let e=new _V,t=[];try{t=$i.readFileSync(SV(),"utf-8").split(mn.NEW_LINE)}catch(r){r.code==="ENOENT"?wt.info("no license file found"):wt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(lV.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=rN(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){wt.error("There was an error parsing the license string."),wt.error(n),e.ram_allocation=mn.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Zf=e,e}a(sN,"licenseSearch");async function gV(){return Zf||await sN(),Zf}a(gV,"getLicense")});var Or=m((wne,RN)=>{"use strict";var uN="username is required",lN="nothing to update, must supply active, role or password to update",_N="password cannot be an empty string",dN="If role is specified, it cannot be empty.",EN="active must be true or false";RN.exports={addUser:UV,alterUser:DV,dropUser:MV,getSuperUser:HV,userInfo:PV,listUsers:dl,listUsersExternal:vV,setUsersToGlobal:Ki,findAndValidateUser:TN,getClusterUser:qV,USERNAME_REQUIRED:uN,ALTERUSER_NOTHING_TO_UPDATE:lN,EMPTY_PASSWORD:_N,EMPTY_ROLE:dN,ACTIVE_BOOLEAN:EN};var fN=Rr(),AV=Zn(),sh=sl(),hN=UO(),mN=Tr(),nh=Fs(),or=x(),SN=require("validate.js"),ue=F(),{promisify:OV}=require("util"),ih=Ps(),iN=g(),oN=Be(),NV=Ar(),bne=Q(),yne=ya(),bV=Yn(),{table:Ine}=(de(),te(Ne)),{handleHDBError:ss,hdb_errors:yV}=W(),{HTTP_STATUS_CODES:ns,AUTHENTICATION_ERROR_MSGS:rh,HDB_ERROR_MSGS:Yi}=yV,{UserEventMsg:oh}=qr(),aN=require("lodash"),{_assignPackageExport:IV}=require("../../index");IV("getUser",TN);var pN={username:!0,active:!0,role:!0,password:!0},cN=new Map,_l=mN.searchByValue,wV=mN.searchByHash,CV=OV(AV.delete);async function UV(e){let t=SN.cleanAttributes(e,pN),r=hN.addUserValidation(t);if(r)throw ss(new Error,r.message,ns.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 _l(s),n=n&&Array.from(n)}catch(u){throw ue.error("There was an error searching for a role in add user"),ue.error(u),u}if(!n||n.length<1)throw ss(new Error,Yi.ROLE_NAME_NOT_FOUND(t.role),ns.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw ss(new Error,Yi.DUP_ROLES_FOUND(t.role),ns.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=ih.encrypt(t.password)),t.password=sh.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await fN.insert(i)}catch(u){throw ue.error("There was an error searching for a user."),ue.error(u),u}ue.debug(o);try{await Ki()}catch(u){throw ue.error("Got an error setting users to global"),ue.error(u),u}if(o.skipped_hashes.length===1)throw ss(new Error,Yi.USER_ALREADY_EXISTS(t.username),ns.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],nh.signalUserChange(new oh(process.pid)),`${c.username} successfully added`}a(UV,"addUser");async function DV(e){let t=SN.cleanAttributes(e,pN);if(or.isEmptyOrZeroLength(t.username))throw new Error(uN);if(or.isEmptyOrZeroLength(t.password)&&or.isEmptyOrZeroLength(t.role)&&or.isEmptyOrZeroLength(t.active))throw new Error(lN);if(!or.isEmpty(t.password)&&or.isEmptyOrZeroLength(t.password.trim()))throw new Error(_N);if(!or.isEmpty(t.active)&&!or.isBoolean(t.active))throw new Error(EN);let r=LV(t.username);if(!or.isEmpty(t.password)&&!or.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=ih.encrypt(t.password)),t.password=sh.hash(t.password)),t.role==="")throw new Error(dN);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 _l(i)||[])}catch(c){throw ue.error("Got an error searching for a role."),ue.error(c),c}if(!o||o.length===0){let c=Yi.ALTER_USER_ROLE_NOT_FOUND(t.role);throw ue.error(c),ss(new Error,c,ns.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Yi.ALTER_USER_DUP_ROLES(t.role);throw ue.error(c),ss(new Error,c,ns.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 fN.update(s)}catch(i){throw ue.error("Error during update."),ue.error(i),i}try{await Ki()}catch(i){throw ue.error("Got an error setting users to global"),ue.error(i),i}return nh.signalUserChange(new oh(process.pid)),n}a(DV,"alterUser");function LV(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(LV,"isClusterUser");async function MV(e){try{let t=hN.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(or.isEmpty(global.hdb_users.get(e.username)))throw ss(new Error,Yi.USER_NOT_EXIST(e.username),ns.NOT_FOUND,void 0,void 0,!0);let s;try{s=await CV(r)}catch(n){throw ue.error("Got an error deleting a user."),ue.error(n),n}ue.debug(s);try{await Ki()}catch(n){throw ue.error("Got an error setting users to global."),ue.error(n),n}return nh.signalUserChange(new oh(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(MV,"dropUser");async function PV(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=e.hdb_user;let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await wV(r)}catch(n){throw ue.error("Got an error searching for a role."),ue.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw ue.error(r),r}return t}a(PV,"userInfo");async function vV(){let e;try{e=await dl()}catch(t){throw ue.error("Got an error listing users."),ue.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(vV,"listUsersExternal");async function dl(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await _l(e)}catch(o){throw ue.error("Got an error searching for roles."),ue.error(o),o}let r={};for(let o of t)r[o.id]=aN.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 _l(s)}catch(o){throw ue.error("Got an error searching for users."),ue.error(o),o}let i=new Map;for(let o of n)o=aN.cloneDeep(o),o.role=r[o.role],BV(o.role),i.set(o.username,o);return i}catch(e){throw ue.error("got an error listing users"),ue.error(e),or.errorizeMessage(e)}return null}a(dl,"listUsers");function BV(e){try{if(!e){ue.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(bV)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){ue.error("Got an error trying to set system permissions."),ue.error(t)}}a(BV,"appendSystemTablesToRole");async function Ki(){try{let e=await dl();global.hdb_users=e}catch(e){throw ue.error(e),e}}a(Ki,"setUsersToGlobal");async function TN(e,t,r=!0){global.hdb_users||await Ki();let s=global.hdb_users.get(e);if(!s)throw ss(new Error,rh.GENERIC_AUTH_FAIL,ns.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw ss(new Error,rh.USER_INACTIVE,ns.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(cN.get(t)===s.password)return n;if(sh.validate(s.password,t))cN.set(t,s.password);else throw ss(new Error,rh.GENERIC_AUTH_FAIL,ns.UNAUTHORIZED,void 0,void 0,!0)}return n}a(TN,"findAndValidateUser");async function HV(){global.hdb_users||await Ki();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(HV,"getSuperUser");async function qV(){let e=await dl(),t=NV.getConfigFromFile(iN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!or.isEmpty(r)&&r?.role?.role===iN.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=ih.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+oN.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+oN.SERVER_SUFFIX.ADMIN,r}a(qV,"getClusterUser")});var wa=m((Lne,NN)=>{"use strict";var ti=F(),ar=g(),FV=XA(),Une=_n(),Dne=Wn(),GV=Or(),{validateEvent:gN}=qr(),Ia=Br(),xV=require("process"),{resetDatabases:kV}=(de(),te(Ne)),VV={[ar.ITC_EVENT_TYPES.SCHEMA]:$V,[ar.ITC_EVENT_TYPES.USER]:ON};async function $V(e){let t=gN(e);if(t){ti.error(t);return}ti.trace("ITC schemaHandler received schema event:",e),await FV(e.message),await YV(e.message)}a($V,"schemaHandler");async function YV(e){try{Ia.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Ia.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Ia.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=kV();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ti.error(t)}}a(YV,"syncSchemaMetadata");var AN=[];async function ON(e){try{try{Ia.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Ia.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ti.warn(r)}let t=gN(e);if(t){ti.error(t);return}ti.trace(`ITC userHandler ${ar.HDB_ITC_CLIENT_PREFIX}${xV.pid} received user event:`,e),await GV.setUsersToGlobal();for(let r of AN)r()}catch(t){ti.error(t)}}a(ON,"userHandler");ON.addListener=function(e){AN.push(e)};NN.exports=VV});var qr=m((qne,yN)=>{"use strict";var Pne=F(),ah=x(),KV=g(),{ITC_ERRORS:Ca}=rr(),{parentPort:vne,threadId:WV,isMainThread:QV,workerData:Bne}=require("worker_threads"),{onMessageFromWorkers:zV,broadcast:Hne,broadcastWithAcknowledgement:JV}=rt();yN.exports={sendItcEvent:XV,validateEvent:bN,SchemaEventMsg:ZV,UserEventMsg:jV};var El;zV(async(e,t)=>{El=El||wa(),bN(e),El[e.type]&&await El[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function XV(e){return!QV&&e.message&&(e.message.originator=WV),JV(e)}a(XV,"sendItcEvent");function bN(e){if(typeof e!="object")return Ca.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||ah.isEmpty(e.type))return Ca.MISSING_TYPE;if(!e.hasOwnProperty("message")||ah.isEmpty(e.message))return Ca.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||ah.isEmpty(e.message.originator))return Ca.MISSING_ORIGIN;if(KV.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Ca.INVALID_EVENT(e.type)}a(bN,"validateEvent");function ZV(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(ZV,"SchemaEventMsg");function jV(e){this.originator=e}a(jV,"UserEventMsg")});var Fs=m((xne,UN)=>{"use strict";var IN=g(),Gne=x(),fl=F(),wN=QA(),Wi,{sendItcEvent:CN}=qr();function e$(e){try{fl.trace("signalSchemaChange called with message:",e),Wi=Wi||wa();let t=new wN(IN.ITC_EVENT_TYPES.SCHEMA,e);return Wi.schema(t),CN(t)}catch(t){fl.error(t)}}a(e$,"signalSchemaChange");function t$(e){try{fl.trace("signalUserChange called with message:",e),Wi=Wi||wa();let t=new wN(IN.ITC_EVENT_TYPES.USER,e);return Wi.user(t),CN(t)}catch(t){fl.error(t)}}a(t$,"signalUserChange");UN.exports={signalSchemaChange:e$,signalUserChange:t$}});var hl=m((Vne,LN)=>{"use strict";var DN=x(),r$=g(),s$=F(),n$=Ku(),i$=Yu(),o$=Fs(),{SchemaEventMsg:a$}=qr(),c$="already exists in";LN.exports=u$;async function u$(e,t,r){if(DN.isEmptyOrZeroLength(r))return r;let s=[];DN.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 l$(e,t.schema,t.name,i)})),n}a(u$,"lmdbCheckForNewAttributes");async function l$(e,t,r,s){let n=new i$(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await _$(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(c$))s$.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(l$,"createNewAttribute");async function _$(e){let t;return t=await n$(e),o$.signalSchemaChange(new a$(process.pid,r$.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(_$,"createAttribute")});var Qi=m((Yne,MN)=>{"use strict";var ch=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}};MN.exports=ch});var vN=m((Wne,PN)=>{"use strict";var d$=Qi(),E$=g().OPERATIONS_ENUM,uh=class extends d${static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(E$.INSERT,r,s,n,i),this.records=t}};PN.exports=uh});var HN=m((zne,BN)=>{"use strict";var f$=Qi(),h$=g().OPERATIONS_ENUM,lh=class extends f${static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(h$.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};BN.exports=lh});var FN=m((Xne,qN)=>{"use strict";var m$=Qi(),S$=g().OPERATIONS_ENUM,_h=class extends m${static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(S$.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};qN.exports=_h});var xN=m((jne,GN)=>{"use strict";var p$=Qi(),T$=g().OPERATIONS_ENUM,dh=class extends p${static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(T$.DELETE,s,n,t,i),this.original_records=r}};GN.exports=dh});var Ua=m((rie,YN)=>{"use strict";var tie=require("path"),kN=ye(),R$=vN(),g$=HN(),A$=FN(),O$=xN(),zi=xe(),VN=x(),{CONFIG_PARAMS:N$}=g(),$N=Q();$N.initSync();var ml=g().OPERATIONS_ENUM,{getTransactionAuditStorePath:b$}=we();YN.exports=y$;async function y$(e,t){if($N.get(N$.LOGGING_AUDITLOG)===!1)return;let r=b$(e.schema,e.table),s=await kN.openEnvironment(r,e.table,!0),n=I$(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){kN.initializeDBIs(s,zi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,zi.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[zi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[zi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),VN.isEmpty(n.user_name)||s.dbis[zi.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[zi.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(y$,"writeTransaction");function I$(e,t){let r=VN.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===ml.INSERT)return new R$(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===ml.UPDATE)return new g$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===ml.UPSERT)return new A$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===ml.DELETE)return new O$(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(I$,"createTransactionObject")});var Eh=m((iie,KN)=>{"use strict";var w$=pa(),nie=Ta(),Da=g(),C$=Oa(),U$=Fi().insertRecords,D$=ye(),L$=F(),M$=hl(),{getSchemaPath:P$}=we(),v$=Ua();KN.exports=B$;async function B$(e){try{let{schema_table:t,attributes:r}=w$(e);C$(e,r,t.hash_attribute),e.schema!==Da.SYSTEM_SCHEMA_NAME&&(r.includes(Da.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Da.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Da.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Da.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await M$(e.hdb_auth_header,t,r),n=P$(e.schema,e.table),i=await D$.openEnvironment(n,e.table),o=await U$(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await v$(e,o)}catch(c){L$.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(B$,"lmdbCreateRecords")});var zN=m((aie,QN)=>{"use strict";var WN=g(),H$=Eh(),q$=Ta(),F$=require("fs-extra"),{getSchemaPath:G$}=we();QN.exports=x$;async function x$(e){let t=[{name:e.schema,createddate:Date.now()}],r=new q$(WN.SYSTEM_SCHEMA_NAME,WN.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await H$(r),await F$.mkdirp(G$(e.schema))}a(x$,"lmdbCreateSchema")});var XN=m((uie,JN)=>{"use strict";var fh=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}};JN.exports=fh});var tb=m((fie,eb)=>{"use strict";var ZN=ye(),hh=vt(),mh=rr().LMDB_ERRORS_ENUM,k$=xe(),jN=F(),_ie=x(),V$=require("lmdb"),$$=XN(),Y$=g(),{OVERFLOW_MARKER:die,MAX_SEARCH_KEY_LENGTH:Eie}=k$,K$=Y$.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function W$(e,t,r,s){if(hh.validateEnv(e),t===void 0)throw new Error(mh.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(mh.IDS_REQUIRED):new Error(mh.IDS_MUST_BE_ITERABLE);try{let n=ZN.listDBIs(e);ZN.initializeDBIs(e,t,n);let i=new $$,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||s&&h[K$]>s){i.skipped.push(o);continue}let T=e.dbis[t].ifVersion(o,V$.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let y=n[S];if(!h.hasOwnProperty(y)||y===t)continue;let O=e.dbis[y],H=h[y];if(H!=null)try{let Y=hh.getIndexedValues(H);if(Y)for(let A=0,w=Y.length;A<w;A++)O.remove(Y[A],o)}catch{jN.warn(`cannot delete from attribute: ${y}, ${H}:${o}`)}}});c.push(T),u.push(o),i.original_records.push(h)}catch(h){jN.warn(h),i.skipped.push(o)}let l=[],_=await Promise.all(c);for(let E=0,f=_.length;E<f;E++)_[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),l.push(E));let d=0;for(let E=0;E<l.length;E++){let f=l[E];i.original_records.splice(f-d,1),d++}return i.txn_time=hh.getNextMonotonicTime(),i}catch(n){throw n}}a(W$,"deleteRecords");eb.exports={deleteRecords:W$}});var La=m((mie,sb)=>{"use strict";var Ji=x(),Q$=tb(),z$=ye(),{getSchemaPath:J$}=we(),X$=Ua(),Z$=F();sb.exports=j$;async function j$(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Ji.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Ji.isEmptyOrZeroLength(e.hash_values)&&!Ji.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Ji.isEmpty(u)||e.hash_values.push(u)}}if(Ji.isEmptyOrZeroLength(e.hash_values))return rb([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Ji.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=J$(e.schema,e.table),i=await z$.openEnvironment(n,e.table),o=await Q$.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await X$(e,o)}catch(c){Z$.error(`unable to write transaction due to ${c.message}`)}return rb(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(j$,"lmdbDeleteRecords");function rb(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(rb,"createDeleteResponse")});var ph=m((Tie,nb)=>{"use strict";var eY=g(),pie=vt();function Sh(e,t){let r=Object.create(null);if(t.length===1&&eY.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(Sh,"parseRow");function tY(e,t,r,s){let n=Sh(r,e);s.push(n)}a(tY,"searchAll");function rY(e,t,r,s){let n=Sh(r,e);s[t]=n}a(rY,"searchAllToMap");function sY(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(sY,"iterateDBI");function ri(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(ri,"pushResults");function nY(e,t,r,s,n,i){t.toString().endsWith(e)&&ri(t,r,s,n,i)}a(nY,"endsWith");function iY(e,t,r,s,n,i){t.toString().includes(e)&&ri(t,r,s,n,i)}a(iY,"contains");function oY(e,t,r,s,n,i){t>e&&ri(t,r,s,n,i)}a(oY,"greaterThanCompare");function aY(e,t,r,s,n,i){t>=e&&ri(t,r,s,n,i)}a(aY,"greaterThanEqualCompare");function cY(e,t,r,s,n,i){t<e&&ri(t,r,s,n,i)}a(cY,"lessThanCompare");function uY(e,t,r,s,n,i){t<=e&&ri(t,r,s,n,i)}a(uY,"lessThanEqualCompare");nb.exports={parseRow:Sh,searchAll:tY,searchAllToMap:rY,iterateDBI:sY,endsWith:nY,contains:iY,greaterThanCompare:oY,greaterThanEqualCompare:aY,lessThanCompare:cY,lessThanEqualCompare:uY,pushResults:ri}});var Xi=m((Nie,_b)=>{"use strict";var Sn=ye(),gie=F(),cr=vt(),Sl=xe(),ke=rr().LMDB_ERRORS_ENUM,Aie=x(),lY=g(),pl=ph(),{parseRow:_Y}=pl,Oie=require("lmdb"),{OVERFLOW_MARKER:ib,MAX_SEARCH_KEY_LENGTH:dY}=Sl;function ob(e,t,r,s=!1,n=void 0,i=void 0){return si(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(ob,"iterateFullIndex");function Ma(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,l=!1){return si(e,t,r,(_,d,E,f)=>{let O={transaction:_,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!l,exclusiveStart:i===!0?l:u};return f===r?(O.values=!1,d.getRange(O).map(H=>({value:H}))):d.getRange(O)})}a(Ma,"iterateRangeBetween");function si(e,t,r,s){let n=e.database||e,i=Sn.openDBI(n,r);i[Sl.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&Sn.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(si,"setupTransaction");function ab(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(ib)){if(!n)if(r)n=Sn.openDBI(e,r);else{let u=Sn.listDBIs(e);for(let l=0,_=u.length;l<_&&(n=Sn.openDBI(e,u[l]),!n[Sl.DBI_DEFINITION_NAME].is_hash_attribute);l++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(ab,"getOverflowCheck");function EY(e,t,r,s=!1,n=void 0,i=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);return si(e,t,t,(o,c,u)=>(Tl(r),r=Pa(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(l=>_Y(l.value,r))))}a(EY,"searchAll");function fY(e,t,r,s=!1,n=void 0,i=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);Tl(r),r=Pa(e.database||e,r);let o=new Map;for(let{key:c,value:u}of ob(e,t,t,s,n,i))o.set(c,pl.parseRow(u,r));return o}a(fY,"searchAllToMap");function hY(e,t,r=!1,s=void 0,n=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=ob(e,void 0,t,r,s,n),c=o.transaction,u=ab(c.database,c,void 0,t);for(let{key:l,value:_}of o){let d=u(l,_);i[d]===void 0&&(i[d]=[]),i[d].push(_)}return i}a(hY,"iterateDBI");function mY(e,t){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);return Sn.statDBI(e,t).entryCount}a(mY,"countAll");function SY(e,t,r,s,n=!1,i=void 0,o=void 0){return pn(e,r,s),si(e,t,r,(c,u,l,_)=>(s=cr.convertKeyValueToWrite(s),_===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(SY,"equals");function pY(e,t,r){return pn(e,t,r),Sn.openDBI(e,t).getValuesCount(r)}a(pY,"count");function TY(e,t,r,s,n=!1,i=void 0,o=void 0){return pn(e,r,s),si(e,null,r,(c,u)=>{s=cr.convertKeyValueToWrite(s);let l=!0;typeof s=="number"&&(l=!1);let _;if(n===!0){let d;for(let E of u.getKeys({transaction:c,start:s}))if(!E.startsWith(s)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),_=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(s))return E;if(l===!0)return _.DONE}}),_.filter(E=>E)}else return _=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(l===!0)return _.DONE}),l?_:_.filter(d=>d)})}a(TY,"startsWith");function RY(e,t,r,s,n=!1,i=void 0,o=void 0){return cb(e,t,r,s,n,i,o,!0)}a(RY,"endsWith");function cb(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return pn(e,r,s),si(e,null,r,(u,l,_,d)=>{let E=ab(_,u,d,r);return o=Number.isInteger(o)?o:0,l.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(f=>{let h=f.toString();return h.endsWith(ib)?l.getValues(f,{transaction:u}).map(T=>{let S=E(f,T);if(c?S.endsWith(s):S.includes(s))return{key:S,value:T}}).filter(T=>T):(c?h.endsWith(s):h.includes(s))?l[Sl.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:l.getValues(f,{transaction:u}).map(T=>({key:f,value:T})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(cb,"contains");function gY(e,t,r,s,n=!1,i=void 0,o=void 0){pn(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Ma(e,t,r,s,u,n,i,o,!0,!1)}a(gY,"greaterThan");function AY(e,t,r,s,n=!1,i=void 0,o=void 0){pn(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Ma(e,t,r,s,u,n,i,o,!1,!1)}a(AY,"greaterThanEqual");function OY(e,t,r,s,n=!1,i=void 0,o=void 0){pn(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Ma(e,t,r,u,s,n,i,o,!1,!0)}a(OY,"lessThan");function NY(e,t,r,s,n=!1,i=void 0,o=void 0){pn(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Ma(e,t,r,u,s,n,i,o,!1,!1)}a(NY,"lessThanEqual");function bY(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(cr.validateEnv(e),r===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ke.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ke.END_VALUE_REQUIRED);if(s=cr.convertKeyValueToWrite(s),n=cr.convertKeyValueToWrite(n),s>n)throw new Error(ke.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Ma(e,t,r,s,n,i,o,c)}a(bY,"between");function yY(e,t,r,s){cr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(Tl(r),r=Pa(n,r),s===void 0)throw new Error(ke.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=pl.parseRow(c,r)),o}a(yY,"searchByHash");function IY(e,t,r){cr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ke.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(IY,"checkHashExists");function wY(e,t,r,s,n=[]){return lb(e,t,r,s,n),ub(e,t,r,s,n).map(i=>i[1])}a(wY,"batchSearchByHash");function CY(e,t,r,s,n=[]){lb(e,t,r,s,n);let i=new Map;for(let[o,c]of ub(e,t,r,s,n))i.set(o,c);return i}a(CY,"batchSearchByHashToMap");function ub(e,t,r,s,n=[]){return si(e,t,t,(i,o,c)=>{r=Pa(c,r);let u=r.length<3;return s.map(l=>{let _=c.dbis[t].get(l,{transaction:i,lazy:u});if(_)return[l,pl.parseRow(_,r)];n.push(l)}).filter(l=>l)})}a(ub,"batchHashSearch");function lb(e,t,r,s,n){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(Tl(r),s==null)throw new Error(ke.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ke.IDS_MUST_BE_ITERABLE)}a(lb,"initializeBatchSearchByHash");function Tl(e){if(!Array.isArray(e))throw e===void 0?new Error(ke.FETCH_ATTRIBUTES_REQUIRED):new Error(ke.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(Tl,"validateFetchAttributes");function pn(e,t,r){if(cr.validateEnv(e),t===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ke.SEARCH_VALUE_REQUIRED);if(r?.length>dY)throw new Error(ke.SEARCH_VALUE_TOO_LARGE)}a(pn,"validateComparisonFunctions");function Pa(e,t){return t.length===1&&lY.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Sn.listDBIs(e)),t}a(Pa,"setGetWholeRowAttributes");_b.exports={searchAll:EY,searchAllToMap:fY,count:pY,countAll:mY,equals:SY,startsWith:TY,endsWith:RY,contains:cb,searchByHash:yY,setGetWholeRowAttributes:Pa,batchSearchByHash:wY,batchSearchByHashToMap:CY,checkHashExists:IY,iterateDBI:hY,greaterThan:gY,greaterThanEqual:AY,lessThan:OY,lessThanEqual:NY,between:bY}});var Zi=m((yie,mb)=>{var db=require("lodash"),Eb=ve(),Ce=require("joi"),UY=x(),{hdb_schema_table:Rl,checkValidTable:fb,hdb_table:hb,hdb_database:gl}=ts(),{handleHDBError:DY,hdb_errors:LY}=W(),{getDatabases:MY}=(de(),te(Ne)),{HTTP_STATUS_CODES:PY}=LY,vY=Ce.object({database:gl,schema:gl,table:hb,search_attribute:Rl,search_value:Ce.any().required(),get_attributes:Ce.array().min(1).items(Rl).optional(),desc:Ce.bool(),limit:Ce.number().integer().min(1),offset:Ce.number().integer().min(0)}),BY=Ce.object({database:gl,schema:gl,table:hb,operator:Ce.string().valid("and","or").default("and").lowercase(),offset:Ce.number().integer().min(0),limit:Ce.number().integer().min(1),get_attributes:Ce.array().min(1).items(Rl).optional(),conditions:Ce.array().min(1).items(Ce.object({search_attribute:Rl,search_type:Ce.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:Ce.when("search_type",{switch:[{is:"equals",then:Ce.any()},{is:"between",then:Ce.array().items(Ce.alternatives([Ce.string(),Ce.number()])).length(2)}],otherwise:Ce.alternatives(Ce.string(),Ce.number())}).required()})).required()});mb.exports=function(e,t){let r=null;switch(t){case"value":r=Eb.validateBySchema(e,vY);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(fb("database",e.schema)),i(fb("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=Eb.validateBySchema(e,BY);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=UY.checkGlobalSchemaTable(e.schema,e.table);if(n)return DY(new Error,n,PY.NOT_FOUND);let o=MY()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let l=0,_=e.conditions.length;l<_;l++){let d=e.conditions[l];c.push(d.search_attribute)}let u=db.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!db.some(o,_=>_===l||_.attribute===l||_.attribute===l.attribute));if(u&&u.length>0){let l=u.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Th=m((wie,Sb)=>{"use strict";var HY=ye(),qY=Zi(),{getSchemaPath:FY}=we();Sb.exports=GY;function GY(e){let t=qY(e,"hashes");if(t)throw t;let r=FY(e.schema,e.table);return HY.openEnvironment(r,e.table)}a(GY,"initialize")});var Rh=m((Uie,pb)=>{"use strict";var xY=Xi(),kY=Th();pb.exports=VY;async function VY(e){let t=await kY(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return xY.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(VY,"lmdbGetDataByHash")});var ji=m((Lie,Tb)=>{"use strict";var gh=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};Tb.exports=gh});var gb=m((vie,Rb)=>{"use strict";var Pie=ji(),$Y=Xi(),YY=Th();Rb.exports=KY;async function KY(e){let t=await YY(e),r=global.hdb_schema[e.schema][e.table];return $Y.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(KY,"lmdbSearchByHash")});var is=m((Hie,Ab)=>{"use strict";var Ah=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,l=void 0,_=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=l,this.offset=_}};Ab.exports=Ah});var Al=m((Fie,wb)=>{"use strict";var Ct=Xi(),WY=ye(),QY=x(),oe=xe(),ni=g(),zY=Yn(),Ob=rr().LMDB_ERRORS_ENUM,{getSchemaPath:JY}=we(),Gs=ni.SEARCH_WILDCARDS;async function XY(e,t,r){let s;e.schema===ni.SYSTEM_SCHEMA_NAME?s=zY[e.table]:s=global.hdb_schema[e.schema][e.table];let n=Ib(e,s.hash_attribute,r,t);return bb(e,n,s.hash_attribute,r)}a(XY,"prepSearch");async function bb(e,t,r,s){let n=JY(e.schema,e.table),i=await WY.openEnvironment(n,e.table),o=yb(i,e,t,r),c=o.transaction||i;if([oe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,oe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,oe.SEARCH_TYPES.SEARCH_ALL,oe.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(ZY(e,r)===!1){let _=e.search_attribute;if(_===r)return s?Nb(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[_]:E.key}),"toObject");return s?Nb(o,d):o.map(d)}let l=e.search_attribute===r?o.map(_=>_.key):o.map(_=>_.value);return s===!0?Ct.batchSearchByHashToMap(c,r,e.get_attributes,l):Ct.batchSearchByHash(c,r,e.get_attributes,l)}a(bb,"executeSearch");function yb(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 oe.SEARCH_TYPES.EQUALS:n=Ct.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case oe.SEARCH_TYPES.CONTAINS:n=Ct.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case oe.SEARCH_TYPES.ENDS_WITH:case oe.SEARCH_TYPES._ENDS_WITH:n=Ct.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case oe.SEARCH_TYPES.STARTS_WITH:case oe.SEARCH_TYPES._STARTS_WITH:n=Ct.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case oe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Ct.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case oe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Ct.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case oe.SEARCH_TYPES.SEARCH_ALL:return Ct.searchAll(e,s,t.get_attributes,o,c,u);case oe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Ct.searchAllToMap(e,s,t.get_attributes,o,c,u);case oe.SEARCH_TYPES.BETWEEN:n=Ct.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case oe.SEARCH_TYPES.GREATER_THAN:case oe.SEARCH_TYPES._GREATER_THAN:n=Ct.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case oe.SEARCH_TYPES.GREATER_THAN_EQUAL:case oe.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Ct.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case oe.SEARCH_TYPES.LESS_THAN:case oe.SEARCH_TYPES._LESS_THAN:n=Ct.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case oe.SEARCH_TYPES.LESS_THAN_EQUAL:case oe.SEARCH_TYPES._LESS_THAN_EQUAL:n=Ct.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(yb,"searchByType");function Nb(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(Nb,"createMapFromIterable");function ZY(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(ZY,"checkToFetchMore");function Ib(e,t,r,s){if(QY.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),Gs.indexOf(n)>-1)return r===!0?oe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:oe.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(Gs[0])<0&&n.indexOf(Gs[1])<0)return c===!0?r===!0?oe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:oe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:oe.SEARCH_TYPES.EQUALS;if(Gs.indexOf(i)>=0&&Gs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),oe.SEARCH_TYPES.CONTAINS;if(Gs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),oe.SEARCH_TYPES.ENDS_WITH;if(Gs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),oe.SEARCH_TYPES.STARTS_WITH;if(n.includes(Gs[0])||n.includes(Gs[1]))return oe.SEARCH_TYPES.EQUALS;throw new Error(Ob.UNKNOWN_SEARCH_TYPE)}else switch(s){case ni.VALUE_SEARCH_COMPARATORS.BETWEEN:return oe.SEARCH_TYPES.BETWEEN;case ni.VALUE_SEARCH_COMPARATORS.GREATER:return oe.SEARCH_TYPES.GREATER_THAN;case ni.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return oe.SEARCH_TYPES.GREATER_THAN_EQUAL;case ni.VALUE_SEARCH_COMPARATORS.LESS:return oe.SEARCH_TYPES.LESS_THAN;case ni.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return oe.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Ob.UNKNOWN_SEARCH_TYPE)}}a(Ib,"createSearchTypeFromSearchObject");wb.exports={executeSearch:bb,createSearchTypeFromSearchObject:Ib,prepSearch:XY,searchByType:yb}});var Ub=m((kie,Cb)=>{"use strict";var xie=is(),jY=Zi(),eK=x(),tK=g(),rK=Al();Cb.exports=sK;function sK(e,t){if(!eK.isEmpty(t)&&tK.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=jY(e,"value");if(s)throw s;let n=!0;return rK.prepSearch(e,t,n)}a(sK,"lmdbGetDataByValue")});var va=m((Yie,Db)=>{"use strict";var $ie=is(),nK=Zi(),iK=x(),oK=g(),aK=Al();Db.exports=cK;async function cK(e,t){if(!iK.isEmpty(t)&&oK.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=nK(e,"value");if(s)throw s;return aK.prepSearch(e,t,!1)}a(cK,"lmdbSearchByValue")});var Mb=m((Qie,Lb)=>{"use strict";var Wie=xe(),Oh=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}},Nh=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},bh=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Lb.exports={SearchByConditionsObject:Oh,SearchCondition:Nh,SortAttribute:bh}});var qb=m((Zie,Hb)=>{"use strict";var Jie=Mb().SearchByConditionsObject,uK=is(),lK=Zi(),yh=Xi(),Ol=xe(),{Resource:Xie}=(Xr(),te(GE)),Bb=Al(),_K=ph(),dK=require("lodash"),{getSchemaPath:EK}=we(),Pb=ye(),{handleHDBError:fK,hdb_errors:hK}=W(),{HTTP_STATUS_CODES:mK}=hK,SK=1e8;Hb.exports=pK;async function pK(e){let t=lK(e,"conditions");if(t)throw fK(t,t.message,mK.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=EK(e.schema,e.table),s=await Pb.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let l of e.conditions)Pb.openDBI(s,l.search_attribute);let i=dK.sortBy(e.conditions,l=>{if(l.estimated_count===void 0){let _=l.search_type;_===Ol.SEARCH_TYPES.EQUALS?l.estimated_count=yh.count(s,l.search_attribute,l.search_value):_===Ol.SEARCH_TYPES.CONTAINS||_===Ol.SEARCH_TYPES.ENDS_WITH?l.estimated_count=1/0:l.estimated_count=SK}return l.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await vb(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let l=s.dbis[n.hash_attribute],_=i.slice(1).map(Bb.filterByType),d=_.length,E=yh.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(f=>l.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!_[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>_K.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await vb(o,e,E,n.hash_attribute);c=c.concat(f)}let l=new Set,_=e.offset||0;c=c.filter(d=>l.has(d)?!1:(l.add(d),!0)).slice(_,e.limit&&e.limit+_),u=yh.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(pK,"lmdbSearchByConditions");async function vb(e,t,r,s){let n=new uK(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===Ol.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,Bb.searchByType(e,n,i,s).map(o=>o.value)}a(vb,"executeConditionSearch")});var Ba=m((eoe,Fb)=>{"use strict";var TK=g().OPERATIONS_ENUM,Ih=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=TK.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};Fb.exports=Ih});var wh=m((roe,Wb)=>{"use strict";var Vb=is(),$b=Ba(),Yb=va(),Kb=La(),Ft=g(),Gb=x(),xb=ye(),{getTransactionAuditStorePath:RK,getSchemaPath:gK}=we(),kb=F();Wb.exports=AK;async function AK(e){try{if(Gb.isEmpty(global.hdb_schema[e.schema])||Gb.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await OK(e),await NK(e);let t=gK(e.schema,e.table);try{await xb.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")kb.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=RK(e.schema,e.table);await xb.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")kb.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(AK,"lmdbDropTable");async function OK(e){let t=new Vb(Ft.SYSTEM_SCHEMA_NAME,Ft.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Yb(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 $b(Ft.SYSTEM_SCHEMA_NAME,Ft.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await Kb(n)}a(OK,"deleteAttributesFromSystem");async function NK(e){let t=new Vb(Ft.SYSTEM_SCHEMA_NAME,Ft.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await Yb(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 $b(Ft.SYSTEM_SCHEMA_NAME,Ft.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await Kb(n)}catch(i){throw i}}a(NK,"dropTableFromSystem")});var zb=m((noe,Qb)=>{"use strict";var bK=require("fs-extra"),yK=is(),IK=ji(),wK=Ba(),CK=wh(),UK=La(),DK=Rh(),LK=va(),xs=g(),{getSchemaPath:MK}=we(),{handleHDBError:PK,hdb_errors:vK}=W(),{HDB_ERROR_MSGS:BK,HTTP_STATUS_CODES:HK}=vK;Qb.exports=qK;async function qK(e){let t;try{t=await FK(e.schema);let r=new yK(xs.SYSTEM_SCHEMA_NAME,xs.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,xs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[xs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await LK(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await CK(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new wK(xs.SYSTEM_SCHEMA_NAME,xs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await UK(n);let i=MK(t);await bK.remove(i)}catch(r){throw r}}a(qK,"lmdbDropSchema");async function FK(e){let t=new IK(xs.SYSTEM_SCHEMA_NAME,xs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[xs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await DK(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw PK(new Error,BK.SCHEMA_NOT_FOUND(e),HK.NOT_FOUND,void 0,void 0,!0);return s}a(FK,"validateDropSchema")});var Uh=m((ooe,Jb)=>{"use strict";var Ch=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};Jb.exports=Ch});var Zb=m((uoe,Xb)=>{"use strict";var GK=require("fs-extra"),Nl=ye(),{getTransactionAuditStorePath:xK}=we(),Dh=xe(),coe=Uh();Xb.exports=kK;async function kK(e){let t;try{let r=xK(e.schema,e.table);await GK.mkdirp(r),t=await Nl.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{Nl.createDBI(t,Dh.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Nl.createDBI(t,Dh.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Nl.createDBI(t,Dh.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(kK,"createTransactionsAuditEnvironment")});var ry=m((_oe,ty)=>{"use strict";var Lh=g(),jb=ye(),VK=Fi(),{getSystemSchemaPath:$K,getSchemaPath:YK}=we(),KK=Yn(),WK=Ku(),Mh=Yu(),QK=F(),zK=Zb(),vh=KK.hdb_table,ey=[];for(let e=0;e<vh.attributes.length;e++)ey.push(vh.attributes[e].attribute);ty.exports=JK;async function JK(e,t){let r=YK(t.schema,t.table),s=new Mh(t.schema,t.table,Lh.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Mh(t.schema,t.table,Lh.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Mh(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await jb.createEnvironment(r,t.table),e!==void 0){let o=await jb.openEnvironment($K(),Lh.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await VK.insertRecords(o,vh.hash_attribute,ey,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Ph(s),await Ph(n),await Ph(i)}await zK(t)}catch(o){throw o}}a(JK,"lmdbCreateTable");async function Ph(e){try{await WK(e)}catch(t){QK.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Ph,"createAttribute")});var ny=m((Eoe,sy)=>{"use strict";var XK=pa(),ZK=Oa(),jK=hl(),Ha=g(),e1=Fi().updateRecords,t1=ye(),{getSchemaPath:r1}=we(),s1=Ua(),n1=F();sy.exports=i1;async function i1(e){try{let{schema_table:t,attributes:r}=XK(e);ZK(e,r,t.hash_attribute),e.schema!==Ha.SYSTEM_SCHEMA_NAME&&(r.includes(Ha.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Ha.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Ha.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Ha.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await jK(e.hdb_auth_header,t,r),n=r1(e.schema,e.table),i=await t1.openEnvironment(n,e.table),o=await e1(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await s1(e,o)}catch(c){n1.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(i1,"lmdbUpdateRecords")});var oy=m((hoe,iy)=>{"use strict";var o1=g().OPERATIONS_ENUM,Bh=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=o1.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};iy.exports=Bh});var cy=m((poe,ay)=>{"use strict";var Soe=oy(),a1=pa(),c1=Oa(),u1=hl(),qa=g(),l1=Fi().upsertRecords,_1=ye(),{getSchemaPath:d1}=we(),E1=Ua(),f1=F(),{handleHDBError:h1,hdb_errors:m1}=W();ay.exports=S1;async function S1(e){let t;try{t=a1(e)}catch(u){throw h1(u,u.message,m1.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;c1(e,s,r.hash_attribute),e.schema!==qa.SYSTEM_SCHEMA_NAME&&(s.includes(qa.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(qa.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(qa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(qa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await u1(e.hdb_auth_header,r,s),i=d1(e.schema,e.table),o=await _1.openEnvironment(i,e.table),c=await l1(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await E1(e,c)}catch(u){f1.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(S1,"lmdbUpsertRecords")});var ly=m((Roe,uy)=>{"use strict";var Hh=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};uy.exports=Hh});var dy=m((Aoe,_y)=>{"use strict";var qh=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}};_y.exports=qh});var hy=m((boe,fy)=>{"use strict";var Fh=ye(),{getTransactionAuditStorePath:p1}=we(),Noe=ly(),Fa=xe(),T1=x(),Ey=dy(),R1=require("util").promisify,g1=R1(setTimeout),A1=1e4,O1=100;fy.exports=N1;async function N1(e){let t=p1(e.schema,e.table),r=await Fh.openEnvironment(t,e.table,!0),s=Fh.listDBIs(r);Fh.initializeDBIs(r,Fa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new Ey;do n=await b1(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 g1(O1);while(n.transactions_deleted>0);return i}a(N1,"deleteAuditLogsBefore");async function b1(e,t){let r=new Ey;try{let s=e.dbis[Fa.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[Fa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];T1.isEmpty(c)||(n=e.dbis[Fa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Fa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>A1)break}return await n,r}catch(s){throw s}}a(b1,"deleteTransactions")});var Sy=m((Ioe,my)=>{"use strict";var Gh=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};my.exports=Gh});var Ty=m((Uoe,py)=>{"use strict";var y1=is(),I1=Ba(),Coe=Sy(),os=g(),w1=x(),xh=ye(),C1=Yn(),U1=va(),D1=La(),{getSchemaPath:L1}=we();py.exports=M1;async function M1(e,t=!0){let r;e.schema===os.SYSTEM_SCHEMA_NAME?r=C1[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await v1(e),n=L1(e.schema,e.table),i=await xh.openEnvironment(n,e.table);return t===!0&&await P1(e,i,r.hash_attribute),xh.dropDBI(i,e.attribute),s}a(M1,"lmdbDropAttribute");async function P1(e,t,r){let s=xh.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let l={};for(let _ in c)_!==i&&(l[_]=c[_]);n=t.dbis[r].put(o,l,u)}await n}a(P1,"removeAttributeFromAllObjects");async function v1(e){let t=new y1(os.SYSTEM_SCHEMA_NAME,os.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,os.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[os.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,os.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await U1(t)).filter(o=>o[os.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(w1.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[os.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new I1(os.SYSTEM_SCHEMA_NAME,os.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return D1(i)}a(v1,"dropAttributeFromSystem")});var by=m((Moe,Ny)=>{"use strict";var kh=ye(),eo=xe(),Loe=vt(),Vh=g(),Ry=x(),{getTransactionAuditStorePath:B1}=we(),H1=Xi(),bl=Qi(),q1=F();Ny.exports=F1;async function F1(e){let t=B1(e.schema,e.table),r=await kh.openEnvironment(t,e.table,!0),s=kh.listDBIs(r);kh.initializeDBIs(r,eo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Vh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return gy(r,e.search_values);case Vh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,x1(r,e.search_values,n);case Vh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return G1(r,e.search_values);default:return gy(r)}}a(F1,"readAuditLog");function gy(e,t=[0,Date.now()]){Ry.isEmpty(t[0])&&(t[0]=0),Ry.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[eo.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 bl,n))}a(gy,"searchTransactionsByTimestamp");function G1(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[eo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,Oy(e,i))}return Object.fromEntries(r)}a(G1,"searchTransactionsByUsername");function x1(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let l=t[c],_=H1.equals(e,eo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,eo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,l);for(let{value:d}of _){let E=Number(d);s.has(E)?s.get(E).push(l.toString()):s.set(E,[l.toString()])}}let n=Array.from(s.keys()),i=Oy(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],l=u.timestamp,_=s.get(l);Ay(u,"records",r,_,o),Ay(u,"original_records",r,_,o)}return Object.fromEntries(o)}a(x1,"searchTransactionsByHashValues");function Ay(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 l=n.get(u),_=l[l.length-1];if(_.timestamp===i)_[t]=[c];else{let d=new bl(e.operation,e.user_name,i,void 0);d[t]=[c],l.push(d)}}else{let l=new bl(e.operation,e.user_name,i,void 0);l[t]=[c],n.set(u,[l])}}}a(Ay,"loopRecords");function Oy(e,t){let r=[];try{let s=e.dbis[eo.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 bl,i);r.push(o)}}catch(i){q1.warn(i)}return r}catch(s){throw s}}a(Oy,"batchSearchTransactions")});var Iy=m((Hoe,yy)=>{"use strict";var{getSchemaPath:voe}=we(),Boe=ye(),{database:k1}=(de(),te(Ne));yy.exports={writeTransaction:V1};async function V1(e,t,r){return k1({database:e,table:t}).transaction(r)}a(V1,"writeTransaction")});var Dy=m((Foe,Uy)=>{"use strict";var{getSchemaPath:wy}=we(),Cy=ye();Uy.exports={flush:$1,resetReadTxn:Y1};async function $1(e,t){return(await Cy.openEnvironment(wy(e,t),t.toString())).flushed}a($1,"flush");async function Y1(e,t){try{(await Cy.openEnvironment(wy(e,t),t.toString())).resetReadTxn()}catch{}}a(Y1,"resetReadTxn")});var vy=m((xoe,Py)=>{"use strict";var{Readable:K1}=require("stream"),{getDatabases:W1}=(de(),te(Ne)),{readSync:Q1,openSync:z1,createReadStream:Ly}=require("fs"),{open:J1}=require("lmdb"),My=vu(),X1=Hu(),{INTERNAL_DBIS_NAME:Z1}=xe();Py.exports=eW;var $h=32768,j1=100;async function eW(e){let t=e.database||e.schema||"data",r=W1()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let l=r[n[0]];if(!l)throw new Error(`Can not find table ${n[0]}`);let _=l.dbisDB,d=J1({noSync:!0,maxDbs:X1.MAX_DBS}),E,f=d.openDB(Z1,new My(!1)),h=_.useReadTransaction(),T=0;for(let{key:y,value:O}of _.getRange({transaction:h,start:!1}))if(n.some(H=>y.startsWith?.(H+"/"))){f.put(y,O);let[,H]=y.split("/"),Y=!H,A=new My(!Y,Y);A.encoding="binary";let w=d.openDB(y,A),G=_.openDB(y,A);for(let{key:k,version:X,value:ge}of G.getRange({transaction:h,versions:Y}))E=w.put(k,ge,X),T++%j1===0&&await new Promise(ut=>setTimeout(ut,20))}await E;let S=Ly(d.path);return S.headers=u(),S.on("close",()=>{h.done(),d.close()}),S}let o=r[Object.keys(r)[0]].primaryStore,c=z1(o.path);return o.transaction(()=>{let l=Buffer.alloc($h);Q1(c,l,0,$h);let _=o.useReadTransaction(),d=Ly(null,{fd:c,start:$h}),E=new K1.from(async function*(){yield l;for await(let f of d)yield f;_.done()}());return E.headers=u(),E});function u(){let l=new Map;return l.set("content-type","application/octet-stream"),l.set("content-disposition",`attachment; filename="${t}"`),l.set("date",s),l}}a(eW,"getBackup")});var qy=m((Voe,Hy)=>{"use strict";var tW=F(),{handleHDBError:rW}=W(),sW=tA(),nW=Ku(),iW=Eh(),oW=zN(),aW=La(),cW=Rh(),uW=gb(),lW=Ub(),_W=va(),dW=qb(),EW=zb(),fW=ry(),hW=ny(),mW=cy(),SW=hy(),pW=wh(),TW=Ty(),RW=by(),gW=Iy(),By=Dy(),AW=vy(),Yh=class extends sW{static{a(this,"LMDBBridge")}async searchByConditions(t){return dW(t)}async getDataByHash(t){return await cW(t)}async searchByHash(t){return await uW(t)}async getDataByValue(t,r){return await lW(t,r)}async searchByValue(t){return await _W(t)}async createSchema(t){return await oW(t)}async dropSchema(t){return await EW(t)}async createTable(t,r){return await fW(t,r)}async dropTable(t){return await pW(t)}async createAttribute(t){return await nW(t)}async createRecords(t){return await iW(t)}async updateRecords(t){return await hW(t)}async upsertRecords(t){try{return await mW(t)}catch(r){throw rW(r,null,null,tW.ERR,r)}}async deleteRecords(t){return await aW(t)}async dropAttribute(t){return await TW(t)}async deleteAuditLogsBefore(t){return await SW(t)}async readAuditLog(t){return await RW(t)}writeTransaction(t,r,s){return gW.writeTransaction(t,r,s)}flush(t,r){return By.flush(t,r)}resetReadTxn(t,r){return By.resetReadTxn(t,r)}getBackup(t){return AW(t)}};Hy.exports=Yh});var Wy={};Ze(Wy,{ResourceBridge:()=>Qh});function zh({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 Gy(e,t){let r=as(e),s=zh(e,r);if(!r)throw new Fr.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};return Ye(i,async function*(o){for(let c of e.hash_values){let u=await r.get({id:c,lazy:n,select:s},i);u=u&&Iu(u),t?yield{key:c,value:u}:yield u}})}function as(e){let t=e.database||e.schema||NW,r=Gr()[t];if(!r)throw(0,Fr.handleHDBError)(new Error,OW.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function xy(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*ky(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,timestamp: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 Vy,yl,Fr,$y,Yy,xr,Kh,Wh,Ky,OW,NW,bW,yW,Fy,Qh,Qy=pe(()=>{"use strict";Vy=D(qy()),yl=D(Zi()),Fr=D(W());de();$y=D(pa()),Yy=D(Oa()),xr=D(g()),Kh=D(Fs()),Wh=D(qr()),Ky=D(x());Vn();wu();({HDB_ERROR_MSGS:OW}=Fr.hdb_errors),NW="data",bW=1e4,yW=10,Qh=class extends Vy.default{static{a(this,"ResourceBridge")}constructor(t){super(t),Fy=this}async searchByConditions(t){let r=(0,yl.default)(t,"conditions");if(r)throw(0,Fr.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=as(t);if(!s)throw new Fr.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i=>({attribute:i.search_attribute,comparator:i.search_type,value:i.search_value}));return s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:zh(t,s),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 Fr.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}]}et({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await as(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=as(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(l=>{if(!l){let{value:_,version:d}=r.primaryStore.getEntry(o);return i(o,_,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(l=>setImmediate(l));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){as(t).dropTable()}createSchema(t){return Ga({database:t.schema,table:null}),Kh.signalSchemaChange(new Wh.SchemaEventMsg(process.pid,xr.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Jh(t.schema),Kh.signalSchemaChange(new Wh.SchemaEventMsg(process.pid,xr.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,Fy.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,$y.default)(t);(0,Yy.default)(t,s,r.primaryKey);let n,i=Gr()[t.schema][t.table],o={user:t.hdb_user};return Ye(o,async c=>{if(!i.schemaDefined){n=[];for(let _ of s)i.attributes.find(E=>E.name==_)||n.push(_);n.length>0&&await i.addAttributes(n.map(_=>({name:_,indexed:!0})))}let u=[],l=[];for(let _ of t.records){let d=await i.get(_[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){l.push(_[i.primaryKey]);continue}d&&(d=Iu(d));for(let E in _)if(Object.prototype.hasOwnProperty.call(_,E)){let f=_[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,_[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(_),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(_,E)||(_[E]=d[E]);await i.put(_,o),u.push(_[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:l}})}async deleteRecords(t){let r=Gr()[t.schema][t.table],s={user:t.hdb_user};return Ye(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 xy(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Gr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Fr.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:xr.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],l=a(async()=>{let _=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(..._.deleted_hashes),o.push(..._.skipped_hashes),await(0,Ky.async_set_timeout)(yW),u=[],n=!0},"chunkDelete");for await(let _ of s)u.push(_[r.primaryKey]),c++,c%bW===0&&await l();return u.length>0&&await l(),n?xy(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){let r=(0,yl.default)(t,"hashes");if(r)throw r;return Gy(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of Gy(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&xr.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);let s=(0,yl.default)(t,"value");if(s)throw s;let n=as(t);if(!n)throw new Fr.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===xr.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:zh(t,n)})}async getDataByValue(t,r){let s=new Map,n=as(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){as({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return as(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=as(t),s={};switch(t.search_type){case xr.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,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case xr.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of ky(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return ky(r,t.search_values?.[0],t.search_values?.[1])}}};a(zh,"getSelect");a(Gy,"getRecords");a(as,"getTable");a(xy,"createDeleteResponse");a(ky,"groupRecordsInHistory")});var Br=m((zoe,zy)=>{"use strict";var{ResourceBridge:IW}=(Qy(),te(Wy)),wW=Q();wW.initSync();var Il;function CW(){return Il||(Il=new IW,Il)}a(CW,"getBridge");zy.exports=CW()});var jy=m((Xoe,Zy)=>{"use strict";var Jy=require("lodash"),xa=require("mathjs"),UW=require("jsonata"),Xy=x();Zy.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?Jy.uniqWith(e,Jy.isEqual):e,searchJSON:DW,mad:ka.bind(null,xa.mad),mean:ka.bind(null,xa.mean),mode:ka.bind(null,xa.mode),prod:ka.bind(null,xa.prod),median:ka.bind(null,xa.median)};function ka(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(ka,"aggregateFunction");function DW(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(Xy.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),Xy.isEmpty(this.__ala__.res[r])){let s=UW(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(DW,"searchJSON")});var tI=m((joe,eI)=>{"use strict";var We=require("moment"),Xh="YYYY-MM-DDTHH:mm:ss.SSSZZ";We.suppressDeprecationWarnings=!0;eI.exports={current_date:()=>We().utc().format("YYYY-MM-DD"),current_time:()=>We().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return We(e).utc().format("YYYY");case"month":return We(e).utc().format("MM");case"day":return We(e).utc().format("DD");case"hour":return We(e).utc().format("HH");case"minute":return We(e).utc().format("mm");case"second":return We(e).utc().format("ss");case"millisecond":return We(e).utc().format("SSS");default:break}},date:e=>We(e).utc().format(Xh),date_format:(e,t)=>We(e).utc().format(t),date_add:(e,t,r)=>We(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>We(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=We(e).utc(),n=We(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>We().utc().valueOf(),get_server_time:()=>We().format(Xh),offset_utc:(e,t)=>We(e).utc().utcOffset(t).format(Xh)}});var iI=m((eae,nI)=>{"use strict";var LW=require("@turf/area"),MW=require("@turf/length"),PW=require("@turf/circle"),vW=require("@turf/difference"),BW=require("@turf/distance"),HW=require("@turf/boolean-contains"),qW=require("@turf/boolean-equal"),FW=require("@turf/boolean-disjoint"),GW=require("@turf/helpers"),rI=g(),le=x();nI.exports={geoArea:xW,geoLength:kW,geoCircle:VW,geoDifference:$W,geoDistance:sI,geoNear:YW,geoContains:KW,geoEqual:WW,geoCrosses:QW,geoConvert:zW};var Zh="geo1 is required",jh="geo2 is required";function xW(e){if(le.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),LW.default(e)}a(xW,"geoArea");function kW(e,t){if(le.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),MW.default(e,{units:t||"kilometers"})}a(kW,"geoLength");function VW(e,t,r){if(le.isEmpty(e))throw new Error("point is required");if(le.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),PW.default(e,t,{units:r||"kilometers"})}a(VW,"geoCircle");function $W(e,t){if(le.isEmpty(e))throw new Error("poly1 is required");if(le.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),vW(e,t)}a($W,"geoDifference");function sI(e,t,r){if(le.isEmpty(e))throw new Error("point1 is required");if(le.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),BW.default(e,t,{units:r||"kilometers"})}a(sI,"geoDistance");function YW(e,t,r,s){if(le.isEmpty(e))throw new Error("point1 is required");if(le.isEmpty(t))throw new Error("point2 is required");if(le.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");return sI(e,t,s)<=r}a(YW,"geoNear");function KW(e,t){if(le.isEmpty(e))throw new Error(Zh);if(le.isEmpty(e))throw new Error(jh);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),HW.default(e,t)}a(KW,"geoContains");function WW(e,t){if(le.isEmpty(e))throw new Error(Zh);if(le.isEmpty(e))throw new Error(jh);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),qW.default(e,t)}a(WW,"geoEqual");function QW(e,t){if(le.isEmpty(e))throw new Error(Zh);if(le.isEmpty(e))throw new Error(jh);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),!FW.default(e,t)}a(QW,"geoCrosses");function zW(e,t,r){if(le.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(le.isEmpty(t))throw new Error("geo_type is required");if(le.isEmpty(rI.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(rI.GEO_CONVERSION_ENUM).join(",")}`);return GW[t](e,r)}a(zW,"geoConvert")});var wl=m((rae,oI)=>{var ii=jy(),ur=tI(),cs=iI();oI.exports=e=>{e.aggr.mad=e.aggr.MAD=ii.mad,e.aggr.mean=e.aggr.MEAN=ii.mean,e.aggr.mode=e.aggr.MODE=ii.mode,e.aggr.prod=e.aggr.PROD=ii.prod,e.aggr.median=e.aggr.MEDIAN=ii.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ii.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ii.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=ur.current_date,e.fn.current_time=e.fn.CURRENT_TIME=ur.current_time,e.fn.extract=e.fn.EXTRACT=ur.extract,e.fn.date=e.fn.DATE=ur.date,e.fn.date_format=e.fn.DATE_FORMAT=ur.date_format,e.fn.date_add=e.fn.DATE_ADD=ur.date_add,e.fn.date_sub=e.fn.DATE_SUB=ur.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=ur.date_diff,e.fn.now=e.fn.NOW=ur.now,e.fn.offset_utc=e.fn.OFFSET_UTC=ur.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=ur.get_server_time,e.fn.getdate=e.fn.GETDATE=ur.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=ur.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=cs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=cs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=cs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=cs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=cs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=cs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=cs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=cs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=cs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=cs.geoNear}});var lI=m((sae,uI)=>{"use strict";var Va=require("lodash"),pt=require("alasql");pt.options.cache=!1;var JW=wl(),aI=require("clone"),Cl=require("recursive-iterator"),se=F(),ne=x(),to=Br(),XW=g(),{hdb_errors:ZW}=W(),{getDatabases:cI}=(de(),te(Ne)),jW="IS NULL",kr="There was a problem performing this search. Please check the logs and try again.";JW(pt);var em=class{static{a(this,"SQLSearch")}constructor(t,r){if(ne.isEmpty(t))throw se.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(),ne.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!ne.isEmptyOrZeroLength(s))return se.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw se.error("Error thrown from checkEmptySQL in SQLSearch class method search."),se.error(s),new Error(kr)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw se.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),se.error(s),new Error(kr)}if(Object.keys(this.data).length===0)return se.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw se.error("Error thrown from processJoins in SQLSearch class method search."),se.error(s),new Error(kr)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw se.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),se.error(s),new Error(kr)}try{return t=await this._finalSQL(),t}catch(s){throw se.error("Error thrown from finalSQL in SQLSearch class method search."),se.error(s),new Error(kr)}}_getColumns(){let t=new Cl(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(aI(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Va.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=cI()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(ne.isEmpty(this.statement.where)){se.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Cl(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!ne.isEmpty(r)&&r.right)if(ne.isNotEmptyAndHasValue(r.right.value)){let s=ne.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new pt.yy.LogicValue({value:s}):r.right instanceof pt.yy.StringValue&&!ne.isEmpty(s)&&ne.autoCasterIsNumberCheck(s.toString())&&(r.right=new pt.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=ne.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new pt.yy.LogicValue({value:i}):s instanceof pt.yy.StringValue&&ne.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new pt.yy.NumValue({value:i}))});if(t){se.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Cl(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(!ne.isEmpty(XW.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(ne.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(ne.isEmptyOrZeroLength(r.left.columnid)||ne.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(ne.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"=":!ne.isEmpty(r.right.value)||!ne.isEmpty(r.left.value)?s.add(ne.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 l=0;l<u.length;l++)if(u[l].value)s.add(u[l].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(ne.isEmptyOrZeroLength(this.all_table_attributes)&&ne.isEmptyOrZeroLength(this.statement.from)&&ne.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&&Va.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(ne.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);ne.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(ne.isEmptyOrZeroLength(this.all_table_attributes)&&!ne.isEmptyOrZeroLength(this.columns.columns))return t;if(ne.isEmptyOrZeroLength(this.all_table_attributes)&&ne.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await pt.promise(r)}catch(r){throw se.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),se.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(aI(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(ne.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(jW)>-1&&this.tables.forEach(n=>{let i={columnid:cI()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Va.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,l=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!ne.isEmpty(this.exact_search_values[l])&&!this.exact_search_values[l].ignore&&!ne.isEmptyOrZeroLength(this.exact_search_values[l].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[l].values);let _=await to.getDataByHash(c);for(let d of c.hash_values)_.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(_){throw se.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),se.error(_),new Error(kr)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[l].values).map(async _=>{let d=Object.assign({},c);d.search_value=_;let E=await to.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]):(this.data[i].__merged_data[f]=[...s[i]],this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(f)))}))}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),se.error(_),new Error(kr)}else if(!ne.isEmpty(this.comparator_search_values[l])&&!this.comparator_search_values[l].ignore&&!ne.isEmptyOrZeroLength(this.comparator_search_values[l].comparators))try{let _=this.comparator_search_values[l].comparators;for(let d=0,E=_.length;d<E;d++){let f=_[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await to.getDataByValue(c,f.operation);if(u)for(let[T]of h)this.data[i].__merged_data[T]||(this.data[i].__merged_data[T]=[...s[i]],this._setMergedHashAttribute(i,ne.autoCast(T)));else for(let[T,S]of h)this.data[i].__merged_data[T]?this._updateMergedAttribute(i,T,n.attribute,S[n.attribute]):(this.data[i].__merged_data[T]=[...s[i]],this._updateMergedAttribute(i,T,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(T)))}}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),se.error(_),new Error(kr)}else try{c.search_attribute=n.attribute,c.search_value="*";let _=await to.getDataByValue(c);if(u)for(let[d]of _)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,ne.autoCast(d)));else for(let[d,E]of _)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(d)))}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),se.error(_),new Error(kr)}}}_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 pt.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 pt.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new pt.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 pt.yy.FuncValue:new pt.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(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,T=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${T}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${T}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"",l="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(l="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let _="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(_=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${l} ${_} ${d}`,h=this._convertColumnsToIndexes(f,n);E=await pt.promise(h,t),t=null}catch(f){throw se.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),se.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let T=E[f];o.forEach(S=>{T[S.key]!==null&&T[S.key]!==void 0&&S.keys.add(T[S.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),T=Va.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,y=T.length;S<y;S++){let O=T[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[O]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Cl(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=Va.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 se.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),se.error(i),new Error(kr)}}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 _ in i)o.push(i[_][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 to.getDataByHash(c),l=n.columns.length;for(let _=0,d=o.length;_<d;_++){let E=o[_],f=u.get(E);for(let h=0;h<l;h++){let T=n.columns[h],S=f[T]===void 0?null:f[T];this.data[s].__merged_data[E].push(S)}}}}catch(r){throw se.error("Error thrown from getDataByHash function in SQLSearch class method getData."),se.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&&delete this.statement.limit,this.statement.offset&&delete this.statement.offset);let s;try{let n=this._buildSQL();se.trace(`Final SQL: ${n}`),s=await pt.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),se.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw se.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),se.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 se.error(ZW.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),se.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return 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],l=new RegExp(`${u}.\`${o}\``,"g"),_=`${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"),l=`[${c}]`;s=s.replace(u,l)});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 to.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 se.error("There was an error when processing this SQL operation. Check your logs"),se.error(o),new Error(kr)}}return Object.values(Object.values(this.data)[0].__merged_data)}};uI.exports=em});var Tr=m((iae,_I)=>{"use strict";var eQ=jg();_I.exports={searchByConditions:rQ,searchByHash:sQ,searchByValue:nQ,search:iQ};var tm=Br(),{transformReq:rm}=x(),tQ=lI();async function rQ(e){return rm(e),tm.searchByConditions(e)}a(rQ,"searchByConditions");async function sQ(e){rm(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of tm.searchByHash(e))r&&t.push(r);return t}a(sQ,"searchByHash");async function nQ(e){rm(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of tm.searchByValue(e))t.push(r);return t}a(nQ,"searchByValue");function iQ(e,t){try{let r=new eQ(e);r.validate(),new tQ(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(iQ,"search")});var Ul=m((aae,dI)=>{"use strict";var oQ=Br();dI.exports={writeTransaction:aQ};function aQ(e,t,r){return oQ.writeTransaction(e,t,r)}a(aQ,"writeTransaction")});var mI=m((lae,hI)=>{"use strict";var cQ=Tr(),uQ=_n(),EI=F(),lQ=Rr(),uae=Ul(),_Q=require("clone"),nm=require("alasql"),dQ=wl(),fI=require("util"),EQ=fI.promisify(uQ.getTableSchema),fQ=fI.promisify(cQ.search),hQ=g(),sm=x();dQ(nm);hI.exports={update:SQ};var mQ="There was a problem performing this update. Please check the logs and try again.";async function SQ({statement:e,hdb_user:t}){let r=await EQ(e.table.databaseid,e.table.tableid),s=pQ(e.columns);sm.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=_Q(n),c=sm.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,l=nm.parse(u).statements[0],_=await fQ(l),d=TQ(s,_);return RQ(o,d,t)}a(SQ,"update");function pQ(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=nm.compile(`SELECT ${r.expression.toString()} AS [${hQ.FUNC_VAL}] FROM ?`)}),t}catch(t){throw EI.error(t),new Error(mQ)}}a(pQ,"createUpdateRecord");function TQ(e,t){return sm.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(TQ,"buildUpdateRecords");async function RQ(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await lQ.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){EI.error(`Error delete new_attributes from update response: ${i}`)}return n}a(RQ,"updateRecords")});var pI=m((fae,SI)=>{var gQ=require("alasql"),AQ=Tr(),OQ=F(),NQ=Br(),om=require("util"),im=x(),bQ=g(),yQ=_n(),dae=Ul(),Eae=Rr(),IQ="record",wQ="successfully deleted",CQ=om.callbackify(MQ),UQ=om.promisify(AQ.search),DQ=om.promisify(yQ.getTableSchema);SI.exports={convertDelete:CQ};function LQ(e){return`${e.deleted_hashes.length} ${IQ}${e.deleted_hashes.length===1?"":"s"} ${wQ}`}a(LQ,"generateReturnMessage");async function MQ({statement:e,hdb_user:t}){let r=await DQ(e.table.databaseid,e.table.tableid);im.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=im.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=gQ.parse(o).statements[0],u={operation:bQ.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await UQ(c);let l=await NQ.deleteRecords(u);return im.isEmptyOrZeroLength(l.message)&&(l.message=LQ(l)),delete l.txn_time,l}catch(l){throw OQ.error(l),l.hdb_code?l.message:l}}a(MQ,"convertDelete")});var OI=m((mae,AI)=>{"use strict";var PQ=Wn(),{hdb_errors:TI}=W(),{getDatabases:RI}=(de(),te(Ne));AI.exports={checkSchemaExists:gI,checkSchemaTableExists:vQ,schema_describe:PQ};async function gI(e){if(!RI()[e])return TI.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(gI,"checkSchemaExists");async function vQ(e,t){let r=await gI(e);if(r)return r;if(!RI()[e][t])return TI.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(vQ,"checkSchemaTableExists")});var $a=m((pae,BQ)=>{BQ.exports={name:"harperdb",version:"4.2.0-alpha.11",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{node:">=14.0.0","preferred-node":"18.15.0","go-lang":"1.19.12","nats-server":"2.9.21"},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":"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: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:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","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":"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.382.0","@aws-sdk/lib-storage":"3.382.0","@aws-sdk/abort-controller":"3.370.0","@endo/static-module-record":"^0.7.16","@fastify/autoload":"~5.7.1","@fastify/compress":"~6.4.0","@fastify/cors":"~8.3.0","@fastify/static":"~6.10.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"1.7.4","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2",esbuild:"^0.18.0","fast-glob":"3.3.1",fastify:"~4.21.0","fastify-plugin":"~4.5.0","fs-extra":"11.1.1",graphql:"^16.6.0","human-readable-ids":"1.0.4",inquirer:"8.2.5","is-number":"7.0.0",joi:"17.9.2",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.1",lmdb:"2.8.4",lodash:"4.17.21",mathjs:"11.9.1",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.0",msgpackr:"1.9.7",nats:"2.16.0",needle:"3.2.0","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.4.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.14.2",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0",ses:"^0.18.1","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.18.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.0","validate.js":"0.13.1",ws:"^8.13.0",yaml:"2.3.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"0.27.2",chai:"4.3.7","chai-integer":"0.1.0",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^4.9.4","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var Bl={};Ze(Bl,{addAnalyticsListener:()=>lm,recordAction:()=>ai,recordActionBinary:()=>vl,setAnalyticsEnabled:()=>HQ});function HQ(e){MI=e}function ai(e,t,r,s,n){if(!MI)return;let i=t+"-"+r;s&&(i+="-"+s);let o=Ml.get(i);o?(o.push(e),o.total+=e):(o=[e],o.total=e,o.description={metric:t,path:r,method:s,type:n},Ml.set(i,o)),Ll||qQ()}function vl(e,t,r,s,n){ai(e?1:0,t,r,s,n)}function lm(e){vI.push(e)}function qQ(){Ll=performance.now(),setTimeout(()=>{let e=performance.now()-Ll;Ll=0;let t=[],r={time:Date.now(),period:e,threadId:oi.threadId,metrics:t};for(let[n,i]of Ml)if(i.sort){i.sort();let o=i.length;t.push(Object.assign(i.description,{median:i[o>>1],mean:i.total/o,p95:i[Math.floor(o*.95)],p90:i[Math.floor(o*.9)],count:o}))}else t.push(i);let s=process.memoryUsage();t.push({metric:"memory",threadId:oi.threadId,...s});for(let n of vI)n(t);Ml=new Map,oi.parentPort?oi.parentPort.postMessage({type:PI,report:r}):HI({report:r})},um).unref()}async function FQ(e,t=6e4){let r=_m(),s;for(let _ of r.primaryStore.getRange({start:Dl+"z",end:Dl,reverse:!0}))if(_.value?.time){s=_.value.time;break}if(Date.now()-t<s)return;let n,i=new Map,o;for(let{key:_,value:d}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!d)continue;if(n){if(_>n+t)break}else n=_;o=_;let{metrics:E}=d;for(let f of E||[]){let{path:h,method:T,type:S,metric:y,count:O,threadId:H,...Y}=f;O||(O=1);let A=y+(h?"-"+h:"");T&&(A+="-"+T);let w=i.get(A);if(w)for(let G in Y){let k=Y[G];if(typeof k=="number"){let X=w.count||1;w[G]=(w[G]*X+k*O)/(w.count=X+O)}}else w=Object.assign({period:t},f),i.set(A,w)}await GQ()}for(let[_,d]of i)d.id=Dl+Math.round(o)+"-"+_,d.time=o,r.put(d);let c=Date.now(),{idle:u,active:l}=performance.eventLoopUtilization();r.put({id:Dl+Math.round(c)+"-main-thread-utilization",metric:"main-thread-utilization",idle:u-NI,active:l-bI,time:c}),NI=u,bI=l}async function xQ(e,t){let r=_m(),s=Date.now()-e;for(let n of r.primaryStore.getKeys({start:!1,end:s}))r.primaryStore.remove(n)}function _m(){return yI||(yI=et({table:"hdb_analytics",database:"system",expiration:864e3,audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"values"}]}))}function VQ(){BI=!0,setInterval(async()=>{await FQ(um,cm),await xQ(kQ,um)},cm/2).unref()}function HI(e,t){let r=e.report;r.threadId=t?.threadId||oi.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(II+=s.mean*s.count);r.totalBytesProcessed=II,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(wI.get(t))}),wI.set(t,t.performance.eventLoopUtilization())),r.id=(0,DI.getNextMonotonicTime)(),_m().put(r),BI||VQ(),$Q&&(qI=KQ(r))}async function KQ(e){if(await qI,!Tn){let r=(0,Ya.dirname)((0,UI.getLogFilePath)());try{Tn=await(0,am.open)((0,Ya.join)(r,"analytics.log"),"r+")}catch{Tn=await(0,am.open)((0,Ya.join)(r,"analytics.log"),"w+")}}let t=(await Tn.stat()).size;if(t>YQ){let r=Buffer.alloc(t);await Tn.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await Tn.write(r,{position:0}),await Tn.truncate(r.length),t=r.length}await Tn.write(JSON.stringify(e)+`
|
|
6
|
-
`,t)}var
|
|
1
|
+
"use strict";var jB=Object.create;var zo=Object.defineProperty;var eH=Object.getOwnPropertyDescriptor;var tH=Object.getOwnPropertyNames;var rH=Object.getPrototypeOf,sH=Object.prototype.hasOwnProperty;var a=(e,t)=>zo(e,"name",{value:t,configurable:!0});var Se=(e,t)=>()=>(e&&(t=e(e=0)),t);var m=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ye=(e,t)=>{for(var r in t)zo(e,r,{get:t[r],enumerable:!0})},SR=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of tH(t))!sH.call(e,n)&&n!==r&&zo(e,n,{get:()=>t[n],enumerable:!(s=eH(t,n))||s.enumerable});return e};var C=(e,t,r)=>(r=e!=null?jB(rH(e)):{},SR(t||!e||!e.__esModule?zo(r,"default",{value:e,enumerable:!0}):r,e)),ee=e=>SR(zo({},"__esModule",{value:!0}),e);var RR=m((rre,TR)=>{var nH=require("fast-glob"),{statSync:gE,existsSync:AE,readFileSync:iH,writeFileSync:oH}=require("fs"),{spawnSync:aH,spawn:cH}=require("child_process"),{isMainThread:uH}=require("worker_threads"),{join:ys,relative:pR}=require("path"),{PACKAGE_ROOT:mr}=A(),{tmpdir:lH}=require("os");require("source-map-support").install();var _H=["resources","server","dataLayer"],Jo="ts-build",OE,dH=__filename.endsWith("tsBuild.js");if(dH){if(uH){let r;try{gE(ys(mr,Jo)),r=!0}catch{}if(r)for(let s of nH.sync(_H.map(n=>n+"/**/*.ts"),{cwd:mr})){let n=0,i=0;try{n=gE(ys(mr,s)).mtimeMs-5e3,i=gE(ys(mr,Jo,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."),OE=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),OE=!0;if(OE){let s=aH(process.argv[0],[ys(mr,"node_modules/.bin/tsc")],{cwd:mr});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let n=ys(lH(),"harperdb-tsc.pid"),i;if(AE(n))try{process.kill(+iH(n,{encoding:"utf8"}),0),i=!0}catch{}if(!i){console.log("starting tsc background process");let o=cH(process.argv[0],[ys(mr,"node_modules/.bin/tsc"),"--watch"],{cwd:mr,detached:!0,stdio:"ignore"});oH(n,o.pid.toString()),o.unref()}}}}let e=TR.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(mr)&&!s[0].includes("node_modules")){let i=pR(mr,s[0]),o;i.startsWith(Jo)?o=ys(mr,pR(Jo,i)):o=ys(mr,Jo,i);let c=ys(o,r),u=c+".js";if(AE(u))return u;if(c.includes(".")&&AE(c))return c}return t(r,s,n)}}});var A=m((ire,PR)=>{"use strict";var Sr=require("path"),EH=require("fs"),{relative:sre,join:nre}=Sr,{existsSync:fH}=EH;function hH(){let e=__dirname;for(;!fH(Sr.join(e,"package.json"));){let t=Sr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(hH,"getHDBPackageRoot");var cn=hH(),gR="js",hu=gR,mH="harperdb-config.yaml",SH="defaultConfig.yaml",pH="hdb",AR=`harperdb.${hu}`,OR=`customFunctionsServer.${hu}`,TH=`restartHdb.${hu}`,bE="HarperDB",fu="Custom Functions",mu="Clustering Hub",Su="Clustering Leaf",RH="Clustering Ingest Service",gH="Clustering Reply Service",AH="foreground.pid",OH="hdb.pid",NH="data",bH={HDB:bE,CLUSTERING_HUB:mu,CLUSTERING_LEAF:Su,CLUSTERING_INGEST_SERVICE:RH,CLUSTERING_REPLY_SERVICE:gH,CUSTOM_FUNCTIONS:fu,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"},yH={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},IH={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},wH={harperdb:bE,"clustering hub":mu,"clustering leaf":Su,"custom functions":fu,custom_functions:fu,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},CH={CLUSTERING_HUB_PROC_DESCRIPTOR:mu,CLUSTERING_LEAF_PROC_DESCRIPTOR:Su},NE={HDB:Sr.join(cn,"server/harperdb"),CUSTOM_FUNCTIONS:Sr.join(cn,"server/customFunctions"),CLUSTERING_HUB:Sr.join(cn,"server/nats"),CLUSTERING_LEAF:Sr.join(cn,"server/nats")},UH={HDB:Sr.join(NE.HDB,AR),CUSTOM_FUNCTIONS:Sr.join(NE.CUSTOM_FUNCTIONS,OR)},DH={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Sr.join(cn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Sr.join(cn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Sr.join(cn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},LH={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},NR="support@harperdb.io",MH="customer-success@harperdb.io",bR=1,PH=4141,yR="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",vH="https://www.harperdb.io/product",BH=`For support, please submit a request at ${yR} or contact ${NR}`,IR=`For license support, please contact ${MH}`,HH="None of the specified records were found.",qH="hash attribute not found",FH=`Your current license only supports ${bR} role. ${IR}`,GH="Your current license only supports 3 connections to a node.",xH="127.0.0.1",kH=1,VH=/^\.$/,$H=/^\.\.$/,YH="U+002E",KH=/\//g,WH="U+002F",QH=/U\+002F/g,zH=/^U\+002E$/,JH=/^U\+002EU\+002E$/,XH="d",ZH=999999,jH="*",e0="--max-old-space-size=",t0="system",r0="__hdb_hash",s0=".harperdb",n0=".hdb",i0="keys",o0="hdb_boot_properties.file",a0=".updateConfig.json",c0="SIGTSTP",u0=24,l0=6e4,_0=448,d0="blob",E0="trash",f0="database",h0="schema",m0="transactions",S0=".count",p0="id",T0="PROCESS_NAME",wR={SETTINGS_PATH_KEY:"settings_path"},CR=require("lodash"),R0={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",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},g0={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},A0={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},O0={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"},N0={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"},tr="hdb_internal:",b0={CREATE_SCHEMA:tr+"create_schema",CREATE_TABLE:tr+"create_table",CREATE_ATTRIBUTE:tr+"create_attribute",ADD_USER:tr+"add_user",ALTER_USER:tr+"alter_user",DROP_USER:tr+"drop_user",HDB_NODES:tr+"hdb_nodes",HDB_USERS:tr+"hdb_users",HDB_WORKERS:tr+"hdb_workers",CATCHUP:tr+"catchup",SCHEMA_CATCHUP:tr+"schema_catchup",WORKER_ROOM:tr+"cluster_workers"},y0={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"},I0="060493.ks",w0=".license",C0={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},K={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",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"},U0={CSV:".csv",JSON:".json"},D0={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},L0={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Xo={};Xo[K.INSERT]=K.INSERT;Xo[K.UPDATE]=K.UPDATE;Xo[K.UPSERT]=K.UPSERT;Xo[K.DELETE]=K.DELETE;var ge=Object.create(null);ge[K.DESCRIBE_ALL]=K.DESCRIBE_ALL;ge[K.DESCRIBE_TABLE]=K.DESCRIBE_TABLE;ge[K.DESCRIBE_SCHEMA]=K.DESCRIBE_SCHEMA;ge[K.READ_LOG]=K.READ_LOG;ge[K.ADD_NODE]=K.ADD_NODE;ge[K.LIST_USERS]=K.LIST_USERS;ge[K.LIST_ROLES]=K.LIST_ROLES;ge[K.USER_INFO]=K.USER_INFO;ge[K.SQL]=K.SQL;ge[K.GET_JOB]=K.GET_JOB;ge[K.SEARCH_JOBS_BY_START_DATE]=K.SEARCH_JOBS_BY_START_DATE;ge[K.DELETE_FILES_BEFORE]=K.DELETE_FILES_BEFORE;ge[K.EXPORT_LOCAL]=K.EXPORT_LOCAL;ge[K.EXPORT_TO_S3]=K.EXPORT_TO_S3;ge[K.CLUSTER_STATUS]=K.CLUSTER_STATUS;ge[K.REMOVE_NODE]=K.REMOVE_NODE;ge[K.RESTART]=K.RESTART;ge[K.CUSTOM_FUNCTIONS_STATUS]=K.CUSTOM_FUNCTIONS_STATUS;ge[K.GET_CUSTOM_FUNCTIONS]=K.GET_CUSTOM_FUNCTIONS;ge[K.GET_CUSTOM_FUNCTION]=K.GET_CUSTOM_FUNCTION;ge[K.SET_CUSTOM_FUNCTION]=K.SET_CUSTOM_FUNCTION;ge[K.DROP_CUSTOM_FUNCTION]=K.DROP_CUSTOM_FUNCTION;ge[K.ADD_CUSTOM_FUNCTION_PROJECT]=K.ADD_CUSTOM_FUNCTION_PROJECT;ge[K.DROP_CUSTOM_FUNCTION_PROJECT]=K.DROP_CUSTOM_FUNCTION_PROJECT;ge[K.PACKAGE_CUSTOM_FUNCTION_PROJECT]=K.PACKAGE_CUSTOM_FUNCTION_PROJECT;ge[K.DEPLOY_CUSTOM_FUNCTION_PROJECT]=K.DEPLOY_CUSTOM_FUNCTION_PROJECT;var M0={DEBUG:"debug",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status"},P0={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},UR={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"},v0=CR.invert(UR),g={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_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",HTTP_THREADS:"http_threads",HTTP_SESSION_AFFINITY:"http_sessionAffinity",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_AUTHENTICATION_OPERATIONTOKENTIMEOUT:"operationsApi_authentication_operationTokenTimeout",OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT:"operationsApi_authentication_refreshTokenTimeout",OPERATIONSAPI_FOREGROUND:"operationsApi_foreground",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",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_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERT_AUTH:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",OPERATIONSAPI_NODEENV:"operationsApi_nodeEnv",ROOTPATH:"rootPath",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",SCHEMAS:"schemas",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication"},DR={settings_path:wR.SETTINGS_PATH_KEY,hdb_root_key:g.ROOTPATH,hdb_root:g.ROOTPATH,server_port_key:g.OPERATIONSAPI_NETWORK_PORT,server_port:g.OPERATIONSAPI_NETWORK_PORT,cert_key:g.OPERATIONSAPI_TLS_CERTIFICATE,certificate:g.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:g.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:g.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:g.OPERATIONSAPI_NETWORK_HTTPS,https_on:g.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:g.OPERATIONSAPI_NETWORK_CORS,cors_on:g.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:g.LOGGING_LEVEL,log_level:g.LOGGING_LEVEL,log_path_key:g.LOGGING_ROOT,log_path:g.LOGGING_ROOT,props_env_key:g.OPERATIONSAPI_NODEENV,node_env:g.OPERATIONSAPI_NODEENV,clustering_node_name_key:g.CLUSTERING_NODENAME,node_name:g.CLUSTERING_NODENAME,clustering_enabled_key:g.CLUSTERING_ENABLED,clustering:g.CLUSTERING_ENABLED,max_http_threads:g.HTTP_THREADS,max_hdb_processes:g.HTTP_THREADS,server_timeout_key:g.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:g.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:g.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:g.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:g.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:g.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:g.LOGGING_AUDITLOG,disable_transaction_log:g.LOGGING_AUDITLOG,operation_token_timeout_key:g.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:g.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:g.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:g.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_enabled_key:g.CUSTOMFUNCTIONS_ENABLED,custom_functions:g.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:g.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:g.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:g.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:g.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:g.HTTP_THREADS,log_to_file:g.LOGGING_FILE,log_to_stdstreams:g.LOGGING_STDSTREAMS,run_in_foreground:g.OPERATIONSAPI_FOREGROUND,local_studio_on:g.LOCALSTUDIO_ENABLED,clustering_port:g.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:g.CLUSTERING_USER,clustering_enabled:g.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:g.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:g.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:g.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:g.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:g.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:g.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:g.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:g.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:g.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:g.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:g.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:g.CLUSTERING_NODENAME,clustering_tls_certificate:g.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:g.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:g.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:g.CLUSTERING_TLS_INSECURE,clustering_tls_verify:g.CLUSTERING_TLS_VERIFY,clustering_loglevel:g.CLUSTERING_LOGLEVEL,clustering_republishmessages:g.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:g.CLUSTERING_DATABASELEVEL,customfunctions_enabled:g.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:g.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:g.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:g.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:g.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:g.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:g.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:g.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:g.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:g.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:g.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:g.CUSTOMFUNCTIONS_NODEENV,http_threads:g.HTTP_THREADS,http_session_affinity:g.HTTP_SESSION_AFFINITY,customfunctions_processes:g.HTTP_THREADS,customfunctions_root:g.CUSTOMFUNCTIONS_ROOT,localstudio_enabled:g.LOCALSTUDIO_ENABLED,logging_file:g.LOGGING_FILE,logging_level:g.LOGGING_LEVEL,logging_root:g.LOGGING_ROOT,logging_rotation_enabled:g.LOGGING_ROTATION_ENABLED,logging_rotation_compress:g.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:g.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:g.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:g.LOGGING_ROTATION_PATH,logging_stdstreams:g.LOGGING_STDSTREAMS,logging_auditlog:g.LOGGING_AUDITLOG,logging_auditretention:g.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:g.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:g.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:g.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:g.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:g.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:g.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:g.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:g.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:g.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:g.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:g.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:g.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:g.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:g.OPERATIONSAPI_TLS_CERT_AUTH,operationsapi_network_timeout:g.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:g.OPERATIONSAPI_NODEENV,operationsapi_root:g.ROOTPATH,schemas:g.SCHEMAS,storage_path:g.STORAGE_PATH,ignorescripts:g.IGNORE_SCRIPTS,mqtt_network_port:g.MQTT_NETWORK_PORT,mqtt_websocket:g.MQTT_WEBSOCKET,mqtt_network_secureport:g.MQTT_NETWORK_SECUREPORT,mqtt_requireauthentication:g.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:g.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:g.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:g.AUTHENTICATION_CACHETTL,authentication_enablesessions:g.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:g.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:g.AUTHENTICATION_REFRESHTOKENTIMEOUT};for(let e in g){let t=g[e];DR[t.toLowerCase()]=t}var B0={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},H0={csv_file_load:"csv_file_load",csv_data_load:K.CSV_DATA_LOAD,csv_url_load:K.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"},q0={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"},F0={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},G0={VERSION_DEFAULT:"2.2.0"},x0={DEVELOPMENT:8192,DEFAULT:512},k0={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"},V0={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"},$0={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},LR={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Y0=Symbol("metadata"),K0="__clustering__",W0=Object.values(LR),Q0=15984864e5,MR={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},z0=CR.invert(MR),J0={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"},X0=111,Z0=`\r
|
|
2
|
+
`,j0={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},eq=["*","%"],tq="unauthorized_access",rq="func_val",sq={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},nq={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},iq={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"},oq={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},aq={HTTP:"http"},cq={STOPPED:"stopped",ONLINE:"online"},uq="3.x.x",lq={SUCCESS:"success",FAILURE:"failure"},_q={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};PR.exports={LOCAL_HARPERDB_OPERATIONS:ge,HDB_SUPPORT_ADDRESS:NR,HDB_SUPPORT_URL:yR,HDB_PRICING_URL:vH,SUPPORT_HELP_MSG:BH,LICENSE_HELP_MSG:IR,HDB_PROC_NAME:AR,HDB_PROC_DESCRIPTOR:bE,CLUSTERING_LEAF_PROC_DESCRIPTOR:Su,CLUSTERING_HUB_PROC_DESCRIPTOR:mu,SYSTEM_SCHEMA_NAME:t0,HASH_FOLDER_NAME:r0,HDB_HOME_DIR_NAME:s0,UPDATE_FILE_NAME:a0,LICENSE_KEY_DIR_NAME:i0,BOOT_PROPS_FILE_NAME:o0,JOB_TYPE_ENUM:H0,JOB_STATUS_ENUM:C0,SYSTEM_TABLE_NAMES:O0,SYSTEM_TABLE_HASH_ATTRIBUTES:N0,OPERATIONS_ENUM:K,VALID_S3_FILE_TYPES:U0,S3_BUCKET_AUTH_KEYS:D0,VALID_SQL_OPS_ENUM:L0,GEO_CONVERSION_ENUM:P0,HDB_SETTINGS_NAMES:UR,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:v0,SERVICE_ACTIONS_ENUM:M0,CLUSTER_MESSAGE_TYPE_ENUM:q0,CLUSTER_CONNECTION_DIRECTION_ENUM:F0,CLUSTER_EVENTS_DEFS_ENUM:k0,PERIOD_REGEX:VH,DOUBLE_PERIOD_REGEX:$H,UNICODE_PERIOD:YH,FORWARD_SLASH_REGEX:KH,UNICODE_FORWARD_SLASH:WH,ESCAPED_FORWARD_SLASH_REGEX:QH,ESCAPED_PERIOD_REGEX:zH,ESCAPED_DOUBLE_PERIOD_REGEX:JH,REG_KEY_FILE_NAME:I0,RESTART_TIMEOUT_MS:l0,HDB_FILE_PERMISSIONS:_0,DATABASES_DIR_NAME:f0,LEGACY_DATABASES_DIR_NAME:h0,TRANSACTIONS_DIR_NAME:m0,LIMIT_COUNT_NAME:S0,ID_ATTRIBUTE_STRING:p0,INSERT_MODULE_ENUM:g0,UPGRADE_JSON_FIELD_NAMES_ENUM:A0,RESTART_CODE:c0,RESTART_CODE_NUM:u0,CLUSTER_OPERATIONS:Xo,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:y0,HDB_INTERNAL_SC_CHANNEL_PREFIX:tr,INTERNAL_SC_CHANNELS:b0,CLUSTERING_MESSAGE_TYPES:J0,HDB_FILE_SUFFIX:n0,BLOB_FOLDER_NAME:d0,HDB_TRASH_DIR:E0,ORIGINATOR_SET_VALUE:X0,LICENSE_VALUES:G0,RAM_ALLOCATION_ENUM:x0,TIME_STAMP_NAMES_ENUM:LR,TIME_STAMP_NAMES:W0,PERMS_UPDATE_RELEASE_TIMESTAMP:Q0,SEARCH_NOT_FOUND_MESSAGE:HH,SEARCH_ATTRIBUTE_NOT_FOUND:qH,LICENSE_ROLE_DENIED_RESPONSE:FH,LICENSE_MAX_CONNS_REACHED:GH,BASIC_LICENSE_MAX_NON_CU_ROLES:bR,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:PH,VALUE_SEARCH_COMPARATORS:MR,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:z0,LICENSE_FILE_NAME:w0,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:V0,NEW_LINE:Z0,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:kH,MOMENT_DAYS_TAG:XH,API_TURNOVER_SEC:ZH,LOOPBACK:xH,CODE_EXTENSION:hu,WILDCARD_SEARCH_VALUE:jH,NODE_ERROR_CODES:$0,JAVASCRIPT_EXTENSION:gR,PERMS_CRUD_ENUM:j0,UNAUTHORIZED_PERMISSION_NAME:tq,SEARCH_WILDCARDS:eq,FUNC_VAL:rq,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:sq,JWT_ENUM:nq,CLUSTERING_FLAG:K0,ITC_EVENT_TYPES:iq,CUSTOM_FUNCTION_PROC_NAME:OR,CUSTOM_FUNCTION_PROC_DESCRIPTOR:fu,SERVICES:oq,THREAD_TYPES:aq,MEM_SETTING_KEY:e0,HDB_RESTART_SCRIPT:TH,PROCESS_DESCRIPTORS:bH,SERVICE_SERVERS:UH,SERVICE_SERVERS_CWD:NE,PROCESS_DESCRIPTORS_VALIDATE:wH,LAUNCH_SERVICE_SCRIPTS:DH,LOG_LEVELS:IH,PROCESS_NAME_ENV_PROP:T0,LOG_NAMES:yH,PM2_PROCESS_STATUSES:cq,CONFIG_PARAM_MAP:DR,CONFIG_PARAMS:g,HDB_CONFIG_FILE:mH,HDB_DEFAULT_CONFIG_FILE:SH,ROLE_TYPES_ENUM:LH,BOOT_PROP_PARAMS:wR,INSTALL_PROMPTS:R0,HDB_ROOT_DIR_NAME:pH,CLUSTERING_PROCESSES:CH,FOREGROUND_PID_FILE:AH,PACKAGE_ROOT:cn,PRE_4_0_0_VERSION:uq,SCHEMAS_PARAM_CONFIG:B0,METADATA_PROPERTY:Y0,AUTH_AUDIT_STATUS:lq,AUTH_AUDIT_TYPES:_q,HDB_PID_FILE:OH,DEFAULT_DATABASE_NAME:NH};RR()});var yE=m((are,HR)=>{"use strict";var vR=require("minimist");HR.exports=dq;function dq(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=BR(process.env),s=BR(vR(process.argv))):(r=process.env,s=vR(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(dq,"assignCMDENVVariables");function BR(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(BR,"objKeysToLowerCase")});var x=m((ure,ME)=>{"use strict";var kn=require("fs-extra"),{workerData:Eq,threadId:fq}=require("worker_threads"),Cs=require("path"),GR=require("yaml"),xR=require("properties-reader"),et=A(),qR=yE(),hq=require("os"),{PACKAGE_ROOT:wE}=A(),{_assignPackageExport:mq}=require("../../index"),jo={};for(let e in console)jo[e]||(jo[e]=console[e]);var Mt={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},kR={STDOUT:"stdOut",STDERR:"stdErr"},Sq=Cs.join(wE,"logs"),pq=Cs.join(wE,"config/yaml/",et.HDB_DEFAULT_CONFIG_FILE),Tq=1e4,Is,ws,Lt,pu,Tu,ea,qi,Zo;Zo===void 0&&VR();ME.exports={notify:KR,fatal:WR,error:ta,warn:LE,info:Ru,debug:DE,trace:UE,setLogLevel:yq,log_level:Lt,loggerWithTag:Rq,suppressLogging:gq,initLogSettings:VR,setupConsoleLogging:$R,logCustomLevel:Nq,closeLogFile:CE,getLogFilePath:()=>ea,OUTPUTS:kR,AuthAuditLog:Cq};mq("logger",ME.exports);function VR(e=!1){try{if(Zo===void 0||e){CE();let t=bq(),r=qR(["ROOTPATH"]);try{Zo=xR(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!kn.pathExistsSync(Cs.join(r.ROOTPATH,et.HDB_CONFIG_FILE)))throw s}({level:Lt,config_log_path:Tu,to_file:Is,to_stream:ws}=Iq(r.ROOTPATH?Cs.join(r.ROOTPATH,et.HDB_CONFIG_FILE):Zo.get("settings_path"))),pu=et.LOG_NAMES.HDB,ea=Cs.join(Tu,pu)}}catch(t){if(Zo=void 0,t.code===et.NODE_ERROR_CODES.ENOENT){let r=qR(Object.keys(et.CONFIG_PARAM_MAP),!0);for(let o in r){let c=et.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===et.CONFIG_PARAMS.LOGGING_LEVEL){Lt=u;continue}if(c===et.CONFIG_PARAMS.LOGGING_STDSTREAMS){ws=u;continue}c===et.CONFIG_PARAMS.LOGGING_FILE&&(Is=c)}let{default_level:s,default_to_file:n,default_to_stream:i}=wq();Is=Is===void 0?n:Is,Is=FR(Is),ws=ws===void 0?i:ws,ws=FR(ws),Lt=Lt===void 0?s:Lt,Tu=Sq,pu=et.LOG_NAMES.INSTALL,ea=Cs.join(Tu,pu);return}throw ta("Error initializing log settings"),ta(t),t}$R()}a(VR,"initLogSettings");var IE=!0;function $R(){Hi("error",ta),Hi("warn",LE),Hi("log",Ru),Hi("info",Ru),Hi("debug",DE),Hi("trace",UE)}a($R,"setupConsoleLogging");function Hi(e,t){console[e]=function(...r){if(IE&&t(...r),!/PM2 log:|App \[/.test(r[0]))return jo[e](...r)}}a(Hi,"logConsole");function Rq(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(KR),fatal:r(WR),error:r(ta),warn:r(LE),info:r(Ru),debug:r(DE),trace:r(UE)};function r(s){return function(...n){return s(t,...n)}}}a(Rq,"loggerWithTag");function gq(e){try{IE=!1,e()}finally{IE=!0}}a(gq,"suppressLogging");var Aq=Eq?.name?.replace(/ /g,"-")||"main";function Us(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||Aq+"/"+fq);c<n;c++){let l=t[c];l instanceof Error&&l.stack?s+=l.stack:typeof l=="object"?s+=JSON.stringify(l):s+=l,c<i&&(s+=" ")}return`${r} [${o.join("] [")}]: ${s}
|
|
3
|
+
`}a(Us,"createLogRecord");function ra(e){Is&&YR(e),ws&&process.stdout.write(e)}a(ra,"logStdOut");function gu(e){Is&&YR(e),ws&&process.stderr.write(e)}a(gu,"logStdErr");function YR(e){Oq(),qi?kn.appendFileSync(qi,e):jo.log(e)}a(YR,"logToFile");function CE(){try{kn.closeSync(qi)}catch{}qi=null}a(CE,"closeLogFile");function Oq(){if(!qi){try{if(!ea)debugger;qi=kn.openSync(ea,"a")}catch(e){jo.error(e)}setTimeout(()=>{CE()},Tq).unref()}}a(Oq,"openLogFile");function Ru(...e){Mt[Lt]<=Mt.info&&ra(Us("info",e))}a(Ru,"info");function UE(...e){Mt[Lt]<=Mt.trace&&ra(Us("trace",e))}a(UE,"trace");function ta(...e){Mt[Lt]<=Mt.error&&gu(Us("error",e))}a(ta,"error");function DE(...e){Mt[Lt]<=Mt.debug&&ra(Us("debug",e))}a(DE,"debug");function KR(...e){Mt[Lt]<=Mt.notify&&ra(Us("notify",e))}a(KR,"notify");function WR(...e){Mt[Lt]<=Mt.fatal&&gu(Us("fatal",e))}a(WR,"fatal");function LE(...e){Mt[Lt]<=Mt.warn&&gu(Us("warn",e))}a(LE,"warn");function Nq(e,t,...r){t===kR.STDERR?gu(Us(e,r)):ra(Us(e,r))}a(Nq,"logCustomLevel");function bq(){let e;try{e=hq.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=Cs.join(e,et.HDB_HOME_DIR_NAME,et.BOOT_PROPS_FILE_NAME);return kn.existsSync(t)||(t=Cs.join(wE,"utility/hdb_boot_properties.file")),t}a(bq,"getPropsFilePath");function yq(e){Lt=e}a(yq,"setLogLevel");function FR(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(FR,"autoCastBoolean");function Iq(e){try{if(e.includes("config/settings.js")){let o=xR(e);return{level:o.get(et.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:Cs.dirname(o.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(et.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=GR.parseDocument(kn.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===et.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Iq,"getLogConfig");function wq(){try{let e=GR.parseDocument(kn.readFileSync(pq,"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(wq,"getDefaultConfig");function Cq(e,t,r,s,n,i){this.username=e,this.status=t,this.type=r,this.originating_ip=s,this.request_method=n,this.path=i}a(Cq,"AuthAuditLog")});var zR=m((_re,QR)=>{"use strict";var Uq=require("util"),Dq=require("path"),Lq=require("child_process"),Mq=Uq.promisify(Lq.execFile),Pq=1e3*1e3*10;QR.exports={findPs:vq};async function vq(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await Mq("ps",["wwxo",`pid,${r}`],{maxBuffer:Pq});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:Dq.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(vq,"findPs")});var xe=m((Ere,XR)=>{"use strict";var Bq="__dbis__",Hq="__txns__",qq="__environment_name__",Fq="__dbi_defintion__",Gq={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"},xq=["__createdtime__","__updatedtime__"],kq="\uFFFF",JR={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},Vq=Object.values(JR);XR.exports={AUDIT_STORE_NAME:Hq,INTERNAL_DBIS_NAME:Bq,DBI_DEFINITION_NAME:Fq,SEARCH_TYPES:Gq,TIMESTAMP_NAMES:xq,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:qq,TRANSACTIONS_DBI_NAMES_ENUM:JR,TRANSACTIONS_DBIS:Vq,OVERFLOW_MARKER:kq}});var rr=m((fre,og)=>{"use strict";var ZR=A(),jR=xe(),eg={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},tg=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),rg={500:tg("There was an error processing your request."),400:"Invalid request"},$q=rg[eg.INTERNAL_SERVER_ERROR],Yq={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.`},Kq={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},Wq={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"},Qq={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 ${jR.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${jR.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"},zq={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${ZR.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 ${ZR.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"},sg={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"},Jq={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."},Xq={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`},Zq={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"},jq={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},eF={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`},ng={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.`},ig={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}`},tF={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."},rF={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},sF={...sg,...Wq,...Yq,...Jq,...Xq,...Zq,...jq,...eF,...zq,...ng,...ig,...tF,...rF,...Kq};og.exports={CHECK_LOGS_WRAPPER:tg,HDB_ERROR_MSGS:sF,DEFAULT_ERROR_MSGS:rg,DEFAULT_ERROR_RESP:$q,HTTP_STATUS_CODES:eg,LMDB_ERRORS_ENUM:Qq,AUTHENTICATION_ERROR_MSGS:sg,VALIDATION_ERROR_MSGS:ng,ITC_ERRORS:ig}});var W=m((mre,ug)=>{"use strict";var Fi=rr(),nF=x(),iF=A(),Au=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,ag),this.statusCode=s||Fi.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Fi.DEFAULT_ERROR_MSGS[s]?Fi.DEFAULT_ERROR_MSGS[s]:Fi.DEFAULT_ERROR_MSGS[Fi.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&&nF[n](i)}},PE=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}},vE=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function ag(e,t,r,s=iF.LOG_LEVELS.ERROR,n=null,i=!1){if(cg(e))return e;let o=new Au(e,t,r,s,n);return i&&delete o.stack,o}a(ag,"handleHDBError");function cg(e){return e.__proto__.constructor.name===Au.name}a(cg,"isHDBError");ug.exports={isHDBError:cg,handleHDBError:ag,ClientError:PE,ServerError:vE,hdb_errors:Fi}});var we=m((pre,mg)=>{"use strict";var aa=A(),oF=V(),Pt=Q(),ca=require("path"),aF=require("minimist"),lg=require("fs-extra"),_g=require("lodash");Pt.initSync();var{CONFIG_PARAMS:un,SCHEMAS_PARAM_CONFIG:sa,SYSTEM_SCHEMA_NAME:Ou}=aa,na,ia,oa;function dg(){if(na!==void 0)return na;if(Pt.getHdbBasePath()!==void 0)return na=Pt.get(un.STORAGE_PATH)||ca.join(Pt.getHdbBasePath(),aa.DATABASES_DIR_NAME),na}a(dg,"getBaseSchemaPath");function Eg(){if(ia!==void 0)return ia;if(Pt.getHdbBasePath()!==void 0)return ia=hg(Ou),ia}a(Eg,"getSystemSchemaPath");function fg(){if(oa!==void 0)return oa;if(Pt.getHdbBasePath()!==void 0)return oa=Pt.get(aa.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||ca.join(Pt.getHdbBasePath(),aa.TRANSACTIONS_DIR_NAME),oa}a(fg,"getTransactionAuditStoreBasePath");function cF(e,t){let r=Pt.get(un.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||ca.join(fg(),e.toString())}a(cF,"getTransactionAuditStorePath");function hg(e,t){e=e.toString(),t=t&&t.toString();let r=Pt.get(aa.CONFIG_PARAMS.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.path||r?.path||ca.join(dg(),e)}a(hg,"getSchemaPath");function uF(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,aF(process.argv));let s=r[un.SCHEMAS.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!oF.isObject(s))throw o;i=s}for(let o of i){let c=o[Ou];if(!c)continue;let u=Pt.get(un.SCHEMAS);u=u??{};let l=c?.tables?.[t]?.[sa.PATH];if(l)return _g.set(u,[Ou,sa.TABLES,t,sa.PATH],l),Pt.setProperty(un.SCHEMAS,u),l;let _=c?.[sa.PATH];if(_)return _g.set(u,[Ou,sa.PATH],_),Pt.setProperty(un.SCHEMAS,u),_}}let n=r[un.STORAGE_PATH.toUpperCase()];if(n){if(!lg.pathExistsSync(n))throw new Error(n+" does not exist");let i=ca.join(n,e);return lg.mkdirsSync(i),Pt.setProperty(un.STORAGE_PATH,n),i}return Eg()}a(uF,"initSystemSchemaPaths");function lF(){na=void 0,ia=void 0,oa=void 0}a(lF,"resetPaths");mg.exports={getBaseSchemaPath:dg,getSystemSchemaPath:Eg,getTransactionAuditStorePath:cF,getTransactionAuditStoreBasePath:fg,getSchemaPath:hg,initSystemSchemaPaths:uF,resetPaths:lF}});var vt=m((Are,gg)=>{"use strict";var _F=rr().LMDB_ERRORS_ENUM,Rre=require("lmdb"),dF=xe(),gre=require("buffer").Buffer,{OVERFLOW_MARKER:Sg,MAX_SEARCH_KEY_LENGTH:Nu}=dF,pg=["number","string","symbol","boolean","bigint"];function EF(e){if(e=e?.primaryStore||e,!e)throw new Error(_F.ENV_REQUIRED)}a(EF,"validateEnv");function fF(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(fF,"stringifyData");function hF(e){return e instanceof Date?e.valueOf():e}a(hF,"convertKeyValueToWrite");function mF(e){if(e==null)return;if(pg.includes(typeof e))return e.length>Nu?[e.slice(0,Nu)+Sg]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];if(pg.includes(typeof n))n.length>Nu?t.push(n.slice(0,Nu)+Sg):t.push(n);else if(n instanceof Date)return t.push(n.getTime())}}else if(e instanceof Date)return[e.getTime()];return t}a(mF,"getIndexedValues");var bu=0,Tg=0;function Rg(){Tg=Date.now()-performance.now()}a(Rg,"adjustStartTime");Rg();var SF=6e4;setInterval(Rg,SF).unref();function pF(){let e=performance.now()+Tg;return e>bu?(bu=e,e):(bu+=488e-6,bu)}a(pF,"getNextMonotonicTime");gg.exports={validateEnv:EF,stringifyData:fF,convertKeyValueToWrite:hF,getNextMonotonicTime:pF,getIndexedValues:mF}});var Ag,Xr,BE,ua=Se(()=>{Ag=require("events"),Xr=class extends Ag.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new BE;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)}},BE=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function la(e){return e[ft]||(e[ft]=Object.create(null))}function Uu(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u={get(){let l=this[ft];if(l&&c in l)return l[c];let _=this[ce]?.[c];if(_&&typeof _=="object"){let d=Og(_,o);if(d)return l||(l=this[ft]=Object.create(null)),l[c]=d}return _},set(l){la(this)[c]=l},enumerable:!0,configurable:!0};switch(u.get.isAttribute=!0,o.type){case"String":u.set=function(l){if(typeof l!="string")throw(0,yu.ClientError)(`${c} must be a string, attempt to assign ${l}`);la(this)[c]=l};break;case"Int":u.set=function(l){if(typeof l!="number")throw(0,yu.ClientError)(`${c} must be a string, attempt to assign ${l}`);la(this)[c]=l};break}s[c]=u,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,u)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[ft];return u?.[o]!==void 0?u[o]:this[ce]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new yu.ClientError("Can not add a property to a sealed table schema");la(this)[o]=c}),i("deleteProperty",function(o){la(this)[o]=void 0}),i("toJSON",function(){let o=this[ft],c;for(let l in o)c||(c=Object.assign({},this[ce])),c[l]=o[l];return Object.keys(this).length>0&&(c||(c=Object.assign({},this[ce])),Object.assign(c,this)),c||this[ce]}),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 Og(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){this[ce]=n}},Uu(r,t)),new r(e)):new Iu(e);case Array:let s=new Cu(e.length);s[ce]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=Og(o,t?.elements)),s[n]=o}return s}}function Du(e){let t=e[ft],r;for(let n in t){r||(r=Object.assign({},e[ce]));let i=t[n];i&&typeof i=="object"&&(i=Du(i)),r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[ce])),Object.assign(r,e)),r||e[ce]}function _a(e){let t;if(e[ce]&&e.constructor===Array&&!Object.isFrozen(e)){t=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=_a(i);o!==i&&t===e&&(t=e.slice(0)),i=o}t[s]=i}return Object.freeze(t)}let r=e[ft];for(let s in r){t||(t=Object.assign({},e[ce]));let n=r[s];n&&typeof n=="object"&&(n=_a(n)),t[s]=n}return t?Object.freeze(t):e[ce]||Object.freeze(e)}function wu(e){let t=e[ce];if(!t)return!0;if(e.constructor===Array){if(e[Vn]||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?.[ce]===n){if(wu(i))return!0}else return!0}}else{let r=e[ft];for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[ce]===i){if(wu(n))return!0}else return!0}else return!0}}return!1}var yu,ft,Iu,Vn,Cu,Lu=Se(()=>{Zr();yu=C(W()),ft=Symbol("own-data");a(la,"getChanges");a(Uu,"assignTrackedAccessors");a(Og,"trackObject");Iu=class{static{a(this,"GenericTrackedObject")}constructor(t){this[ce]=t}};Uu(Iu,{});a(Du,"collapseData");a(_a,"deepFreeze");a(wu,"hasChanges");Vn=Symbol.for("has-array-changes"),Cu=class extends Array{static{a(this,"TrackedArray")}[Vn];constructor(t){super(t)}splice(...t){return this[Vn]=!0,super.splice(...t)}push(...t){return this[Vn]=!0,super.push(...t)}pop(){return this[Vn]=!0,super.pop()}unshift(...t){return this[Vn]=!0,super.unshift(...t)}shift(){return this[Vn]=!0,super.shift()}};Cu.prototype.constructor=Array});function Ke(e,t){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let r=e.transaction=new HE;e.timestamp&&(r.timestamp=e.timestamp),r[Ae]=e,e.resourceCache=[];let s;try{if(s=t(r),s?.then)return s.then(n,i)}catch(o){i(o)}return n(s);function n(o){let c=r.commit();return c.then?c.then(()=>(e.transaction=null,o)):(e.transaction=null,o)}function i(o){throw r.abort(),e.transaction=null,o}}var Ng,bg,HE,$n=Se(()=>{Ng=C(vt()),bg=require("../../index");Zr();a(Ke,"transaction");(0,bg._assignPackageExport)("transaction",Ke);Ke.commit=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ke.abort=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()};HE=class extends Array{static{a(this,"TransactionSet")}commit(t=!0){let r=[],s=this.length;for(let n=0;n<s;n++)this[n].validate?.();this.timestamp||(this.timestamp=(0,Ng.getNextMonotonicTime)());for(let n=0;n<s;n++){let o=this[n].commit(this.timestamp,t);o?.then&&r.push(o)}return r.length>0?Promise.all(r).then(()=>(this.splice(0,s),this.commit(t))):this.length>s?(this.splice(0,s),this.commit(t)):(this.length=0,{txnTime:this.timestamp})}abort(){for(let t of this)t.abort?.()}doneReading(){for(let t of this)t.doneReading?.()}}});function GE(e,t,r,s,n){let i=e[0]??e.attribute,o,c,u,l,_=e[1]??e.value;_ instanceof Date&&(_=_.getTime());let d=e.comparator,E;switch(RF[d]||d){case"lt":o=!0,c=_;break;case"le":o=!0,c=_,u=!0;break;case"gt":o=_,l=!0;break;case"ge":o=_;break;case"prefix":o=_,c=_.slice(0),c[c.length-1]=es.MAXIMUM_KEY;break;case"starts_with":o=_.toString(),c=_+String.fromCharCode(65535);break;case"between":o=_[0],o instanceof Date&&(o=o.getTime()),c=_[1],c instanceof Date&&(c=c.getTime()),u=!0;break;case _t.SEARCH_TYPES.EQUALS:case void 0:o=_,c=_,u=!0;break;case"ne":case"contains":case"ends_with":E=!0;break}if(r){let p=o;o=c,c=p,p=!l,l=!u,u=p}let f=i===s.primaryKey||i==null,h=f?s.primaryStore:s.indices[i];if(!h||h.isIndexing||E){if(!n)throw new qE.ClientError(`"${i}" is not indexed${h?.isIndexing?" yet":""}, can not search for this attribute`,404);let p=xE(e);if(!p)throw new qE.ClientError(`Unknown search operator ${e.comparator}`);return s.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:R,value:O})=>new Promise(k=>setImmediate(()=>k(p(O)?R:Ig.SKIP))))}let T={start:o,end:c,inclusiveEnd:u,exclusiveStart:l,values:!f,transaction:t,reverse:r};return f?h.getRange(T):h.getRange(T).map(({value:p})=>p)}function xE(e){let t=e.comparator,r=e[0]??e.attribute,s=e[1]??e.value;switch(s instanceof Date&&(s=s.getTime()),t){case _t.SEARCH_TYPES.EQUALS:case void 0:return jr(r,n=>n===s);case _t.SEARCH_TYPES.CONTAINS:return jr(r,n=>n?.toString().includes(s));case _t.SEARCH_TYPES.ENDS_WITH:case _t.SEARCH_TYPES._ENDS_WITH:return jr(r,n=>n?.toString().endsWith(s));case _t.SEARCH_TYPES.STARTS_WITH:case _t.SEARCH_TYPES._STARTS_WITH:return jr(r,n=>typeof n=="string"&&n.startsWith(s));case _t.SEARCH_TYPES.BETWEEN:return s[0]instanceof Date&&(s[0]=s[0].getTime()),s[1]instanceof Date&&(s[1]=s[1].getTime()),jr(r,n=>(0,es.compareKeys)(n,s[0])>=0&&(0,es.compareKeys)(n,s[1])<=0);case"gt":case _t.SEARCH_TYPES.GREATER_THAN:case _t.SEARCH_TYPES._GREATER_THAN:return jr(r,n=>(0,es.compareKeys)(n,s)>0);case"ge":case _t.SEARCH_TYPES.GREATER_THAN_EQUAL:case _t.SEARCH_TYPES._GREATER_THAN_EQUAL:return jr(r,n=>(0,es.compareKeys)(n,s)>=0);case _t.SEARCH_TYPES.LESS_THAN:case"lt":case _t.SEARCH_TYPES._LESS_THAN:return jr(r,n=>(0,es.compareKeys)(n,s)<0);case"le":case _t.SEARCH_TYPES.LESS_THAN_EQUAL:case _t.SEARCH_TYPES._LESS_THAN_EQUAL:return jr(r,n=>(0,es.compareKeys)(n,s)<=0);case"ne":return jr(r,n=>(0,es.compareKeys)(n,s)!==0);default:return}}function jr(e,t){return r=>{let s=r[e];return typeof s!="object"||!s?t(s):Array.isArray(s)?s.some(t):s instanceof Date?t(s.getTime()):!1}}function Mu(e){if(!e)return;let t=new FE,r,s,n,i,o;for(;r=yg.exec(e);){i=yg.lastIndex;let[,c,u]=r;switch(u){case")":switch(o){case"limit":if(c.indexOf(",")>-1){let[l,_]=c.split(",");t.offset=+l,t.limit=_-t.offset}else t.limit=+c;break;case"select":if(c[0]==="["){if(c[c.length-1]!=="]")throw new Error("Unmatched brackets");t.select=c.slice(1,-1).split(","),t.select.asArray=!0}else c.indexOf(",")>-1?t.select=(c.endsWith(",")?c.slice(0,-1):c).split(","):t.select=c;break;case"group-by":throw new Error("Group by is not implemented yet");case"sort":t.sort=c.split(",").map(l=>{switch(l[0]){case"-":return{attribute:l.slice(1),descending:!0};case"+":return{attribute:l.slice(1),descending:!1};default:return{attribute:l,descending:!1}}});break;default:throw new Error(`Unknown query function call ${o}`)}break;case"(":o=c;break;case"=":s?c.length<=2&&(n=c):(n="equals",s=decodeURIComponent(c));break;case"!=":case"<":case"<=":case">":case">=":n=TF[u],s=decodeURIComponent(c);break;case"=*":n="ends_with",s=decodeURIComponent(c);break;case"*":case"*&":t.conditions.push({comparator:n==="ends_with"?"contains":"starts_with",attribute:s,value:decodeURIComponent(c)}),s=null;break;case"":case void 0:case"&":case"|":if(!s)throw new Error(`Unable to parse query, no part before ${u} at ${i} in ${e}`);t.conditions.push({comparator:n,attribute:s,value:decodeURIComponent(c)}),s=void 0;break;default:throw new Error(`Unknown operator ${u} in query ${e}`)}}if(i!==e.length)throw new Error(`Unable to parse query, unexpected end in ${e}`);return t}var qE,_t,es,Ig,yg,TF,RF,FE,Pu=Se(()=>{qE=C(W()),_t=C(xe()),es=require("ordered-binary"),Ig=require("lmdb"),yg=/([^?&|=<>!()*]+)([&|=<>!()*]*)/g,TF={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne"};a(GE,"idsForCondition");RF={greater_than:"gt",greater_than_equal:"ge",less_than:"lt",less_than_equal:"le",not_equal:"ne",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(xE,"filterByType");a(jr,"attributeComparator");a(Mu,"parseQuery");FE=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}}}});var $E={};Ye($E,{CONTEXT:()=>Ae,ID_PROPERTY:()=>ae,IS_COLLECTION:()=>Ds,RECORD_PROPERTY:()=>ce,Resource:()=>ht,SAVE_UPDATES_PROPERTY:()=>Mg,snake_case:()=>AF});function AF(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function wg(e,t){if(e=e.slice(1),e.indexOf("/")===-1)return e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e));let r=e.split("/"),s=new VE(r.length);for(let n=0;n<r.length;n++)s[n]=t.coerceId(decodeURIComponent(r[n]));return s}function pr(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[Ae]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Ae]||i):l=i:(l=n,c=l[ae]??l[this.primaryKey]??null):i?o=i[Ae]||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=[];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)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let h=this.parseQuery(c.slice(E+1));u?u=Object.assign(h,u):u=h,c=c.slice(0,E)}let f=this.parsePath(c,o,u);f?.query?(u=f.query,c=f.id):c=f}c===void 0&&(c=n.id??null)}else c=n??null;o||(o={});let _;if(u?.allowInvalidated?(_=Object.assign({},t),_.allowInvalidated=!0):_=t,o.transaction){let E=this.getResource(c,o,_);return E.then?E.then(d):d(E)}else return Ke(o,()=>{let E=this.getResource(c,o,_);return E.then?E.then(d):d(E)});function d(E){if(t.type==="read"&&(E[Mg]=!1),o.authorize){o.authorize=!1;let f=t.type==="read"?E.allowRead(o.user,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,o):E.allowUpdate(o.user,o):t.type==="create"?E.allowCreate(o.user,o):E.allowDelete(o.user,o);if(f?.then)return f.then(h=>{if(!h)throw new vu(o.user);return typeof l?.then=="function"?l.then(T=>e(E,u,o,T)):e(E,u,o,l)});if(!f)throw new vu(o.user)}return typeof l?.then=="function"?l.then(f=>e(E,u,o,f)):e(E,u,o,l)}a(d,"authorizeActionOnResource")}}function Tr(e,t){let r=new Lg.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 kE(e){let t=e[ce];if(t){let r=e[ft];return s=>{let n;return e.hasOwnProperty(s)&&typeof(n=e[s])!="function"?n:r&&s in r?r[s]:t[s]}}else return r=>e[r]}function Cg(e){if(typeof e=="string")return t=>kE(t)(e);if(typeof e=="object"){if(e.asArray)return r=>{let s=[],n=kE(r);for(let i of e)s.push(n(i));return s};let t=e.forceNulls;return r=>{let s={},n=kE(r);for(let i of e){let o=n(i);o===void 0&&t&&(o=null),s[i]=o}return s}}else throw new Error("Invalid select argument type "+typeof e)}var Ug,Dg,Lg,Ae,ae,Ds,Mg,ce,gF,ht,vu,VE,Zr=Se(()=>{Ug=require("crypto");ua();Dg=require("../../index"),Lg=C(W());Lu();$n();Pu();Ae=Symbol.for("context"),ae=Symbol.for("primary-key"),Ds=Symbol("is-collection"),Mg=Symbol("save-updates"),ce=Symbol("stored-record"),gF={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},ht=class{static{a(this,"Resource")}[Ae];[ae];static transactions;constructor(t,r){this[ae]=t;let s=r?.[Ae];this[Ae]=s!==void 0?s:r||null}updateModificationTime(t=Date.now()){t>this[LAST_MODIFICATION_PROPERTY]&&(this[LAST_MODIFICATION_PROPERTY]=t)}static get=pr(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){let l=Cg(u);return typeof c?.map=="function"?c.map(l):l(c)}return c}},{type:"read"});static put=pr(function(t,r,s,n){if(Array.isArray(n)&&t[Ds]){let i=[],o=s.authorize;for(let c of n)o&&(s.authorize=!0),i.push(this.put(t,r,s,c));return i}return t.put?t.put(n,r):Tr(t,"put")},{hasContent:!0,type:"update"});static delete=pr(function(t,r,s,n){return t.delete?t.delete(r):Tr(t,"delete")},{hasContent:!1,type:"delete",allowInvalidated:!0});static getNewId(){return(0,Ug.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),Ke(s,()=>{let i=new this(n,s),o=i.put?i.put(r):Tr(i,"put");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=pr(function(t,r,s,n){return t.invalidate?t.invalidate(r):Tr(t,"delete")},{hasContent:!1,type:"update",allowInvalidated:!0});static post=pr(function(t,r,s,n){return t[ae]!=null&&t.update(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=pr(function(t,r,s,n){return t.connect?t.connect(r):Tr(t,"connect")},{type:"read"});static subscribe=pr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Tr(t,"subscribe")},{type:"read"});static publish=pr(function(t,r,s,n){return t[ae]!=null&&t.update(),t.publish?t.publish(n,r):Tr(t,"publish")},{hasContent:!0,type:"create"});static search=pr(function(t,r,s,n){let i=t.search?t.search(s):Tr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null){let c=Cg(o);return i.map(c)}return i},{type:"read"});static query=pr(function(t,r,s,n){return t.search?t.search(n,r):Tr(t,"search")},{hasContent:!0,type:"read"});static copy=pr(function(t,r,s,n){return t.copy?t.copy(s.headers?.destination,r):Tr(t,"copy")},{type:"create"});static move=pr(function(t,r,s,n){return t.move?t.move(s.headers?.destination,r):Tr(t,"move")},{type:"delete"});post(t){if(this[Ds])return this.constructor.create(this[ae],t,this[Ae]);Tr(this,"post")}static isCollection(t){return t?.[Ds]}static coerceId(t){return t}static parseQuery(t){return Mu(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let i=t.slice(n+1);t=t.slice(0,n);let o=r?.headers&&gF[i];if(o)r.headers.accept=o;else if(s)s.property=i;else return{query:{property:i},id:wg(t,this)}}return wg(t,this)}static getResource(t,r,s){let n,i=r[Ae],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=t==null||Array.isArray(t)&&t[t.length-1]==null;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 l=u.asMap.get(t);if(n=l?.find(_=>_.constructor===c),n)return n;l||u.asMap.set(t,l=[]),l.push(n=new c(t,i))}else{if(n=u.find(l=>l[ae]===t&&l.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let l=new Map;for(let _ of u){let d=_[ae],E=l.get(d);E?E.push(_):l.set(d,[_])}i.resourceCache.length=0,i.resourceCache.asMap=l}}}else n=new c(t,i);return o&&(n[Ds]=!0),n}connect(t){let r=new Xr;if(t?.subscribe!==!1){let s={listener:i=>{r.send(i)}},n=this.subscribe?.(s);r.on("close",()=>n?.end())}return r}update(t){throw new Error("Not implemented")}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[ae]}getContext(){return this[Ae]}};ht.prototype[Ae]=null;(0,Dg._assignPackageExport)("Resource",ht);a(AF,"snake_case");vu=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(wg,"pathToId");VE=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(pr,"transactional");a(Tr,"missingMethod");a(kE,"selectFromObject");a(Cg,"transformForSelect")});var da={};Ye(da,{server:()=>tt});var Pg,tt,Pr=Se(()=>{Pg=require("../../index"),tt={};(0,Pg._assignPackageExport)("server",tt)});var WE={};Ye(WE,{loadGQLSchema:()=>NF,start:()=>KE,startOnMainThread:()=>OF});function KE({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:l,StringValueNode:_}=await import("graphql"),d=o(new c(r.toString(),n)),E=new Map,f=[],h;for(let T of d.definitions)switch(T.kind){case u.OBJECT_TYPE_DEFINITION:let $=function(U){if(U.kind==="NonNullType"){let P=$(U.type);return P.nullable=!0,P}return U.kind==="ListType"?{type:"array",elements:$(U.type)}:{type:U.name?.value}};a($,"getProperty");let p=T.name.value,R=[],O={table:null,database:null,properties:R};E.set(p,O);for(let U of T.directives){if(U.name.value==="table"){for(let b of U.arguments)O[b.name.value]=b.value.value;O.schema&&(O.database=O.schema),O.table||(O.table=p),O.audit&&(O.audit=O.audit!=="false"),O.attributes=O.properties,f.push(O)}if(U.name.value==="sealed"&&(O.sealed=!0),U.name.value==="export"){O.export=!0;for(let b of U.arguments)b.name.value==="name"&&(O.export={name:b.value.value})}}let k=!1;for(let U of T.fields){let b=$(U.type);b.name=U.name.value,R.push(b);for(let P of U.directives)if(P.name.value==="primaryKey")k?console.warn("Can not define two attributes as a primary key"):(b.isPrimaryKey=!0,k=!0);else if(P.name.value==="indexed")b.indexed=!0;else if(P.name.value==="createdTime")b.assignCreatedTime=!0;else if(P.name.value==="updatedTime")b.assignUpdatedTime=!0;else if(P.name.value==="expiresAt")b.expiresAt=!0;else if(P.name.value==="allow"){let z=b.authorizedRoles=[];for(let q of P.arguments)q.name.value==="role"&&z.push(q.value.value)}}O.typeName=p,p==="Query"&&(h=O)}for(let[T,p]of E)for(let R of p.properties){let O=E.get(R.type);O&&(R.properties=O.properties)}for(let T of f)T.tableClass=e(T),T.export&&i.set((0,YE.dirname)(s)+"/"+(T.export.name||T.typeName),T.tableClass);if(h)for(let T of h.properties){let p=E.get(T.type);if(!p)throw new Error(`${T.type} was not found as a Query export`);i.set((0,YE.dirname)(s)+"/"+T.name,p.tableClass)}}}var YE,OF,NF,vg=Se(()=>{YE=require("path");de();a(KE,"start");OF=KE,NF=KE({ensureTable:rt}).handleFile});async function Bu(e){return bF?(Ea||(Ea=yF(wF)),(await(await Ea).import(e)).namespace):import(e)}async function yF(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Ea=new Compartment({console,Math,Date,fetch:IF,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,Hg.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:ht,tables:sr,databases:Pe})}};let s=await(0,Bg.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),Ea}function IF(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 wF(){return{Resource:ht,tables:sr}}var Bg,Hg,bF,Ea,QE=Se(()=>{Zr();de();Bg=require("fs/promises"),Hg=require("path"),bF=!1;a(Bu,"secureImport");a(yF,"getCompartment");a(IF,"secureOnlyFetch");a(wF,"getGlobalVars")});var JE={};Ye(JE,{handleFile:()=>CF});async function CF(e,t,r,s){let n=new Map,i=(0,qg.pathToFileURL)(r).toString(),o=await Bu(i);u(o.default)&&s.set((0,zE.dirname)(t),o.default),c(o,(0,zE.dirname)(t));function c(l,_){for(let d in l){let E=l[d];u(E)?s.set(_+"/"+d,E):typeof E=="object"&&c(E,_+"/"+d)}}a(c,"recurseForResources");function u(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return a(u,"isResource"),n}var qg,zE,Fg=Se(()=>{qg=require("url");QE();zE=require("path");a(CF,"handleFile")});var ZE={};Ye(ZE,{start:()=>UF});function UF({resources:e}){e.set("login",XE),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var XE,Gg=Se(()=>{Zr();a(UF,"start");XE=class extends ht{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 ef=m((Jre,Vg)=>{"use strict";var{Readable:DF}=require("stream"),LF=1e4;Vg.exports={streamAsJSON(e){return new jE({value:e})}};var jE=class extends DF{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0)}*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](),o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){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),xg)}catch(n){yield xg(n)}else yield JSON.stringify(t)}else yield JSON.stringify(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);kg(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>LF?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 kg(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}}};function xg(e){return console.error(e),JSON.stringify(e.toString())}a(xg,"handleError");function kg(e,t,r){return e&&e.then?r?e.then(t,r):e.then(t):t(e)}a(kg,"when")});var rA=m((jre,tA)=>{"use strict";var tf=require("recursive-iterator"),MF=require("alasql"),rf=require("clone"),$g=V(),{handleHDBError:Yg,hdb_errors:PF}=W(),{HDB_ERROR_MSGS:Kg,HTTP_STATUS_CODES:Wg}=PF,{getDatabases:vF}=(de(),ee(Ne)),BF=["DISTINCT_ARRAY"],Qg=Symbol("validateTables"),sf=Symbol("validateTable"),Zre=Symbol("getAllColumns"),zg=Symbol("validateAllColumns"),Hu=Symbol("findColumn"),Jg=Symbol("validateOrderBy"),fa=Symbol("validateSegment"),nf=Symbol("validateColumn"),Xg=Symbol("setColumnsForTable"),Zg=Symbol("checkColumnsForAsterisk"),jg=Symbol("validateGroupBy"),eA=Symbol("hasColumns"),of=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Qg](),this[Zg](),this[zg]()}[Qg](){if(this[eA]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[sf](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[sf](t.table)})}}[eA](){let t=!1,r=new tf(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[sf](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=vF();if(!r[t.databaseid])throw Yg(new Error,Kg.SCHEMA_NOT_FOUND(t.databaseid),Wg.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Yg(new Error,Kg.TABLE_NOT_FOUND(t.databaseid,t.tableid),Wg.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=rf(n);i.table=rf(t),this.attributes.push(i)})}[Hu](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)}[Zg](){let t=new tf(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[Xg](r.tableid)}[Xg](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new MF.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[zg](){this[fa](this.statement.columns,!1),this[fa](this.statement.joins,!1),this[fa](this.statement.where,!1),this[jg](this.statement.group,!1),this[fa](this.statement.order,!0)}[fa](t,r){if(!t)return;let s=new tf(t),n=[];for(let{node:i,path:o}of s)!$g.isEmpty(i)&&!$g.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Jg](i):n.push(this[nf](i)));return n}[jg](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&BF.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=rf(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Hu](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[Hu](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`}[Jg](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[nf](t)}[nf](t){let r=this[Hu](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]}};tA.exports=of});var nA=m((tse,sA)=>{"use strict";var af=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")}};sA.exports=af});var oA=m((sse,iA)=>{"use strict";var cf=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};iA.exports=cf});var qu=m((ise,aA)=>{"use strict";var lf=Q(),_f=A();lf.initSync();var HF=lf.get(_f.CONFIG_PARAMS.STORAGE_COMPRESSION),qF=lf.get(_f.CONFIG_PARAMS.STORAGE_CACHING)!==!1,FF=_f.UPDATES_PROPERTY,uf=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=HF&&r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=qF&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.alwaysLazyProperty=s=>s===FF)}};aA.exports=uf});var Gu=m((ase,uA)=>{"use strict";var Gi=Q(),ha=A();Gi.initSync();var GF=Gi.get(ha.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Gi.get(ha.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Gi.get(ha.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",cA=Gi.get(ha.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),xF=Gi.get(ha.CONFIG_PARAMS.STORAGE_NOREADAHEAD),Fu=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=GF,this.noFSAccess=!0,cA!==void 0&&(this.overlappingSync=cA),this.noReadAhead=xF}};uA.exports=Fu;Fu.MAX_DBS=1e4});var ye=m((use,TA)=>{"use strict";var Ef=require("lmdb"),vr=require("fs-extra"),nr=require("path"),xu=vt(),dA=x(),Bt=rr().LMDB_ERRORS_ENUM,ku=oA(),ff=qu(),EA=Gu(),ln=xe(),lA=A(),{table:kF,resetDatabases:VF}=(de(),ee(Ne)),_A=Q(),Br=ln.INTERNAL_DBIS_NAME,fA=ln.DBI_DEFINITION_NAME,$F="data.mdb",YF="lock.mdb",ma=".mdb",KF="-lock",df=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=Rr(t,r),this.key_type=this.dbi[ln.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ln.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new Ef.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function Vu(e,t){if(e===void 0)throw new Error(Bt.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Bt.ENV_NAME_REQUIRED)}a(Vu,"pathEnvNameValidation");async function hf(e,t,r=!0){try{await vr.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Bt.INVALID_BASE_PATH):s}try{let s=nr.join(e,t+ma);return await vr.access(s,vr.constants.R_OK|vr.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await vr.access(nr.join(e,t,$F),vr.constants.R_OK|vr.constants.F_OK),nr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Bt.INVALID_ENVIRONMENT)}else throw new Error(Bt.INVALID_ENVIRONMENT);throw s}}a(hf,"validateEnvironmentPath");function $u(e,t){if(xu.validateEnv(e),t===void 0)throw new Error(Bt.DBI_NAME_REQUIRED)}a($u,"validateEnvDBIName");async function WF(e,t,r=!1,s=!1){Vu(e,t);let n=nr.basename(e);t=t.toString();let i=_A.get(lA.CONFIG_PARAMS.SCHEMAS);i||_A.setProperty(lA.CONFIG_PARAMS.SCHEMAS,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await hf(e,t,s),hA(e,t,r)}catch(o){if(o.message===Bt.INVALID_ENVIRONMENT){let c=nr.join(e,t);await vr.mkdirp(s?c:e);let u=new EA(s?c:c+ma,!1),l=Ef.open(u);l.dbis=Object.create(null);let _=new ff(!1);l.openDB(Br,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=mf(e,t,r);return l[ln.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=l,l}throw o}}a(WF,"createEnvironment");async function QF(e,t,r,s=!0){Vu(e,t),t=t.toString();let n=nr.join(e,t);return kF({table:t,database:nr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(QF,"copyEnvironment");async function hA(e,t,r=!1){Vu(e,t),t=t.toString();let s=mf(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 hf(e,t),i=nr.join(e,t+ma),o=n!=i,c=new EA(n,o),u=Ef.open(c);u.dbis=Object.create(null);let l=SA(u);for(let _=0;_<l.length;_++)Rr(u,l[_]);return u[ln.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(hA,"openEnvironment");async function zF(e,t,r=!1){Vu(e,t),t=t.toString();let s=nr.join(e,t+ma),n=await hf(e,t);if(global.lmdb_map!==void 0){let i=mf(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await mA(o),delete global.lmdb_map[i]}}await vr.remove(n),await vr.remove(n===s?n+KF:nr.join(nr.dirname(n),YF))}a(zF,"deleteEnvironment");async function mA(e){xu.validateEnv(e);let t=e[ln.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(mA,"closeEnvironment");function mf(e,t,r=!1){let n=`${nr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(mf,"getCachedEnvironmentName");function JF(e){xu.validateEnv(e);let t=Object.create(null),r=Rr(e,Br);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==Br)try{t[s]=Object.assign(new ku,n)}catch{dA.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(JF,"listDBIDefinitions");function SA(e){xu.validateEnv(e);let t=[],r=Rr(e,Br);for(let{key:s}of r.getRange({start:!1}))s!==Br&&t.push(s);return t}a(SA,"listDBIs");function XF(e,t){let s=Rr(e,Br).getEntry(t),n=new ku;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{dA.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(XF,"getDBIDefinition");function pA(e,t,r,s=!r){if($u(e,t),t=t.toString(),t===Br)throw new Error(Bt.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Rr(e,t)}catch(n){if(n.message===Bt.DBI_DOES_NOT_EXIST){let i=new ff(r,s===!0),o=e.openDB(t,i),c=new ku(r===!0,s);return o[fA]=c,Rr(e,Br).putSync(t,c),e.dbis[t]=o,o}throw n}}a(pA,"createDBI");function Rr(e,t){if($u(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Br?r=XF(e,t):r=new ku,r===void 0)throw new Error(Bt.DBI_DOES_NOT_EXIST);let s;try{let n=new ff(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(Bt.DBI_DOES_NOT_EXIST):n}return s[fA]=r,e.dbis[t]=s,s}a(Rr,"openDBI");function ZF(e,t){$u(e,t),t=t.toString();let r=Rr(e,t),s=r.getStats();return r[ln.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(ZF,"statDBI");async function jF(e,t){try{let r=nr.join(e,t+ma);return(await vr.stat(r)).size}catch{throw new Error(Bt.INVALID_ENVIRONMENT)}}a(jF,"environmentDataSize");function eG(e,t){if($u(e,t),t=t.toString(),t===Br)throw new Error(Bt.CANNOT_DROP_INTERNAL_DBIS_NAME);Rr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Rr(e,Br).removeSync(t)}a(eG,"dropDBI");function tG(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{Rr(e,i)}catch(o){if(o.message===Bt.DBI_DOES_NOT_EXIST)pA(e,i,i!==t,i===t),s=!0;else throw o}}s&&VF()}a(tG,"initializeDBIs");TA.exports={openDBI:Rr,openEnvironment:hA,createEnvironment:WF,listDBIs:SA,listDBIDefinitions:JF,createDBI:pA,dropDBI:eG,statDBI:ZF,deleteEnvironment:zF,initializeDBIs:tG,TransactionCursor:df,environmentDataSize:jF,copyEnvironment:QF,closeEnvironment:mA}});var gA=m((_se,RA)=>{"use strict";var Sf=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};RA.exports=Sf});var OA=m((Ese,AA)=>{"use strict";var pf=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}};AA.exports=pf});var bA=m((hse,NA)=>{"use strict";var Tf=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};NA.exports=Tf});var xi=m((Rse,wA)=>{"use strict";var rG=ye(),sG=gA(),nG=OA(),iG=bA(),ts=vt(),Sa=rr().LMDB_ERRORS_ENUM,oG=xe(),Ls=A(),aG=V(),cG=require("uuid"),Sse=require("lmdb"),{handleHDBError:uG,hdb_errors:lG}=W(),{OVERFLOW_MARKER:pse,MAX_SEARCH_KEY_LENGTH:Tse}=oG,yA=Q();yA.initSync();var Yu=yA.get(Ls.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Rf=Ls.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Yn=Ls.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function _G(e,t,r,s,n=ts.getNextMonotonicTime()){Nf(e,t,r,s),gf(e,t,r);let i=new sG,o=[],c=[];for(let u=0;u<s.length;u++){let l=s[u];IA(l,!0,n);let _=dG(e,t,r,l),d=l[t];o.push(_),c.push(d)}return Af(o,c,s,i,n)}a(_G,"insertRecords");function dG(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 _=c([[{}]]);Array.isArray(_)&&(c=_[0][Ls.FUNC_VAL],s[o]=c)}let u=ts.getIndexedValues(c),l=e.dbis[o];if(u){Yu&&l.prefetch(u.map(_=>({key:_,value:n})),Ku);for(let _=0,d=u.length;_<d;_++)l.put(u[_],n)}}Yu&&e.dbis[t].prefetch([n],Ku),e.dbis[t].put(n,s,s[Yn])})}a(dG,"insertRecord");function EG(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(EG,"removeSkippedRecords");function IA(e,t,r){let s=r>0;(s||!Number.isInteger(e[Yn]))&&(e[Yn]=r||(r=ts.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[Rf]))&&(e[Rf]=r||ts.getNextMonotonicTime()):delete e[Rf]}a(IA,"setTimestamps");function gf(e,t,r){r.indexOf(Ls.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ls.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ls.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ls.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),rG.initializeDBIs(e,t,r)}a(gf,"initializeTransaction");async function fG(e,t,r,s,n=ts.getNextMonotonicTime()){Nf(e,t,r,s),gf(e,t,r);let i=new nG,o=[],c=[],u=[];for(let l=0;l<s.length;l++){let _=s[l],d=_[t],E;try{E=Of(e,t,_,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(l);continue}c.push(E),u.push(d)}return Af(c,u,s,i,n,o)}a(fG,"updateRecords");async function hG(e,t,r,s,n=ts.getNextMonotonicTime()){try{Nf(e,t,r,s)}catch(u){throw uG(u,u.message,lG.HTTP_STATUS_CODES.BAD_REQUEST)}gf(e,t,r);let i=new iG,o=[],c=[];for(let u=0;u<s.length;u++){let l=s[u],_;aG.isEmpty(l[t])?(_=cG.v4(),l[t]=_):_=l[t];let d=Of(e,t,l,_,i,!1,n);o.push(d),c.push(_)}return Af(o,c,s,i,n)}a(hG,"upsertRecords");async function Af(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||ts.getNextMonotonicTime(),EG(r,i),s}a(Af,"finalizeWrite");function Of(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),l=u?.value,_=l;if(!l){if(i)return!1;l={}}if(IA(r,!_,o),Number.isInteger(r[Yn])&&l[Yn]>r[Yn])return!1;_&&n.original_records.push(l);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let T=r[h],p=e.dbis[h];if(p===void 0)continue;let R=l[h];if(typeof T=="function"){let k=T([[l]]);Array.isArray(k)&&(T=k[0][Ls.FUNC_VAL],r[h]=T)}if(T===R)continue;let O=ts.getIndexedValues(R);if(O){Yu&&p.prefetch(O.map(k=>({key:k,value:s})),Ku);for(let k=0,$=O.length;k<$;k++)p.remove(O[k],s)}if(O=ts.getIndexedValues(T),O){Yu&&p.prefetch(O.map(k=>({key:k,value:s})),Ku);for(let k=0,$=O.length;k<$;k++)p.put(O[k],s)}}let f=Object.assign({},l,r);c.put(s,f,f[Yn])},"do_put");return u?d=c.ifVersion(s,u.version,E):d=c.ifNoExists(s,E),d.then(f=>f?!0:Of(e,t,r,s,n,i,o))}a(Of,"updateUpsertRecord");function mG(e,t,r){if(ts.validateEnv(e),t===void 0)throw new Error(Sa.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Sa.WRITE_ATTRIBUTES_REQUIRED):new Error(Sa.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(mG,"validateBasic");function Nf(e,t,r,s){if(mG(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Sa.RECORDS_REQUIRED):new Error(Sa.RECORDS_MUST_BE_ARRAY)}a(Nf,"validateWrite");function Ku(){}a(Ku,"noop");wA.exports={insertRecords:_G,updateRecords:fG,upsertRecords:hG}});var Kn=m((Ase,SG)=>{SG.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",attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var rs=m((Ose,DA)=>{"use strict";var UA=V(),CA=A(),ki=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Ms=require("joi"),_n={schema_format:{pattern:ki,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},pG=Ms.alternatives(Ms.string().min(1).max(_n.schema_length.maximum).pattern(ki).messages({"string.pattern.base":"{:#label} "+_n.schema_format.message}),Ms.number()).required(),TG=Ms.alternatives(Ms.string().min(1).max(_n.schema_length.maximum).pattern(ki).messages({"string.pattern.base":"{:#label} "+_n.schema_format.message}),Ms.number()),RG=Ms.alternatives(Ms.string().min(1).max(_n.schema_length.maximum).pattern(ki).messages({"string.pattern.base":"{:#label} "+_n.schema_format.message}),Ms.number()).required();function gG(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>_n.schema_length.maximum?`'${e}' maximum of 250 characters`:ki.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(gG,"checkValidTable");function AG(e,t){return UA.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(AG,"validateSchemaExists");function OG(e,t){let r=t.state.ancestors[0].schema;return UA.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(OG,"validateTableExists");function NG(e,t){return e.toLowerCase()===CA.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${CA.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(NG,"validateSchemaName");DA.exports={common_validators:_n,schema_regex:ki,hdb_schema_table:pG,validateSchemaExists:AG,validateTableExists:OG,validateSchemaName:NG,checkValidTable:gG,hdb_database:TG,hdb_table:RG}});var ve=m((bse,LA)=>{"use strict";var Ht=require("validate.js");Ht.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||Ht.validators.type.checks[t](e)?null:` must be a '${t}' value`};Ht.validators.type.checks={Object:function(e){return Ht.isObject(e)&&!Ht.isArray(e)},Array:Ht.isArray,Integer:Ht.isInteger,Number:Ht.isNumber,String:Ht.isString,Date:Ht.isDate,Boolean:function(e){return typeof e=="boolean"}};Ht.validators.hasValidFileExt=function(e,t){return Ht.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};LA.exports={validateObject:bG,validateObjectAsync:yG,validateBySchema:IG};function bG(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=Ht(e,t,{format:"flat"});return r?new Error(r):null}a(bG,"validateObject");async function yG(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await Ht.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(yG,"validateObjectAsync");function IG(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(IG,"validateBySchema")});var Wu=m((Ise,MA)=>{var{common_validators:ss}=rs(),Ta=ve(),pa="is required",We={database:{presence:!1,format:ss.schema_format,length:ss.schema_length},schema:{presence:!1,format:ss.schema_format,length:ss.schema_length},table:{presence:!0,format:ss.schema_format,length:ss.schema_length},attribute:{presence:!0,format:ss.schema_format,length:ss.schema_length},hash_attribute:{presence:!0,format:ss.schema_format,length:ss.schema_length}};function Ra(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(Ra,"makeAttributesStrings");function wG(e){return e=Ra(e),We.table.presence=!1,We.attribute.presence=!1,We.hash_attribute.presence=!1,Ta.validateObject(e,We)}a(wG,"schema_object");function CG(e){return e=Ra(e),We.table.presence={message:pa},We.attribute.presence=!1,We.hash_attribute.presence=!1,Ta.validateObject(e,We)}a(CG,"table_object");function UG(e){return e=Ra(e),We.table.presence={message:pa},We.attribute.presence=!1,Ta.validateObject(e,We)}a(UG,"create_table_object");function DG(e){return e=Ra(e),We.table.presence={message:pa},We.attribute.presence={message:pa},We.hash_attribute.presence=!1,Ta.validateObject(e,We)}a(DG,"attribute_object");function LG(e){return e=Ra(e),We.table.presence={message:pa},We.attribute.presence=!1,We.hash_attribute.presence=!1,Ta.validateObject(e,We)}a(LG,"describe_table");function MG(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(MG,"validateTableResidence");MA.exports={schema_object:wG,create_table_object:UG,table_object:CG,attribute_object:DG,describe_table:LG,validateTableResidence:MG}});var vA=m((Cse,PA)=>{"use strict";var PG=require("uuid"),bf=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||PG.v4(),this.schema_table=`${this.schema}.${this.table}`}};PA.exports=bf});var Qu=m((Dse,BA)=>{"use strict";var vG=vA(),yf=class extends vG{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}};BA.exports=yf});var qA=m((Mse,HA)=>{"use strict";HA.exports=HG;var BG="inserted";function HG(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===BG?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(HG,"returnObject")});var zu=m((vse,VA)=>{"use strict";var qG=A(),If=ye(),FG=xi(),{getSystemSchemaPath:GG,getSchemaPath:xG}=we(),kG=Kn(),VG=Wu(),$G=Qu(),YG=qA(),{handleHDBError:FA,hdb_errors:xA}=W(),GA=V(),{HTTP_STATUS_CODES:KG}=xA,wf=kG.hdb_attribute,kA=[];for(let e=0;e<wf.attributes.length;e++)kA.push(wf.attributes[e].attribute);var WG="inserted";VA.exports=QG;async function QG(e){let t=VG.attribute_object(e);if(t)throw FA(new Error,t.message,xA.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&GA.checkGlobalSchemaTable(e.schema,e.table);if(r)throw FA(new Error,r,KG.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=GA.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 $G(e.schema,e.table,e.attribute,e.id);try{let i=await If.openEnvironment(xG(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}`);If.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await If.openEnvironment(GG(),qG.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await FG.insertRecords(o,wf.hash_attribute,kA,[n]);return YG(WG,c,{records:[n]},u)}catch(i){throw i}}a(QG,"lmdbCreateAttribute")});var Uf=m((Hse,YA)=>{var{hdb_table:zG,hdb_database:$A}=rs(),JG=ve(),Cf=require("joi"),XG={undefined:"undefined",null:"null"},ZG=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||XG[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"),jG=Cf.object({database:$A,schema:$A,table:zG,records:Cf.array().items(Cf.object().custom(ZG)).required()});YA.exports=function(e){return JG.validateBySchema(e,jG)}});var ga=m((Gse,WA)=>{"use strict";var Ps=V(),KA=x(),Fse=Uf(),{getDatabases:ex}=(de(),ee(Ne)),{ClientError:Wn}=W();WA.exports=tx;function tx(e){if(Ps.isEmpty(e))throw new Wn("invalid update parameters defined.");if(Ps.isEmptyOrZeroLength(e.schema))throw new Wn("invalid schema specified.");if(Ps.isEmptyOrZeroLength(e.table))throw new Wn("invalid table specified.");if(!Array.isArray(e.records))throw new Wn("records must be an array");let t=ex()[e.schema]?.[e.table];if(Ps.isEmpty(t))throw new Wn(`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&&Ps.isEmptyOrZeroLength(o[r]))throw KA.error("a valid hash attribute must be provided with update record:",o),new Wn("a valid hash attribute must be provided with update record, check log for more info");if(!Ps.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw KA.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Wn(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Ps.isEmpty(o[r])&&o[r]!==""&&s.has(Ps.autoCast(o[r]))&&(o.skip=!0),s.add(Ps.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(tx,"insertUpdateValidate")});var Aa=m((kse,QA)=>{"use strict";var rx=A().OPERATIONS_ENUM,Df=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=rx.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};QA.exports=Df});var ya=m((Yse,zA)=>{"use strict";var $se=Aa(),Ju=A(),Mf=V(),Lf=x(),sx=require("uuid"),{handleHDBError:Oa,hdb_errors:nx}=W(),{HDB_ERROR_MSGS:Na,HTTP_STATUS_CODES:ba}=nx;zA.exports=ix;function ix(e,t,r){for(let n=0;n<t.length;n++)ox(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];ax(i,r,e.operation)}}a(ix,"processRows");function ox(e){if(Buffer.byteLength(String(e))>Ju.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Oa(new Error,Na.ATTR_NAME_LENGTH_ERR(e),ba.BAD_REQUEST,void 0,void 0,!0);if(Mf.isEmptyOrZeroLength(e)||Mf.isEmpty(e.trim()))throw Oa(new Error,Na.ATTR_NAME_NULLISH_ERR,ba.BAD_REQUEST,void 0,void 0,!0)}a(ox,"validateAttribute");function ax(e,t,r){if(!e.hasOwnProperty(t)||Mf.isEmptyOrZeroLength(e[t])){if(r===Ju.OPERATIONS_ENUM.INSERT||r===Ju.OPERATIONS_ENUM.UPSERT){e[t]=sx.v4();return}throw Lf.error("Update transaction aborted due to record with no hash value:",e),Oa(new Error,Na.RECORD_MISSING_HASH_ERR,ba.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>Ju.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Lf.error(e),Oa(new Error,Na.HASH_VAL_LENGTH_ERR,ba.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Lf.error(e),Oa(new Error,Na.INVALID_FORWARD_SLASH_IN_HASH_ERR,ba.BAD_REQUEST,void 0,void 0,!0)}a(ax,"validateHash")});var XA=m((Wse,JA)=>{"use strict";var Pf=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};JA.exports=Pf});var eO=m((zse,jA)=>{"use strict";var vf=ye(),cx=x(),ZA=rr().LMDB_ERRORS_ENUM;jA.exports=ux;async function ux(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 vf.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==ZA.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await vf.closeEnvironment(global.lmdb_map[s]),await vf.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==ZA.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){cx.error(t)}}a(ux,"cleanLMDBMap")});var vs=m((Xse,nO)=>{"use strict";var Ia=require("crypto"),lx=Q(),{CONFIG_PARAMS:_x}=A(),rO="aes-256-cbc",dx=32,Ex=16,Bf=64,sO=32,fx=Bf+sO,tO=new Map;nO.exports={encrypt:hx,decrypt:mx,createNatsTableStreamName:Sx};function hx(e){let t=Ia.randomBytes(dx),r=Ia.randomBytes(Ex),s=Ia.createCipheriv(rO,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(hx,"encrypt");function mx(e){let t=e.substr(0,Bf),r=e.substr(Bf,sO),s=e.substr(fx,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Ia.createDecipheriv(rO,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(mx,"decrypt");function Sx(e,t){let r=lx.get(_x.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=tO.get(r);return s||(s=Ia.createHash("md5").update(r).digest("hex"),tO.set(r,s)),s}a(Sx,"createNatsTableStreamName")});var Qn=m((ene,oO)=>{"use strict";var jse=gr(),Xu=x(),iO=Wu(),px=vs(),Zu=V(),{handleHDBError:ju,hdb_errors:Tx}=W(),{HDB_ERROR_MSGS:el,HTTP_STATUS_CODES:Hf}=Tx,Rx=Q();Rx.initSync();var{getDatabases:qf}=(de(),ee(Ne));oO.exports={describeAll:gx,describeTable:tl,describeSchema:Ax};async function gx(e){try{let t=Zu.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=qf(),i={},o={},c=[];for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let _=n[l];for(let d in _)try{let E;if(t||s)E=await tl({schema:l,table:d});else if(r&&r[l].describe&&r[l].tables[d].describe){let f=r[l].tables[d].attribute_permissions;E=await tl({schema:l,table:d},f)}E&&c.push(E)}catch(E){Xu.error(E)}}let u={};for(let l in c)t||s?(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?u[l]={}:o[l]&&(u[l]={});return u}catch(t){return Xu.error("Got an error in describeAll"),Xu.error(t),ju(new Error,el.DESCRIBE_ALL_ERR)}}a(gx,"describeAll");async function tl(e,t){Zu.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=iO.describe_table(e);if(i)throw i;let c=qf()[r];if(!c)throw ju(new Error,el.SCHEMA_NOT_FOUND(e.schema),Hf.NOT_FOUND);let u=c[s];if(!u)throw ju(new Error,el.TABLE_NOT_FOUND(e.schema,e.table),Hf.NOT_FOUND);let l=[];if(n){let d={};n.forEach(E=>{E.describe&&(d[E.attribute_name]=!0)}),u.attributes.forEach(E=>{d[E.name]&&l.push(E)})}else l=u.attributes;let _={schema:r,name:u.tableName,attributes:l,hash_attribute:u.attributes.find(d=>d.isPrimaryKey||d.is_hash_attribute)?.name};_.clustering_stream_name=px.createNatsTableStreamName(_.schema,_.name);try{_.record_count=u.getRecordCount();let d=u.auditStore;if(d)for(let E of d.getKeys({reverse:!0,limit:1}))_.last_updated_record=E[0];if(!_.last_updated_record&&u.indices.__updatedtime__)for(let E of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))_.last_updated_record=E}catch(d){Xu.warn(`unable to stat table dbi due to ${d}`)}return _}a(tl,"descTable");async function Ax(e){Zu.transformReq(e);let t=iO.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=qf()[s];if(!i)throw ju(new Error,el.SCHEMA_NOT_FOUND(e.schema),Hf.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),Zu.isEmpty(u)||u.describe){let l=await tl({schema:e.schema,table:c},u?u.attribute_permissions:null);l&&(o[l.name]=l)}}return o}a(Ax,"describeSchema")});var dn=m((nne,_O)=>{var Ox=Kn(),{callbackify:cO,promisify:Nx}=require("util"),{getDatabases:uO}=(de(),ee(Ne));_O.exports={setSchemaDataToGlobal:aO,getTableSchema:bx,getSystemSchema:yx,setSchemaDataToGlobalAsync:Nx(aO)};var lO=Qn(),rne=cO(lO.describeAll),sne=cO(lO.describeTable);function aO(e){global.hdb_schema=uO(),e&&e()}a(aO,"setSchemaDataToGlobal");function bx(e,t,r){let s=uO()[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(bx,"getTableSchema");function yx(){return Ox}a(yx,"getSystemSchema")});var Ar=m((one,hO)=>{"use strict";var sl=Uf(),mt=V(),Ix=require("util"),nl=Hr(),wx=dn(),dO=x(),{handleHDBError:zn,hdb_errors:Cx}=W(),{HTTP_STATUS_CODES:Jn}=Cx,Ux=Ix.promisify(wx.getTableSchema),Dx="updated",EO="inserted",fO="upserted";hO.exports={insert:Mx,update:Px,upsert:vx,validation:Lx,flush:Bx};async function Lx(e){if(mt.isEmpty(e))throw new Error("invalid update parameters defined.");if(mt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(mt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await Ux(e.schema,e.table),r=sl(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&&mt.isEmptyOrZeroLength(c[s]))throw dO.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(!mt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw dO.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!mt.isEmpty(c[s])&&c[s]!==""&&n.has(mt.autoCast(c[s]))&&(c.skip=!0),n.add(mt.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(Lx,"validation");async function Mx(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=sl(e);if(t)throw zn(new Error,t.message,Jn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw zn(new Error,r,Jn.BAD_REQUEST);let s=await nl.createRecords(e);return rl(EO,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(Mx,"insertData");async function Px(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=sl(e);if(t)throw zn(new Error,t.message,Jn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw zn(new Error,r,Jn.BAD_REQUEST);let s=await nl.updateRecords(e);return mt.isEmpty(s.existing_rows)?rl(Dx,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):rl(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(Px,"updateData");async function vx(e){if(e.operation!=="upsert")throw zn(new Error,"invalid operation, must be upsert",Jn.INTERNAL_SERVER_ERROR);let t=sl(e);if(t)throw zn(new Error,t.message,Jn.BAD_REQUEST);mt.transformReq(e);let r=mt.checkSchemaTableExist(e.schema,e.table);if(r)throw zn(new Error,r,Jn.BAD_REQUEST);let s=await nl.upsertRecords(e);return rl(fO,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(vx,"upsertData");function rl(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===EO?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===fO?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(rl,"returnObject");function Bx(e){return mt.transformReq(e),nl.flush(e.schema,e.table)}a(Bx,"flush")});var Gf=m((cne,pO)=>{var Hx=ve(),Ff=require("joi"),{hdb_table:qx,hdb_database:mO}=rs(),SO={schema:mO,database:mO,table:qx},Fx={date:Ff.date().iso().required()},Gx={timestamp:Ff.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};pO.exports=function(e,t){let r=t==="timestamp"?{...SO,...Gx}:{...SO,...Fx},s=Ff.object(r);return Hx.validateBySchema(e,s)}});var gO=m((une,RO)=>{var xx=ve(),xf=require("joi"),{hdb_table:kx,hdb_database:TO}=rs(),Vx=xf.object({schema:TO,database:TO,table:kx,hash_values:xf.array().required(),ids:xf.array()});RO.exports=function(e){return xx.validateBySchema(e,Vx)}});var OO=m((lne,AO)=>{"use strict";var kf=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}},Vf=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}},$f=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};AO.exports={InsertObject:kf,NoSQLSeachObject:Vf,DeleteResponseObject:$f}});var jn=m((dne,wO)=>{"use strict";var bO=Gf(),$x=gO(),Xn=V(),NO=require("moment"),yO=x(),{promisify:Yx,callbackify:Kx}=require("util"),Zn=A(),Wx=dn(),Yf=Yx(Wx.getTableSchema),Kf=Hr(),{DeleteResponseObject:Qx}=OO(),{handleHDBError:En,hdb_errors:zx}=W(),{HDB_ERROR_MSGS:il,HTTP_STATUS_CODES:fn}=zx,Jx="records successfully deleted",Xx=Kx(IO);wO.exports={delete:Xx,deleteRecord:IO,deleteFilesBefore:Zx,deleteAuditLogsBefore:jx};async function Zx(e){let t=bO(e,"date");if(t)throw En(t,t.message,fn.BAD_REQUEST,void 0,void 0,!0);if(Xn.transformReq(e),!NO(e.date,NO.ISO_8601).isValid())throw En(new Error,il.INVALID_DATE,fn.BAD_REQUEST,Zn.LOG_LEVELS.ERROR,il.INVALID_DATE,!0);let s=Xn.checkSchemaTableExist(e.schema,e.table);if(s)throw En(new Error,s,fn.NOT_FOUND,Zn.LOG_LEVELS.ERROR,s,!0);let n=await Kf.deleteRecordsBefore(e);if(await Yf(e.schema,e.table),yO.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(Zx,"deleteFilesBefore");async function jx(e){let t=bO(e,"timestamp");if(t)throw En(t,t.message,fn.BAD_REQUEST,void 0,void 0,!0);if(Xn.transformReq(e),isNaN(e.timestamp))throw En(new Error,il.INVALID_VALUE("Timestamp"),fn.BAD_REQUEST,Zn.LOG_LEVELS.ERROR,il.INVALID_VALUE("Timestamp"),!0);let r=Xn.checkSchemaTableExist(e.schema,e.table);if(r)throw En(new Error,r,fn.NOT_FOUND,Zn.LOG_LEVELS.ERROR,r,!0);let s=await Kf.deleteAuditLogsBefore(e);return await Yf(e.schema,e.table),yO.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(jx,"deleteAuditLogsBefore");async function IO(e){e.ids&&(e.hash_values=e.ids);let t=$x(e);if(t)throw En(t,t.message,fn.BAD_REQUEST,void 0,void 0,!0);Xn.transformReq(e);let r=Xn.checkSchemaTableExist(e.schema,e.table);if(r)throw En(new Error,r,fn.NOT_FOUND,Zn.LOG_LEVELS.ERROR,r,!0);try{await Yf(e.schema,e.table);let s=await Kf.deleteRecords(e);return Xn.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${Jx}`),s}catch(s){if(s.message===Zn.SEARCH_NOT_FOUND_MESSAGE){let n=new Qx;return n.message=Zn.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(IO,"deleteRecord")});var ol=m((fne,DO)=>{var ek=require("crypto"),CO=9;function tk(e){let t=sk(CO),r=UO(e+t);return t+r}a(tk,"createHash");function rk(e,t){let r=e.substr(0,CO),s=r+UO(t+r);return e===s}a(rk,"validateHash");function sk(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(sk,"generateSalt");function UO(e){return ek.createHash("md5").update(e).digest("hex")}a(UO,"md5");DO.exports={hash:tk,validate:rk}});var MO=m((mne,LO)=>{var Wf=ve(),It={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 nk(e){return It.password.presence=!0,It.username.presence=!0,It.role.presence=!0,It.active.presence=!0,Wf.validateObject(e,It)}a(nk,"addUserValidation");function ik(e){return It.password.presence=!1,It.username.presence=!0,It.role.presence=!1,It.active.presence=!1,Wf.validateObject(e,It)}a(ik,"alterUserValidation");function ok(e){return It.password.presence=!1,It.username.presence=!0,It.role.presence=!1,It.active.presence=!1,Wf.validateObject(e,It)}a(ok,"dropUserValidation");LO.exports={addUserValidation:nk,alterUserValidation:ik,dropUserValidation:ok}});var Be=m((Tne,vO)=>{"use strict";var{platform:pne}=require("os"),ak="nats-server.zip",Qf="nats-server",ck=process.platform==="win32"?`${Qf}.exe`:Qf,zf="HDB",uk=/^[^\s.,*>]+$/,PO="__request__",lk=a(e=>`${e}.${PO}`,"REQUEST_SUBJECT"),_k={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin"},dk={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},Ek={HUB:"hub.pid",LEAF:"leaf.pid"},fk={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},hk={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:zf,deliver_subject:"__HDB__.WORKQUEUE"},mk={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:zf,deliver_subject:"HDB.SCHEMAQUEUE"},Sk={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:zf,deliver_subject:"HDB.USERQUEUE"},pk={SUCCESS:"success",ERROR:"error"},Tk={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},Rk={TXN:"txn",MSGID:"msgid"},Vi={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},gk={[Vi.ERR]:1,[Vi.WRN]:2,[Vi.INF]:3,[Vi.DBG]:4,[Vi.TRC]:5},Ak={debug:"-D",trace:"-DVV"};vO.exports={NATS_SERVER_ZIP:ak,NATS_SERVER_NAME:Qf,NATS_BINARY_NAME:ck,PID_FILES:Ek,NATS_CONFIG_FILES:dk,SERVER_SUFFIX:fk,WORK_QUEUE_CONSUMER_NAMES:hk,SCHEMA_QUEUE_CONSUMER_NAMES:mk,USER_QUEUE_CONSUMER_NAMES:Sk,NATS_TERM_CONSTRAINTS_RX:uk,REQUEST_SUFFIX:PO,UPDATE_REMOTE_RESPONSE_STATUSES:pk,CLUSTER_STATUS_STATUSES:Tk,REQUEST_SUBJECT:lk,SUBJECT_PREFIXES:Rk,MSG_HEADERS:_k,LOG_LEVELS:Vi,LOG_LEVEL_FLAGS:Ak,LOG_LEVEL_HIERARCHY:gk}});var HO=m((gne,BO)=>{"use strict";var Ok={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,String.fromCharCode(13,10)),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,String.fromCharCode(13,10))},Nk="certificate.pem",bk="privateKey.pem",yk="ca.pem";BO.exports={CERTIFICATE_VALUES:Ok,CERTIFICATE_PEM_NAME:Nk,PRIVATEKEY_PEM_NAME:bk,CA_PEM_NAME:yk}});var Xf=m((One,VO)=>{"use strict";var xO=require("fs-extra"),te=require("joi"),Ik=require("os"),{boolean:pe,string:Hs,number:ir,array:Jf}=te.types(),{totalmem:qO}=require("os"),$i=require("path"),wk=x(),cl=V(),Ane=HO(),FO=A(),Ck=ve(),GO="log",Uk="components",Dk="Invalid logging.rotation.maxSize unit. Available units are G, M or K",Lk="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Mk="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",Pk="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",vk="rootPath config parameter is undefined",Bk="clustering.enabled config parameter is undefined",Bs=ir.min(0).required(),ul=Jf.items({host:Hs.required(),port:Bs}).empty(null),qs;VO.exports={configValidator:Hk,routesValidator:Vk,route_constraints:ul};function Hk(e){if(qs=e.rootPath,cl.isEmpty(qs))throw vk;let t=pe.required(),r=te.valid("production","development").required(),s=ir.min(0).max(1e3).empty(null).default(kk),n=Hs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(al),i=te.custom(qk).messages({"any.custom":"{:#label} {:#error}"}),o=Hs.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=te.string().empty(null).default(al),u=te.custom(Fk).empty(null).default(al),l=e.clustering?.enabled;if(cl.isEmpty(l))throw Bk;let _;return l===!0?_=te.object({enabled:t,hubServer:te.object({cluster:te.object({name:te.required().empty(null),network:te.object({port:Bs,routes:ul}).required()}).required(),leafNodes:te.object({network:te.object({port:Bs}).required()}).required(),network:te.object({port:Bs}).required()}).required(),leafServer:te.object({network:te.object({port:Bs,routes:ul}).required(),streams:te.object({maxAge:ir.min(120).allow(null).optional(),maxBytes:ir.min(1).allow(null).optional(),maxMsgs:ir.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:te.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:pe.optional(),databaseLevel:pe.optional(),tls:te.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:pe.required(),verify:pe.optional()}),user:Hs.optional().empty(null)}).required():_=te.object({enabled:t,tls:te.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:pe.required()})}).required(),te.object({authentication:te.object({authorizeLocal:pe,cacheTTL:ir.required(),enableSessions:pe,operationTokenTimeout:te.required(),refreshTokenTimeout:te.required()}),analytics:te.object({aggregatePeriod:ir}),clustering:_,customFunctions:te.object({enabled:t,network:te.object({cors:pe.required(),corsAccessList:Jf.required(),headersTimeout:ir.min(1).required(),https:pe.required(),keepAliveTimeout:ir.min(1).required(),port:Bs,timeout:ir.min(1).required()}),nodeEnv:r,root:n,tls:te.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),localStudio:te.object({enabled:t}).required(),logging:te.object({auditAuthEvents:te.object({logFailed:pe,logSuccessful:pe}),file:pe.required(),level:te.valid("notify","fatal","error","warn","info","debug","trace"),rotation:te.object({enabled:pe.optional(),compress:pe.optional(),interval:Hs.custom(xk).optional().empty(null),maxSize:Hs.custom(Gk).optional().empty(null),path:Hs.optional().empty(null).default(al)}).required(),root:n,stdStreams:pe.required(),auditLog:pe.required()}).required(),operationsApi:te.object({foreground:pe.required(),network:te.object({cors:pe.required(),corsAccessList:Jf.required(),headersTimeout:ir.min(1).required(),https:pe.required(),keepAliveTimeout:ir.min(1).required(),port:Bs,timeout:ir.min(1).required()}).required(),nodeEnv:r,tls:te.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Hs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:te.object({network:te.object({port:Bs,securePort:Bs}).required(),webSocket:pe.optional(),requireAuthentication:pe.optional()}),http:te.object({threads:s}).required(),storage:te.object({writeAsync:pe.required(),overlappingSync:pe.optional(),caching:pe.optional(),compression:pe.optional(),noReadAhead:pe.optional(),path:u,prefetchWrites:pe.optional()}).required(),ignoreScripts:pe.optional()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Hk,"configValidator");function kO(e){return xO.existsSync(e)?null:`Specified path ${e} does not exist.`}a(kO,"doesPathExist");function qk(e,t){if(e===null)return;let r=kO(e);return r?t.message(r):e}a(qk,"validatePemFile");function Fk(e,t){te.assert(e,Hs.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=kO(e);if(r)return t.message(r)}a(Fk,"validatePath");function Gk(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(Dk);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(Mk):e}a(Gk,"validateRotationMaxSize");function xk(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(Lk);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(Pk):e}a(xk,"validateRotationInterval");function kk(e,t){let r=t.state.path.join("."),s=Ik.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||qO();return i=Math.round(Math.min(i,qO())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),wk.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(kk,"setDefaultThreads");function al(e,t){if(!cl.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(cl.isEmpty(qs))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return $i.join(qs,Uk);case"logging.root":return $i.join(qs,GO);case"clustering.leafServer.streams.path":return $i.join(qs,"clustering","leaf");case"storage.path":let s=$i.join(qs,FO.LEGACY_DATABASES_DIR_NAME);return xO.existsSync(s)?s:$i.join(qs,FO.DATABASES_DIR_NAME);case"logging.rotation.path":return $i.join(qs,GO);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(al,"setDefaultRoot");function Vk(e){let t=te.object({routes:ul});return Ck.validateBySchema({routes:e},t)}a(Vk,"routesValidator")});var Nr=m((yne,jO)=>{"use strict";var Or=A(),dt=V(),st=x(),{configValidator:$k,routesValidator:$O}=Xf(),qt=require("fs-extra"),Yk=require("yaml"),qr=require("path"),Kk=require("is-number"),KO=require("properties-reader"),Wk=require("lodash"),{handleHDBError:Qk}=W(),{HTTP_STATUS_CODES:zk,HDB_ERROR_MSGS:ll}=rr(),bne=require("minimist"),{server:Jk}=(Pr(),ee(da)),{SCHEMAS_PARAM_CONFIG:wa,CONFIG_PARAMS:hn,CONFIG_PARAM_MAP:Fs}=Or,Xk="Unable to get config value because config is uninitialized",Zk="Config successfully initialized",jk="Error backing up config file",eV="Empty parameter sent to getConfigValue",WO=qr.join(Or.PACKAGE_ROOT,"config","yaml",Or.HDB_DEFAULT_CONFIG_FILE),tV="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",YO={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"},_l,St;jO.exports={createConfigFile:rV,getDefaultConfig:sV,getConfigValue:zO,initConfig:JO,flattenConfig:ti,updateConfigValue:XO,updateConfigObject:iV,getConfiguration:cV,setConfiguration:uV,readConfigFile:eh,getClusteringRoutes:lV,initOldConfig:ZO,getConfigFromFile:_V,getConfigFilePath:ei,addConfig:dV,deleteConfigFromFile:EV};function rV(e){let t=mn(WO);_l=ti(t.toJSON());let r;for(let o in e){let c=Fs[o.toLowerCase()];if(c===hn.SCHEMAS){r=e[o];continue}if(c!==void 0){let u=c.split("_"),l=Zf(c,e[o]);c==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{t.setIn([...u],l)}catch(_){st.error(_)}}}r&&QO(t,r),jf(t);let s=t.toJSON();St=ti(s);let n=t.getIn(["rootPath"]),i=qr.join(n,Or.HDB_CONFIG_FILE);qt.createFileSync(i),qt.writeFileSync(i,String(t)),st.trace(`Config file written to ${i}`)}a(rV,"createConfigFile");function QO(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!dt.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(wa.TABLES))for(let i in s[n][wa.TABLES])for(let o in s[n][wa.TABLES][i]){let c=s[n][wa.TABLES][i][o],u=[hn.SCHEMAS,n,wa.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=[hn.SCHEMAS,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){st.error("Error parsing schemas CLI/env config arguments",s)}}a(QO,"setSchemasConfig");function sV(e){if(_l===void 0){let r=mn(WO);_l=ti(r.toJSON())}let t=Fs[e.toLowerCase()];if(t!==void 0)return _l[t.toLowerCase()]}a(sV,"getDefaultConfig");function zO(e){if(e==null){st.error(eV);return}if(St===void 0){st.trace(Xk);return}let t=Fs[e.toLowerCase()];if(t!==void 0)return St[t.toLowerCase()]}a(zO,"getConfigValue");function ei(e=dt.getPropsFilePath()){let t=dt.getEnvCliRootPath();return t?qr.join(t,Or.HDB_CONFIG_FILE):KO(e).get(Or.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(ei,"getConfigFilePath");function JO(e=!1){if(St===void 0||e){let t;if(!dt.noBootFile()){t=dt.getPropsFilePath();try{qt.accessSync(t,qt.constants.F_OK|qt.constants.R_OK)}catch(i){throw st.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=ei(t),s;if(r.includes("config/settings.js"))try{ZO(r);return}catch(i){if(i.code!==Or.NODE_ERROR_CODES.ENOENT)throw i}try{s=mn(r)}catch(i){if(i.code===Or.NODE_ERROR_CODES.ENOENT){st.trace(`HarperDB config file not found at ${r}.
|
|
5
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw st.error(i),new Error(`Error reading HarperDB config file at ${r}`)}nV(s,r),jf(s);let n=s.toJSON();if(Jk.config=n,St=ti(n),St.logging_rotation_rotate)for(let i in YO)St[i]&&st.error(`Config ${YO[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);st.trace(Zk)}}a(JO,"initConfig");function nV(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],qr.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],qr.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],qr.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(st.trace("Updating config file with missing config params"),qt.writeFileSync(t,String(e)))}a(nV,"checkForUpdatedConfig");function jf(e){let t=e.toJSON(),r=$k(t);if(r.error)throw ll.CONFIG_VALIDATION(r.error.message);e.setIn(["http","threads"],r.value.http.threads),e.setIn(["customFunctions","root"],r.value.customFunctions.root),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)}a(jf,"validateConfig");function iV(e,t){St===void 0&&(St={});let r=Fs[e.toLowerCase()];if(r===void 0){st.trace(`Unable to update config object because config param '${e}' does not exist`);return}St[r.toLowerCase()]=t}a(iV,"updateConfigObject");function XO(e,t,r=void 0,s=!1,n=!1,i=!1){St===void 0&&JO();let o=zO(Fs.hdb_root),c=qr.join(o,Or.HDB_CONFIG_FILE),u=mn(c),l;if(r===void 0&&e.toLowerCase()===hn.SCHEMAS)l=t;else if(r===void 0){let E;if(i)E=e;else if(E=Fs[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=Zf(E,t);u.setIn([...f],h)}else for(let E in r){let f=Fs[E.toLowerCase()];if(f===hn.SCHEMAS){l=r[E];continue}if(f!==void 0){let h=f.split("_"),T=Zf(f,r[E]);f==="rootPath"&&T?.endsWith("/")&&(T=T.slice(0,-1));try{u.setIn([...h],T)}catch(p){st.error(p)}}}l&&QO(u,l),jf(u);let _=u.getIn(["rootPath"]),d=qr.join(_,Or.HDB_CONFIG_FILE);s===!0&&oV(c,_),qt.writeFileSync(d,String(u)),n&&(St=ti(u.toJSON())),st.trace(`Config parameter: ${e} updated with value: ${t}`)}a(XO,"updateConfigValue");function oV(e,t){try{let r=qr.join(t,"backup",`${Or.HDB_CONFIG_FILE}.bak`);qt.copySync(e,r),st.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){st.error(jk),st.error(r)}}a(oV,"backupConfigFile");var aV=["schemas"];function ti(e){let t={};for(let r in e)if(e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])&&!aV.includes(r)){let s=ti(e[r]);for(let n in s)s.hasOwnProperty(n)&&(t[r.toLowerCase()+"_"+n]=s[n])}else t[r.toLowerCase()]=e[r];return t}a(ti,"flattenConfig");function Zf(e,t){if(e===hn.CLUSTERING_NODENAME||e===hn.CLUSTERING_USER){if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(Kk(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||dt.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 dt.autoCast(t)}a(Zf,"castConfigValue");function cV(){let e=dt.getPropsFilePath(),t=ei(e);return mn(t).toJSON()}a(cV,"getConfiguration");async function uV(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return XO(void 0,void 0,n,!0),tV}catch(i){throw typeof i=="string"||i instanceof String?Qk(i,i,zk.BAD_REQUEST,void 0,void 0,!0):i}}a(uV,"setConfiguration");function eh(){let e=dt.getPropsFilePath();try{qt.accessSync(e,qt.constants.F_OK|qt.constants.R_OK)}catch(s){if(!dt.noBootFile())throw st.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=ei(e);return mn(t).toJSON()}a(eh,"readConfigFile");function mn(e){return Yk.parseDocument(qt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(mn,"parseYamlDoc");function lV(){let e=eh(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=dt.isEmptyOrZeroLength(t)?[]:t;let r=$O(t);if(r)throw ll.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=dt.isEmptyOrZeroLength(s)?[]:s;let n=$O(s);if(n)throw ll.CONFIG_VALIDATION(n.message);if(!dt.isEmptyOrZeroLength(s)&&!dt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!dt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw ll.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(lV,"getClusteringRoutes");function ZO(e){let t=KO(e);St={};for(let r in Fs){let s=t.get(r.toUpperCase());if(dt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=Fs[r].toLowerCase();n===hn.LOGGING_ROOT?St[n]=qr.dirname(s):St[n]=s}return St}a(ZO,"initOldConfig");function _V(e){let t=eh();return Wk.get(t,e.replaceAll("_","."))}a(_V,"getConfigFromFile");async function dV(e,t){let r=mn(ei());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await qt.writeFile(ei(),String(r))}a(dV,"addConfig");function EV(e){let t=ei(dt.getPropsFilePath()),r=mn(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=qr.join(s,Or.HDB_CONFIG_FILE);qt.writeFileSync(n,String(r))}a(EV,"deleteConfigFromFile")});var tN=m((wne,eN)=>{"use strict";var dl=A(),El=class{static{a(this,"BaseLicense")}constructor(t=0,r=dl.RAM_ALLOCATION_ENUM.DEFAULT,s=dl.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},th=class extends El{static{a(this,"ExtendedLicense")}constructor(t=0,r=dl.RAM_ALLOCATION_ENUM.DEFAULT,s=dl.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};eN.exports={BaseLicense:El,ExtendedLicense:th}});var Ca=m((Une,aN)=>{"use strict";var Ki=require("fs-extra"),rN=ol(),sN=require("crypto"),fV=require("moment"),hV=require("uuid").v4,wt=x(),sh=require("path"),mV=V(),Sn=A(),SV=tN().ExtendedLicense,Yi="invalid license key format",pV="061183",TV="mofi25",RV="aes-256-cbc",gV=16,AV=32,nN=Q();nN.initSync();var rh;aN.exports={validateLicense:iN,generateFingerPrint:NV,licenseSearch:oN,getLicense:IV};function nh(){return sh.join(nN.getHdbBasePath(),Sn.LICENSE_KEY_DIR_NAME,Sn.LICENSE_FILE_NAME)}a(nh,"getLicenseDirPath");function OV(){let e=nh();return sh.join(e,Sn.LICENSE_FILE_NAME)}a(OV,"getLicenseFilePath");function ih(){let e=nh();return sh.join(e,Sn.REG_KEY_FILE_NAME)}a(ih,"getFingerPrintFilePath");async function NV(){let e=ih();try{return await Ki.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await bV();throw wt.error(`Error writing fingerprint file to ${e}`),wt.error(t),new Error("There was an error generating the fingerprint")}}a(NV,"generateFingerPrint");async function bV(){let e=hV(),t=rN.hash(e),r=ih();try{await Ki.mkdirp(nh()),await Ki.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw wt.error(`Error writing fingerprint file to ${r}`),wt.error(s),new Error("There was an error generating the fingerprint")}return t}a(bV,"writeFingerprint");function iN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:Sn.RAM_ALLOCATION_ENUM.DEFAULT,version:Sn.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return wt.error("empty license key passed to validate."),r;let s=ih(),n=!1;try{n=Ki.statSync(s)}catch(i){wt.error(i)}if(n){let i;try{i=Ki.readFileSync(s,"utf8")}catch{wt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(TV),c=o[1];c=Buffer.concat([Buffer.from(c)],gV);let u=Buffer.concat([Buffer.from(i)],AV),l=sN.createDecipheriv(RV,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let _=null;try{_=l.update(o[0],"hex","utf8"),_.trim(),_+=l.final("utf8")}catch{let f=yV(o[0],i);if(f)_=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Yi),wt.error(Yi),new Error(Yi)}let d;if(isNaN(_))try{d=JSON.parse(_),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(Yi),wt.error(Yi),new Error(Yi)}else r.exp_date=_;r.exp_date<fV().valueOf()&&(r.valid_date=!1),rN.validate(o[1],`${pV}${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||wt.error("Invalid licence"),r}a(iN,"validateLicense");function yV(e,t){try{let r=sN.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{wt.warn("Check old license failed")}}a(yV,"checkOldLicense");function oN(){let e=new SV,t=[];try{t=Ki.readFileSync(OV(),"utf-8").split(Sn.NEW_LINE)}catch(r){r.code==="ENOENT"?wt.info("no license file found"):wt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(mV.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=iN(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){wt.error("There was an error parsing the license string."),wt.error(n),e.ram_allocation=Sn.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return rh=e,e}a(oN,"licenseSearch");async function IV(){return rh||await oN(),rh}a(IV,"getLicense")});var br=m((vne,ON)=>{"use strict";var dN="username is required",EN="nothing to update, must supply active, role or password to update",fN="password cannot be an empty string",hN="If role is specified, it cannot be empty.",mN="active must be true or false";ON.exports={addUser:BV,alterUser:HV,dropUser:FV,getSuperUser:VV,userInfo:GV,listUsers:hl,listUsersExternal:xV,setUsersToGlobal:Qi,findAndValidateUser:AN,getClusterUser:$V,USERNAME_REQUIRED:dN,ALTERUSER_NOTHING_TO_UPDATE:EN,EMPTY_PASSWORD:fN,EMPTY_ROLE:hN,ACTIVE_BOOLEAN:mN};var SN=Ar(),wV=jn(),ah=ol(),pN=MO(),TN=gr(),ch=Gs(),or=V(),RN=require("validate.js"),ue=x(),{promisify:CV}=require("util"),uh=vs(),cN=A(),uN=Be(),UV=Nr(),Lne=Q(),Mne=Ca(),DV=Kn(),{table:Pne}=(de(),ee(Ne)),{handleHDBError:ns,hdb_errors:LV}=W(),{HTTP_STATUS_CODES:is,AUTHENTICATION_ERROR_MSGS:oh,HDB_ERROR_MSGS:Wi}=LV,{UserEventMsg:lh}=Fr(),lN=require("lodash"),{_assignPackageExport:MV}=require("../../index");MV("getUser",AN);var gN={username:!0,active:!0,role:!0,password:!0},_N=new Map,fl=TN.searchByValue,PV=TN.searchByHash,vV=CV(wV.delete);async function BV(e){let t=RN.cleanAttributes(e,gN),r=pN.addUserValidation(t);if(r)throw ns(new Error,r.message,is.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 fl(s),n=n&&Array.from(n)}catch(u){throw ue.error("There was an error searching for a role in add user"),ue.error(u),u}if(!n||n.length<1)throw ns(new Error,Wi.ROLE_NAME_NOT_FOUND(t.role),is.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw ns(new Error,Wi.DUP_ROLES_FOUND(t.role),is.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=uh.encrypt(t.password)),t.password=ah.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await SN.insert(i)}catch(u){throw ue.error("There was an error searching for a user."),ue.error(u),u}ue.debug(o);try{await Qi()}catch(u){throw ue.error("Got an error setting users to global"),ue.error(u),u}if(o.skipped_hashes.length===1)throw ns(new Error,Wi.USER_ALREADY_EXISTS(t.username),is.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],ch.signalUserChange(new lh(process.pid)),`${c.username} successfully added`}a(BV,"addUser");async function HV(e){let t=RN.cleanAttributes(e,gN);if(or.isEmptyOrZeroLength(t.username))throw new Error(dN);if(or.isEmptyOrZeroLength(t.password)&&or.isEmptyOrZeroLength(t.role)&&or.isEmptyOrZeroLength(t.active))throw new Error(EN);if(!or.isEmpty(t.password)&&or.isEmptyOrZeroLength(t.password.trim()))throw new Error(fN);if(!or.isEmpty(t.active)&&!or.isBoolean(t.active))throw new Error(mN);let r=qV(t.username);if(!or.isEmpty(t.password)&&!or.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=uh.encrypt(t.password)),t.password=ah.hash(t.password)),t.role==="")throw new Error(hN);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 fl(i)||[])}catch(c){throw ue.error("Got an error searching for a role."),ue.error(c),c}if(!o||o.length===0){let c=Wi.ALTER_USER_ROLE_NOT_FOUND(t.role);throw ue.error(c),ns(new Error,c,is.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Wi.ALTER_USER_DUP_ROLES(t.role);throw ue.error(c),ns(new Error,c,is.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 SN.update(s)}catch(i){throw ue.error("Error during update."),ue.error(i),i}try{await Qi()}catch(i){throw ue.error("Got an error setting users to global"),ue.error(i),i}return ch.signalUserChange(new lh(process.pid)),n}a(HV,"alterUser");function qV(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(qV,"isClusterUser");async function FV(e){try{let t=pN.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(or.isEmpty(global.hdb_users.get(e.username)))throw ns(new Error,Wi.USER_NOT_EXIST(e.username),is.NOT_FOUND,void 0,void 0,!0);let s;try{s=await vV(r)}catch(n){throw ue.error("Got an error deleting a user."),ue.error(n),n}ue.debug(s);try{await Qi()}catch(n){throw ue.error("Got an error setting users to global."),ue.error(n),n}return ch.signalUserChange(new lh(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(FV,"dropUser");async function GV(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=e.hdb_user;let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await PV(r)}catch(n){throw ue.error("Got an error searching for a role."),ue.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw ue.error(r),r}return t}a(GV,"userInfo");async function xV(){let e;try{e=await hl()}catch(t){throw ue.error("Got an error listing users."),ue.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(xV,"listUsersExternal");async function hl(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await fl(e)}catch(o){throw ue.error("Got an error searching for roles."),ue.error(o),o}let r={};for(let o of t)r[o.id]=lN.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 fl(s)}catch(o){throw ue.error("Got an error searching for users."),ue.error(o),o}let i=new Map;for(let o of n)o=lN.cloneDeep(o),o.role=r[o.role],kV(o.role),i.set(o.username,o);return i}catch(e){throw ue.error("got an error listing users"),ue.error(e),or.errorizeMessage(e)}return null}a(hl,"listUsers");function kV(e){try{if(!e){ue.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(DV)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){ue.error("Got an error trying to set system permissions."),ue.error(t)}}a(kV,"appendSystemTablesToRole");async function Qi(){try{let e=await hl();global.hdb_users=e}catch(e){throw ue.error(e),e}}a(Qi,"setUsersToGlobal");async function AN(e,t,r=!0){global.hdb_users||await Qi();let s=global.hdb_users.get(e);if(!s)throw ns(new Error,oh.GENERIC_AUTH_FAIL,is.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw ns(new Error,oh.USER_INACTIVE,is.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(_N.get(t)===s.password)return n;if(ah.validate(s.password,t))_N.set(t,s.password);else throw ns(new Error,oh.GENERIC_AUTH_FAIL,is.UNAUTHORIZED,void 0,void 0,!0)}return n}a(AN,"findAndValidateUser");async function VV(){global.hdb_users||await Qi();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(VV,"getSuperUser");async function $V(){let e=await hl(),t=UV.getConfigFromFile(cN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!or.isEmpty(r)&&r?.role?.role===cN.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=uh.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+uN.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+uN.SERVER_SUFFIX.ADMIN,r}a($V,"getClusterUser")});var Da=m((Fne,IN)=>{"use strict";var ri=x(),ar=A(),YV=eO(),Hne=dn(),qne=Qn(),KV=br(),{validateEvent:NN}=Fr(),Ua=Hr(),WV=require("process"),{resetDatabases:QV}=(de(),ee(Ne)),zV={[ar.ITC_EVENT_TYPES.SCHEMA]:JV,[ar.ITC_EVENT_TYPES.USER]:yN};async function JV(e){let t=NN(e);if(t){ri.error(t);return}ri.trace("ITC schemaHandler received schema event:",e),await YV(e.message),await XV(e.message)}a(JV,"schemaHandler");async function XV(e){try{Ua.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Ua.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Ua.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=QV();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ri.error(t)}}a(XV,"syncSchemaMetadata");var bN=[];async function yN(e){try{try{Ua.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Ua.resetReadTxn(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ri.warn(r)}let t=NN(e);if(t){ri.error(t);return}ri.trace(`ITC userHandler ${ar.HDB_ITC_CLIENT_PREFIX}${WV.pid} received user event:`,e),await KV.setUsersToGlobal();for(let r of bN)r()}catch(t){ri.error(t)}}a(yN,"userHandler");yN.addListener=function(e){bN.push(e)};IN.exports=zV});var Fr=m((Yne,CN)=>{"use strict";var xne=x(),_h=V(),ZV=A(),{ITC_ERRORS:La}=rr(),{parentPort:kne,threadId:jV,isMainThread:e$,workerData:Vne}=require("worker_threads"),{onMessageFromWorkers:t$,broadcast:$ne,broadcastWithAcknowledgement:r$}=nt();CN.exports={sendItcEvent:s$,validateEvent:wN,SchemaEventMsg:n$,UserEventMsg:i$};var ml;t$(async(e,t)=>{ml=ml||Da(),wN(e),ml[e.type]&&await ml[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function s$(e){return!e$&&e.message&&(e.message.originator=jV),r$(e)}a(s$,"sendItcEvent");function wN(e){if(typeof e!="object")return La.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||_h.isEmpty(e.type))return La.MISSING_TYPE;if(!e.hasOwnProperty("message")||_h.isEmpty(e.message))return La.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||_h.isEmpty(e.message.originator))return La.MISSING_ORIGIN;if(ZV.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return La.INVALID_EVENT(e.type)}a(wN,"validateEvent");function n$(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(n$,"SchemaEventMsg");function i$(e){this.originator=e}a(i$,"UserEventMsg")});var Gs=m((Qne,MN)=>{"use strict";var UN=A(),Wne=V(),Sl=x(),DN=XA(),zi,{sendItcEvent:LN}=Fr();function o$(e){try{Sl.trace("signalSchemaChange called with message:",e),zi=zi||Da();let t=new DN(UN.ITC_EVENT_TYPES.SCHEMA,e);return zi.schema(t),LN(t)}catch(t){Sl.error(t)}}a(o$,"signalSchemaChange");function a$(e){try{Sl.trace("signalUserChange called with message:",e),zi=zi||Da();let t=new DN(UN.ITC_EVENT_TYPES.USER,e);return zi.user(t),LN(t)}catch(t){Sl.error(t)}}a(a$,"signalUserChange");MN.exports={signalSchemaChange:o$,signalUserChange:a$}});var pl=m((Jne,vN)=>{"use strict";var PN=V(),c$=A(),u$=x(),l$=zu(),_$=Qu(),d$=Gs(),{SchemaEventMsg:E$}=Fr(),f$="already exists in";vN.exports=h$;async function h$(e,t,r){if(PN.isEmptyOrZeroLength(r))return r;let s=[];PN.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 m$(e,t.schema,t.name,i)})),n}a(h$,"lmdbCheckForNewAttributes");async function m$(e,t,r,s){let n=new _$(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await S$(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(f$))u$.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(m$,"createNewAttribute");async function S$(e){let t;return t=await l$(e),d$.signalSchemaChange(new E$(process.pid,c$.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(S$,"createAttribute")});var Ji=m((Zne,BN)=>{"use strict";var dh=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}};BN.exports=dh});var qN=m((eie,HN)=>{"use strict";var p$=Ji(),T$=A().OPERATIONS_ENUM,Eh=class extends p${static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(T$.INSERT,r,s,n,i),this.records=t}};HN.exports=Eh});var GN=m((rie,FN)=>{"use strict";var R$=Ji(),g$=A().OPERATIONS_ENUM,fh=class extends R${static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(g$.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};FN.exports=fh});var kN=m((nie,xN)=>{"use strict";var A$=Ji(),O$=A().OPERATIONS_ENUM,hh=class extends A${static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(O$.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};xN.exports=hh});var $N=m((oie,VN)=>{"use strict";var N$=Ji(),b$=A().OPERATIONS_ENUM,mh=class extends N${static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(b$.DELETE,s,n,t,i),this.original_records=r}};VN.exports=mh});var Ma=m((uie,QN)=>{"use strict";var cie=require("path"),YN=ye(),y$=qN(),I$=GN(),w$=kN(),C$=$N(),Xi=xe(),KN=V(),{CONFIG_PARAMS:U$}=A(),WN=Q();WN.initSync();var Tl=A().OPERATIONS_ENUM,{getTransactionAuditStorePath:D$}=we();QN.exports=L$;async function L$(e,t){if(WN.get(U$.LOGGING_AUDITLOG)===!1)return;let r=D$(e.schema,e.table),s=await YN.openEnvironment(r,e.table,!0),n=M$(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){YN.initializeDBIs(s,Xi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Xi.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[Xi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[Xi.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),KN.isEmpty(n.user_name)||s.dbis[Xi.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[Xi.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(L$,"writeTransaction");function M$(e,t){let r=KN.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===Tl.INSERT)return new y$(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Tl.UPDATE)return new I$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Tl.UPSERT)return new w$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===Tl.DELETE)return new C$(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(M$,"createTransactionObject")});var Sh=m((die,zN)=>{"use strict";var P$=ga(),_ie=Aa(),Pa=A(),v$=ya(),B$=xi().insertRecords,H$=ye(),q$=x(),F$=pl(),{getSchemaPath:G$}=we(),x$=Ma();zN.exports=k$;async function k$(e){try{let{schema_table:t,attributes:r}=P$(e);v$(e,r,t.hash_attribute),e.schema!==Pa.SYSTEM_SCHEMA_NAME&&(r.includes(Pa.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Pa.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Pa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Pa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await F$(e.hdb_auth_header,t,r),n=G$(e.schema,e.table),i=await H$.openEnvironment(n,e.table),o=await B$(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await x$(e,o)}catch(c){q$.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(k$,"lmdbCreateRecords")});var ZN=m((fie,XN)=>{"use strict";var JN=A(),V$=Sh(),$$=Aa(),Y$=require("fs-extra"),{getSchemaPath:K$}=we();XN.exports=W$;async function W$(e){let t=[{name:e.schema,createddate:Date.now()}],r=new $$(JN.SYSTEM_SCHEMA_NAME,JN.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await V$(r),await Y$.mkdirp(K$(e.schema))}a(W$,"lmdbCreateSchema")});var eb=m((mie,jN)=>{"use strict";var ph=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}};jN.exports=ph});var nb=m((gie,sb)=>{"use strict";var tb=ye(),Th=vt(),Rh=rr().LMDB_ERRORS_ENUM,Q$=xe(),rb=x(),pie=V(),z$=require("lmdb"),J$=eb(),X$=A(),{OVERFLOW_MARKER:Tie,MAX_SEARCH_KEY_LENGTH:Rie}=Q$,Z$=X$.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function j$(e,t,r,s){if(Th.validateEnv(e),t===void 0)throw new Error(Rh.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Rh.IDS_REQUIRED):new Error(Rh.IDS_MUST_BE_ITERABLE);try{let n=tb.listDBIs(e);tb.initializeDBIs(e,t,n);let i=new J$,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||s&&h[Z$]>s){i.skipped.push(o);continue}let T=e.dbis[t].ifVersion(o,z$.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let p=0;p<n.length;p++){let R=n[p];if(!h.hasOwnProperty(R)||R===t)continue;let O=e.dbis[R],k=h[R];if(k!=null)try{let $=Th.getIndexedValues(k);if($)for(let U=0,b=$.length;U<b;U++)O.remove($[U],o)}catch{rb.warn(`cannot delete from attribute: ${R}, ${k}:${o}`)}}});c.push(T),u.push(o),i.original_records.push(h)}catch(h){rb.warn(h),i.skipped.push(o)}let l=[],_=await Promise.all(c);for(let E=0,f=_.length;E<f;E++)_[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),l.push(E));let d=0;for(let E=0;E<l.length;E++){let f=l[E];i.original_records.splice(f-d,1),d++}return i.txn_time=Th.getNextMonotonicTime(),i}catch(n){throw n}}a(j$,"deleteRecords");sb.exports={deleteRecords:j$}});var va=m((Oie,ob)=>{"use strict";var Zi=V(),eY=nb(),tY=ye(),{getSchemaPath:rY}=we(),sY=Ma(),nY=x();ob.exports=iY;async function iY(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Zi.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Zi.isEmptyOrZeroLength(e.hash_values)&&!Zi.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Zi.isEmpty(u)||e.hash_values.push(u)}}if(Zi.isEmptyOrZeroLength(e.hash_values))return ib([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Zi.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=rY(e.schema,e.table),i=await tY.openEnvironment(n,e.table),o=await eY.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await sY(e,o)}catch(c){nY.error(`unable to write transaction due to ${c.message}`)}return ib(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(iY,"lmdbDeleteRecords");function ib(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(ib,"createDeleteResponse")});var Ah=m((yie,ab)=>{"use strict";var oY=A(),bie=vt();function gh(e,t){let r=Object.create(null);if(t.length===1&&oY.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(gh,"parseRow");function aY(e,t,r,s){let n=gh(r,e);s.push(n)}a(aY,"searchAll");function cY(e,t,r,s){let n=gh(r,e);s[t]=n}a(cY,"searchAllToMap");function uY(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(uY,"iterateDBI");function si(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(si,"pushResults");function lY(e,t,r,s,n,i){t.toString().endsWith(e)&&si(t,r,s,n,i)}a(lY,"endsWith");function _Y(e,t,r,s,n,i){t.toString().includes(e)&&si(t,r,s,n,i)}a(_Y,"contains");function dY(e,t,r,s,n,i){t>e&&si(t,r,s,n,i)}a(dY,"greaterThanCompare");function EY(e,t,r,s,n,i){t>=e&&si(t,r,s,n,i)}a(EY,"greaterThanEqualCompare");function fY(e,t,r,s,n,i){t<e&&si(t,r,s,n,i)}a(fY,"lessThanCompare");function hY(e,t,r,s,n,i){t<=e&&si(t,r,s,n,i)}a(hY,"lessThanEqualCompare");ab.exports={parseRow:gh,searchAll:aY,searchAllToMap:cY,iterateDBI:uY,endsWith:lY,contains:_Y,greaterThanCompare:dY,greaterThanEqualCompare:EY,lessThanCompare:fY,lessThanEqualCompare:hY,pushResults:si}});var ji=m((Die,fb)=>{"use strict";var pn=ye(),wie=x(),cr=vt(),Rl=xe(),ke=rr().LMDB_ERRORS_ENUM,Cie=V(),mY=A(),gl=Ah(),{parseRow:SY}=gl,Uie=require("lmdb"),{OVERFLOW_MARKER:cb,MAX_SEARCH_KEY_LENGTH:pY}=Rl;function ub(e,t,r,s=!1,n=void 0,i=void 0){return ni(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(ub,"iterateFullIndex");function Ba(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,l=!1){return ni(e,t,r,(_,d,E,f)=>{let O={transaction:_,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!l,exclusiveStart:i===!0?l:u};return f===r?(O.values=!1,d.getRange(O).map(k=>({value:k}))):d.getRange(O)})}a(Ba,"iterateRangeBetween");function ni(e,t,r,s){let n=e.database||e,i=pn.openDBI(n,r);i[Rl.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&pn.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(ni,"setupTransaction");function lb(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(cb)){if(!n)if(r)n=pn.openDBI(e,r);else{let u=pn.listDBIs(e);for(let l=0,_=u.length;l<_&&(n=pn.openDBI(e,u[l]),!n[Rl.DBI_DEFINITION_NAME].is_hash_attribute);l++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(lb,"getOverflowCheck");function TY(e,t,r,s=!1,n=void 0,i=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);return ni(e,t,t,(o,c,u)=>(Al(r),r=Ha(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(l=>SY(l.value,r))))}a(TY,"searchAll");function RY(e,t,r,s=!1,n=void 0,i=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);Al(r),r=Ha(e.database||e,r);let o=new Map;for(let{key:c,value:u}of ub(e,t,t,s,n,i))o.set(c,gl.parseRow(u,r));return o}a(RY,"searchAllToMap");function gY(e,t,r=!1,s=void 0,n=void 0){if(cr.validateEnv(e),t===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=ub(e,void 0,t,r,s,n),c=o.transaction,u=lb(c.database,c,void 0,t);for(let{key:l,value:_}of o){let d=u(l,_);i[d]===void 0&&(i[d]=[]),i[d].push(_)}return i}a(gY,"iterateDBI");function AY(e,t){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);return pn.statDBI(e,t).entryCount}a(AY,"countAll");function OY(e,t,r,s,n=!1,i=void 0,o=void 0){return Tn(e,r,s),ni(e,t,r,(c,u,l,_)=>(s=cr.convertKeyValueToWrite(s),_===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(OY,"equals");function NY(e,t,r){return Tn(e,t,r),pn.openDBI(e,t).getValuesCount(r)}a(NY,"count");function bY(e,t,r,s,n=!1,i=void 0,o=void 0){return Tn(e,r,s),ni(e,null,r,(c,u)=>{s=cr.convertKeyValueToWrite(s);let l=!0;typeof s=="number"&&(l=!1);let _;if(n===!0){let d;for(let E of u.getKeys({transaction:c,start:s}))if(!E.startsWith(s)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),_=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(s))return E;if(l===!0)return _.DONE}}),_.filter(E=>E)}else return _=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(l===!0)return _.DONE}),l?_:_.filter(d=>d)})}a(bY,"startsWith");function yY(e,t,r,s,n=!1,i=void 0,o=void 0){return _b(e,t,r,s,n,i,o,!0)}a(yY,"endsWith");function _b(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return Tn(e,r,s),ni(e,null,r,(u,l,_,d)=>{let E=lb(_,u,d,r);return o=Number.isInteger(o)?o:0,l.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(f=>{let h=f.toString();return h.endsWith(cb)?l.getValues(f,{transaction:u}).map(T=>{let p=E(f,T);if(c?p.endsWith(s):p.includes(s))return{key:p,value:T}}).filter(T=>T):(c?h.endsWith(s):h.includes(s))?l[Rl.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:l.getValues(f,{transaction:u}).map(T=>({key:f,value:T})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(_b,"contains");function IY(e,t,r,s,n=!1,i=void 0,o=void 0){Tn(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Ba(e,t,r,s,u,n,i,o,!0,!1)}a(IY,"greaterThan");function wY(e,t,r,s,n=!1,i=void 0,o=void 0){Tn(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Ba(e,t,r,s,u,n,i,o,!1,!1)}a(wY,"greaterThanEqual");function CY(e,t,r,s,n=!1,i=void 0,o=void 0){Tn(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Ba(e,t,r,u,s,n,i,o,!1,!0)}a(CY,"lessThan");function UY(e,t,r,s,n=!1,i=void 0,o=void 0){Tn(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Ba(e,t,r,u,s,n,i,o,!1,!1)}a(UY,"lessThanEqual");function DY(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(cr.validateEnv(e),r===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ke.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ke.END_VALUE_REQUIRED);if(s=cr.convertKeyValueToWrite(s),n=cr.convertKeyValueToWrite(n),s>n)throw new Error(ke.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Ba(e,t,r,s,n,i,o,c)}a(DY,"between");function LY(e,t,r,s){cr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(Al(r),r=Ha(n,r),s===void 0)throw new Error(ke.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=gl.parseRow(c,r)),o}a(LY,"searchByHash");function MY(e,t,r){cr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ke.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(MY,"checkHashExists");function PY(e,t,r,s,n=[]){return Eb(e,t,r,s,n),db(e,t,r,s,n).map(i=>i[1])}a(PY,"batchSearchByHash");function vY(e,t,r,s,n=[]){Eb(e,t,r,s,n);let i=new Map;for(let[o,c]of db(e,t,r,s,n))i.set(o,c);return i}a(vY,"batchSearchByHashToMap");function db(e,t,r,s,n=[]){return ni(e,t,t,(i,o,c)=>{r=Ha(c,r);let u=r.length<3;return s.map(l=>{let _=c.dbis[t].get(l,{transaction:i,lazy:u});if(_)return[l,gl.parseRow(_,r)];n.push(l)}).filter(l=>l)})}a(db,"batchHashSearch");function Eb(e,t,r,s,n){if(cr.validateEnv(e),t===void 0)throw new Error(ke.HASH_ATTRIBUTE_REQUIRED);if(Al(r),s==null)throw new Error(ke.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ke.IDS_MUST_BE_ITERABLE)}a(Eb,"initializeBatchSearchByHash");function Al(e){if(!Array.isArray(e))throw e===void 0?new Error(ke.FETCH_ATTRIBUTES_REQUIRED):new Error(ke.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(Al,"validateFetchAttributes");function Tn(e,t,r){if(cr.validateEnv(e),t===void 0)throw new Error(ke.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ke.SEARCH_VALUE_REQUIRED);if(r?.length>pY)throw new Error(ke.SEARCH_VALUE_TOO_LARGE)}a(Tn,"validateComparisonFunctions");function Ha(e,t){return t.length===1&&mY.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=pn.listDBIs(e)),t}a(Ha,"setGetWholeRowAttributes");fb.exports={searchAll:TY,searchAllToMap:RY,count:NY,countAll:AY,equals:OY,startsWith:bY,endsWith:yY,contains:_b,searchByHash:LY,setGetWholeRowAttributes:Ha,batchSearchByHash:PY,batchSearchByHashToMap:vY,checkHashExists:MY,iterateDBI:gY,greaterThan:IY,greaterThanEqual:wY,lessThan:CY,lessThanEqual:UY,between:DY}});var eo=m((Mie,Tb)=>{var hb=require("lodash"),mb=ve(),Ce=require("joi"),BY=V(),{hdb_schema_table:Ol,checkValidTable:Sb,hdb_table:pb,hdb_database:Nl}=rs(),{handleHDBError:HY,hdb_errors:qY}=W(),{getDatabases:FY}=(de(),ee(Ne)),{HTTP_STATUS_CODES:GY}=qY,xY=Ce.object({database:Nl,schema:Nl,table:pb,search_attribute:Ol,search_value:Ce.any().required(),get_attributes:Ce.array().min(1).items(Ol).optional(),desc:Ce.bool(),limit:Ce.number().integer().min(1),offset:Ce.number().integer().min(0)}),kY=Ce.object({database:Nl,schema:Nl,table:pb,operator:Ce.string().valid("and","or").default("and").lowercase(),offset:Ce.number().integer().min(0),limit:Ce.number().integer().min(1),get_attributes:Ce.array().min(1).items(Ol).optional(),conditions:Ce.array().min(1).items(Ce.object({search_attribute:Ol,search_type:Ce.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:Ce.when("search_type",{switch:[{is:"equals",then:Ce.any()},{is:"between",then:Ce.array().items(Ce.alternatives([Ce.string(),Ce.number()])).length(2)}],otherwise:Ce.alternatives(Ce.string(),Ce.number())}).required()})).required()});Tb.exports=function(e,t){let r=null;switch(t){case"value":r=mb.validateBySchema(e,xY);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(Sb("database",e.schema)),i(Sb("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=mb.validateBySchema(e,kY);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=BY.checkGlobalSchemaTable(e.schema,e.table);if(n)return HY(new Error,n,GY.NOT_FOUND);let o=FY()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let l=0,_=e.conditions.length;l<_;l++){let d=e.conditions[l];c.push(d.search_attribute)}let u=hb.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!hb.some(o,_=>_===l||_.attribute===l||_.attribute===l.attribute));if(u&&u.length>0){let l=u.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Oh=m((vie,Rb)=>{"use strict";var VY=ye(),$Y=eo(),{getSchemaPath:YY}=we();Rb.exports=KY;function KY(e){let t=$Y(e,"hashes");if(t)throw t;let r=YY(e.schema,e.table);return VY.openEnvironment(r,e.table)}a(KY,"initialize")});var Nh=m((Hie,gb)=>{"use strict";var WY=ji(),QY=Oh();gb.exports=zY;async function zY(e){let t=await QY(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return WY.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(zY,"lmdbGetDataByHash")});var to=m((Fie,Ab)=>{"use strict";var bh=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};Ab.exports=bh});var Nb=m((kie,Ob)=>{"use strict";var xie=to(),JY=ji(),XY=Oh();Ob.exports=ZY;async function ZY(e){let t=await XY(e),r=global.hdb_schema[e.schema][e.table];return JY.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(ZY,"lmdbSearchByHash")});var os=m(($ie,bb)=>{"use strict";var yh=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,l=void 0,_=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=l,this.offset=_}};bb.exports=yh});var bl=m((Kie,Db)=>{"use strict";var Ct=ji(),jY=ye(),eK=V(),ie=xe(),ii=A(),tK=Kn(),yb=rr().LMDB_ERRORS_ENUM,{getSchemaPath:rK}=we(),xs=ii.SEARCH_WILDCARDS;async function sK(e,t,r){let s;e.schema===ii.SYSTEM_SCHEMA_NAME?s=tK[e.table]:s=global.hdb_schema[e.schema][e.table];let n=Ub(e,s.hash_attribute,r,t);return wb(e,n,s.hash_attribute,r)}a(sK,"prepSearch");async function wb(e,t,r,s){let n=rK(e.schema,e.table),i=await jY.openEnvironment(n,e.table),o=Cb(i,e,t,r),c=o.transaction||i;if([ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,ie.SEARCH_TYPES.SEARCH_ALL,ie.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(nK(e,r)===!1){let _=e.search_attribute;if(_===r)return s?Ib(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[_]:E.key}),"toObject");return s?Ib(o,d):o.map(d)}let l=e.search_attribute===r?o.map(_=>_.key):o.map(_=>_.value);return s===!0?Ct.batchSearchByHashToMap(c,r,e.get_attributes,l):Ct.batchSearchByHash(c,r,e.get_attributes,l)}a(wb,"executeSearch");function Cb(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 ie.SEARCH_TYPES.EQUALS:n=Ct.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.CONTAINS:n=Ct.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.ENDS_WITH:case ie.SEARCH_TYPES._ENDS_WITH:n=Ct.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.STARTS_WITH:case ie.SEARCH_TYPES._STARTS_WITH:n=Ct.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Ct.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Ct.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case ie.SEARCH_TYPES.SEARCH_ALL:return Ct.searchAll(e,s,t.get_attributes,o,c,u);case ie.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Ct.searchAllToMap(e,s,t.get_attributes,o,c,u);case ie.SEARCH_TYPES.BETWEEN:n=Ct.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case ie.SEARCH_TYPES.GREATER_THAN:case ie.SEARCH_TYPES._GREATER_THAN:n=Ct.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.GREATER_THAN_EQUAL:case ie.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Ct.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.LESS_THAN:case ie.SEARCH_TYPES._LESS_THAN:n=Ct.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case ie.SEARCH_TYPES.LESS_THAN_EQUAL:case ie.SEARCH_TYPES._LESS_THAN_EQUAL:n=Ct.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(Cb,"searchByType");function Ib(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(Ib,"createMapFromIterable");function nK(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(nK,"checkToFetchMore");function Ub(e,t,r,s){if(eK.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),xs.indexOf(n)>-1)return r===!0?ie.SEARCH_TYPES.SEARCH_ALL_TO_MAP:ie.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(xs[0])<0&&n.indexOf(xs[1])<0)return c===!0?r===!0?ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:ie.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:ie.SEARCH_TYPES.EQUALS;if(xs.indexOf(i)>=0&&xs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),ie.SEARCH_TYPES.CONTAINS;if(xs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),ie.SEARCH_TYPES.ENDS_WITH;if(xs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),ie.SEARCH_TYPES.STARTS_WITH;if(n.includes(xs[0])||n.includes(xs[1]))return ie.SEARCH_TYPES.EQUALS;throw new Error(yb.UNKNOWN_SEARCH_TYPE)}else switch(s){case ii.VALUE_SEARCH_COMPARATORS.BETWEEN:return ie.SEARCH_TYPES.BETWEEN;case ii.VALUE_SEARCH_COMPARATORS.GREATER:return ie.SEARCH_TYPES.GREATER_THAN;case ii.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return ie.SEARCH_TYPES.GREATER_THAN_EQUAL;case ii.VALUE_SEARCH_COMPARATORS.LESS:return ie.SEARCH_TYPES.LESS_THAN;case ii.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return ie.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(yb.UNKNOWN_SEARCH_TYPE)}}a(Ub,"createSearchTypeFromSearchObject");Db.exports={executeSearch:wb,createSearchTypeFromSearchObject:Ub,prepSearch:sK,searchByType:Cb}});var Mb=m((zie,Lb)=>{"use strict";var Qie=os(),iK=eo(),oK=V(),aK=A(),cK=bl();Lb.exports=uK;function uK(e,t){if(!oK.isEmpty(t)&&aK.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=iK(e,"value");if(s)throw s;let n=!0;return cK.prepSearch(e,t,n)}a(uK,"lmdbGetDataByValue")});var qa=m((Zie,Pb)=>{"use strict";var Xie=os(),lK=eo(),_K=V(),dK=A(),EK=bl();Pb.exports=fK;async function fK(e,t){if(!_K.isEmpty(t)&&dK.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=lK(e,"value");if(s)throw s;return EK.prepSearch(e,t,!1)}a(fK,"lmdbSearchByValue")});var Bb=m((toe,vb)=>{"use strict";var eoe=xe(),Ih=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}},wh=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Ch=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};vb.exports={SearchByConditionsObject:Ih,SearchCondition:wh,SortAttribute:Ch}});var xb=m((ioe,Gb)=>{"use strict";var soe=Bb().SearchByConditionsObject,hK=os(),mK=eo(),Uh=ji(),yl=xe(),{Resource:noe}=(Zr(),ee($E)),Fb=bl(),SK=Ah(),pK=require("lodash"),{getSchemaPath:TK}=we(),Hb=ye(),{handleHDBError:RK,hdb_errors:gK}=W(),{HTTP_STATUS_CODES:AK}=gK,OK=1e8;Gb.exports=NK;async function NK(e){let t=mK(e,"conditions");if(t)throw RK(t,t.message,AK.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=TK(e.schema,e.table),s=await Hb.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let l of e.conditions)Hb.openDBI(s,l.search_attribute);let i=pK.sortBy(e.conditions,l=>{if(l.estimated_count===void 0){let _=l.search_type;_===yl.SEARCH_TYPES.EQUALS?l.estimated_count=Uh.count(s,l.search_attribute,l.search_value):_===yl.SEARCH_TYPES.CONTAINS||_===yl.SEARCH_TYPES.ENDS_WITH?l.estimated_count=1/0:l.estimated_count=OK}return l.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await qb(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let l=s.dbis[n.hash_attribute],_=i.slice(1).map(Fb.filterByType),d=_.length,E=Uh.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(f=>l.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!_[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>SK.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await qb(o,e,E,n.hash_attribute);c=c.concat(f)}let l=new Set,_=e.offset||0;c=c.filter(d=>l.has(d)?!1:(l.add(d),!0)).slice(_,e.limit&&e.limit+_),u=Uh.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(NK,"lmdbSearchByConditions");async function qb(e,t,r,s){let n=new hK(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===yl.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,Fb.searchByType(e,n,i,s).map(o=>o.value)}a(qb,"executeConditionSearch")});var Fa=m((aoe,kb)=>{"use strict";var bK=A().OPERATIONS_ENUM,Dh=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=bK.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};kb.exports=Dh});var Lh=m((uoe,Jb)=>{"use strict";var Kb=os(),Wb=Fa(),Qb=qa(),zb=va(),Ft=A(),Vb=V(),$b=ye(),{getTransactionAuditStorePath:yK,getSchemaPath:IK}=we(),Yb=x();Jb.exports=wK;async function wK(e){try{if(Vb.isEmpty(global.hdb_schema[e.schema])||Vb.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await CK(e),await UK(e);let t=IK(e.schema,e.table);try{await $b.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Yb.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=yK(e.schema,e.table);await $b.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Yb.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(wK,"lmdbDropTable");async function CK(e){let t=new Kb(Ft.SYSTEM_SCHEMA_NAME,Ft.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Qb(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 Wb(Ft.SYSTEM_SCHEMA_NAME,Ft.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await zb(n)}a(CK,"deleteAttributesFromSystem");async function UK(e){let t=new Kb(Ft.SYSTEM_SCHEMA_NAME,Ft.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,Ft.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await Qb(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 Wb(Ft.SYSTEM_SCHEMA_NAME,Ft.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await zb(n)}catch(i){throw i}}a(UK,"dropTableFromSystem")});var Zb=m((_oe,Xb)=>{"use strict";var DK=require("fs-extra"),LK=os(),MK=to(),PK=Fa(),vK=Lh(),BK=va(),HK=Nh(),qK=qa(),ks=A(),{getSchemaPath:FK}=we(),{handleHDBError:GK,hdb_errors:xK}=W(),{HDB_ERROR_MSGS:kK,HTTP_STATUS_CODES:VK}=xK;Xb.exports=$K;async function $K(e){let t;try{t=await YK(e.schema);let r=new LK(ks.SYSTEM_SCHEMA_NAME,ks.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ks.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[ks.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await qK(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await vK(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new PK(ks.SYSTEM_SCHEMA_NAME,ks.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await BK(n);let i=FK(t);await DK.remove(i)}catch(r){throw r}}a($K,"lmdbDropSchema");async function YK(e){let t=new MK(ks.SYSTEM_SCHEMA_NAME,ks.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[ks.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await HK(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw GK(new Error,kK.SCHEMA_NOT_FOUND(e),VK.NOT_FOUND,void 0,void 0,!0);return s}a(YK,"validateDropSchema")});var Ph=m((Eoe,jb)=>{"use strict";var Mh=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};jb.exports=Mh});var ty=m((moe,ey)=>{"use strict";var KK=require("fs-extra"),Il=ye(),{getTransactionAuditStorePath:WK}=we(),vh=xe(),hoe=Ph();ey.exports=QK;async function QK(e){let t;try{let r=WK(e.schema,e.table);await KK.mkdirp(r),t=await Il.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{Il.createDBI(t,vh.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Il.createDBI(t,vh.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Il.createDBI(t,vh.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(QK,"createTransactionsAuditEnvironment")});var iy=m((poe,ny)=>{"use strict";var Bh=A(),ry=ye(),zK=xi(),{getSystemSchemaPath:JK,getSchemaPath:XK}=we(),ZK=Kn(),jK=zu(),Hh=Qu(),e1=x(),t1=ty(),Fh=ZK.hdb_table,sy=[];for(let e=0;e<Fh.attributes.length;e++)sy.push(Fh.attributes[e].attribute);ny.exports=r1;async function r1(e,t){let r=XK(t.schema,t.table),s=new Hh(t.schema,t.table,Bh.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Hh(t.schema,t.table,Bh.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Hh(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await ry.createEnvironment(r,t.table),e!==void 0){let o=await ry.openEnvironment(JK(),Bh.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await zK.insertRecords(o,Fh.hash_attribute,sy,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await qh(s),await qh(n),await qh(i)}await t1(t)}catch(o){throw o}}a(r1,"lmdbCreateTable");async function qh(e){try{await jK(e)}catch(t){e1.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(qh,"createAttribute")});var ay=m((Roe,oy)=>{"use strict";var s1=ga(),n1=ya(),i1=pl(),Ga=A(),o1=xi().updateRecords,a1=ye(),{getSchemaPath:c1}=we(),u1=Ma(),l1=x();oy.exports=_1;async function _1(e){try{let{schema_table:t,attributes:r}=s1(e);n1(e,r,t.hash_attribute),e.schema!==Ga.SYSTEM_SCHEMA_NAME&&(r.includes(Ga.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Ga.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Ga.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Ga.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await i1(e.hdb_auth_header,t,r),n=c1(e.schema,e.table),i=await a1.openEnvironment(n,e.table),o=await o1(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await u1(e,o)}catch(c){l1.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(_1,"lmdbUpdateRecords")});var uy=m((Aoe,cy)=>{"use strict";var d1=A().OPERATIONS_ENUM,Gh=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=d1.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};cy.exports=Gh});var _y=m((boe,ly)=>{"use strict";var Noe=uy(),E1=ga(),f1=ya(),h1=pl(),xa=A(),m1=xi().upsertRecords,S1=ye(),{getSchemaPath:p1}=we(),T1=Ma(),R1=x(),{handleHDBError:g1,hdb_errors:A1}=W();ly.exports=O1;async function O1(e){let t;try{t=E1(e)}catch(u){throw g1(u,u.message,A1.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;f1(e,s,r.hash_attribute),e.schema!==xa.SYSTEM_SCHEMA_NAME&&(s.includes(xa.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(xa.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(xa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(xa.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await h1(e.hdb_auth_header,r,s),i=p1(e.schema,e.table),o=await S1.openEnvironment(i,e.table),c=await m1(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await T1(e,c)}catch(u){R1.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(O1,"lmdbUpsertRecords")});var Ey=m((Ioe,dy)=>{"use strict";var xh=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};dy.exports=xh});var hy=m((Coe,fy)=>{"use strict";var kh=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}};fy.exports=kh});var py=m((Loe,Sy)=>{"use strict";var Vh=ye(),{getTransactionAuditStorePath:N1}=we(),Doe=Ey(),ka=xe(),b1=V(),my=hy(),y1=require("util").promisify,I1=y1(setTimeout),w1=1e4,C1=100;Sy.exports=U1;async function U1(e){let t=N1(e.schema,e.table),r=await Vh.openEnvironment(t,e.table,!0),s=Vh.listDBIs(r);Vh.initializeDBIs(r,ka.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new my;do n=await D1(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 I1(C1);while(n.transactions_deleted>0);return i}a(U1,"deleteAuditLogsBefore");async function D1(e,t){let r=new my;try{let s=e.dbis[ka.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[ka.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];b1.isEmpty(c)||(n=e.dbis[ka.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[ka.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>w1)break}return await n,r}catch(s){throw s}}a(D1,"deleteTransactions")});var Ry=m((Poe,Ty)=>{"use strict";var $h=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};Ty.exports=$h});var Ay=m((Hoe,gy)=>{"use strict";var L1=os(),M1=Fa(),Boe=Ry(),as=A(),P1=V(),Yh=ye(),v1=Kn(),B1=qa(),H1=va(),{getSchemaPath:q1}=we();gy.exports=F1;async function F1(e,t=!0){let r;e.schema===as.SYSTEM_SCHEMA_NAME?r=v1[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await x1(e),n=q1(e.schema,e.table),i=await Yh.openEnvironment(n,e.table);return t===!0&&await G1(e,i,r.hash_attribute),Yh.dropDBI(i,e.attribute),s}a(F1,"lmdbDropAttribute");async function G1(e,t,r){let s=Yh.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let l={};for(let _ in c)_!==i&&(l[_]=c[_]);n=t.dbis[r].put(o,l,u)}await n}a(G1,"removeAttributeFromAllObjects");async function x1(e){let t=new L1(as.SYSTEM_SCHEMA_NAME,as.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await B1(t)).filter(o=>o[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(P1.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[as.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new M1(as.SYSTEM_SCHEMA_NAME,as.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return H1(i)}a(x1,"dropAttributeFromSystem")});var wy=m((Goe,Iy)=>{"use strict";var Kh=ye(),ro=xe(),Foe=vt(),Wh=A(),Oy=V(),{getTransactionAuditStorePath:k1}=we(),V1=ji(),wl=Ji(),$1=x();Iy.exports=Y1;async function Y1(e){let t=k1(e.schema,e.table),r=await Kh.openEnvironment(t,e.table,!0),s=Kh.listDBIs(r);Kh.initializeDBIs(r,ro.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Wh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return Ny(r,e.search_values);case Wh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,W1(r,e.search_values,n);case Wh.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return K1(r,e.search_values);default:return Ny(r)}}a(Y1,"readAuditLog");function Ny(e,t=[0,Date.now()]){Oy.isEmpty(t[0])&&(t[0]=0),Oy.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[ro.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 wl,n))}a(Ny,"searchTransactionsByTimestamp");function K1(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[ro.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,yy(e,i))}return Object.fromEntries(r)}a(K1,"searchTransactionsByUsername");function W1(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let l=t[c],_=V1.equals(e,ro.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ro.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,l);for(let{value:d}of _){let E=Number(d);s.has(E)?s.get(E).push(l.toString()):s.set(E,[l.toString()])}}let n=Array.from(s.keys()),i=yy(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],l=u.timestamp,_=s.get(l);by(u,"records",r,_,o),by(u,"original_records",r,_,o)}return Object.fromEntries(o)}a(W1,"searchTransactionsByHashValues");function by(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 l=n.get(u),_=l[l.length-1];if(_.timestamp===i)_[t]=[c];else{let d=new wl(e.operation,e.user_name,i,void 0);d[t]=[c],l.push(d)}}else{let l=new wl(e.operation,e.user_name,i,void 0);l[t]=[c],n.set(u,[l])}}}a(by,"loopRecords");function yy(e,t){let r=[];try{let s=e.dbis[ro.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 wl,i);r.push(o)}}catch(i){$1.warn(i)}return r}catch(s){throw s}}a(yy,"batchSearchTransactions")});var Uy=m(($oe,Cy)=>{"use strict";var{getSchemaPath:koe}=we(),Voe=ye(),{database:Q1}=(de(),ee(Ne));Cy.exports={writeTransaction:z1};async function z1(e,t,r){return Q1({database:e,table:t}).transaction(r)}a(z1,"writeTransaction")});var Py=m((Koe,My)=>{"use strict";var{getSchemaPath:Dy}=we(),Ly=ye();My.exports={flush:J1,resetReadTxn:X1};async function J1(e,t){return(await Ly.openEnvironment(Dy(e,t),t.toString())).flushed}a(J1,"flush");async function X1(e,t){try{(await Ly.openEnvironment(Dy(e,t),t.toString())).resetReadTxn()}catch{}}a(X1,"resetReadTxn")});var qy=m((Qoe,Hy)=>{"use strict";var{Readable:Z1}=require("stream"),{getDatabases:j1}=(de(),ee(Ne)),{readSync:eW,openSync:tW,createReadStream:vy}=require("fs"),{open:rW}=require("lmdb"),By=qu(),sW=Gu(),{INTERNAL_DBIS_NAME:nW}=xe();Hy.exports=oW;var Qh=32768,iW=100;async function oW(e){let t=e.database||e.schema||"data",r=j1()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let l=r[n[0]];if(!l)throw new Error(`Can not find table ${n[0]}`);let _=l.dbisDB,d=rW({noSync:!0,maxDbs:sW.MAX_DBS}),E,f=d.openDB(nW,new By(!1)),h=_.useReadTransaction(),T=0;for(let{key:R,value:O}of _.getRange({transaction:h,start:!1}))if(n.some(k=>R.startsWith?.(k+"/"))){f.put(R,O);let[,k]=R.split("/"),$=!k,U=new By(!$,$);U.encoding="binary";let b=d.openDB(R,U),P=_.openDB(R,U);for(let{key:z,version:q,value:Oe}of P.getRange({transaction:h,versions:$}))E=b.put(z,Oe,q),T++%iW===0&&await new Promise(je=>setTimeout(je,20))}await E;let p=vy(d.path);return p.headers=u(),p.on("close",()=>{h.done(),d.close()}),p}let o=r[Object.keys(r)[0]].primaryStore,c=tW(o.path);return o.transaction(()=>{let l=Buffer.alloc(Qh);eW(c,l,0,Qh);let _=o.useReadTransaction(),d=vy(null,{fd:c,start:Qh}),E=new Z1.from(async function*(){yield l;for await(let f of d)yield f;_.done()}());return E.headers=u(),E});function u(){let l=new Map;return l.set("content-type","application/octet-stream"),l.set("content-disposition",`attachment; filename="${t}"`),l.set("date",s),l}}a(oW,"getBackup")});var xy=m((Joe,Gy)=>{"use strict";var aW=x(),{handleHDBError:cW}=W(),uW=nA(),lW=zu(),_W=Sh(),dW=ZN(),EW=va(),fW=Nh(),hW=Nb(),mW=Mb(),SW=qa(),pW=xb(),TW=Zb(),RW=iy(),gW=ay(),AW=_y(),OW=py(),NW=Lh(),bW=Ay(),yW=wy(),IW=Uy(),Fy=Py(),wW=qy(),zh=class extends uW{static{a(this,"LMDBBridge")}async searchByConditions(t){return pW(t)}async getDataByHash(t){return await fW(t)}async searchByHash(t){return await hW(t)}async getDataByValue(t,r){return await mW(t,r)}async searchByValue(t){return await SW(t)}async createSchema(t){return await dW(t)}async dropSchema(t){return await TW(t)}async createTable(t,r){return await RW(t,r)}async dropTable(t){return await NW(t)}async createAttribute(t){return await lW(t)}async createRecords(t){return await _W(t)}async updateRecords(t){return await gW(t)}async upsertRecords(t){try{return await AW(t)}catch(r){throw cW(r,null,null,aW.ERR,r)}}async deleteRecords(t){return await EW(t)}async dropAttribute(t){return await bW(t)}async deleteAuditLogsBefore(t){return await OW(t)}async readAuditLog(t){return await yW(t)}writeTransaction(t,r,s){return IW.writeTransaction(t,r,s)}flush(t,r){return Fy.flush(t,r)}resetReadTxn(t,r){return Fy.resetReadTxn(t,r)}getBackup(t){return wW(t)}};Gy.exports=zh});var Jy={};Ye(Jy,{ResourceBridge:()=>Zh});function jh({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 Vy(e,t){let r=cs(e),s=jh(e,r);if(!r)throw new Gr.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};return Ke(i,async function*(o){for(let c of e.hash_values){let u=await r.get({id:c,lazy:n,select:s},i);u=u&&Du(u),t?yield{key:c,value:u}:yield u}})}function cs(e){let t=e.database||e.schema||UW,r=xr()[t];if(!r)throw(0,Gr.handleHDBError)(new Error,CW.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function $y(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*Yy(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,timestamp: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 Ky,Cl,Gr,Wy,Qy,kr,Jh,Xh,zy,CW,UW,DW,LW,ky,Zh,Xy=Se(()=>{"use strict";Ky=C(xy()),Cl=C(eo()),Gr=C(W());de();Wy=C(ga()),Qy=C(ya()),kr=C(A()),Jh=C(Gs()),Xh=C(Fr()),zy=C(V());$n();Lu();({HDB_ERROR_MSGS:CW}=Gr.hdb_errors),UW="data",DW=1e4,LW=10,Zh=class extends Ky.default{static{a(this,"ResourceBridge")}constructor(t){super(t),ky=this}async searchByConditions(t){let r=(0,Cl.default)(t,"conditions");if(r)throw(0,Gr.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=cs(t);if(!s)throw new Gr.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i=>({attribute:i.search_attribute,comparator:i.search_type,value:i.search_value}));return s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:jh(t,s),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 Gr.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}]}rt({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await cs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=cs(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(l=>{if(!l){let{value:_,version:d}=r.primaryStore.getEntry(o);return i(o,_,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(l=>setImmediate(l));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){cs(t).dropTable()}createSchema(t){return Va({database:t.schema,table:null}),Jh.signalSchemaChange(new Xh.SchemaEventMsg(process.pid,kr.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await em(t.schema),Jh.signalSchemaChange(new Xh.SchemaEventMsg(process.pid,kr.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,ky.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,Wy.default)(t);(0,Qy.default)(t,s,r.primaryKey);let n,i=xr()[t.schema][t.table],o={user:t.hdb_user};return Ke(o,async c=>{if(!i.schemaDefined){n=[];for(let _ of s)i.attributes.find(E=>E.name==_)||n.push(_);n.length>0&&await i.addAttributes(n.map(_=>({name:_,indexed:!0})))}let u=[],l=[];for(let _ of t.records){let d=await i.get(_[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){l.push(_[i.primaryKey]);continue}d&&(d=Du(d));for(let E in _)if(Object.prototype.hasOwnProperty.call(_,E)){let f=_[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,_[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(_),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(_,E)||(_[E]=d[E]);await i.put(_,o),u.push(_[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:l}})}async deleteRecords(t){let r=xr()[t.schema][t.table],s={user:t.hdb_user};return Ke(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 $y(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=xr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Gr.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:kr.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],l=a(async()=>{let _=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(..._.deleted_hashes),o.push(..._.skipped_hashes),await(0,zy.async_set_timeout)(LW),u=[],n=!0},"chunkDelete");for await(let _ of s)u.push(_[r.primaryKey]),c++,c%DW===0&&await l();return u.length>0&&await l(),n?$y(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){let r=(0,Cl.default)(t,"hashes");if(r)throw r;return Vy(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of Vy(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&kr.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);let s=(0,Cl.default)(t,"value");if(s)throw s;let n=cs(t);if(!n)throw new Gr.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===kr.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:jh(t,n)})}async getDataByValue(t,r){let s=new Map,n=cs(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){cs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return cs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=cs(t),s={};switch(t.search_type){case kr.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,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case kr.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of Yy(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return Yy(r,t.search_values?.[0],t.search_values?.[1])}}};a(jh,"getSelect");a(Vy,"getRecords");a(cs,"getTable");a($y,"createDeleteResponse");a(Yy,"groupRecordsInHistory")});var Hr=m((rae,Zy)=>{"use strict";var{ResourceBridge:MW}=(Xy(),ee(Jy)),PW=Q();PW.initSync();var Ul;function vW(){return Ul||(Ul=new MW,Ul)}a(vW,"getBridge");Zy.exports=vW()});var rI=m((nae,tI)=>{"use strict";var jy=require("lodash"),$a=require("mathjs"),BW=require("jsonata"),eI=V();tI.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?jy.uniqWith(e,jy.isEqual):e,searchJSON:HW,mad:Ya.bind(null,$a.mad),mean:Ya.bind(null,$a.mean),mode:Ya.bind(null,$a.mode),prod:Ya.bind(null,$a.prod),median:Ya.bind(null,$a.median)};function Ya(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(Ya,"aggregateFunction");function HW(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(eI.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),eI.isEmpty(this.__ala__.res[r])){let s=BW(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(HW,"searchJSON")});var nI=m((oae,sI)=>{"use strict";var Qe=require("moment"),tm="YYYY-MM-DDTHH:mm:ss.SSSZZ";Qe.suppressDeprecationWarnings=!0;sI.exports={current_date:()=>Qe().utc().format("YYYY-MM-DD"),current_time:()=>Qe().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Qe(e).utc().format("YYYY");case"month":return Qe(e).utc().format("MM");case"day":return Qe(e).utc().format("DD");case"hour":return Qe(e).utc().format("HH");case"minute":return Qe(e).utc().format("mm");case"second":return Qe(e).utc().format("ss");case"millisecond":return Qe(e).utc().format("SSS");default:break}},date:e=>Qe(e).utc().format(tm),date_format:(e,t)=>Qe(e).utc().format(t),date_add:(e,t,r)=>Qe(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Qe(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=Qe(e).utc(),n=Qe(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>Qe().utc().valueOf(),get_server_time:()=>Qe().format(tm),offset_utc:(e,t)=>Qe(e).utc().utcOffset(t).format(tm)}});var cI=m((aae,aI)=>{"use strict";var qW=require("@turf/area"),FW=require("@turf/length"),GW=require("@turf/circle"),xW=require("@turf/difference"),kW=require("@turf/distance"),VW=require("@turf/boolean-contains"),$W=require("@turf/boolean-equal"),YW=require("@turf/boolean-disjoint"),KW=require("@turf/helpers"),iI=A(),le=V();aI.exports={geoArea:WW,geoLength:QW,geoCircle:zW,geoDifference:JW,geoDistance:oI,geoNear:XW,geoContains:ZW,geoEqual:jW,geoCrosses:eQ,geoConvert:tQ};var rm="geo1 is required",sm="geo2 is required";function WW(e){if(le.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),qW.default(e)}a(WW,"geoArea");function QW(e,t){if(le.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),FW.default(e,{units:t||"kilometers"})}a(QW,"geoLength");function zW(e,t,r){if(le.isEmpty(e))throw new Error("point is required");if(le.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),GW.default(e,t,{units:r||"kilometers"})}a(zW,"geoCircle");function JW(e,t){if(le.isEmpty(e))throw new Error("poly1 is required");if(le.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),xW(e,t)}a(JW,"geoDifference");function oI(e,t,r){if(le.isEmpty(e))throw new Error("point1 is required");if(le.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),kW.default(e,t,{units:r||"kilometers"})}a(oI,"geoDistance");function XW(e,t,r,s){if(le.isEmpty(e))throw new Error("point1 is required");if(le.isEmpty(t))throw new Error("point2 is required");if(le.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");return oI(e,t,s)<=r}a(XW,"geoNear");function ZW(e,t){if(le.isEmpty(e))throw new Error(rm);if(le.isEmpty(e))throw new Error(sm);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),VW.default(e,t)}a(ZW,"geoContains");function jW(e,t){if(le.isEmpty(e))throw new Error(rm);if(le.isEmpty(e))throw new Error(sm);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),$W.default(e,t)}a(jW,"geoEqual");function eQ(e,t){if(le.isEmpty(e))throw new Error(rm);if(le.isEmpty(e))throw new Error(sm);return typeof e=="string"&&(e=le.autoCastJSON(e)),typeof t=="string"&&(t=le.autoCastJSON(t)),!YW.default(e,t)}a(eQ,"geoCrosses");function tQ(e,t,r){if(le.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(le.isEmpty(t))throw new Error("geo_type is required");if(le.isEmpty(iI.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(iI.GEO_CONVERSION_ENUM).join(",")}`);return KW[t](e,r)}a(tQ,"geoConvert")});var Dl=m((uae,uI)=>{var oi=rI(),ur=nI(),us=cI();uI.exports=e=>{e.aggr.mad=e.aggr.MAD=oi.mad,e.aggr.mean=e.aggr.MEAN=oi.mean,e.aggr.mode=e.aggr.MODE=oi.mode,e.aggr.prod=e.aggr.PROD=oi.prod,e.aggr.median=e.aggr.MEDIAN=oi.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=oi.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=oi.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=ur.current_date,e.fn.current_time=e.fn.CURRENT_TIME=ur.current_time,e.fn.extract=e.fn.EXTRACT=ur.extract,e.fn.date=e.fn.DATE=ur.date,e.fn.date_format=e.fn.DATE_FORMAT=ur.date_format,e.fn.date_add=e.fn.DATE_ADD=ur.date_add,e.fn.date_sub=e.fn.DATE_SUB=ur.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=ur.date_diff,e.fn.now=e.fn.NOW=ur.now,e.fn.offset_utc=e.fn.OFFSET_UTC=ur.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=ur.get_server_time,e.fn.getdate=e.fn.GETDATE=ur.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=ur.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=us.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=us.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=us.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=us.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=us.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=us.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=us.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=us.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=us.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=us.geoNear}});var EI=m((lae,dI)=>{"use strict";var Ka=require("lodash"),pt=require("alasql");pt.options.cache=!1;var rQ=Dl(),lI=require("clone"),Ll=require("recursive-iterator"),se=x(),ne=V(),so=Hr(),sQ=A(),{hdb_errors:nQ}=W(),{getDatabases:_I}=(de(),ee(Ne)),iQ="IS NULL",Vr="There was a problem performing this search. Please check the logs and try again.";rQ(pt);var nm=class{static{a(this,"SQLSearch")}constructor(t,r){if(ne.isEmpty(t))throw se.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(),ne.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!ne.isEmptyOrZeroLength(s))return se.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw se.error("Error thrown from checkEmptySQL in SQLSearch class method search."),se.error(s),new Error(Vr)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw se.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),se.error(s),new Error(Vr)}if(Object.keys(this.data).length===0)return se.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw se.error("Error thrown from processJoins in SQLSearch class method search."),se.error(s),new Error(Vr)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw se.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),se.error(s),new Error(Vr)}try{return t=await this._finalSQL(),t}catch(s){throw se.error("Error thrown from finalSQL in SQLSearch class method search."),se.error(s),new Error(Vr)}}_getColumns(){let t=new Ll(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(lI(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Ka.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=_I()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(ne.isEmpty(this.statement.where)){se.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Ll(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!ne.isEmpty(r)&&r.right)if(ne.isNotEmptyAndHasValue(r.right.value)){let s=ne.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new pt.yy.LogicValue({value:s}):r.right instanceof pt.yy.StringValue&&!ne.isEmpty(s)&&ne.autoCasterIsNumberCheck(s.toString())&&(r.right=new pt.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=ne.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new pt.yy.LogicValue({value:i}):s instanceof pt.yy.StringValue&&ne.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new pt.yy.NumValue({value:i}))});if(t){se.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Ll(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(!ne.isEmpty(sQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(ne.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(ne.isEmptyOrZeroLength(r.left.columnid)||ne.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(ne.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"=":!ne.isEmpty(r.right.value)||!ne.isEmpty(r.left.value)?s.add(ne.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 l=0;l<u.length;l++)if(u[l].value)s.add(u[l].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(ne.isEmptyOrZeroLength(this.all_table_attributes)&&ne.isEmptyOrZeroLength(this.statement.from)&&ne.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&&Ka.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(ne.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);ne.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(ne.isEmptyOrZeroLength(this.all_table_attributes)&&!ne.isEmptyOrZeroLength(this.columns.columns))return t;if(ne.isEmptyOrZeroLength(this.all_table_attributes)&&ne.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await pt.promise(r)}catch(r){throw se.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),se.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(lI(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(ne.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(iQ)>-1&&this.tables.forEach(n=>{let i={columnid:_I()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Ka.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,l=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!ne.isEmpty(this.exact_search_values[l])&&!this.exact_search_values[l].ignore&&!ne.isEmptyOrZeroLength(this.exact_search_values[l].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[l].values);let _=await so.getDataByHash(c);for(let d of c.hash_values)_.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(_){throw se.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),se.error(_),new Error(Vr)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[l].values).map(async _=>{let d=Object.assign({},c);d.search_value=_;let E=await so.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]):(this.data[i].__merged_data[f]=[...s[i]],this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(f)))}))}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),se.error(_),new Error(Vr)}else if(!ne.isEmpty(this.comparator_search_values[l])&&!this.comparator_search_values[l].ignore&&!ne.isEmptyOrZeroLength(this.comparator_search_values[l].comparators))try{let _=this.comparator_search_values[l].comparators;for(let d=0,E=_.length;d<E;d++){let f=_[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await so.getDataByValue(c,f.operation);if(u)for(let[T]of h)this.data[i].__merged_data[T]||(this.data[i].__merged_data[T]=[...s[i]],this._setMergedHashAttribute(i,ne.autoCast(T)));else for(let[T,p]of h)this.data[i].__merged_data[T]?this._updateMergedAttribute(i,T,n.attribute,p[n.attribute]):(this.data[i].__merged_data[T]=[...s[i]],this._updateMergedAttribute(i,T,n.attribute,p[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(T)))}}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),se.error(_),new Error(Vr)}else try{c.search_attribute=n.attribute,c.search_value="*";let _=await so.getDataByValue(c);if(u)for(let[d]of _)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,ne.autoCast(d)));else for(let[d,E]of _)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]),this._setMergedHashAttribute(i,ne.autoCast(d)))}catch(_){throw se.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),se.error(_),new Error(Vr)}}}_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 pt.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 pt.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new pt.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 pt.yy.FuncValue:new pt.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(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,T=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${T}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${T}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"",l="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(l="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let _="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(_=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${l} ${_} ${d}`,h=this._convertColumnsToIndexes(f,n);E=await pt.promise(h,t),t=null}catch(f){throw se.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),se.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let T=E[f];o.forEach(p=>{T[p.key]!==null&&T[p.key]!==void 0&&p.keys.add(T[p.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),T=Ka.difference(h,[...f.keys].map(p=>p.toString()));for(let p=0,R=T.length;p<R;p++){let O=T[p];delete this.data[`${f.schema}_${f.table}`].__merged_data[O]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Ll(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=Ka.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 se.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),se.error(i),new Error(Vr)}}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 _ in i)o.push(i[_][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 so.getDataByHash(c),l=n.columns.length;for(let _=0,d=o.length;_<d;_++){let E=o[_],f=u.get(E);for(let h=0;h<l;h++){let T=n.columns[h],p=f[T]===void 0?null:f[T];this.data[s].__merged_data[E].push(p)}}}}catch(r){throw se.error("Error thrown from getDataByHash function in SQLSearch class method getData."),se.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&&delete this.statement.limit,this.statement.offset&&delete this.statement.offset);let s;try{let n=this._buildSQL();se.trace(`Final SQL: ${n}`),s=await pt.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),se.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw se.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),se.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 se.error(nQ.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),se.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return 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],l=new RegExp(`${u}.\`${o}\``,"g"),_=`${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"),l=`[${c}]`;s=s.replace(u,l)});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 so.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 se.error("There was an error when processing this SQL operation. Check your logs"),se.error(o),new Error(Vr)}}return Object.values(Object.values(this.data)[0].__merged_data)}};dI.exports=nm});var gr=m((dae,fI)=>{"use strict";var oQ=rA();fI.exports={searchByConditions:cQ,searchByHash:uQ,searchByValue:lQ,search:_Q};var im=Hr(),{transformReq:om}=V(),aQ=EI();async function cQ(e){return om(e),im.searchByConditions(e)}a(cQ,"searchByConditions");async function uQ(e){om(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of im.searchByHash(e))r&&t.push(r);return t}a(uQ,"searchByHash");async function lQ(e){om(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of im.searchByValue(e))t.push(r);return t}a(lQ,"searchByValue");function _Q(e,t){try{let r=new oQ(e);r.validate(),new aQ(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(_Q,"search")});var Ml=m((fae,hI)=>{"use strict";var dQ=Hr();hI.exports={writeTransaction:EQ};function EQ(e,t,r){return dQ.writeTransaction(e,t,r)}a(EQ,"writeTransaction")});var TI=m((Sae,pI)=>{"use strict";var fQ=gr(),hQ=dn(),mI=x(),mQ=Ar(),mae=Ml(),SQ=require("clone"),cm=require("alasql"),pQ=Dl(),SI=require("util"),TQ=SI.promisify(hQ.getTableSchema),RQ=SI.promisify(fQ.search),gQ=A(),am=V();pQ(cm);pI.exports={update:OQ};var AQ="There was a problem performing this update. Please check the logs and try again.";async function OQ({statement:e,hdb_user:t}){let r=await TQ(e.table.databaseid,e.table.tableid),s=NQ(e.columns);am.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=SQ(n),c=am.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,l=cm.parse(u).statements[0],_=await RQ(l),d=bQ(s,_);return yQ(o,d,t)}a(OQ,"update");function NQ(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=cm.compile(`SELECT ${r.expression.toString()} AS [${gQ.FUNC_VAL}] FROM ?`)}),t}catch(t){throw mI.error(t),new Error(AQ)}}a(NQ,"createUpdateRecord");function bQ(e,t){return am.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(bQ,"buildUpdateRecords");async function yQ(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await mQ.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){mI.error(`Error delete new_attributes from update response: ${i}`)}return n}a(yQ,"updateRecords")});var gI=m((gae,RI)=>{var IQ=require("alasql"),wQ=gr(),CQ=x(),UQ=Hr(),lm=require("util"),um=V(),DQ=A(),LQ=dn(),Tae=Ml(),Rae=Ar(),MQ="record",PQ="successfully deleted",vQ=lm.callbackify(FQ),BQ=lm.promisify(wQ.search),HQ=lm.promisify(LQ.getTableSchema);RI.exports={convertDelete:vQ};function qQ(e){return`${e.deleted_hashes.length} ${MQ}${e.deleted_hashes.length===1?"":"s"} ${PQ}`}a(qQ,"generateReturnMessage");async function FQ({statement:e,hdb_user:t}){let r=await HQ(e.table.databaseid,e.table.tableid);um.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=um.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=IQ.parse(o).statements[0],u={operation:DQ.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await BQ(c);let l=await UQ.deleteRecords(u);return um.isEmptyOrZeroLength(l.message)&&(l.message=qQ(l)),delete l.txn_time,l}catch(l){throw CQ.error(l),l.hdb_code?l.message:l}}a(FQ,"convertDelete")});var yI=m((Oae,bI)=>{"use strict";var GQ=Qn(),{hdb_errors:AI}=W(),{getDatabases:OI}=(de(),ee(Ne));bI.exports={checkSchemaExists:NI,checkSchemaTableExists:xQ,schema_describe:GQ};async function NI(e){if(!OI()[e])return AI.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(NI,"checkSchemaExists");async function xQ(e,t){let r=await NI(e);if(r)return r;if(!OI()[e][t])return AI.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(xQ,"checkSchemaTableExists")});var Wa=m((bae,kQ)=>{kQ.exports={name:"harperdb",version:"4.2.0-alpha.13",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{node:">=14.0.0","preferred-node":"18.15.0","go-lang":"1.19.12","nats-server":"2.9.21"},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":"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: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:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","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":"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.383.0","@aws-sdk/lib-storage":"3.383.0","@aws-sdk/abort-controller":"3.370.0","@endo/static-module-record":"^0.7.16","@fastify/autoload":"~5.7.1","@fastify/compress":"~6.4.0","@fastify/cors":"~8.3.0","@fastify/static":"~6.10.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"1.7.4","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2",esbuild:"^0.18.0","fast-glob":"3.3.1",fastify:"~4.21.0","fastify-plugin":"~4.5.0","fs-extra":"11.1.1",graphql:"^16.6.0","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.9.2",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.1",lmdb:"2.8.4",lodash:"4.17.21",mathjs:"11.9.1",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.0",msgpackr:"1.9.7",nats:"2.16.0",needle:"3.2.0","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.4.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.15.0",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0",ses:"^0.18.1","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.18.11","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.0","validate.js":"0.13.1",ws:"^8.13.0",yaml:"2.3.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"0.27.2",chai:"4.3.7","chai-integer":"0.1.0",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^4.9.4","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var ql={};Ye(ql,{addAnalyticsListener:()=>fm,recordAction:()=>ls,recordActionBinary:()=>no,setAnalyticsEnabled:()=>VQ});function VQ(e){BI=e}function ls(e,t,r,s,n){if(!BI)return;let i=t+(r?"-"+r:"");s&&(i+="-"+s);let o=Bl.get(i);o?(o.push(e),o.total+=e):(o=[e],o.total=e,o.description={metric:t,path:r,method:s,type:n},Bl.set(i,o)),vl||$Q()}function no(e,t,r,s,n){ls(e?1:0,t,r,s,n)}function fm(e){qI.push(e)}function $Q(){vl=performance.now(),setTimeout(()=>{let e=performance.now()-vl;vl=0;let t=[],r={time:Date.now(),period:e,threadId:ai.threadId,metrics:t};for(let[n,i]of Bl)if(i.sort){i.sort();let o=i.length;t.push(Object.assign(i.description,{median:i[o>>1],mean:i.total/o,p95:i[Math.floor(o*.95)],p90:i[Math.floor(o*.9)],count:o}))}else t.push(i);let s=process.memoryUsage();t.push({metric:"memory",threadId:ai.threadId,...s});for(let n of qI)n(t);Bl=new Map,ai.parentPort?ai.parentPort.postMessage({type:HI,report:r}):GI({report:r})},Em).unref()}async function YQ(e,t=6e4){let r=hm(),s;for(let _ of r.primaryStore.getRange({start:Pl+"z",end:Pl,reverse:!0}))if(_.value?.time){s=_.value.time;break}if(Date.now()-t<s)return;let n,i=new Map,o;for(let{key:_,value:d}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!d)continue;if(n){if(_>n+t)break}else n=_;o=_;let{metrics:E}=d;for(let f of E||[]){let{path:h,method:T,type:p,metric:R,count:O,threadId:k,...$}=f;O||(O=1);let U=R+(h?"-"+h:"");T&&(U+="-"+T);let b=i.get(U);if(b)for(let P in $){let z=$[P];if(typeof z=="number"){let q=b.count||1;b[P]=(b[P]*q+z*O)/(b.count=q+O)}}else b=Object.assign({period:t},f),i.set(U,b)}await KQ()}for(let[_,d]of i)d.id=Pl+Math.round(o)+"-"+_,d.time=o,r.put(d);let c=Date.now(),{idle:u,active:l}=performance.eventLoopUtilization();r.put({id:Pl+Math.round(c)+"-main-thread-utilization",metric:"main-thread-utilization",idle:u-II,active:l-wI,time:c}),II=u,wI=l}async function WQ(e,t){let r=hm(),s=Date.now()-e;for(let n of r.primaryStore.getKeys({start:!1,end:s}))r.primaryStore.remove(n)}function hm(){return CI||(CI=rt({table:"hdb_analytics",database:"system",expiration:864e3,audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"values"}]}))}function zQ(){FI=!0,setInterval(async()=>{await YQ(Em,dm),await WQ(QQ,Em)},dm/2).unref()}function GI(e,t){let r=e.report;r.threadId=t?.threadId||ai.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(UI+=s.mean*s.count);r.totalBytesProcessed=UI,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(DI.get(t))}),DI.set(t,t.performance.eventLoopUtilization())),r.id=(0,PI.getNextMonotonicTime)(),hm().put(r),FI||zQ(),JQ&&(xI=ZQ(r))}async function ZQ(e){if(await xI,!Rn){let r=(0,Qa.dirname)((0,MI.getLogFilePath)());try{Rn=await(0,_m.open)((0,Qa.join)(r,"analytics.log"),"r+")}catch{Rn=await(0,_m.open)((0,Qa.join)(r,"analytics.log"),"w+")}}let t=(await Rn.stat()).size;if(t>XQ){let r=Buffer.alloc(t);await Rn.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await Rn.write(r,{position:0}),await Rn.truncate(r.length),t=r.length}await Rn.write(JSON.stringify(e)+`
|
|
6
|
+
`,t)}var ai,LI,MI,Qa,_m,PI,Hl,vI,Bl,dm,BI,vl,Em,HI,qI,Pl,II,wI,KQ,QQ,CI,FI,UI,DI,JQ,xI,Rn,XQ,ci=Se(()=>{ai=require("worker_threads"),LI=C(nt());de();MI=C(x()),Qa=require("path"),_m=require("fs/promises"),PI=C(vt()),Hl=C(Q()),vI=C(A());Pr();(0,Hl.initSync)();Bl=new Map,dm=(0,Hl.get)(vI.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3,BI=dm>0;a(VQ,"setAnalyticsEnabled");a(ls,"recordAction");tt.recordAnalytics=ls;a(no,"recordActionBinary");vl=0,Em=1e3,HI="analytics-report",qI=[];a(fm,"addAnalyticsListener");a($Q,"sendAnalytics");Pl="sum-";a(YQ,"aggregation");II=0,wI=0,KQ=a(()=>new Promise(setImmediate),"rest");a(WQ,"cleanup");QQ=36e5;a(hm,"getAnalyticsTable");(0,LI.setChildListenerByType)(HI,GI);a(zQ,"startScheduledTasks");UI=0,DI=new Map,JQ=!1;a(GI,"recordAnalytics");XQ=1e6;a(ZQ,"logAnalytics")});var it=m((Fae,ow)=>{"use strict";var Tt=Q();Tt.initSync();var jQ=require("fs-extra"),ez=require("semver"),Za=require("path"),{monotonicFactory:tz}=require("ulidx"),Tm=tz(),rz=require("util"),VI=require("child_process"),sz=rz.promisify(VI.exec),nz=VI.spawn,_e=Be(),Te=A(),Fl=V(),yr=x(),Gl=vs(),iz=Ml(),za=Nr(),{Encoder:oz,decode:Rm}=require("msgpackr"),$I=new oz,{isEmpty:ui}=Fl,YI=br(),KI=12e10,az=48*36e11,cz=5e9,{connect:uz,StorageType:WI,RetentionPolicy:QI,AckPolicy:xl,DeliverPolicy:kl,DiscardPolicy:lz,NatsConnection:vae,JetStreamManager:Bae,JetStreamClient:Hae,StringCodec:qae,JSONCodec:_z,createInbox:gm,headers:dz,ErrorCode:kI}=require("nats"),{PACKAGE_ROOT:Ez}=A(),fz=Wa(),{recordAction:hz}=(ci(),ee(ql)),zI=_z(),mz="clustering",Sz=fz.engines[_e.NATS_SERVER_NAME],pz=Za.join(Ez,"dependencies"),pm=Za.join(pz,`${process.platform}-${process.arch}`,_e.NATS_BINARY_NAME),mm,Sm,Ja,io,oo;ow.exports={runCommand:JI,checkNATSServerInstalled:Tz,createConnection:Am,getConnection:Vl,getJetStreamManager:ja,getJetStream:XI,getNATSReferences:Gt,getServerList:gz,createLocalStream:Om,listStreams:ZI,deleteLocalStream:Az,getServerConfig:ec,listRemoteStreams:Oz,viewStream:Nz,viewStreamIterator:bz,publishToStream:yz,createWorkQueueStream:Iz,addSourceToWorkStream:ew,request:Cz,removeSourceFromWorkStream:rw,reloadNATS:Nm,reloadNATSHub:Uz,reloadNATSLeaf:Dz,extractServerName:tw,requestErrorHandler:Lz,updateWorkStream:Mz,createLocalTableStream:nw,createTableStreams:Pz,purgeTableStream:iw,purgeSchemaTableStreams:vz,getStreamInfo:Bz,updateLocalStreams:qz,closeConnection:Rz,getJsmServerName:tc,addNatsMsgHeader:jI,updateIngestStreamConsumer:wz};async function JI(e,t=void 0){let{stdout:r,stderr:s}=await sz(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
7
7
|
`,""));return r.replace(`
|
|
8
|
-
`,"")}a(WI,"runCommand");async function Ez(){try{await WQ.access(fm)}catch{return!1}let e=await WI(`${fm} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return QQ.eq(t,_z)}a(Ez,"checkNATSServerInstalled");async function pm(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await kI.getClusterUser();if(ci(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Nr.trace("create nats connection called");let i=await sz({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:3e4,tls:{keyFile:Tt.get(Te.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Tt.get(Te.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Tt.get(Te.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return Nr.trace("create connection established a nats client connection with id",i?.info?.client_id),i}a(pm,"createConnection");async function fz(){us&&(await us.drain(),us=void 0,so=void 0,no=void 0,Qa=void 0)}a(fz,"closeConnection");var us,Qa;async function xl(){return Qa||(Qa=pm(Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),us=await Qa),us||Qa}a(xl,"getConnection");async function Ja(){if(so)return so;ci(us)&&await xl();let{domain:e}=Xa(Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ci(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return so=await us.jetstreamManager({domain:e}),so}a(Ja,"getJetStreamManager");async function QI(){if(no)return no;ci(us)&&await xl();let{domain:e}=Xa(Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ci(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return no=us.jetstream({domain:e}),no}a(QI,"getJetStream");async function Gt(){let e=us||await xl(),t=so||await Ja(),r=no||await QI();return{connection:e,jsm:t,js:r}}a(Gt,"getNATSReferences");async function hz(e){let t=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await kI.getClusterUser(),n=await pm(t,r,s),i=Sm(),o=n.subscribe(i),c=[],u,l=(async()=>{for await(let _ of o){let d=KI.decode(_.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 Hl.async_set_timeout(e),await o.drain(),await n.close(),await l,c}a(hz,"getServerList");async function Tm(e,t){let{jsm:r}=await Gt(),s=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:$I.File,retention:YI.Limits,subjects:t,discard:nz.Old,duplicate_window:VI,max_msgs:n,max_bytes:i,max_age:s})}a(Tm,"createLocalStream");async function zI(){let{jsm:e}=await Gt(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(zI,"listStreams");async function mz(e){let{jsm:t}=await Gt();await t.streams.delete(e)}a(mz,"deleteLocalStream");async function Sz(e){let{connection:t}=await Gt(),r=[],s=Sm(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(KI.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(Sz,"listRemoteStreams");async function pz(e,t=void 0,r=void 0){let{jsm:s,js:n}=await Gt(),i=hm(),o={durable_name:i,ack_policy:Fl.Explicit};t&&(o.deliver_policy=Gl.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 l=[];for await(let _ of u){let d=mm(_.data),E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};if(_.headers&&(E.origin=_.headers.get(_e.MSG_HEADERS.ORIGIN),E.nats_msg_id=_.headers.get(_e.MSG_HEADERS.NATS_MSG_ID)),l.push(E),_.ack(),_.info.pending===0)break}return await c.delete(),l}a(pz,"viewStream");async function*Tz(e,t=void 0,r=void 0){let{jsm:s,js:n}=await Gt(),i=hm(),o={durable_name:i,ack_policy:Fl.Explicit};t&&(o.deliver_policy=Gl.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 l of u){let _=mm(l.data);_[0]||(_=[_]);for(let d of _){let E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};l.headers&&(E.origin=l.headers.get(_e.MSG_HEADERS.ORIGIN),E.nats_msg_id=l.headers.get(_e.MSG_HEADERS.NATS_MSG_ID)),yield E}if(l.ack(),l.info.pending===0)break}await c.delete()}a(Tz,"viewStreamIterator");async function Rz(e,t,r,s){Nr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=JI(s,r);let{js:n}=await Gt(),i=await Za(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:xI.encode(s);try{Nr.trace(`publishToStream publishing to subject: ${o}`),uz(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 ew(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Nr.trace(`publishToStream creating stream: ${t}`);let _=o.split(".");_[2]="*",await Tm(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(Rz,"publishToStream");function JI(e,t){t===void 0&&(t=oz());let r=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_NODENAME);if(!t.has(_e.MSG_HEADERS.NATS_MSG_ID)){let s=Hl.getTableHashAttribute(e.schema,e.table),n=e.action?e.action:e.operation,i=`${r}.${e.schema}.${e.table}.${n}.${s}.${Date.now()}.${hm()}`;t.append(_e.MSG_HEADERS.NATS_MSG_ID,i)}return t.has(_e.MSG_HEADERS.ORIGIN)||t.append(_e.MSG_HEADERS.ORIGIN,r),t}a(JI,"addNatsMsgHeader");function Xa(e){e=e.toLowerCase();let t=za.join(Tt.get(Te.CONFIG_PARAMS.ROOTPATH),lz);if(e===Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ci(Em)&&(Em={port:Ka.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Ka.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.HUB,config_file:_e.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:za.join(t,_e.PID_FILES.HUB),hdb_nats_path:t}),Em;if(e===Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ci(dm)&&(dm={port:Ka.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Ka.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.LEAF,config_file:_e.NATS_CONFIG_FILES.LEAF_SERVER,domain:Ka.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.LEAF,pid_file_path:za.join(t,_e.PID_FILES.LEAF),hdb_nats_path:t}),dm;Nr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Xa,"getServerConfig");async function gz(e){let{jsm:t}=await Gt(),r=await Za();try{await t.streams.add({name:e.stream_name,storage:$I.File,retention:YI.Limits,duplicate_window:VI,max_age:tz,max_bytes:rz,subjects:[`${_e.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:Fl.Explicit,durable_name:e.durable_name,deliver_policy:Gl.All,max_ack_pending:1e4});else throw s}}a(gz,"createWorkQueueStream");async function Az(){let{jsm:e}=await Gt();(await e.consumers.info(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,_e.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Nr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,_e.WORK_QUEUE_CONSUMER_NAMES.durable_name),Nr.info("Adding pull consumer to ingest stream"),await e.consumers.add(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:Fl.Explicit,durable_name:_e.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:Gl.All,max_ack_pending:1e4}))}a(Az,"updateIngestStreamConsumer");async function XI(e,t,r){let{jsm:s}=await Gt(),n=await s.streams.info(t),i=ZI(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,l=ql.createNatsTableStreamName(c,u),_=i===e,d,E,f=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let T=0,S=n.config.sources.length;T<S;T++)if(d=n.config.sources[T],E=T,_&&d.name===l||!_&&d.name===l&&d.external&&d.external.api===`$JS.${e}.API`){f=!0;break}if(f===!0){if(d.opt_start_time===o)return;n.config.sources.splice(E,1),await s.streams.update(t,n.config)}let h={name:l,opt_start_time:o,filter_subject:`${_e.SUBJECT_PREFIXES.TXN}.>`};_||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(XI,"addSourceToWorkStream");function ZI(e){return e.split(".")[1]}a(ZI,"extractServerName");async function jI(e,t,r){let{schema:s,table:n}=r,i=ql.createNatsTableStreamName(s,n),{jsm:o}=await Gt(),c=await o.streams.info(t);if(!Array.isArray(c.config.sources)||c.config.sources.length===0)return;let u=c.config.sources.length,l;for(;u--;)if(l=c.config.sources[u],l.name===i&&l.external.api===`$JS.${e}.API`){c.config.sources.splice(u,1);break}await o.streams.update(t,c.config)}a(jI,"removeSourceFromWorkStream");async function Oz(e,t,r=2e4,s=Sm()){if(!Hl.isObject(t))throw new Error("data param must be an object");let n=xI.encode(t),{connection:i}=await Gt(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return mm(c.data)}a(Oz,"request");function Rm(e){return new Promise(async(t,r)=>{let s=ZQ(fm,["--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(Rm,"reloadNATS");async function Nz(){let{pid_file_path:e}=Xa(Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await Rm(e)}a(Nz,"reloadNATSHub");async function bz(){let{pid_file_path:e}=Xa(Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await Rm(e)}a(bz,"reloadNATSLeaf");function yz(e,t,r){let s;switch(e.code){case FI.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case FI.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(yz,"requestErrorHandler");async function Iz(e,t){let r=t+_e.SERVER_SUFFIX.LEAF;await ew(async()=>{e.subscribe===!0?await XI(r,_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await jI(r,_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(Iz,"updateWorkStream");function ew(e){return jQ.writeTransaction(Te.SYSTEM_SCHEMA_NAME,Te.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(ew,"exclusiveLock");async function tw(e,t){let r=ql.createNatsTableStreamName(e,t),s=await Za(),n=Dz(e,t,s);await Tm(r,[n])}a(tw,"createLocalTableStream");async function wz(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await tw(s,n)}}a(wz,"createTableStreams");async function rw(e,t){if(Tt.get(Te.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=ql.createNatsTableStreamName(e,t),{jsm:s}=await Gt();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")Nr.warn(r);else throw r}}a(rw,"purgeTableStream");async function Cz(e,t){if(Tt.get(Te.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await rw(e,t[r])}a(Cz,"purgeSchemaTableStreams");async function Uz(e){return(await Ja()).streams.info(e)}a(Uz,"getStreamInfo");function Dz(e,t,r){return`${_e.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Dz,"createSubjectName");async function Za(){if(Wa)return Wa;if(Wa=(await Ja())?.nc?.info?.server_name,Wa===void 0)throw new Error("Unable to get jetstream manager server name");return Wa}a(Za,"getJsmServerName");async function Lz(){let e=await Ja(),t=await Za(),r=await zI();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=Mz(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===_e.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let l=`${_e.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Nr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}else if(n.name===_e.WORK_QUEUE_CONSUMER_NAMES.stream_name){let l=`${_e.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Nr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}else{let l=i.split(".");l[l.length-1]=t;let _=l.join(".");Nr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}await e.streams.update(n.name,n)}}}a(Lz,"updateLocalStreams");function Mz(e){let{config:t}=e,r=!1;if(t.name===_e.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===_e.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Tt.get(Te.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(Mz,"updateStreamLimits")});var Yl=m((Pae,aw)=>{"use strict";var io=$u(),oo=OI(),Pz=F(),vz=require("uuid").v4,Mae=require("clone"),Vl=Fs(),ao=g(),Bz=require("util"),Rn=Br(),{handleHDBError:xt,hdb_errors:Hz}=W(),{HDB_ERROR_MSGS:kl,HTTP_STATUS_CODES:kt}=Hz,{SchemaEventMsg:$l}=qr(),nw=st(),{getDatabases:qz}=(de(),te(Ne)),{transformReq:co}=x();aw.exports={createSchema:Fz,createSchemaStructure:iw,createTable:Gz,createTableStructure:ow,createAttribute:Yz,dropSchema:xz,dropTable:kz,dropAttribute:Vz,getBackup:Kz};async function Fz(e){let t=await iw(e);return Vl.signalSchemaChange(new $l(process.pid,e.operation,e.schema)),t}a(Fz,"createSchema");async function iw(e){let t=io.schema_object(e);if(t)throw xt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);if(co(e),!await oo.checkSchemaExists(e.schema))throw xt(new Error,kl.SCHEMA_EXISTS_ERR(e.schema),kt.BAD_REQUEST,ao.LOG_LEVELS.ERROR,kl.SCHEMA_EXISTS_ERR(e.schema),!0);return await Rn.createSchema(e),`database '${e.schema}' successfully created`}a(iw,"createSchemaStructure");async function Gz(e){return co(e),await ow(e)}a(Gz,"createTable");async function ow(e){let t=io.create_table_object(e);if(t)throw xt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);if(io.validateTableResidence(e.residence),!await oo.checkSchemaTableExists(e.schema,e.table))throw xt(new Error,kl.TABLE_EXISTS_ERR(e.schema,e.table),kt.BAD_REQUEST,ao.LOG_LEVELS.ERROR,kl.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:vz(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await Rn.createTable(s,e);else throw xt(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",kt.BAD_REQUEST);else await Rn.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(ow,"createTableStructure");async function xz(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=io.schema_object(e),s=t??r;if(s)throw xt(s,s.message,kt.BAD_REQUEST,void 0,void 0,!0);co(e);let n=await oo.checkSchemaExists(e.schema);if(n)throw xt(new Error,n,kt.NOT_FOUND,ao.LOG_LEVELS.ERROR,n,!0);let i=await oo.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await Rn.dropSchema(e),Vl.signalSchemaChange(new $l(process.pid,e.operation,e.schema)),await nw.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(xz,"dropSchema");async function kz(e){let t=io.table_object(e);if(t)throw xt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);co(e);let r=await oo.checkSchemaTableExists(e.schema,e.table);if(r)throw xt(new Error,r,kt.NOT_FOUND,ao.LOG_LEVELS.ERROR,r,!0);return await Rn.dropTable(e),await nw.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(kz,"dropTable");async function Vz(e){let t=io.attribute_object(e);if(t)throw xt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);co(e);let r=await oo.checkSchemaTableExists(e.schema,e.table);if(r)throw xt(new Error,r,kt.NOT_FOUND,ao.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw xt(new Error,"You cannot drop a hash attribute",kt.BAD_REQUEST,void 0,void 0,!0);if(ao.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw xt(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,kt.BAD_REQUEST,void 0,void 0,!0);try{return await Rn.dropAttribute(e),$z(e),Vl.signalSchemaChange(new $l(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw Pz.error(`Got an error deleting attribute ${Bz.inspect(e)}.`),s}}a(Vz,"dropAttribute");function $z(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($z,"dropAttributeFromGlobal");async function Yz(e){co(e);let t=qz()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw xt(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,kt.BAD_REQUEST,void 0,void 0,!0);return await Rn.createAttribute(e),Vl.signalSchemaChange(new $l(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Yz,"createAttribute");function Kz(e){return Rn.getBackup(e)}a(Kz,"getBackup")});var uw=m((Bae,cw)=>{"use strict";var{OPERATIONS_ENUM:Wz}=g(),gm=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=Wz.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};cw.exports=gm});var Am=m((Fae,fw)=>{"use strict";var Qz=Br(),qae=uw(),Kl=x(),Wl=g(),zz=Q(),{handleHDBError:lw,hdb_errors:Jz}=W(),{HDB_ERROR_MSGS:_w,HTTP_STATUS_CODES:dw}=Jz,Xz=Object.values(Wl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),Ew="To use this operation audit log must be enabled in harperdb-config.yaml";fw.exports=Zz;async function Zz(e){if(Kl.isEmpty(e.schema))throw new Error(_w.SCHEMA_REQUIRED_ERR);if(Kl.isEmpty(e.table))throw new Error(_w.TABLE_REQUIRED_ERR);if(!zz.get(Wl.CONFIG_PARAMS.LOGGING_AUDITLOG))throw lw(new Error,Ew,dw.BAD_REQUEST,Wl.LOG_LEVELS.ERROR,Ew,!0);let t=Kl.checkSchemaTableExist(e.schema,e.table);if(t)throw lw(new Error,t,dw.NOT_FOUND,Wl.LOG_LEVELS.ERROR,t,!0);if(!Kl.isEmpty(e.search_type)&&Xz.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await Qz.readAuditLog(e)}a(Zz,"readAuditLog")});var mw=m((xae,hw)=>{"use strict";var{OPERATIONS_ENUM:jz}=g(),Om=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=jz.GET_BACKUP,this.schema=t,this.table=r}};hw.exports=Om});var Tw=m((Yae,pw)=>{"use strict";var eJ=Br(),Vae=mw(),Nm=x(),tJ=g(),$ae=Q(),{handleHDBError:rJ,hdb_errors:sJ}=W(),{HDB_ERROR_MSGS:Sw,HTTP_STATUS_CODES:nJ}=sJ;pw.exports=iJ;async function iJ(e){if(Nm.isEmpty(e.schema))throw new Error(Sw.SCHEMA_REQUIRED_ERR);if(Nm.isEmpty(e.table))throw new Error(Sw.TABLE_REQUIRED_ERR);let t=Nm.checkSchemaTableExist(e.schema,e.table);if(t)throw rJ(new Error,t,nJ.NOT_FOUND,tJ.LOG_LEVELS.ERROR,t,!0);return await eJ.getBackup(read_audit_log_object)}a(iJ,"getBackup")});var bw=m((Wae,Nw)=>{var gn=require("validate.js"),gw=ve(),uo=g(),{handleHDBError:oJ,hdb_errors:aJ}=W(),{HDB_ERROR_MSGS:Ve,HTTP_STATUS_CODES:cJ}=aJ,bm=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),uJ={STRUCTURE_USER:"structure_user"},Rw=Object.values(uo.ROLE_TYPES_ENUM),lJ="attribute_permissions",_J="attribute_name",{PERMS_CRUD_ENUM:lo}=uo,dJ=[lJ,...Object.values(lo)],Aw=[lo.READ,lo.INSERT,lo.UPDATE],EJ=[_J,...Aw];function fJ(e){let t=bm();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,Ow(e,t)}a(fJ,"addRoleValidation");function hJ(e){let t=bm();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,Ow(e,t)}a(hJ,"alterRoleValidation");function mJ(e){let t=bm();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,gw.validateObject(e,t)}a(mJ,"dropRoleValidation");var SJ=["operation","role","id","permission","hdb_user","hdb_auth_header"];function Ow(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)SJ.includes(s[o])||n.push(s[o]);n.length>0&&Qe(Ve.INVALID_ROLE_JSON_KEYS(n),r);let i=gw.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Qe(o,r)}),e.permission){let o=pJ(e);o&&Qe(o,r),Rw.forEach(c=>{e.permission[c]&&!gn.isBoolean(e.permission[c])&&Qe(Ve.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(Rw.indexOf(o)<0){if(o===uJ.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let l=0,_=u.length;l<_;l++){let d=u[l];global.hdb_schema[d]||Qe(Ve.SCHEMA_NOT_FOUND(d),r)}continue}Qe(Ve.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Qe(Ve.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let l=c.tables[u];if(!u||!global.hdb_schema[o][u]){Qe(Ve.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(l).forEach(_=>{dJ.includes(_)||Qe(Ve.INVALID_PERM_KEY(_),r,o,u)}),Object.values(lo).forEach(_=>{gn.isDefined(l[_])?gn.isBoolean(l[_])||Qe(Ve.TABLE_PERM_NOT_BOOLEAN(_),r,o,u):Qe(Ve.TABLE_PERM_MISSING(_),r,o,u)}),gn.isDefined(l.attribute_permissions)){if(!gn.isArray(l.attribute_permissions)){Qe(Ve.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Qe(Ve.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(l.attribute_permissions){let _=global.hdb_schema[o][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in l.attribute_permissions){let f=l.attribute_permissions[E];if(Object.keys(f).forEach(T=>{!EJ.includes(T)&&T!==lo.DELETE&&Qe(Ve.INVALID_ATTR_PERM_KEY(T),r,o,u)}),!gn.isDefined(f.attribute_name)){Qe(Ve.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!_.includes(h)){Qe(Ve.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}Aw.forEach(T=>{gn.isDefined(f[T])?gn.isBoolean(f[T])||Qe(Ve.ATTR_PERM_NOT_BOOLEAN(T,h),r,o,u):Qe(Ve.ATTR_PERM_MISSING(T,h),r,o,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(l.read===!1&&d.read===!0||l.insert===!1&&d.insert===!0||l.update===!1&&d.update===!0){let E=`${o}.${u}`;Qe(Ve.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return TJ(r)}a(Ow,"customValidate");Nw.exports={addRoleValidation:fJ,alterRoleValidation:hJ,dropRoleValidation:mJ};function pJ(e){let{operation:t,permission:r}=e;if(t===uo.OPERATIONS_ENUM.ADD_ROLE||t===uo.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 Ve.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?uo.ROLE_TYPES_ENUM.SUPER_USER:uo.ROLE_TYPES_ENUM.CLUSTER_USER;return Ve.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(pJ,"validateNoSUPerms");function TJ(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:Ve.ROLE_PERMS_ERROR,...e};return oJ(new Error,s,cJ.BAD_REQUEST)}else return null}a(TJ,"generateRolePermResponse");function Qe(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(Qe,"addPermError")});var Dm=m((zae,Cw)=>{"use strict";var yw=Rr(),Iw=Tr(),RJ=Zn(),Im=bw(),wm=Fs(),gJ=require("uuid").v4,AJ=require("util"),Ql=g(),OJ=x(),Cm=Iw.searchByValue,NJ=Iw.searchByHash,bJ=AJ.promisify(RJ.delete),yJ=is(),IJ=ji(),{hdb_errors:wJ,handleHDBError:_o}=W(),{HDB_ERROR_MSGS:ww,HTTP_STATUS_CODES:zl}=wJ,{UserEventMsg:Um}=qr();Cw.exports={addRole:CJ,alterRole:UJ,dropRole:DJ,listRoles:LJ};function ym(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(ym,"scrubRoleDetails");async function CJ(e){let t=Im.addRoleValidation(e);if(t)throw t;e=ym(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 Cm(r)||[])}catch(i){throw _o(i)}if(s&&s.length>0)throw _o(new Error,ww.ROLE_ALREADY_EXISTS(e.role),zl.CONFLICT,void 0,void 0,!0);e.id||(e.id=gJ());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await yw.insert(n),wm.signalUserChange(new Um(process.pid)),e=ym(e),e}a(CJ,"addRole");async function UJ(e){let t=Im.alterRoleValidation(e);if(t)throw t;e=ym(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await yw.update(r)}catch(n){throw _o(n)}if(s&&s?.message==="updated 0 of 1 records")throw _o(new Error,"Invalid role id",zl.BAD_REQUEST,void 0,void 0,!0);return await wm.signalUserChange(new Um(process.pid)),e}a(UJ,"alterRole");async function DJ(e){let t=Im.dropRoleValidation(e);if(t)throw _o(new Error,t,zl.BAD_REQUEST,void 0,void 0,!0);let r=new IJ(Ql.SYSTEM_SCHEMA_NAME,Ql.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await NJ(r));if(s.length===0)throw _o(new Error,ww.ROLE_NOT_FOUND,zl.NOT_FOUND,void 0,void 0,!0);let n=new yJ(Ql.SYSTEM_SCHEMA_NAME,Ql.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await Cm(n)),o=!1;if(OJ.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw new Error(`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await bJ(c),wm.signalUserChange(new Um(process.pid)),`${s[0].role} successfully deleted`}a(DJ,"dropRole");async function LJ(){return Cm({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(LJ,"listRoles")});var Mw=m((Xae,Lw)=>{"use strict";var MJ=Q(),An=require("joi"),PJ=ve(),Uw=require("moment"),vJ=require("fs-extra"),Lm=require("path"),BJ=require("lodash"),ja=g(),{LOG_LEVELS:ui}=g(),HJ="YYYY-MM-DD hh:mm:ss",qJ=Lm.resolve(__dirname,"../logs");Lw.exports=function(e){return PJ.validateBySchema(e,FJ)};var FJ=An.object({from:An.custom(Dw),until:An.custom(Dw),level:An.valid(ui.NOTIFY,ui.FATAL,ui.ERROR,ui.WARN,ui.INFO,ui.DEBUG,ui.TRACE),order:An.valid("asc","desc"),limit:An.number().min(1),start:An.number().min(0),log_name:An.custom(GJ)});function Dw(e,t){if(Uw(e,Uw.ISO_8601).format(HJ)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(Dw,"validateDatetime");function GJ(e,t){if(BJ.invert(ja.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=MJ.get(ja.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?ja.LOG_NAMES.HDB:e,i=n===ja.LOG_NAMES.INSTALL?Lm.join(qJ,ja.LOG_NAMES.INSTALL):Lm.join(s,n);return vJ.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(GJ,"validateReadLogPath")});var Pm=m((jae,Pw)=>{"use strict";var Jl=g(),xJ=F(),kJ=Q(),VJ=Mw(),Mm=require("path"),$J=require("fs-extra"),{once:YJ}=require("events"),{handleHDBError:KJ,hdb_errors:WJ}=W(),{PACKAGE_ROOT:QJ}=g(),zJ=Mm.join(QJ,"logs"),JJ=1e3;Pw.exports=XJ;async function XJ(e){let t=VJ(e);if(t)throw KJ(t,t.message,WJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=kJ.get(Jl.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?Jl.LOG_NAMES.HDB:e.log_name,n=s===Jl.LOG_NAMES.INSTALL?Mm.join(zJ,Jl.LOG_NAMES.INSTALL):Mm.join(r,s),i=$J.createReadStream(n);i.on("error",A=>{xJ.error(A)});let o=e.level!==void 0,c=o?e.level:void 0,u=e.from!==void 0,l=u?new Date(e.from):void 0,_=e.until!==void 0,d=_?new Date(e.until):void 0,E=e.limit===void 0?JJ:e.limit,f=e.order===void 0?void 0:e.order,h=e.start===void 0?0:e.start,T=h+E,S=0,y=[],O="",H;i.on("data",A=>{let w=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;A=O+A;let G=0,k;for(;(k=w.exec(A))&&!i.destroyed;){H&&(H.message=A.slice(G,k.index),Y(H));let[X,ge,ut]=k,Pi=ut.split("] ["),Ko=Pi[0],Gn=Pi[1];Pi.splice(0,2),H={timestamp:ge,thread:Ko,level:Gn,tags:Pi,message:""},G=k.index+X.length}O=A.slice(G)}),i.on("end",A=>{i.destroyed||H&&(H.message=O.trim(),Y(H))}),i.resume();function Y(A){let w,G,k;switch(!0){case(o&&u&&_):w=new Date(A.timestamp),G=new Date(l),k=new Date(d),A.level===c&&w>=G&&w<=k&&S<h?S++:A.level===c&&w>=G&&w<=k&&(On(A,f,y),S++,S===T&&i.destroy());break;case(o&&u):w=new Date(A.timestamp),G=new Date(l),A.level===c&&w>=G&&S<h?S++:A.level===c&&w>=G&&(On(A,f,y),S++,S===T&&i.destroy());break;case(o&&_):w=new Date(A.timestamp),k=new Date(d),A.level===c&&w<=k&&S<h?S++:A.level===c&&w<=k&&(On(A,f,y),S++,S===T&&i.destroy());break;case(u&&_):w=new Date(A.timestamp),G=new Date(l),k=new Date(d),w>=G&&w<=k&&S<h?S++:w>=G&&w<=k&&(On(A,f,y),S++,S===T&&i.destroy());break;case o:A.level===c&&S<h?S++:A.level===c&&(On(A,f,y),S++,S===T&&i.destroy());break;case u:w=new Date(A.timestamp),G=new Date(l),w>=G&&S<h?S++:w>=G&&S>=h&&(On(A,f,y),S++,S===T&&i.destroy());break;case _:w=new Date(A.timestamp),k=new Date(d),w<=k&&S<h?S++:w<=k&&S>=h&&(On(A,f,y),S++,S===T&&i.destroy());break;default:S<h?S++:(On(A,f,y),S++,S===T&&i.destroy())}}return a(Y,"onLogMessage"),await YJ(i,"close"),y}a(XJ,"readLog");function On(e,t,r){t==="desc"?ZJ(e,r):t==="asc"?jJ(e,r):r.push(e)}a(On,"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 Zl=m((nce,qw)=>{"use strict";var vm=require("joi"),{string:Xl,boolean:vw,date:e2}=vm.types(),t2=ve(),{validateSchemaExists:tce,validateTableExists:rce,validateSchemaName:sce}=ts(),r2=g(),s2=Be(),Bw=Q();Bw.initSync();var n2=Xl.invalid(Bw.get(r2.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(s2.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(),Hw={operation:Xl.valid("add_node","update_node"),node_name:n2,subscriptions:vm.array().items({table:Xl.optional(),schema:Xl.required(),subscribe:vw.required(),publish:vw.required().custom(o2),start_time:e2.iso()}).min(1).required()};function i2(e){return t2.validateBySchema(e,vm.object(Hw))}a(i2,"addUpdateNodeValidator");function o2(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(o2,"checkForFalsy");qw.exports={addUpdateNodeValidator:i2,validation_schema:Hw}});var Gw=m((oce,Fw)=>{var a2=ve(),c2={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};Fw.exports=function(e){return a2.validateObject(e,c2)}});var Hm=m((ace,xw)=>{"use strict";var u2=g().OPERATIONS_ENUM,Bm=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=u2.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};xw.exports=Bm});var Vw=m((uce,kw)=>{"use strict";var l2={OPERATION:"operation",REFRESH:"refresh"},qm=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},Fm=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};kw.exports={JWTTokens:qm,TOKEN_TYPE_ENUM:l2,JWTRSAKeys:Fm}});var rc=m((_ce,Ww)=>{"use strict";var tc=require("jsonwebtoken"),Gm=require("fs-extra"),xm=x(),br=g(),{handleHDBError:Vt,hdb_errors:_2}=W(),{HTTP_STATUS_CODES:$t,AUTHENTICATION_ERROR_MSGS:Yt}=_2,ec=F(),$w=sl(),$m=Or(),d2=Rr().update,E2=Hm(),f2=Fs(),{UserEventMsg:h2}=qr(),Nn=Q();Nn.initSync();var km=require("path"),{JWTTokens:m2,JWTRSAKeys:S2,TOKEN_TYPE_ENUM:jl}=Vw(),p2=Nn.get(br.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?Nn.get(br.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",T2=Nn.get(br.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?Nn.get(br.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",e_="RS256",Vm;Ww.exports={createTokens:R2,validateOperationToken:A2,refreshOperationToken:g2,validateRefreshToken:Kw};async function R2(e){if(xm.isEmpty(e)||typeof e!="object")throw Vt(new Error,Yt.INVALID_AUTH_OBJECT,$t.BAD_REQUEST,void 0,void 0,!0);if(xm.isEmpty(e.username))throw Vt(new Error,Yt.USERNAME_REQUIRED,$t.BAD_REQUEST,void 0,void 0,!0);if(xm.isEmpty(e.password))throw Vt(new Error,Yt.PASSWORD_REQUIRED,$t.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await $m.findAndValidateUser(e.username,e.password),!t)throw Vt(new Error,Yt.INVALID_CREDENTIALS,$t.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw ec.error(E),Vt(new Error,Yt.INVALID_CREDENTIALS,$t.UNAUTHORIZED,void 0,void 0,!0)}let r=await t_(),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 Yw(i,r.private_key,r.passphrase),c=await tc.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:T2,algorithm:e_,subject:jl.REFRESH}),u=$w.hash(c),l=new E2(br.SYSTEM_SCHEMA_NAME,br.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),_,d;try{_=await d2(l)}catch(E){ec.error(E),d=E}if(d!==void 0||_.skipped_hashes.length>0)throw Vt(new Error,Yt.REFRESH_TOKEN_SAVE_FAILED,$t.INTERNAL_SERVER_ERROR);return f2.signalUserChange(new h2(process.pid)),new m2(o,c)}a(R2,"createTokens");async function Yw(e,t,r){return await tc.sign(e,{key:t,passphrase:r},{expiresIn:p2,algorithm:e_,subject:jl.OPERATION})}a(Yw,"signOperationToken");async function t_(){if(Vm===void 0)try{let e=km.join(Nn.getHdbBasePath(),br.LICENSE_KEY_DIR_NAME,br.JWT_ENUM.JWT_PASSPHRASE_NAME),t=km.join(Nn.getHdbBasePath(),br.LICENSE_KEY_DIR_NAME,br.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=km.join(Nn.getHdbBasePath(),br.LICENSE_KEY_DIR_NAME,br.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await Gm.readFile(e)).toString(),n=(await Gm.readFile(t)).toString(),i=(await Gm.readFile(r)).toString();Vm=new S2(i,n,s)}catch(e){throw ec.error(e),Vt(new Error,Yt.NO_ENCRYPTION_KEYS,$t.INTERNAL_SERVER_ERROR)}return Vm}a(t_,"getJWTRSAKeys");async function g2(e){if(!e)throw Vt(new Error,Yt.INVALID_BODY,$t.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Vt(new Error,Yt.REFRESH_TOKEN_REQUIRED,$t.BAD_REQUEST,void 0,void 0,!0);await Kw(e.refresh_token);let t=await t_(),r=await tc.decode(e.refresh_token);return{operation_token:await Yw({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(g2,"refreshOperationToken");async function A2(e){try{let t=await t_(),r=await tc.verify(e,t.public_key,{algorithms:e_,subject:jl.OPERATION});return await $m.findAndValidateUser(r.username,void 0,!1)}catch(t){throw ec.warn(t),t.name&&t.name==="TokenExpiredError"?Vt(new Error,Yt.TOKEN_EXPIRED,$t.FORBIDDEN):Vt(new Error,Yt.INVALID_TOKEN,$t.UNAUTHORIZED)}}a(A2,"validateOperationToken");async function Kw(e){let t;try{let r=await t_(),s=await tc.verify(e,r.public_key,{algorithms:e_,subject:jl.REFRESH});t=await $m.findAndValidateUser(s.username,void 0,!1)}catch(r){throw ec.warn(r),r.name&&r.name==="TokenExpiredError"?Vt(new Error,Yt.TOKEN_EXPIRED,$t.FORBIDDEN):Vt(new Error,Yt.INVALID_TOKEN,$t.UNAUTHORIZED)}if(!$w.validate(t.refresh_token,e))throw Vt(new Error,Yt.INVALID_TOKEN,$t.UNAUTHORIZED);return t}a(Kw,"validateRefreshToken")});var Ym=m((fce,Jw)=>{"use strict";var O2=Gw(),Eo=require("passport"),N2=require("passport-local").Strategy,b2=require("passport-http").BasicStrategy,y2=require("util"),I2=Or(),zw=y2.callbackify(I2.findAndValidateUser),Ece=rr(),w2=g(),Qw=rc();Eo.use(new N2(function(e,t,r){zw(e,t,r)}));Eo.use(new b2(function(e,t,r){zw(e,t,r)}));Eo.serializeUser(function(e,t){t(null,e)});Eo.deserializeUser(function(e,t){t(null,e)});function C2(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":Eo.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===w2.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?Qw.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):Qw.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Eo.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(C2,"authorize");function U2(e,t){let r=O2(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(U2,"checkPermissions");Jw.exports={authorize:C2,checkPermissions:U2}});var fo=m((mce,Xw)=>{"use strict";var Km=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},Wm=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};Xw.exports={Node:Km,NodeSubscription:Wm}});var jw=m((pce,Zw)=>{"use strict";var D2=g().OPERATIONS_ENUM,Qm=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=D2.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};Zw.exports=Qm});var sc=m((Rce,eC)=>{"use strict";var zm=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},Jm=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,this.attributes=c}};eC.exports={RemotePayloadObject:zm,RemotePayloadSubscription:Jm}});var rC=m((Ace,tC)=>{"use strict";var Xm=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}};tC.exports=Xm});var iC=m((Ice,nC)=>{"use strict";var L2=rC(),Nce=xe(),sC=ye(),M2=F(),{getSchemaPath:bce,getTransactionAuditStorePath:yce}=we(),{getDatabases:P2}=(de(),te(Ne));nC.exports=v2;async function v2(e){let t=new L2;try{let r=P2()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await sC.environmentDataSize(schema_path,e.name),o=await sC.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){M2.warn(`unable to stat table dbi due to ${r}`)}return t}a(v2,"lmdbGetTableSize")});var aC=m((Cce,oC)=>{"use strict";var Zm=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}};oC.exports=Zm});var ho=m((Mce,_C)=>{"use strict";var B2=require("fs-extra"),H2=require("path"),Ut=require("systeminformation"),bn=F(),q2=st(),jm=Be(),s_=g(),F2=iC(),lC=Wn(),{getThreadInfo:cC}=rt(),uS=Q();uS.initSync();var G2=aC(),{openEnvironment:Dce}=ye(),{getSchemaPath:Lce}=we(),{database:x2}=(de(),te(Ne)),r_;_C.exports={getHDBProcessInfo:sS,getNetworkInfo:iS,getDiskInfo:nS,getMemoryInfo:rS,getCPUInfo:tS,getTimeInfo:eS,getSystemInformation:oS,systemInformation:k2,getTableSize:aS,getMetrics:cS};function eS(){return Ut.time()}a(eS,"getTimeInfo");async function tS(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:l,..._}=await Ut.cpu();_.cpu_speed=await Ut.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:T,raw_currentload_user:S,cpus:y,...O}=await Ut.currentLoad();return O.cpus=[],y.forEach(H=>{let{raw_load:Y,raw_load_idle:A,raw_load_irq:w,raw_load_nice:G,raw_load_system:k,raw_load_user:X,...ge}=H;O.cpus.push(ge)}),_.current_load=O,_}catch(e){return bn.error(`error in getCPUInfo: ${e}`),{}}}a(tS,"getCPUInfo");async function rS(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Ut.mem();return Object.assign(n,process.memoryUsage())}catch(e){return bn.error(`error in getMemoryInfo: ${e}`),{}}}a(rS,"getMemoryInfo");async function sS(){let e={core:[],clustering:[]};try{let t=await Ut.processes(),r;try{r=Number.parseInt(await B2.readFile(H2.join(uS.get(s_.CONFIG_PARAMS.ROOTPATH),s_.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===s_.NODE_ERROR_CODES.ENOENT)bn.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return bn.error(`error in getHDBProcessInfo: ${t}`),e}}a(sS,"getHDBProcessInfo");async function nS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Ut.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,...l}=await Ut.fsStats();return e.read_write=l,e.size=await Ut.fsSize(),e}catch(t){return bn.error(`error in getDiskInfo: ${t}`),e}}a(nS,"getDiskInfo");async function iS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Ut.networkInterfaceDefault(),e.latency=await Ut.inetChecksite("google.com"),(await Ut.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:l,ieee8021xState:_,carrier_changes:d,...E}=s;e.interfaces.push(E)}),(await Ut.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return bn.error(`error in getNetworkInfo: ${t}`),e}}a(iS,"getNetworkInfo");async function oS(){if(r_!==void 0)return r_;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Ut.osInfo();e=c;let u=await Ut.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,r_=e,r_}catch(t){return bn.error(`error in getSystemInformation: ${t}`),e}}a(oS,"getSystemInformation");async function aS(){let e=[],t=await lC.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await F2(s));return e}a(aS,"getTableSize");async function cS(){let e=await lC.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let o=x2({database:r,table:n}).getStats();s[n]={puts:o.puts,deletes:o.deletes,txns:o.txns,pageFlushes:o.pageFlushes,writes:o.writes,pagesWritten:o.pagesWritten,timeDuringTxns:o.timeDuringTxns,timeStartTxns:o.timeStartTxns,timePageFlushes:o.timePageFlushes,timeSync:o.timeSync}}catch(i){bn.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(cS,"getMetrics");async function uC(){if(uS.get(s_.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await q2.getNATSReferences(),r=await t.streams.info(jm.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(jm.WORK_QUEUE_CONSUMER_NAMES.stream_name,jm.WORK_QUEUE_CONSUMER_NAMES.durable_name),n={ingest:{stream:{...r.state},consumer:{num_ack_pending:s._info.num_ack_pending,num_redelivered:s._info.num_redelivered,num_waiting:s._info.num_waiting,num_pending:s._info.num_pending}}};return r.config?.sources&&(n.ingest.stream.sources=r.config.sources),n}}a(uC,"getNatsStreamInfo");async function k2(e){let t=new G2;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await oS(),t.time=eS(),t.cpu=await tS(),t.memory=await rS(),t.disk=await nS(),t.network=await iS(),t.harperdb_processes=await sS(),t.table_size=await aS(),t.metrics=await cS(),t.threads=await cC(),t.replication=await uC(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await oS();break;case"time":t.time=eS();break;case"cpu":t.cpu=await tS();break;case"memory":t.memory=await rS();break;case"disk":t.disk=await nS();break;case"network":t.network=await iS();break;case"harperdb_processes":t.harperdb_processes=await sS();break;case"table_size":t.table_size=await aS();break;case"database_metrics":case"metrics":t.metrics=await cS();break;case"threads":t.threads=await cC();break;case"replication":t.replication=await uC();break;default:break}return t}a(k2,"systemInformation")});var lS=m((Hce,dC)=>{"use strict";var vce=require("fs-extra"),Bce=F();dC.exports={version:V2,printVersion:Y2,nodeVersion:$2};var yn=$a();function V2(){if(yn)return yn.version}a(V2,"version");function $2(){if(yn&&yn.engines&&yn.engines["preferred-node"])return yn.engines["preferred-node"]}a($2,"nodeVersion");function Y2(){yn&&console.log(`HarperDB Version ${yn.version}`)}a(Y2,"printVersion")});var ks=m((xce,mC)=>{"use strict";var K2=Rr(),_S=x(),W2=require("util"),li=g(),EC=Q();EC.initSync();var Q2=Ym(),fC=Tr(),{Node:Fce,NodeSubscription:Gce}=fo(),z2=ji(),J2=jw(),{RemotePayloadObject:X2,RemotePayloadSubscription:Z2}=sc(),{handleHDBError:j2,hdb_errors:e3}=W(),{HTTP_STATUS_CODES:t3,HDB_ERROR_MSGS:r3}=e3,s3=is(),n3=ho(),i3=lS(),{getDatabases:o3}=(de(),te(Ne)),a3=W2.promisify(Q2.authorize),c3=fC.searchByHash,u3=fC.searchByValue;mC.exports={authHeaderToUser:l3,isEmpty:_3,getNodeRecord:d3,upsertNodeRecord:E3,buildNodePayloads:f3,checkClusteringEnabled:h3,getAllNodeRecords:m3,getSystemInfo:S3,reverseSubscription:hC};async function l3(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await a3(t,null),e}a(l3,"authHeaderToUser");function _3(e){return e==null}a(_3,"isEmpty");async function d3(e){let t=new z2(li.SYSTEM_SCHEMA_NAME,li.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return c3(t)}a(d3,"getNodeRecord");async function E3(e){let t=new J2(li.SYSTEM_SCHEMA_NAME,li.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return K2.upsert(t)}a(E3,"upsertNodeRecord");function hC(e){if(_S.isEmpty(e.subscribe)||_S.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(hC,"reverseSubscription");function f3(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:l}=c,_=_S.getTableHashAttribute(u,l),{subscribe:d,publish:E}=hC(c),f=o3()[u]?.[l],h=new Z2(u,l,_,E,d,c.start_time,f.schemaDefined&&f.attributes);n.push(h)}return new X2(r,t,n,s)}a(f3,"buildNodePayloads");function h3(){if(!EC.get(li.CONFIG_PARAMS.CLUSTERING_ENABLED))throw j2(new Error,r3.CLUSTERING_NOT_ENABLED,t3.BAD_REQUEST,void 0,void 0,!0)}a(h3,"checkClusteringEnabled");async function m3(){let e=new s3(li.SYSTEM_SCHEMA_NAME,li.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await u3(e))}a(m3,"getAllNodeRecords");async function S3(){let e=await n3.getSystemInformation();return{hdb_version:i3.version(),node_version:e.node_version,platform:e.platform}}a(S3,"getSystemInfo")});var dS=m((Vce,NC)=>{"use strict";var n_=st(),SC=x(),pC=Be(),TC=g(),i_=F(),RC=Yl(),p3=Uh(),{RemotePayloadObject:T3}=sc(),{handleHDBError:gC,hdb_errors:R3}=W(),{HTTP_STATUS_CODES:AC}=R3,{NodeSubscription:OC}=fo();NC.exports=g3;async function g3(e,t){let r;try{r=await n_.request(`${t}.${pC.REQUEST_SUFFIX}`,new T3(TC.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),i_.trace("Response from remote describe all request:",r)}catch(o){i_.error(`addNode received error from describe all request to remote node: ${o}`);let c=n_.requestErrorHandler(o,"add_node",t);throw gC(new Error,c,AC.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===pC.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw gC(new Error,o,AC.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:u}=o;if(c===TC.SYSTEM_SCHEMA_NAME){await n_.createLocalTableStream(c,u);let h=new OC(c,u,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let l=SC.doesSchemaExist(c),_=s[c]!==void 0,d=u?SC.doesTableExist(c,u):!0,E=u?s?.[c]?.[u]!==void 0:!0;if(!l&&!_||!d&&!E){n.push(o);continue}if(!l&&_&&(i_.trace(`addNode creating schema: ${c}`),await RC.createSchema({operation:"create_schema",schema:c})),!d&&E){i_.trace(`addNode creating table: ${u} in schema: ${c}`);let h=new p3(c,u,s[c][u].hash_attribute);h.attributes=s[c][u].attributes,await RC.createTable(h)}await n_.createLocalTableStream(c,u);let f=new OC(c,u,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:n}}a(g3,"reviewSubscriptions")});var c_=m((Yce,IC)=>{"use strict";var{handleHDBError:o_,hdb_errors:A3}=W(),{HTTP_STATUS_CODES:a_}=A3,{addUpdateNodeValidator:O3}=Zl(),nc=F(),yC=g(),bC=Be(),N3=x(),ES=st(),ic=ks(),b3=Q(),y3=dS(),{Node:I3,NodeSubscription:w3}=fo(),{broadcast:C3}=rt(),U3="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",D3="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",L3=b3.get(yC.CONFIG_PARAMS.CLUSTERING_NODENAME);IC.exports=M3;async function M3(e,t=!1){nc.trace("addNode called with:",e),ic.checkClusteringEnabled();let r=O3(e);if(r)throw o_(r,r.message,a_.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await ic.getNodeRecord(s);if(!N3.isEmptyOrZeroLength(d))throw o_(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,a_.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await y3(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=U3,o;let c=ic.buildNodePayloads(n,L3,yC.OPERATIONS_ENUM.ADD_NODE,await ic.getSystemInfo());nc.trace("addNode sending remote payload:",c);let u;try{u=await ES.request(`${s}.${bC.REQUEST_SUFFIX}`,c)}catch(d){nc.error(`addNode received error from request: ${d}`);let E=ES.requestErrorHandler(d,"add_node",s);throw o_(new Error,E,a_.INTERNAL_SERVER_ERROR,"error",E)}if(u.status===bC.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw o_(new Error,d,a_.INTERNAL_SERVER_ERROR,"error",d)}nc.trace(u);let l=[];for(let d=0,E=n.length;d<E;d++){let f=n[d];nc.trace("Add node updating work stream for node:",s,"subscriptions:",f),await ES.updateWorkStream(f,s),n[d].start_time===void 0&&delete n[d].start_time,l.push(new w3(f.schema,f.table,f.publish,f.subscribe))}let _=new I3(s,l,u.system_info);return await ic.upsertNodeRecord(_),C3({type:"nats_update"}),i.length>0?o.message=D3:o.message=`Successfully added '${s}' to manifest`,o}a(M3,"addNode")});var hS=m((Wce,UC)=>{"use strict";var{handleHDBError:u_,hdb_errors:P3}=W(),{HTTP_STATUS_CODES:l_}=P3,{addUpdateNodeValidator:v3}=Zl(),oc=F(),CC=g(),wC=Be(),B3=x(),fS=st(),ac=ks(),H3=Q(),{cloneDeep:q3}=require("lodash"),F3=dS(),{NodeSubscription:G3}=fo(),{broadcast:x3}=rt(),k3="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",V3="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",$3=H3.get(CC.CONFIG_PARAMS.CLUSTERING_NODENAME);UC.exports=Y3;async function Y3(e){oc.trace("updateNode called with:",e),ac.checkClusteringEnabled();let t=v3(e);if(t)throw u_(t,t.message,l_.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=q3(await ac.getNodeRecord(r));if(B3.isEmptyOrZeroLength(s))throw u_(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,l_.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await F3(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=k3,o;let c=ac.buildNodePayloads(n,$3,CC.OPERATIONS_ENUM.UPDATE_NODE,await ac.getSystemInfo());oc.trace("updateNode sending remote payload:",c);let u;try{u=await fS.request(`${r}.${wC.REQUEST_SUFFIX}`,c)}catch(l){oc.error(`updateNode received error from request: ${l}`);let _=fS.requestErrorHandler(l,"update_node",r);throw u_(new Error,_,l_.INTERNAL_SERVER_ERROR,"error",_)}if(u.status===wC.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${u.message}`;throw u_(new Error,l,l_.INTERNAL_SERVER_ERROR,"error",l)}oc.trace(u);for(let l=0,_=n.length;l<_;l++){let d=n[l];oc.trace(`updateNode updating work stream for node: ${r} subscription:`,d),await fS.updateWorkStream(d,r),n[l].start_time===void 0&&delete n[l].start_time}return await K3(s[0],n,u.system_info),i.length>0?o.message=V3:o.message=`Successfully updated '${r}'`,o}a(Y3,"updateNode");async function K3(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,l=e.subscriptions.length;u<l;u++){let _=s.subscriptions[u];if(_.schema===o.schema&&_.table===o.table){_.publish=o.publish,_.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new G3(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await ac.upsertNodeRecord(s),x3({type:"nats_update"})}a(K3,"updateNodeTable")});var vC=m((zce,PC)=>{"use strict";var MC=require("joi"),{string:DC}=MC.types(),W3=ve(),LC=g(),Q3=Q(),z3=Be();PC.exports=J3;function J3(e){let t=DC.invalid(Q3.get(LC.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(z3.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=MC.object({operation:DC.valid(LC.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return W3.validateBySchema(e,r)}a(J3,"removeNodeValidator")});var d_=m((Xce,xC)=>{"use strict";var{handleHDBError:BC,hdb_errors:X3}=W(),{HTTP_STATUS_CODES:HC}=X3,Z3=vC(),cc=F(),qC=ks(),j3=x(),__=g(),FC=Be(),GC=st(),e4=Q(),{RemotePayloadObject:t4}=sc(),{NodeSubscription:r4}=fo(),s4=Ba(),n4=Zn(),{broadcast:i4}=rt(),o4=e4.get(__.CONFIG_PARAMS.CLUSTERING_NODENAME);xC.exports=a4;async function a4(e){cc.trace("removeNode called with:",e),qC.checkClusteringEnabled();let t=Z3(e);if(t)throw BC(t,t.message,HC.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await qC.getNodeRecord(r);if(j3.isEmptyOrZeroLength(s))throw BC(new Error,`Node '${r}' was not found.`,HC.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new t4(__.OPERATIONS_ENUM.REMOVE_NODE,o4,[]),i,o=!1;try{i=await GC.request(`${r}.${FC.REQUEST_SUFFIX}`,n),cc.trace("Remove node reply from remote node:",r,i)}catch(u){cc.error("removeNode received error from request:",u),o=!0}for(let u=0,l=s.subscriptions.length;u<l;u++){let _=s.subscriptions[u];cc.trace(`Remove node removing subscription: ${_.schema}.${_.table} for node: ${r}`);let d=new r4(_.schema,_.table,!1,!1);await GC.updateWorkStream(d,r)}let c=new s4(__.SYSTEM_SCHEMA_NAME,__.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await n4.deleteRecord(c),i4({type:"nats_update"}),i?.status===FC.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(cc.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(a4,"removeNode")});var $C=m((jce,VC)=>{"use strict";var kC=require("joi"),{string:c4,array:u4}=kC.types(),l4=ve(),_4=Zl();VC.exports=d4;function d4(e){let t=kC.object({operation:c4.valid("configure_cluster").required(),connections:u4.items(_4.validation_schema).required()});return l4.validateBySchema(e,t)}a(d4,"configureClusterValidator")});var mS=m((tue,zC)=>{"use strict";var E4=g(),E_=F(),f4=x(),h4=d_(),m4=c_(),YC=ks(),S4=$C(),{handleHDBError:KC,hdb_errors:p4}=W(),{HTTP_STATUS_CODES:WC}=p4,T4="Configure cluster complete.",R4="Failed to configure the cluster. Check the logs for more details.",g4="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";zC.exports=A4;async function A4(e){E_.trace("configure cluster called with:",e),YC.checkClusteringEnabled();let t=S4(e);if(t)throw KC(t,t.message,WC.BAD_REQUEST,void 0,void 0,!0);let r=await YC.getAllNodeRecords(),s=[];for(let E=0,f=r.length;E<f;E++)s.push(QC(h4,{operation:E4.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[E].name},r[E].name));let n=await Promise.allSettled(s);E_.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let E=0;E<o;E++){let f=e.connections[E];i.push(QC(m4,f,f.node_name))}let c=await Promise.allSettled(i);E_.trace("All results from configure_cluster add node:",c);let u=[],l=[],_=!1,d=n.concat(c);for(let E=0,f=d.length;E<f;E++){let h=d[E];h.status==="rejected"&&(E_.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(_=!0);let T=h?.value?.result;typeof T=="string"&&T.includes("Successfully removed")||h.status==="rejected"||l.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(f4.isEmptyOrZeroLength(u))return{message:T4,connections:l};if(_)return{message:g4,failed_nodes:u,connections:l};throw KC(new Error,R4,WC.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(A4,"configureCluster");async function QC(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(QC,"functionWrapper")});var XC=m((sue,JC)=>{"use strict";var f_=require("joi"),O4=ve(),{validateSchemaExists:N4,validateTableExists:b4,validateSchemaName:y4}=ts(),I4=f_.object({operation:f_.string().valid("purge_stream"),schema:f_.string().custom(N4).custom(y4).required(),table:f_.string().custom(b4).required()});function w4(e){return O4.validateBySchema(e,I4)}a(w4,"purgeStreamValidator");JC.exports=w4});var SS=m((iue,ZC)=>{"use strict";var{handleHDBError:C4,hdb_errors:U4}=W(),{HTTP_STATUS_CODES:D4}=U4,L4=XC(),M4=st(),P4=ks();ZC.exports=v4;async function v4(e){let t=L4(e);if(t)throw C4(t,t.message,D4.BAD_REQUEST,void 0,void 0,!0);P4.checkClusteringEnabled();let{schema:r,table:s}=e;return await M4.purgeTableStream(r,s),`Successfully purged table '${r}.${s}'`}a(v4,"purgeStream")});var RS=m((aue,nU)=>{"use strict";var TS=ks(),B4=st(),tU=Q(),h_=g(),_i=Be(),H4=x(),pS=F(),{RemotePayloadObject:q4}=sc(),{ErrorCode:jC}=require("nats"),eU=tU.get(h_.CONFIG_PARAMS.CLUSTERING_ENABLED),rU=tU.get(h_.CONFIG_PARAMS.CLUSTERING_NODENAME);nU.exports={clusterStatus:F4,buildNodeStatus:sU};async function F4(){let e={node_name:rU,is_enabled:eU,connections:[]};if(!eU)return e;let t=await TS.getAllNodeRecords();if(H4.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(sU(t[s],e.connections));return await Promise.allSettled(r),e}a(F4,"clusterStatus");async function sU(e,t){let r=e.name,s=new q4(h_.OPERATIONS_ENUM.CLUSTER_STATUS,rU,void 0,await TS.getSystemInfo()),n,i,o=_i.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await B4.request(_i.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===_i.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=_i.CLUSTER_STATUS_STATUSES.CLOSED,pS.error(`Error getting node status from ${r} `,n))}catch(u){pS.warn(`Error getting node status from ${r}`,u),u.code===jC.NoResponders?o=_i.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===jC.Timeout?o=_i.CLUSTER_STATUS_STATUSES.TIMEOUT:o=_i.CLUSTER_STATUS_STATUSES.CLOSED}let c=new G4(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!==h_.PRE_4_0_0_VERSION&&await TS.upsertNodeRecord(u)}catch(u){pS.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(sU,"buildNodeStatus");function G4(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(G4,"NodeStatusObject")});var AS=m((uue,iU)=>{"use strict";var{handleHDBError:x4,hdb_errors:k4}=W(),{HTTP_STATUS_CODES:V4}=k4,$4=st(),Y4=ks(),gS=x(),m_=require("joi"),K4=ve(),W4=2e3,Q4=m_.object({timeout:m_.number().min(1),connected_nodes:m_.boolean(),routes:m_.boolean()});iU.exports=z4;async function z4(e){Y4.checkClusteringEnabled();let t=K4.validateBySchema(e,Q4);if(t)throw x4(t,t.message,V4.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||gS.autoCastBoolean(s),o=n===void 0||gS.autoCastBoolean(n),c={nodes:[]},u=await $4.getServerList(r??W4),l={};if(i)for(let _=0,d=u.length;_<d;_++){let E=u[_].statsz;E&&(l[u[_].server.name]=E.routes)}for(let _=0,d=u.length;_<d;_++){if(u[_].statsz)continue;let E=u[_].server,f=u[_].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[_].response_time};i&&(h.connected_nodes=l[E.name]?l[E.name].map(T=>T.name.slice(0,-4)):[]),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(T=>({host:T.split(":")[0],port:gS.autoCast(T.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(z4,"clusterNetwork")});var uU=m((_ue,cU)=>{"use strict";var OS=require("joi"),oU=ve(),{route_constraints:aU}=Wf();cU.exports={setRoutesValidator:J4,deleteRoutesValidator:X4};function J4(e){let t=OS.object({server:OS.valid("hub","leaf").required(),routes:aU.required()});return oU.validateBySchema(e,t)}a(J4,"setRoutesValidator");function X4(e){let t=OS.object({routes:aU.required()});return oU.validateBySchema(e,t)}a(X4,"deleteRoutesValidator")});var bS=m((Eue,EU)=>{"use strict";var di=Ar(),NS=x(),S_=g(),lU=uU(),{handleHDBError:_U,hdb_errors:Z4}=W(),{HTTP_STATUS_CODES:dU}=Z4,j4="cluster routes successfully set",eX="cluster routes successfully deleted";EU.exports={setRoutes:tX,getRoutes:rX,deleteRoutes:sX};function tX(e){let t=lU.setRoutesValidator(e);if(t)throw _U(t,t.message,dU.BAD_REQUEST,void 0,void 0,!0);let r=di.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 l=e.routes[c];l.port=NS.autoCast(l.port);let _=s.some(E=>E.host===l.host&&E.port===l.port),d=n.some(E=>E.host===l.host&&E.port===l.port);_||d?i.push(l):(s.push(l),o.push(l))}return e.server==="hub"?di.updateConfigValue(S_.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):di.updateConfigValue(S_.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:j4,set:o,skipped:i}}a(tX,"setRoutes");function rX(){let e=di.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(rX,"getRoutes");function sX(e){let t=lU.deleteRoutesValidator(e);if(t)throw _U(t,t.message,dU.BAD_REQUEST,void 0,void 0,!0);let r=di.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let l=0,_=e.routes.length;l<_;l++){let d=e.routes[l],E=!1;for(let f=0,h=s.length;f<h;f++){let T=s[f];if(d.host===T.host&&d.port===T.port){s.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,T=n.length;h<T;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(s=NS.isEmptyOrZeroLength(s)?null:s,di.updateConfigValue(S_.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=NS.isEmptyOrZeroLength(n)?null:n,di.updateConfigValue(S_.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:eX,deleted:i,skipped:o}}a(sX,"deleteRoutes")});var hU=m((hue,fU)=>{"use strict";var uc=require("alasql"),Ei=require("recursive-iterator"),Vr=F(),nX=x(),lc=g(),yS=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,oX(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=>lc.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=>!lc.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][lc.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=iX(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(l=>({attribute_name:l.attribute}));let u=this.affected_attributes.get(i).get(o).filter(l=>!lc.SEARCH_WILDCARDS.includes(l));c.forEach(({attribute_name:l})=>{let _=new uc.yy.Column({columnid:l});n.tableid&&(_.tableid=n.tableid),this.ast.columns.push(_),u.includes(l)||u.push(l)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function iX(e){return e.filter(t=>t[lc.PERMS_CRUD_ENUM.READ])}a(iX,"filterReadRestrictedAttrs");function oX(e,t,r,s,n){aX(e,t,r,s,n)}a(oX,"interpretAST");function _c(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(_c,"addSchemaTableToMap");function aX(e,t,r,s,n){if(!e){Vr.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof uc.yy.Insert?_X(e,t,r):e instanceof uc.yy.Select?cX(e,t,r,s,n):e instanceof uc.yy.Update?uX(e,t,r):e instanceof uc.yy.Delete?lX(e,t,r):Vr.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(aX,"getRecordAttributesAST");function cX(e,t,r,s,n){if(!e){Vr.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(nX.isEmptyOrZeroLength(i)){Vr.error("No schema specified");return}e.from.forEach(c=>{_c(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),_c(c.table,t,r,s,n)});let o=new Ei(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,l=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(l).has(u))if(r.has(u))u=r.get(u);else{Vr.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(c.columnid)<0&&t.get(l).get(u).push(c.columnid)}if(e.where){let c=new Ei(e.where),u=e.from[0].tableid;for(let{node:l}of c)if(l&&l.columnid){let _=l.tableid?l.tableid:u;if(!t.get(i).has(_))if(r.has(_))_=r.get(_);else{Vr.info(`table specified as ${_} not found.`);continue}t.get(i).get(_).indexOf(l.columnid)<0&&t.get(i).get(_).push(l.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new Ei(c.on);for(let{node:l}of u)if(l&&l.columnid){let _=l.tableid,d=n.get(_);if(!t.get(d).has(_))if(r.has(_))_=r.get(_);else{Vr.info(`table specified as ${_} not found.`);continue}t.get(d).get(_).indexOf(l.columnid)<0&&t.get(d).get(_).push(l.columnid)}}),e.order){let c=new Ei(e.order);for(let{node:u}of c)if(u&&u.columnid){let l=u.tableid,_=s.has(l)?s.get(l):i;if(l||(l=e.from[0].tableid),!t.get(_).has(l))if(r.has(l))l=r.get(l);else{Vr.info(`table specified as ${l} not found.`);return}t.get(_).get(l).indexOf(u.columnid)<0&&t.get(_).get(l).push(u.columnid)}}}a(cX,"getSelectAttributes");function uX(e,t,r){if(!e){Vr.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new Ei(e.columns),n=e.table.databaseid;_c(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&IS(e.table.tableid,n,i.columnid,t,r)}a(uX,"getUpdateAttributes");function lX(e,t,r){if(!e){Vr.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new Ei(e.where),n=e.table.databaseid;_c(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&IS(e.table.tableid,n,i.columnid,t,r)}a(lX,"getDeleteAttributes");function _X(e,t,r){if(!e){Vr.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new Ei(e.columns),n=e.into.databaseid;_c(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&IS(e.into.tableid,n,i.columnid,t,r)}a(_X,"getInsertAttributes");function IS(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(IS,"pushAttribute");fU.exports=yS});var US=m((Sue,TU)=>{var p_=ya(),mU=require("chalk"),lr=F(),SU=require("prompt"),{promisify:dX}=require("util"),wS=g(),EX=require("fs-extra"),fX=require("path"),hX=x(),mX=lS(),pU=Q();pU.initSync();var SX=require("moment"),pX=dX(SU.get),TX=fX.join(pU.getHdbBasePath(),wS.LICENSE_KEY_DIR_NAME,wS.LICENSE_FILE_NAME,wS.LICENSE_FILE_NAME);TU.exports={getFingerprint:gX,setLicense:RX,parseLicense:CS,register:AX,getRegistrationInfo:NX};async function RX(e){if(e&&e.key&&e.company){try{lr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await CS(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw lr.error(r),lr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(RX,"setLicense");async function gX(){let e={};try{e=await p_.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw lr.error(r),lr.error(t),new Error(r)}return e}a(gX,"getFingerprint");async function CS(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");lr.info("Validating license input...");let r=p_.validateLicense(e,t);if(lr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(lr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(lr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{lr.info("writing license to disk"),await EX.writeFile(TX,JSON.stringify({license_key:e,company:t}))}catch(s){throw lr.error("Failed to write License"),s}return"Registration successful."}a(CS,"parseLicense");async function AX(){let e=await OX();return CS(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(AX,"register");async function OX(){let e=await p_.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:mU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:mU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{SU.start()}catch(s){lr.error(s)}let r;try{r=await pX(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(OX,"promptForRegistration");async function NX(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await p_.getLicense()}catch(r){throw lr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(hX.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=mX.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=SX.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(NX,"getRegistrationInfo")});var gU=m((Tue,RU)=>{"use strict";var bX=Be(),DS=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,l,_,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+bX.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:l,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:_,port:d,routes:E,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};RU.exports=DS});var NU=m((gue,OU)=>{"use strict";var AU=Be(),LS=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+AU.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+AU.SERVER_SUFFIX.LEAF},this.tls={cert_file:l,key_file:_,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"}};OU.exports=LS});var yU=m((Oue,bU)=>{"use strict";var MS=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};bU.exports=MS});var wU=m((bue,IU)=>{"use strict";var yX=Be(),PS=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+yX.SERVER_SUFFIX.ADMIN,this.password=r}};IU.exports=PS});var HS=m((Iue,DU)=>{"use strict";var dc=require("path"),A_=require("fs-extra"),IX=gU(),wX=NU(),CX=yU(),UX=wU(),vS=Or(),mo=x(),Kt=Ar(),g_=g(),T_=Be(),{CONFIG_PARAMS:ze}=g_,fc=F(),O_=Q(),CU=Ps(),BS=st(),Ec="clustering",DX=1e4,UU=5;DU.exports={generateNatsConfig:LX,removeNatsConfig:MX};async function LX(e=!1,t=void 0){O_.initSync();let r=O_.get(ze.ROOTPATH),s=dc.join(r,Ec,T_.PID_FILES.HUB),n=dc.join(r,Ec,T_.PID_FILES.LEAF),i=Kt.getConfigFromFile(ze.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=dc.join(r,Ec,T_.NATS_CONFIG_FILES.HUB_SERVER),c=dc.join(r,Ec,T_.NATS_CONFIG_FILES.LEAF_SERVER),u=Kt.getConfigFromFile(ze.CLUSTERING_TLS_CERTIFICATE),l=Kt.getConfigFromFile(ze.CLUSTERING_TLS_PRIVATEKEY),_=Kt.getConfigFromFile(ze.CLUSTERING_TLS_CERT_AUTH),d=Kt.getConfigFromFile(ze.CLUSTERING_TLS_INSECURE),E=Kt.getConfigFromFile(ze.CLUSTERING_TLS_VERIFY),f=Kt.getConfigFromFile(ze.CLUSTERING_NODENAME),h=Kt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await BS.checkNATSServerInstalled()||N_("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let T=await vS.listUsers(),S=Kt.getConfigFromFile(ze.CLUSTERING_USER),y=await vS.getClusterUser();(mo.isEmpty(y)||y.active!==!0)&&N_(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await R_(ze.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await R_(ze.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await R_(ze.CLUSTERING_HUBSERVER_NETWORK_PORT),await R_(ze.CLUSTERING_LEAFSERVER_NETWORK_PORT));let O=[],H=[];for(let[ge,ut]of T.entries())ut.role.role===g_.ROLE_TYPES_ENUM.CLUSTER_USER&&ut.active&&(O.push(new UX(ut.username,CU.decrypt(ut.hash))),H.push(new CX(ut.username,CU.decrypt(ut.hash))));let Y=[],{hub_routes:A}=Kt.getClusteringRoutes();if(!mo.isEmptyOrZeroLength(A))for(let ge of A)Y.push(`tls://${y.sys_name_encoded}:${y.uri_encoded_d_hash}@${ge.host}:${ge.port}`);let w=new IX(Kt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_NETWORK_PORT),f,s,u,l,_,d,E,h,Kt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_CLUSTER_NAME),Kt.getConfigFromFile(ze.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),Y,O,H);_==null&&(delete w.tls.ca_file,delete w.leafnodes.tls.ca_file),t=mo.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===g_.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await A_.writeJson(o,w),fc.trace(`Hub server config written to ${o}`));let G=`tls://${y.sys_name_encoded}:${y.uri_encoded_d_hash}@0.0.0.0:${h}`,k=`tls://${y.uri_encoded_name}:${y.uri_encoded_d_hash}@0.0.0.0:${h}`,X=new wX(Kt.getConfigFromFile(ze.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,n,i,[G],[k],O,H,u,l,_,d);_==null&&delete X.tls.ca_file,(t===void 0||t===g_.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await A_.writeJson(c,X),fc.trace(`Leaf server config written to ${c}`))}a(LX,"generateNatsConfig");async function R_(e){let t=O_.get(e);return mo.isEmpty(t)&&N_(`port undefined for '${e}'`),await mo.isPortTaken(t)&&N_(`'${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(R_,"isPortAvailable");function N_(e){let t=`Error generating clustering config: ${e}`;fc.error(t),console.error(t),process.exit(1)}a(N_,"generateNatsConfigError");async function MX(e){let{port:t,config_file:r}=BS.getServerConfig(e),{username:s,decrypt_hash:n}=await vS.getClusterUser(),i=0,o=500;for(;i<UU;){try{let l=await BS.createConnection(t,s,n,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){fc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=UU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check the ${e} log for further details.`);await mo.async_set_timeout(o*i)}let c="0".repeat(DX),u=dc.join(O_.get(ze.ROOTPATH),Ec,r);await A_.writeFile(u,c),await A_.remove(u),fc.notify(e,"started.")}a(MX,"removeNatsConfig")});var HU=m((Cue,BU)=>{"use strict";var _r=Q(),PX=ya(),ae=g(),hc=Be(),Vs=require("path"),{PACKAGE_ROOT:y_}=g(),LU=Q(),b_=x(),So="/dev/null",vX=Vs.join(y_,"launchServiceScripts"),MU=Vs.join(y_,"utility/scripts"),BX=Vs.join(MU,ae.HDB_RESTART_SCRIPT),PU=Vs.resolve(y_,"dependencies",`${process.platform}-${process.arch}`,hc.NATS_BINARY_NAME);function vU(){let t=PX.licenseSearch().ram_allocation||ae.RAM_ALLOCATION_ENUM.DEFAULT,r=ae.MEM_SETTING_KEY+t,s={[ae.PROCESS_NAME_ENV_PROP]:ae.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return b_.noBootFile()&&(s[ae.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=b_.getEnvCliRootPath()),{name:ae.PROCESS_DESCRIPTORS.HDB,script:ae.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:y_}}a(vU,"generateMainServerConfig");var HX=9930;function qX(){_r.initSync(!0);let e=_r.get(ae.CONFIG_PARAMS.ROOTPATH),t=Vs.join(e,"clustering",hc.NATS_CONFIG_FILES.HUB_SERVER),r=Vs.join(_r.get(ae.HDB_SETTINGS_NAMES.LOG_PATH_KEY),ae.LOG_NAMES.HDB),s=LU.get(ae.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=hc.LOG_LEVEL_FLAGS[_r.get(ae.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:ae.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==HX?"-"+s:""),script:PU,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[ae.PROCESS_NAME_ENV_PROP]:ae.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return _r.get(ae.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=So,i.error_file=So),i}a(qX,"generateNatsHubServerConfig");var FX=9940;function GX(){_r.initSync(!0);let e=_r.get(ae.CONFIG_PARAMS.ROOTPATH),t=Vs.join(e,"clustering",hc.NATS_CONFIG_FILES.LEAF_SERVER),r=Vs.join(_r.get(ae.HDB_SETTINGS_NAMES.LOG_PATH_KEY),ae.LOG_NAMES.HDB),s=LU.get(ae.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=hc.LOG_LEVEL_FLAGS[_r.get(ae.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:ae.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==FX?"-"+s:""),script:PU,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[ae.PROCESS_NAME_ENV_PROP]:ae.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return _r.get(ae.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=So,i.error_file=So),i}a(GX,"generateNatsLeafServerConfig");function xX(){_r.initSync();let e=Vs.join(_r.get(ae.CONFIG_PARAMS.LOGGING_ROOT),ae.LOG_NAMES.HDB),t={name:ae.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:ae.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[ae.PROCESS_NAME_ENV_PROP]:ae.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:vX,autorestart:!1};return _r.get(ae.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=So,t.error_file=So),t}a(xX,"generateClusteringUpgradeV4ServiceConfig");function kX(){let e={[ae.PROCESS_NAME_ENV_PROP]:ae.PROCESS_DESCRIPTORS.RESTART_HDB};return b_.noBootFile()&&(e[ae.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=b_.getEnvCliRootPath()),{...{name:ae.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:MU},script:BX}}a(kX,"generateRestart");function VX(){return{apps:[vU()]}}a(VX,"generateAllServiceConfigs");BU.exports={generateAllServiceConfigs:VX,generateMainServerConfig:vU,generateRestart:kX,generateNatsHubServerConfig:qX,generateNatsLeafServerConfig:GX,generateClusteringUpgradeV4ServiceConfig:xX}});var ZU=m((Bue,XU)=>{"use strict";var Re=g(),$X=x(),mc=HS(),Sc=st(),ls=Be(),In=HU(),I_=Q(),$s=F(),YX=ks(),{startWorker:qU,onMessageFromWorkers:KX}=rt(),WX=ho(),QX=require("util"),GU=require("child_process"),{execFile:zX}=GU,Due=QX.promisify(GU.exec),Lue=require("systeminformation"),fe;XU.exports={enterPM2Mode:JX,start:fi,stop:qS,reload:xU,restart:kU,list:FS,describe:$U,connect:Ys,kill:tZ,startAllServices:rZ,startService:GS,getUniqueServicesList:YU,restartAllServices:sZ,isServiceRegistered:KU,reloadStopStart:WU,restartHdb:VU,deleteProcess:jX,startClusteringProcesses:zU,startClusteringThreads:JU,isHdbRestartRunning:eZ,isClusteringRunning:iZ,stopClustering:nZ,reloadClustering:oZ};var{PACKAGE_ROOT:Mue}=g(),Pue=g(),{loggerWithTag:vue}=$s,pc=!1;KX(e=>{e.type==="restart"&&I_.initSync(!0)});function JX(){pc=!0}a(JX,"enterPM2Mode");function Ys(){return fe||(fe=require("pm2")),new Promise((e,t)=>{fe.connect((r,s)=>{$s.setupConsoleLogging(),r&&t(r),e(s)})})}a(Ys,"connect");var Wt,XX=10,FU;function fi(e){if(pc)return ZX(e);let t=zX(e.script,e.args.split(" "),e);t.name=e.name,t.on("exit",n=>{let i=Wt.indexOf(t);i>-1&&Wt.splice(i,1),!FU&&n>0&&(e.restarts=(e.restarts||0)+1,e.restarts<XX&&fi(e))});let r={serviceName:e.name.replace(/ /g,"-")};function s(n){let i=I_.get(Re.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),o=/\[\d+][^\[]+\[(\w+)]/g,c,u=0,l;for(;c=o.exec(n);){if(c.index&&ls.LOG_LEVEL_HIERARCHY[i]>=ls.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===ls.LOG_LEVELS.ERR||l===ls.LOG_LEVELS.WRN?$s.OUTPUTS.STDERR:$s.OUTPUTS.STDOUT;$s.logCustomLevel(l||"info",E,r,n.slice(u,c.index).trim())}let[_,d]=c;u=c.index+_.length,l=ls.LOG_LEVELS[d]}if(ls.LOG_LEVEL_HIERARCHY[i]>=ls.LOG_LEVEL_HIERARCHY[l||"info"]){let _=l===ls.LOG_LEVELS.ERR||l===ls.LOG_LEVELS.WRN?$s.OUTPUTS.STDERR:$s.OUTPUTS.STDOUT;$s.logCustomLevel(l||"info",_,r,n.slice(u).trim())}}if(a(s,"extractMessages"),t.stdout.on("data",s),t.stderr.on("data",s),t.unref(),!Wt){Wt=[];let n=a(()=>{FU=!0,Wt&&(Wt.map(i=>i.kill()),process.exit(0))},"kill_children");process.on("exit",n),process.on("SIGINT",n),process.on("SIGQUIT",n),process.on("SIGTERM",n)}Wt.push(t)}a(fi,"start");function ZX(e){return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.start(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(ZX,"startWithPM2");function qS(e){if(!pc){for(let t of Wt||[])t.name===e&&(Wt.splice(Wt.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.stop(e,async(s,n)=>{s&&(fe.disconnect(),r(s)),fe.delete(e,(i,o)=>{i&&(fe.disconnect(),r(s)),fe.disconnect(),t(o)})})})}a(qS,"stop");function xU(e){return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.reload(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(xU,"reload");function kU(e){if(!pc)for(let t of Wt||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.restart(e,(s,n)=>{fe.disconnect(),t(n)})})}a(kU,"restart");function jX(e){return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.delete(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(jX,"deleteProcess");async function VU(){await fi(In.generateRestart())}a(VU,"restartHdb");async function eZ(){let e=await FS();for(let t in e)if(e[t].name===Re.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(eZ,"isHdbRestartRunning");function FS(){return new Promise(async(e,t)=>{try{await Ys()}catch(r){t(r)}fe.list((r,s)=>{r&&(fe.disconnect(),t(r)),fe.disconnect(),e(s)})})}a(FS,"list");function $U(e){return new Promise(async(t,r)=>{try{await Ys()}catch(s){r(s)}fe.describe(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a($U,"describe");function tZ(){if(!pc){for(let e of Wt||[])e.kill();Wt=[];return}return new Promise(async(e,t)=>{try{await Ys()}catch(r){t(r)}fe.killDaemon((r,s)=>{r&&(fe.disconnect(),t(r)),fe.disconnect(),e(s)})})}a(tZ,"kill");async function rZ(){try{await zU(),await JU(),await fi(In.generateAllServiceConfigs())}catch(e){throw fe.disconnect(),e}}a(rZ,"startAllServices");async function GS(e){try{let t;switch(e=e.toLowerCase(),e){case Re.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=In.generateMainServerConfig();break;case Re.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=In.generateNatsIngestServiceConfig();break;case Re.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=In.generateNatsReplyServiceConfig();break;case Re.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=In.generateNatsHubServerConfig(),await fi(t),await mc.removeNatsConfig(e);return;case Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=In.generateNatsLeafServerConfig(),await fi(t),await mc.removeNatsConfig(e);return;case Re.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=In.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await fi(t)}catch(t){throw fe.disconnect(),t}}a(GS,"startService");async function YU(){try{let e=await FS(),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 fe.disconnect(),e}}a(YU,"getUniqueServicesList");async function sZ(e=[]){try{let t=!1,r=await YU();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===Re.PROCESS_DESCRIPTORS.HDB?t=!0:await kU(o))}t&&await WU(Re.PROCESS_DESCRIPTORS.HDB)}catch(t){throw fe.disconnect(),t}}a(sZ,"restartAllServices");async function KU(e){if(Wt?.find(r=>r.name===e))return!0;let t=await WX.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(KU,"isServiceRegistered");async function WU(e){let t=e===Re.PROCESS_DESCRIPTORS.HDB?I_.get(Re.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):I_.get(Re.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await $U(e),s=$X.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await qS(e),await GS(e)):e===Re.PROCESS_DESCRIPTORS.HDB?await VU():await xU(e)}a(WU,"reloadStopStart");var QU;async function zU(){for(let e in Re.CLUSTERING_PROCESSES){let t=Re.CLUSTERING_PROCESSES[e];await GS(t)}}a(zU,"startClusteringProcesses");async function JU(){QU=qU(Re.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Re.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Sc.createWorkQueueStream(ls.WORK_QUEUE_CONSUMER_NAMES),await Sc.updateIngestStreamConsumer(),await Sc.updateLocalStreams();let e=await YX.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Re.PRE_4_0_0_VERSION){$s.info("Starting clustering upgrade 4.0.0 process"),qU(Re.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(JU,"startClusteringThreads");async function nZ(){for(let e in Re.CLUSTERING_PROCESSES)if(e!==Re.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Re.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await QU.terminate();else{let t=Re.CLUSTERING_PROCESSES[e];await qS(t)}}a(nZ,"stopClustering");async function iZ(){for(let e in Re.CLUSTERING_PROCESSES){let t=Re.CLUSTERING_PROCESSES[e];if(await KU(t)===!1)return!1}return!0}a(iZ,"isClusteringRunning");async function oZ(){await mc.generateNatsConfig(!0),await Sc.reloadNATSHub(),await Sc.reloadNATSLeaf(),await mc.removeNatsConfig(Re.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await mc.removeNatsConfig(Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(oZ,"reloadClustering")});var WS=m((que,nD)=>{"use strict";var aZ=require("minimist"),{isMainThread:VS,parentPort:tD}=require("worker_threads"),He=g(),{PROCESS_DESCRIPTORS_VALIDATE:Tc}=He,_s=F(),$S=x(),w_=HS(),po=st(),xS=Be(),rD=Ar(),ds=ZU(),jU=ho(),cZ=AE(),{restartWorkers:C_,onMessageByType:uZ}=rt(),{handleHDBError:lZ,hdb_errors:_Z}=W(),{HTTP_STATUS_CODES:dZ}=_Z,U_=Q();U_.initSync();var Rc=`Restarting HarperDB. This may take up to ${He.RESTART_TIMEOUT_MS/1e3} seconds.`,EZ="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",eD="Clustering is not enabled so cannot be restarted",fZ="Invalid service",hi,$r;nD.exports={restart:sD,restartService:YS};VS&&uZ(He.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?YS({service:e.workerType}):sD({operation:"restart"})});async function sD(e){$r=Object.keys(e).length===0,hi=await ds.isServiceRegistered(He.HDB_PROC_DESCRIPTOR);let t=aZ(process.argv);if(t.service){await YS(t);return}if($r&&!hi){console.error(EZ);return}if($r&&console.log(Rc),hi){ds.enterPM2Mode(),_s.notify(Rc);let r=cZ(Object.keys(He.CONFIG_PARAM_MAP),!0);return $S.isEmptyOrZeroLength(Object.keys(r))||rD.updateConfigValue(void 0,void 0,r,!0,!0),mZ(),Rc}return VS?(_s.notify(Rc),await KS(),setTimeout(()=>{C_()},50)):tD.postMessage({type:He.ITC_EVENT_TYPES.RESTART}),Rc}a(sD,"restart");async function YS(e){let{service:t}=e;if(He.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw lZ(new Error,fZ,dZ.BAD_REQUEST,void 0,void 0,!0);if(hi=await ds.isServiceRegistered(He.HDB_PROC_DESCRIPTOR),!VS)return tD.postMessage({type:He.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Tc.clustering:if(!U_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=eD;break}$r&&console.log("Restarting clustering"),_s.notify("Restarting clustering"),await KS();break;case Tc.clustering_config:case Tc["clustering config"]:if(!U_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=eD;break}$r&&console.log("Restarting clustering_config"),_s.notify("Restarting clustering_config"),await ds.reloadClustering();break;case"custom_functions":case"custom functions":case Tc.harperdb:case Tc.http_workers:if($r&&!hi){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}$r&&console.log("Restarting http_workers"),_s.notify("Restarting http_workers"),hi?await ds.restart(He.HDB_PROC_DESCRIPTOR):setTimeout(()=>{C_("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(_s.error(r),$r&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(YS,"restartService");async function hZ(){await po.publishToStream(`${xS.SUBJECT_PREFIXES.TXN}.${xS.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,xS.WORK_QUEUE_CONSUMER_NAMES.stream_name,po.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(hZ,"postDummyNatsMsg");async function mZ(){await KS(),await ds.restart(He.HDB_PROC_DESCRIPTOR),await $S.async_set_timeout(2e3),U_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await kS(),$r&&(await po.closeConnection(),process.exit(0))}a(mZ,"restartPM2Mode");async function KS(){if(!rD.getConfigFromFile(He.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await jU.getHDBProcessInfo()).clustering.length===0)_s.trace("Clustering not running, restart will start clustering services"),await w_.generateNatsConfig(!0),await ds.startClusteringProcesses(),await ds.startClusteringThreads(),await kS(),$r&&await po.closeConnection();else{await hZ(),await w_.generateNatsConfig(!0),hi?(_s.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await ds.restart(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ds.restart(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await jU.getHDBProcessInfo()).clustering.forEach(n=>{_s.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await $S.async_set_timeout(3e3),await kS(),await po.updateLocalStreams(),$r&&await po.closeConnection(),_s.trace("Restart clustering restarting ingest and reply service threads");let t=C_(He.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=C_(He.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(KS,"restartClustering");async function kS(){await w_.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await w_.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(kS,"removeNatsConfig")});var hD=m((xue,fD)=>{"use strict";var Gue=require("lodash"),Qt=g(),{handleHDBError:iD,hdb_errors:SZ}=W(),{HDB_ERROR_MSGS:pZ,HTTP_STATUS_CODES:TZ}=SZ,QS=F();fD.exports={getRolePermissions:gZ};var mi=Object.create(null),RZ=a(e=>({key:e,perms:{}}),"perms_template_obj"),uD=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),lD=a((e=!1,t=!1,r=!1,s=!1)=>({[Qt.PERMS_CRUD_ENUM.READ]:e,[Qt.PERMS_CRUD_ENUM.INSERT]:t,[Qt.PERMS_CRUD_ENUM.UPDATE]:r,[Qt.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),zS=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...lD(t,r,s,n)}),"table_perms_template"),oD=a((e,t=lD())=>({attribute_name:e,describe:ED(t),[gc]:t[gc],[JS]:t[JS],[XS]:t[XS]}),"attr_perms_template"),aD=a((e,t=!1)=>({attribute_name:e,describe:t,[gc]:t}),"timestamp_attr_perms_template"),{READ:gc,INSERT:JS,UPDATE:XS}=Qt.PERMS_CRUD_ENUM,_D=Object.values(Qt.PERMS_CRUD_ENUM),dD=[gc,JS,XS];function gZ(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[Qt.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(mi[t]&&mi[t].key===s)return mi[t].perms;let n=AZ(e,r);return mi[t]?mi[t].key=s:mi[t]=RZ(s),mi[t].perms=n,n}catch(r){if(!e[Qt.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Qt.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Qt.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 QS.error(s),QS.debug(r),iD(new Error,pZ.OUTDATED_PERMS_TRANSLATION_ERROR,TZ.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
9
|
-
${r.stack}`;throw QS.error(s),iD(new Error)}}}a(gZ,"getRolePermissions");function AZ(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[Qt.SYSTEM_SCHEMA_NAME]=s[Qt.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]=OZ(t[i]);return}r[i]=uD(),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],l=NZ(c,u);r[i].describe||_D.forEach(_=>{l[_]&&(r[i].describe=!0)}),r[i].tables[o]=l}else r[i].tables[o]=zS()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=zS()})}),r}a(AZ,"translateRolePermissions");function OZ(e){let t=uD(!0);return Object.keys(e).forEach(r=>{t.tables[r]=zS(!0,!0,!0,!0,!0)}),t}a(OZ,"createStructureUserPermissions");function NZ(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}=_,E=_;return Qt.TIME_STAMP_NAMES.includes(d)&&(E=aD(d,_[gc])),l[d]=E,l},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=oD(o);return t.attributes.forEach(({attribute:l})=>{if(i[l]){let _=i[l];_.describe=ED(_),n.attribute_permissions.push(_),c||bZ(_,u)}else if(l!==o){let _;Qt.TIME_STAMP_NAMES.includes(l)?_=aD(l):_=oD(l),n.attribute_permissions.push(_)}}),c||n.attribute_permissions.push(u),n.describe=cD(n),n}else return e.describe=cD(e),e}a(NZ,"getTableAttrPerms");function cD(e){return _D.filter(t=>e[t]).length>0}a(cD,"getSchemaTableDescribePerm");function ED(e){return dD.filter(t=>e[t]).length>0}a(ED,"getAttributeDescribePerm");function bZ(e,t){dD.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(bZ,"checkForHashPerms")});var mD={};Ze(mD,{Resources:()=>D_,keyArrayToString:()=>To,resetResources:()=>yZ,resources:()=>wn});function yZ(){return wn=new D_}function To(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var D_,wn,Ac=pe(()=>{Vn();D_=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 l=2;for(;(l=c.indexOf("/",l))>-1;){let _=this.get(c.slice(0,l));_&&(_.hasSubPaths=!0),l+=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&&(n.relativeURL="")),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 Ye(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(yZ,"resetResources");a(To,"keyArrayToString")});var Oc={};Ze(Oc,{authentication:()=>AD,login:()=>vZ,logout:()=>BZ,start:()=>PZ});async function AD(e,t){let r=e.headers,s=r.authorization,n=r.cookie,i=r.origin,o=[];if(i){let f=e.isOperationsServer?UZ?CZ:[]:wZ?IZ:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h={"Access-Control-Allow-Methods":"POST, GET, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Accept, Content-Type, Authorization","Access-Control-Allow-Origin":i};return L_&&(h["Access-Control-Allow-Credentials"]="true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),L_&&o.push("Access-Control-Allow-Credentials","true")}}let c,u;if(L_){let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(f);if(h>=0){let T=n.indexOf(";",h),S=n.indexOf("=",h);c=n.slice(S+1,T===-1?n.length:T),u=await pD.get(c)}e.session=u||(u={})}e.user=null;let l=a((f,h,T)=>{let S=new v_.AuthAuditLog(f,h,Rt.AUTH_AUDIT_TYPES.AUTHENTICATION,e.headers["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=T,c&&(S.session_id=c),e.headers.referer&&(S.referer=e.headers.referer),e.headers.origin&&(S.origin=e.headers.origin),h===Rt.AUTH_AUDIT_STATUS.SUCCESS?SD.notify(S):SD.error(S)},"authAuditLog"),_;if(s){if(_=Ro.get(s),!_){let[f,h]=s.split(" "),T,S;try{switch(f){case"Basic":[T,S]=atob(h).split(":"),_=T||S?await ht.auth(T,S):null;break;case"Bearer":try{_=await(0,P_.validateOperationToken)(h)}catch(y){if(y.message==="invalid token")try{return await(0,P_.validateRefreshToken)(h),{status:-1}}catch{throw y}}break}}catch(y){return MZ&&(Ro.get(h)||(Ro.set(h,h),l(T,Rt.AUTH_AUDIT_STATUS.FAILURE,f))),{status:401,body:Ks({error:y.message},e)}}Ro.set(s,_),LZ&&l(_.username,Rt.AUTH_AUDIT_STATUS.SUCCESS,f)}e.user=_}else u?.user?e.user=await ht.auth(u.user,null,!1):DZ&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")&&(e.user=_=await(0,M_.getSuperUser)());L_&&(e.session.update=function(f){if(!c){c=(0,RD.v4)();let T=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${c}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("set-cookie",T):d?.headers?.set&&d.headers.set("set-cookie",T)}return f.id=c,pD.put(f)},e.login=async function(f,h){e.user=await ht.auth(f,h),e.session.update({user:e.user.username})},(_&&!u||u?.user?.username!==_?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let d=await t(e);if(!d)return d;d.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&wn.loginPath?(d.status=302,d.headers.Location=wn.loginPath(e)):d.headers["WWW-Authenticate"]="Basic");let E=o.length;if(E>0){let f=d.headers;f||(d.headers=f={});for(let h=0;h<E;){let T=o[h++];f[T]=o[h++]}}return o=null,d}function PZ({server:e,port:t}){e.request(AD,{port:t||"all"}),TD||(TD=!0,setInterval(()=>{Ro=new Map},yr.get(Rt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),gD.user.addListener(()=>{Ro=new Map}))}async function vZ(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 BZ(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var M_,P_,RD,yr,Rt,v_,gD,SD,IZ,wZ,CZ,UZ,pD,L_,DZ,LZ,MZ,Ro,TD,B_=pe(()=>{M_=D(Or());Us();Ac();P_=D(rc());de();RD=require("uuid"),yr=D(Q()),Rt=D(g()),v_=D(F());go();gD=D(wa()),SD=(0,v_.loggerWithTag)("auth-event");yr.initSync();IZ=yr.get(Rt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),wZ=yr.get(Rt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS),CZ=yr.get(Rt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),UZ=yr.get(Rt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS);ht.auth=M_.findAndValidateUser;pD=et({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),L_=yr.get(Rt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,DZ=yr.get(Rt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??!0,LZ=yr.get(Rt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,MZ=yr.get(Rt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,Ro=new Map;a(AD,"authentication");a(PZ,"start");a(vZ,"login");a(BZ,"logout")});var CD=m((Jue,wD)=>{"use strict";var he=require("joi"),OD=require("fs-extra"),ND=require("path"),Qs=ve(),bD=Q(),yD=g(),ID=F(),{hdb_errors:HZ}=W(),{HDB_ERROR_MSGS:Dt}=HZ,Ws=/^[a-zA-Z0-9-_]+$/;wD.exports={getDropCustomFunctionValidator:FZ,setCustomFunctionValidator:GZ,addComponentValidator:$Z,dropCustomFunctionProjectValidator:YZ,packageComponentValidator:KZ,deployComponentValidator:WZ,setComponentFileValidator:xZ,getComponentFileValidator:VZ,dropComponentFileValidator:kZ};function H_(e,t,r){try{let s=bD.get(yD.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=ND.join(s,t);return OD.existsSync(n)?e?t:r.message(Dt.PROJECT_EXISTS):e?r.message(Dt.NO_PROJECT):t}catch(s){return ID.error(s),r.message(Dt.VALIDATION_ERR)}}a(H_,"checkProjectExists");function Nc(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Nc,"checkFilePath");function qZ(e,t,r,s){try{let n=bD.get(yD.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=ND.join(n,e,t,r+".js");return OD.existsSync(i)?r:s.message(Dt.NO_FILE)}catch(n){return ID.error(n),s.message(Dt.VALIDATION_ERR)}}a(qZ,"checkFileExists");function FZ(e){let t=he.object({project:he.string().pattern(Ws).custom(H_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),type:he.string().valid("helpers","routes").required(),file:he.string().pattern(Ws).custom(qZ.bind(null,e.project,e.type)).custom(Nc).required().messages({"string.pattern.base":Dt.BAD_FILE_NAME})});return Qs.validateBySchema(e,t)}a(FZ,"getDropCustomFunctionValidator");function GZ(e){let t=he.object({project:he.string().pattern(Ws).custom(H_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),type:he.string().valid("helpers","routes").required(),file:he.string().custom(Nc).required(),function_content:he.string().required()});return Qs.validateBySchema(e,t)}a(GZ,"setCustomFunctionValidator");function xZ(e){let t=he.object({project:he.string().pattern(Ws).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),file:he.string().custom(Nc).required(),payload:he.string().optional(),encoding:he.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Qs.validateBySchema(e,t)}a(xZ,"setComponentFileValidator");function kZ(e){let t=he.object({project:he.string().pattern(Ws).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),file:he.string().custom(Nc).optional()});return Qs.validateBySchema(e,t)}a(kZ,"dropComponentFileValidator");function VZ(e){let t=he.object({project:he.string().required(),file:he.string().custom(Nc).required(),encoding:he.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Qs.validateBySchema(e,t)}a(VZ,"getComponentFileValidator");function $Z(e){let t=he.object({project:he.string().pattern(Ws).custom(H_.bind(null,!1)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME})});return Qs.validateBySchema(e,t)}a($Z,"addComponentValidator");function YZ(e){let t=he.object({project:he.string().pattern(Ws).custom(H_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME})});return Qs.validateBySchema(e,t)}a(YZ,"dropCustomFunctionProjectValidator");function KZ(e){let t=he.object({project:he.string().pattern(Ws).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),skip_node_modules:he.boolean()});return Qs.validateBySchema(e,t)}a(KZ,"packageComponentValidator");function WZ(e){let t=he.object({project:he.string().pattern(Ws).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),payload:he.string().optional().messages({"string.pattern.base":Dt.BAD_PACKAGE}),package:he.string().optional()});return Qs.validateBySchema(e,t)}a(WZ,"deployComponentValidator")});var tp=m((Zue,LD)=>{"use strict";var be=require("fs-extra"),ZS=require("fast-glob"),me=require("path"),UD=require("tar-fs"),QZ=require("uuid").v4,jS=require("normalize-path"),Es=CD(),gt=F(),Ie=g(),$e=Q(),q_=Ar(),zZ=x(),{PACKAGE_ROOT:JZ}=g(),{handleHDBError:nt,hdb_errors:XZ}=W(),{HDB_ERROR_MSGS:Cn,HTTP_STATUS_CODES:it}=XZ,ZZ=me.join(JZ,"application-template"),ep=me.join($e.get(Ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function DD(){let e=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw nt(new Error,Cn.NOT_ENABLED,it.BAD_REQUEST,void 0,void 0,!0)}a(DD,"isCFEnabled");function jZ(){gt.trace("getting custom api status");let e={};try{e={is_enabled:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw nt(new Error,Cn.FUNCTION_STATUS,it.INTERNAL_SERVER_ERROR,gt.ERR,t)}return e}a(jZ,"customFunctionsStatus");function ej(){gt.trace("getting custom api endpoints");let e={},t=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{ZS.sync(jS(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:ZS.sync(jS(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:ZS.sync(jS(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw nt(new Error,Cn.GET_FUNCTIONS,it.INTERNAL_SERVER_ERROR,gt.ERR,r)}return e}a(ej,"getCustomFunctions");function tj(e){e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=Es.getDropCustomFunctionValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);gt.trace("getting custom api endpoint file content");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=me.join(r,s,n,i+".js");try{return be.readFileSync(o,{encoding:"utf8"})}catch(c){throw nt(new Error,Cn.GET_FUNCTION,it.INTERNAL_SERVER_ERROR,gt.ERR,c)}}a(tj,"getCustomFunction");function rj(e){DD(),e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=Es.setCustomFunctionValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);gt.trace("setting custom function file content");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return be.outputFileSync(me.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw nt(new Error,Cn.SET_FUNCTION,it.INTERNAL_SERVER_ERROR,gt.ERR,c)}}a(rj,"setCustomFunction");function sj(e){e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=Es.getDropCustomFunctionValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);gt.trace("dropping custom function file");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return be.unlinkSync(me.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw nt(new Error,Cn.DROP_FUNCTION,it.INTERNAL_SERVER_ERROR,gt.ERR,o)}}a(sj,"dropCustomFunction");function nj(e){DD(),e.project&&(e.project=me.parse(e.project).name);let t=Es.addComponentValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);gt.trace("adding component");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=me.join(r,s);return be.mkdirSync(n,{recursive:!0}),be.copySync(ZZ,n),`Successfully added project: ${s}`}catch(n){throw nt(new Error,Cn.ADD_FUNCTION,it.INTERNAL_SERVER_ERROR,gt.ERR,n)}}a(nj,"addComponent");function ij(e){e.project&&(e.project=me.parse(e.project).name);let t=Es.dropCustomFunctionProjectValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);gt.trace("dropping custom function project");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=$e.get(Ie.CONFIG_PARAMS.APPS);if(!zZ.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 q_.updateConfigValue(Ie.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=me.join(r,s);return be.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw nt(new Error,Cn.DROP_FUNCTION_PROJECT,it.INTERNAL_SERVER_ERROR,gt.ERR,i)}}a(ij,"dropCustomFunctionProject");async function oj(e){e.project&&(e.project=me.parse(e.project).name);let t=Es.packageComponentValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;gt.trace("packaging component",s);let n;try{n=await be.realpath(me.join(r,s))}catch(u){if(u.code!==Ie.NODE_ERROR_CODES.ENOENT)throw u;try{n=await be.realpath(me.join($e.get(Ie.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(l){if(l.code===Ie.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await be.ensureDir(ep);let i=me.join(ep,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(me.join(n,"node_modules"))}),UD.pack(n,o).pipe(be.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=be.readFileSync(i,{encoding:"base64"});return await be.remove(i),{project:s,payload:c}}a(oj,"packageComponent");async function aj(e){e.project&&(e.project=me.parse(e.project).name);let t=Es.deployComponentValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,package:i}=e;if(gt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");if(n){let o=me.join(r,s);i="file:"+o,await be.ensureDir(o);let c,u;do c=me.join(ep,QZ()+".tar"),u=await be.pathExists(c);while(u);await be.outputFile(c,n,{encoding:"base64"});let l=be.createReadStream(c);l.pipe(UD.extract(o)),await new Promise(_=>l.on("end",_)),await be.unlink(c)}return q_.updateConfigValue(`${s}_package`,i,void 0,!1,!1,!0),`Successfully deployed: ${s}`}a(aj,"deployComponent");async function cj(){let e=q_.getConfiguration(),t=[];for(let s in e)if(e[s]?.package){if(e[s].package.startsWith("file:"))continue;t.push(Object.assign(e[s],{name:s}))}let r=a(async(s,n)=>{let i=await be.readdir(s,{withFileTypes:!0});for(let o of i){let c=o.name;if(c.startsWith(".")||c==="node_modules")continue;let u=me.join(s,c);if(await o.isDirectory()){let l={name:c,entries:[]};n.entries.push(l),await r(u,l)}else{let l=await be.stat(u),_={name:me.basename(c),mtime:l.mtime,size:l.size};n.entries.push(_)}}return n},"walk_dir");return r($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),{name:$e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT).split(me.sep).slice(-1).pop(),entries:t})}a(cj,"getComponents");async function uj(e){let t=Es.getComponentFileValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{return await be.readFile(me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),e.project,e.file),r)}catch(s){throw s.code===Ie.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${me.join(e.project,e.file)}'`):s}}a(uj,"getComponentFile");async function lj(e){let t=Es.setComponentFileValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),e.project,e.file);return e.payload!==void 0?(await be.ensureFile(s),await be.outputFile(s,e.payload,r)):await be.ensureDir(s),"Successfully set component: "+e.file}a(lj,"setComponentFile");async function _j(e){let t=Es.dropComponentFileValidator(e);if(t)throw nt(t,t.message,it.BAD_REQUEST);let r=e.file?me.join(e.project,e.file):e.project,s=me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),r);return await be.pathExists(s)&&await be.remove(s),q_.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(_j,"dropComponent");LD.exports={customFunctionsStatus:jZ,getCustomFunctions:ej,getCustomFunction:tj,setCustomFunction:rj,dropCustomFunction:sj,addComponent:nj,dropCustomFunctionProject:ij,packageComponent:oj,deployComponent:aj,getComponents:cj,getComponentFile:uj,setComponentFile:lj,dropComponent:_j}});var rp=m((ele,PD)=>{"use strict";var hs=require("joi"),MD=ve();PD.exports={readTransactionLogValidator:dj,deleteTransactionLogsBeforeValidator:Ej};function dj(e){let t=hs.object({schema:hs.string().required(),table:hs.string().required(),from:hs.date().timestamp(),to:hs.date().timestamp(),limit:hs.number().min(1)});return MD.validateBySchema(e,t)}a(dj,"readTransactionLogValidator");function Ej(e){let t=hs.object({schema:hs.string().required(),table:hs.string().required(),timestamp:hs.date().timestamp().required()});return MD.validateBySchema(e,t)}a(Ej,"deleteTransactionLogsBeforeValidator")});var G_=m((rle,FD)=>{"use strict";var sp=g(),F_=st(),vD=x(),BD=Q(),HD=Ps(),{handleHDBError:Ao,hdb_errors:fj}=W(),{HTTP_STATUS_CODES:Oo}=fj,{readTransactionLogValidator:hj,deleteTransactionLogsBeforeValidator:mj}=rp(),qD="This operation relies on clustering and cannot run with it disable.",Sj="Logs successfully deleted from transaction log.",pj="All logs successfully deleted from transaction log.";FD.exports={readTransactionLog:Tj,deleteTransactionLogsBefore:Rj};async function*Tj(e){let t=hj(e);if(t)throw Ao(t,t.message,Oo.BAD_REQUEST,void 0,void 0,!0);if(!BD.get(sp.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ao(new Error,qD,Oo.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=vD.checkSchemaTableExist(r,s);if(n)throw Ao(new Error,n,Oo.NOT_FOUND,void 0,void 0,!0);let i=HD.createNatsTableStreamName(r,s),o=await F_.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 l={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===sp.OPERATIONS_ENUM.DELETE&&(l.hash_values=c?.entry?.hash_values),yield l}}a(Tj,"readTransactionLog");async function Rj(e){let t=mj(e);if(t)throw Ao(t,t.message,Oo.BAD_REQUEST,void 0,void 0,!0);if(!BD.get(sp.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ao(new Error,qD,Oo.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=vD.checkSchemaTableExist(r,s);if(i)throw Ao(new Error,i,Oo.NOT_FOUND,void 0,void 0,!0);let o=HD.createNatsTableStreamName(r,s),{jsm:c}=await F_.getNATSReferences(),u=await F_.getStreamInfo(o),l=new Date(u.state.first_ts).getTime();if(n<=l)return`No transactions exist before: ${n}`;let _=Sj,d,E=new Date(u.state.last_ts).getTime();return n>E?(d=u.state.last_seq+1,_=pj):d=(await F_.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),_}a(Rj,"deleteTransactionLogsBefore")});var $_=m((nle,KD)=>{"use strict";var x_=require("joi"),k_=require("path"),GD=require("fs-extra"),{exec:gj}=require("child_process"),Aj=require("util"),xD=Aj.promisify(gj),bc=g(),{handleHDBError:No,hdb_errors:Oj}=W(),{HTTP_STATUS_CODES:bo}=Oj,Ic=Q(),Nj=ve(),yc=F();Ic.initSync();var np=Ic.get(bc.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),kD="npm install --omit=dev --json",bj=`${kD} --dry-run`;KD.exports={installModules:Cj,auditModules:Uj,installAllRootModules:yj,uninstallRootModule:Ij,linkHarperdb:wj};async function yj(e=!1){await V_(),await wc(e?"npm install --ignore-scripts":"npm install",Ic.get(bc.CONFIG_PARAMS.ROOTPATH))}a(yj,"installAllRootModules");async function Ij(e){await wc(`npm uninstall ${e}`,Ic.get(bc.CONFIG_PARAMS.ROOTPATH))}a(Ij,"uninstallRootModule");async function wj(){await V_(),await wc(`npm link ${bc.PACKAGE_ROOT}`,Ic.get(bc.CONFIG_PARAMS.ROOTPATH))}a(wj,"linkHarperdb");async function wc(e,t=void 0){let{stdout:r,stderr:s}=await xD(e,{cwd:t});if(s&&!s.includes("Debugger listening"))throw new Error(s.replace(`
|
|
10
|
-
`,""));return
|
|
11
|
-
`,"")}a(
|
|
8
|
+
`,"")}a(JI,"runCommand");async function Tz(){try{await jQ.access(pm)}catch{return!1}let e=await JI(`${pm} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return ez.eq(t,Sz)}a(Tz,"checkNATSServerInstalled");async function Am(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await YI.getClusterUser();if(ui(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}yr.trace("create nats connection called");let i=await uz({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:3e4,tls:{keyFile:Tt.get(Te.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Tt.get(Te.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Tt.get(Te.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return yr.trace("create connection established a nats client connection with id",i?.info?.client_id),i}a(Am,"createConnection");async function Rz(){_s&&(await _s.drain(),_s=void 0,io=void 0,oo=void 0,Xa=void 0)}a(Rz,"closeConnection");var _s,Xa;async function Vl(){return Xa||(Xa=Am(Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),_s=await Xa),_s||Xa}a(Vl,"getConnection");async function ja(){if(io)return io;ui(_s)&&await Vl();let{domain:e}=ec(Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ui(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await _s.jetstreamManager({domain:e}),io}a(ja,"getJetStreamManager");async function XI(){if(oo)return oo;ui(_s)&&await Vl();let{domain:e}=ec(Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ui(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=_s.jetstream({domain:e}),oo}a(XI,"getJetStream");async function Gt(){let e=_s||await Vl(),t=io||await ja(),r=oo||await XI();return{connection:e,jsm:t,js:r}}a(Gt,"getNATSReferences");async function gz(e){let t=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await YI.getClusterUser(),n=await Am(t,r,s),i=gm(),o=n.subscribe(i),c=[],u,l=(async()=>{for await(let _ of o){let d=zI.decode(_.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 Fl.async_set_timeout(e),await o.drain(),await n.close(),await l,c}a(gz,"getServerList");async function Om(e,t){let{jsm:r}=await Gt(),s=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:WI.File,retention:QI.Limits,subjects:t,discard:lz.Old,duplicate_window:KI,max_msgs:n,max_bytes:i,max_age:s})}a(Om,"createLocalStream");async function ZI(){let{jsm:e}=await Gt(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(ZI,"listStreams");async function Az(e){let{jsm:t}=await Gt();await t.streams.delete(e)}a(Az,"deleteLocalStream");async function Oz(e){let{connection:t}=await Gt(),r=[],s=gm(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(zI.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(Oz,"listRemoteStreams");async function Nz(e,t=void 0,r=void 0){let{jsm:s,js:n}=await Gt(),i=Tm(),o={durable_name:i,ack_policy:xl.Explicit};t&&(o.deliver_policy=kl.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 l=[];for await(let _ of u){let d=Rm(_.data),E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};if(_.headers&&(E.origin=_.headers.get(_e.MSG_HEADERS.ORIGIN),E.nats_msg_id=_.headers.get(_e.MSG_HEADERS.NATS_MSG_ID)),l.push(E),_.ack(),_.info.pending===0)break}return await c.delete(),l}a(Nz,"viewStream");async function*bz(e,t=void 0,r=void 0){let{jsm:s,js:n}=await Gt(),i=Tm(),o={durable_name:i,ack_policy:xl.Explicit};t&&(o.deliver_policy=kl.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 l of u){let _=Rm(l.data);_[0]||(_=[_]);for(let d of _){let E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};l.headers&&(E.origin=l.headers.get(_e.MSG_HEADERS.ORIGIN),E.nats_msg_id=l.headers.get(_e.MSG_HEADERS.NATS_MSG_ID)),yield E}if(l.ack(),l.info.pending===0)break}await c.delete()}a(bz,"viewStreamIterator");async function yz(e,t,r,s){yr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=jI(s,r);let{js:n}=await Gt(),i=await tc(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:$I.encode(s);try{yr.trace(`publishToStream publishing to subject: ${o}`),hz(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 sw(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){yr.trace(`publishToStream creating stream: ${t}`);let _=o.split(".");_[2]="*",await Om(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(yz,"publishToStream");function jI(e,t){t===void 0&&(t=dz());let r=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_NODENAME);if(!t.has(_e.MSG_HEADERS.NATS_MSG_ID)){let s=Fl.getTableHashAttribute(e.schema,e.table),n=e.action?e.action:e.operation,i=`${r}.${e.schema}.${e.table}.${n}.${s}.${Date.now()}.${Tm()}`;t.append(_e.MSG_HEADERS.NATS_MSG_ID,i)}return t.has(_e.MSG_HEADERS.ORIGIN)||t.append(_e.MSG_HEADERS.ORIGIN,r),t}a(jI,"addNatsMsgHeader");function ec(e){e=e.toLowerCase();let t=Za.join(Tt.get(Te.CONFIG_PARAMS.ROOTPATH),mz);if(e===Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ui(Sm)&&(Sm={port:za.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:za.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.HUB,config_file:_e.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:Za.join(t,_e.PID_FILES.HUB),hdb_nats_path:t}),Sm;if(e===Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ui(mm)&&(mm={port:za.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:za.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.LEAF,config_file:_e.NATS_CONFIG_FILES.LEAF_SERVER,domain:za.getConfigFromFile(Te.CONFIG_PARAMS.CLUSTERING_NODENAME)+_e.SERVER_SUFFIX.LEAF,pid_file_path:Za.join(t,_e.PID_FILES.LEAF),hdb_nats_path:t}),mm;yr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(ec,"getServerConfig");async function Iz(e){let{jsm:t}=await Gt(),r=await tc();try{await t.streams.add({name:e.stream_name,storage:WI.File,retention:QI.Limits,duplicate_window:KI,max_age:az,max_bytes:cz,subjects:[`${_e.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:xl.Explicit,durable_name:e.durable_name,deliver_policy:kl.All,max_ack_pending:1e4});else throw s}}a(Iz,"createWorkQueueStream");async function wz(){let{jsm:e}=await Gt();(await e.consumers.info(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,_e.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(yr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,_e.WORK_QUEUE_CONSUMER_NAMES.durable_name),yr.info("Adding pull consumer to ingest stream"),await e.consumers.add(_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:xl.Explicit,durable_name:_e.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:kl.All,max_ack_pending:1e4}))}a(wz,"updateIngestStreamConsumer");async function ew(e,t,r){let{jsm:s}=await Gt(),n=await s.streams.info(t),i=tw(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,l=Gl.createNatsTableStreamName(c,u),_=i===e,d,E,f=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let T=0,p=n.config.sources.length;T<p;T++)if(d=n.config.sources[T],E=T,_&&d.name===l||!_&&d.name===l&&d.external&&d.external.api===`$JS.${e}.API`){f=!0;break}if(f===!0){if(d.opt_start_time===o)return;n.config.sources.splice(E,1),await s.streams.update(t,n.config)}let h={name:l,opt_start_time:o,filter_subject:`${_e.SUBJECT_PREFIXES.TXN}.>`};_||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(ew,"addSourceToWorkStream");function tw(e){return e.split(".")[1]}a(tw,"extractServerName");async function rw(e,t,r){let{schema:s,table:n}=r,i=Gl.createNatsTableStreamName(s,n),{jsm:o}=await Gt(),c=await o.streams.info(t);if(!Array.isArray(c.config.sources)||c.config.sources.length===0)return;let u=c.config.sources.length,l;for(;u--;)if(l=c.config.sources[u],l.name===i&&l.external.api===`$JS.${e}.API`){c.config.sources.splice(u,1);break}await o.streams.update(t,c.config)}a(rw,"removeSourceFromWorkStream");async function Cz(e,t,r=2e4,s=gm()){if(!Fl.isObject(t))throw new Error("data param must be an object");let n=$I.encode(t),{connection:i}=await Gt(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return Rm(c.data)}a(Cz,"request");function Nm(e){return new Promise(async(t,r)=>{let s=nz(pm,["--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(Nm,"reloadNATS");async function Uz(){let{pid_file_path:e}=ec(Te.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await Nm(e)}a(Uz,"reloadNATSHub");async function Dz(){let{pid_file_path:e}=ec(Te.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await Nm(e)}a(Dz,"reloadNATSLeaf");function Lz(e,t,r){let s;switch(e.code){case kI.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case kI.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(Lz,"requestErrorHandler");async function Mz(e,t){let r=t+_e.SERVER_SUFFIX.LEAF;await sw(async()=>{e.subscribe===!0?await ew(r,_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await rw(r,_e.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(Mz,"updateWorkStream");function sw(e){return iz.writeTransaction(Te.SYSTEM_SCHEMA_NAME,Te.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(sw,"exclusiveLock");async function nw(e,t){let r=Gl.createNatsTableStreamName(e,t),s=await tc(),n=Hz(e,t,s);await Om(r,[n])}a(nw,"createLocalTableStream");async function Pz(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await nw(s,n)}}a(Pz,"createTableStreams");async function iw(e,t){if(Tt.get(Te.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=Gl.createNatsTableStreamName(e,t),{jsm:s}=await Gt();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")yr.warn(r);else throw r}}a(iw,"purgeTableStream");async function vz(e,t){if(Tt.get(Te.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await iw(e,t[r])}a(vz,"purgeSchemaTableStreams");async function Bz(e){return(await ja()).streams.info(e)}a(Bz,"getStreamInfo");function Hz(e,t,r){return`${_e.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Hz,"createSubjectName");async function tc(){if(Ja)return Ja;if(Ja=(await ja())?.nc?.info?.server_name,Ja===void 0)throw new Error("Unable to get jetstream manager server name");return Ja}a(tc,"getJsmServerName");async function qz(){let e=await ja(),t=await tc(),r=await ZI();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=Fz(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===_e.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let l=`${_e.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;yr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}else if(n.name===_e.WORK_QUEUE_CONSUMER_NAMES.stream_name){let l=`${_e.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;yr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}else{let l=i.split(".");l[l.length-1]=t;let _=l.join(".");yr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}await e.streams.update(n.name,n)}}}a(qz,"updateLocalStreams");function Fz(e){let{config:t}=e,r=!1;if(t.name===_e.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===_e.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Tt.get(Te.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Tt.get(Te.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(Fz,"updateStreamLimits")});var Wl=m((kae,lw)=>{"use strict";var ao=Wu(),co=yI(),Gz=x(),xz=require("uuid").v4,xae=require("clone"),Yl=Gs(),uo=A(),kz=require("util"),gn=Hr(),{handleHDBError:xt,hdb_errors:Vz}=W(),{HDB_ERROR_MSGS:$l,HTTP_STATUS_CODES:kt}=Vz,{SchemaEventMsg:Kl}=Fr(),aw=it(),{getDatabases:$z}=(de(),ee(Ne)),{transformReq:lo}=V();lw.exports={createSchema:Yz,createSchemaStructure:cw,createTable:Kz,createTableStructure:uw,createAttribute:Xz,dropSchema:Wz,dropTable:Qz,dropAttribute:zz,getBackup:Zz};async function Yz(e){let t=await cw(e);return Yl.signalSchemaChange(new Kl(process.pid,e.operation,e.schema)),t}a(Yz,"createSchema");async function cw(e){let t=ao.schema_object(e);if(t)throw xt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);if(lo(e),!await co.checkSchemaExists(e.schema))throw xt(new Error,$l.SCHEMA_EXISTS_ERR(e.schema),kt.BAD_REQUEST,uo.LOG_LEVELS.ERROR,$l.SCHEMA_EXISTS_ERR(e.schema),!0);return await gn.createSchema(e),`database '${e.schema}' successfully created`}a(cw,"createSchemaStructure");async function Kz(e){return lo(e),await uw(e)}a(Kz,"createTable");async function uw(e){let t=ao.create_table_object(e);if(t)throw xt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);if(ao.validateTableResidence(e.residence),!await co.checkSchemaTableExists(e.schema,e.table))throw xt(new Error,$l.TABLE_EXISTS_ERR(e.schema,e.table),kt.BAD_REQUEST,uo.LOG_LEVELS.ERROR,$l.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:xz(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await gn.createTable(s,e);else throw xt(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",kt.BAD_REQUEST);else await gn.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(uw,"createTableStructure");async function Wz(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=ao.schema_object(e),s=t??r;if(s)throw xt(s,s.message,kt.BAD_REQUEST,void 0,void 0,!0);lo(e);let n=await co.checkSchemaExists(e.schema);if(n)throw xt(new Error,n,kt.NOT_FOUND,uo.LOG_LEVELS.ERROR,n,!0);let i=await co.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await gn.dropSchema(e),Yl.signalSchemaChange(new Kl(process.pid,e.operation,e.schema)),await aw.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(Wz,"dropSchema");async function Qz(e){let t=ao.table_object(e);if(t)throw xt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);lo(e);let r=await co.checkSchemaTableExists(e.schema,e.table);if(r)throw xt(new Error,r,kt.NOT_FOUND,uo.LOG_LEVELS.ERROR,r,!0);return await gn.dropTable(e),await aw.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Qz,"dropTable");async function zz(e){let t=ao.attribute_object(e);if(t)throw xt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);lo(e);let r=await co.checkSchemaTableExists(e.schema,e.table);if(r)throw xt(new Error,r,kt.NOT_FOUND,uo.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw xt(new Error,"You cannot drop a hash attribute",kt.BAD_REQUEST,void 0,void 0,!0);if(uo.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw xt(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,kt.BAD_REQUEST,void 0,void 0,!0);try{return await gn.dropAttribute(e),Jz(e),Yl.signalSchemaChange(new Kl(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw Gz.error(`Got an error deleting attribute ${kz.inspect(e)}.`),s}}a(zz,"dropAttribute");function Jz(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(Jz,"dropAttributeFromGlobal");async function Xz(e){lo(e);let t=$z()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw xt(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,kt.BAD_REQUEST,void 0,void 0,!0);return await gn.createAttribute(e),Yl.signalSchemaChange(new Kl(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Xz,"createAttribute");function Zz(e){return gn.getBackup(e)}a(Zz,"getBackup")});var dw=m(($ae,_w)=>{"use strict";var{OPERATIONS_ENUM:jz}=A(),bm=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=jz.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};_w.exports=bm});var ym=m((Wae,Sw)=>{"use strict";var eJ=Hr(),Kae=dw(),Ql=V(),zl=A(),tJ=Q(),{handleHDBError:Ew,hdb_errors:rJ}=W(),{HDB_ERROR_MSGS:fw,HTTP_STATUS_CODES:hw}=rJ,sJ=Object.values(zl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),mw="To use this operation audit log must be enabled in harperdb-config.yaml";Sw.exports=nJ;async function nJ(e){if(Ql.isEmpty(e.schema))throw new Error(fw.SCHEMA_REQUIRED_ERR);if(Ql.isEmpty(e.table))throw new Error(fw.TABLE_REQUIRED_ERR);if(!tJ.get(zl.CONFIG_PARAMS.LOGGING_AUDITLOG))throw Ew(new Error,mw,hw.BAD_REQUEST,zl.LOG_LEVELS.ERROR,mw,!0);let t=Ql.checkSchemaTableExist(e.schema,e.table);if(t)throw Ew(new Error,t,hw.NOT_FOUND,zl.LOG_LEVELS.ERROR,t,!0);if(!Ql.isEmpty(e.search_type)&&sJ.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await eJ.readAuditLog(e)}a(nJ,"readAuditLog")});var Tw=m((zae,pw)=>{"use strict";var{OPERATIONS_ENUM:iJ}=A(),Im=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=iJ.GET_BACKUP,this.schema=t,this.table=r}};pw.exports=Im});var Aw=m((jae,gw)=>{"use strict";var oJ=Hr(),Xae=Tw(),wm=V(),aJ=A(),Zae=Q(),{handleHDBError:cJ,hdb_errors:uJ}=W(),{HDB_ERROR_MSGS:Rw,HTTP_STATUS_CODES:lJ}=uJ;gw.exports=_J;async function _J(e){if(wm.isEmpty(e.schema))throw new Error(Rw.SCHEMA_REQUIRED_ERR);if(wm.isEmpty(e.table))throw new Error(Rw.TABLE_REQUIRED_ERR);let t=wm.checkSchemaTableExist(e.schema,e.table);if(t)throw cJ(new Error,t,lJ.NOT_FOUND,aJ.LOG_LEVELS.ERROR,t,!0);return await oJ.getBackup(read_audit_log_object)}a(_J,"getBackup")});var ww=m((tce,Iw)=>{var An=require("validate.js"),Nw=ve(),_o=A(),{handleHDBError:dJ,hdb_errors:EJ}=W(),{HDB_ERROR_MSGS:Ve,HTTP_STATUS_CODES:fJ}=EJ,Cm=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),hJ={STRUCTURE_USER:"structure_user"},Ow=Object.values(_o.ROLE_TYPES_ENUM),mJ="attribute_permissions",SJ="attribute_name",{PERMS_CRUD_ENUM:Eo}=_o,pJ=[mJ,...Object.values(Eo)],bw=[Eo.READ,Eo.INSERT,Eo.UPDATE],TJ=[SJ,...bw];function RJ(e){let t=Cm();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,yw(e,t)}a(RJ,"addRoleValidation");function gJ(e){let t=Cm();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,yw(e,t)}a(gJ,"alterRoleValidation");function AJ(e){let t=Cm();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,Nw.validateObject(e,t)}a(AJ,"dropRoleValidation");var OJ=["operation","role","id","permission","hdb_user","hdb_auth_header"];function yw(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)OJ.includes(s[o])||n.push(s[o]);n.length>0&&ze(Ve.INVALID_ROLE_JSON_KEYS(n),r);let i=Nw.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{ze(o,r)}),e.permission){let o=NJ(e);o&&ze(o,r),Ow.forEach(c=>{e.permission[c]&&!An.isBoolean(e.permission[c])&&ze(Ve.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(Ow.indexOf(o)<0){if(o===hJ.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let l=0,_=u.length;l<_;l++){let d=u[l];global.hdb_schema[d]||ze(Ve.SCHEMA_NOT_FOUND(d),r)}continue}ze(Ve.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){ze(Ve.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let l=c.tables[u];if(!u||!global.hdb_schema[o][u]){ze(Ve.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(l).forEach(_=>{pJ.includes(_)||ze(Ve.INVALID_PERM_KEY(_),r,o,u)}),Object.values(Eo).forEach(_=>{An.isDefined(l[_])?An.isBoolean(l[_])||ze(Ve.TABLE_PERM_NOT_BOOLEAN(_),r,o,u):ze(Ve.TABLE_PERM_MISSING(_),r,o,u)}),An.isDefined(l.attribute_permissions)){if(!An.isArray(l.attribute_permissions)){ze(Ve.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{ze(Ve.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(l.attribute_permissions){let _=global.hdb_schema[o][u].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in l.attribute_permissions){let f=l.attribute_permissions[E];if(Object.keys(f).forEach(T=>{!TJ.includes(T)&&T!==Eo.DELETE&&ze(Ve.INVALID_ATTR_PERM_KEY(T),r,o,u)}),!An.isDefined(f.attribute_name)){ze(Ve.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!_.includes(h)){ze(Ve.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}bw.forEach(T=>{An.isDefined(f[T])?An.isBoolean(f[T])||ze(Ve.ATTR_PERM_NOT_BOOLEAN(T,h),r,o,u):ze(Ve.ATTR_PERM_MISSING(T,h),r,o,u)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(l.read===!1&&d.read===!0||l.insert===!1&&d.insert===!0||l.update===!1&&d.update===!0){let E=`${o}.${u}`;ze(Ve.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return bJ(r)}a(yw,"customValidate");Iw.exports={addRoleValidation:RJ,alterRoleValidation:gJ,dropRoleValidation:AJ};function NJ(e){let{operation:t,permission:r}=e;if(t===_o.OPERATIONS_ENUM.ADD_ROLE||t===_o.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 Ve.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?_o.ROLE_TYPES_ENUM.SUPER_USER:_o.ROLE_TYPES_ENUM.CLUSTER_USER;return Ve.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(NJ,"validateNoSUPerms");function bJ(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:Ve.ROLE_PERMS_ERROR,...e};return dJ(new Error,s,fJ.BAD_REQUEST)}else return null}a(bJ,"generateRolePermResponse");function ze(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(ze,"addPermError")});var vm=m((sce,Lw)=>{"use strict";var Cw=Ar(),Uw=gr(),yJ=jn(),Dm=ww(),Lm=Gs(),IJ=require("uuid").v4,wJ=require("util"),Jl=A(),CJ=V(),Mm=Uw.searchByValue,UJ=Uw.searchByHash,DJ=wJ.promisify(yJ.delete),LJ=os(),MJ=to(),{hdb_errors:PJ,handleHDBError:fo}=W(),{HDB_ERROR_MSGS:Dw,HTTP_STATUS_CODES:Xl}=PJ,{UserEventMsg:Pm}=Fr();Lw.exports={addRole:vJ,alterRole:BJ,dropRole:HJ,listRoles:qJ};function Um(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(Um,"scrubRoleDetails");async function vJ(e){let t=Dm.addRoleValidation(e);if(t)throw t;e=Um(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 Mm(r)||[])}catch(i){throw fo(i)}if(s&&s.length>0)throw fo(new Error,Dw.ROLE_ALREADY_EXISTS(e.role),Xl.CONFLICT,void 0,void 0,!0);e.id||(e.id=IJ());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await Cw.insert(n),Lm.signalUserChange(new Pm(process.pid)),e=Um(e),e}a(vJ,"addRole");async function BJ(e){let t=Dm.alterRoleValidation(e);if(t)throw t;e=Um(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await Cw.update(r)}catch(n){throw fo(n)}if(s&&s?.message==="updated 0 of 1 records")throw fo(new Error,"Invalid role id",Xl.BAD_REQUEST,void 0,void 0,!0);return await Lm.signalUserChange(new Pm(process.pid)),e}a(BJ,"alterRole");async function HJ(e){let t=Dm.dropRoleValidation(e);if(t)throw fo(new Error,t,Xl.BAD_REQUEST,void 0,void 0,!0);let r=new MJ(Jl.SYSTEM_SCHEMA_NAME,Jl.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await UJ(r));if(s.length===0)throw fo(new Error,Dw.ROLE_NOT_FOUND,Xl.NOT_FOUND,void 0,void 0,!0);let n=new LJ(Jl.SYSTEM_SCHEMA_NAME,Jl.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await Mm(n)),o=!1;if(CJ.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw new Error(`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await DJ(c),Lm.signalUserChange(new Pm(process.pid)),`${s[0].role} successfully deleted`}a(HJ,"dropRole");async function qJ(){return Mm({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(qJ,"listRoles")});var Bw=m((ice,vw)=>{"use strict";var FJ=Q(),On=require("joi"),GJ=ve(),Mw=require("moment"),xJ=require("fs-extra"),Bm=require("path"),kJ=require("lodash"),rc=A(),{LOG_LEVELS:li}=A(),VJ="YYYY-MM-DD hh:mm:ss",$J=Bm.resolve(__dirname,"../logs");vw.exports=function(e){return GJ.validateBySchema(e,YJ)};var YJ=On.object({from:On.custom(Pw),until:On.custom(Pw),level:On.valid(li.NOTIFY,li.FATAL,li.ERROR,li.WARN,li.INFO,li.DEBUG,li.TRACE),order:On.valid("asc","desc"),limit:On.number().min(1),start:On.number().min(0),log_name:On.custom(KJ)});function Pw(e,t){if(Mw(e,Mw.ISO_8601).format(VJ)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(Pw,"validateDatetime");function KJ(e,t){if(kJ.invert(rc.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=FJ.get(rc.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?rc.LOG_NAMES.HDB:e,i=n===rc.LOG_NAMES.INSTALL?Bm.join($J,rc.LOG_NAMES.INSTALL):Bm.join(s,n);return xJ.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(KJ,"validateReadLogPath")});var qm=m((ace,qw)=>{"use strict";var Zl=A(),WJ=x(),QJ=Q(),zJ=Bw(),Hm=require("path"),Hw=require("fs-extra"),{once:JJ}=require("events"),{handleHDBError:XJ,hdb_errors:ZJ}=W(),{PACKAGE_ROOT:jJ}=A(),e2=Hm.join(jJ,"logs"),t2=1e3,r2=200;qw.exports=s2;async function s2(e){let t=zJ(e);if(t)throw XJ(t,t.message,ZJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=QJ.get(Zl.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?Zl.LOG_NAMES.HDB:e.log_name,n=s===Zl.LOG_NAMES.INSTALL?Hm.join(e2,Zl.LOG_NAMES.INSTALL):Hm.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,l=e.until!==void 0,_=l?new Date(e.until):void 0,d=e.limit===void 0?t2:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,T=0;E==="desc"&&!u&&!_&&(T=Math.max(Hw.statSync(n).size-(h+5)*r2,0));let p=Hw.createReadStream(n,{start:T});p.on("error",b=>{WJ.error(b)});let R=0,O=[],k="",$;p.on("data",b=>{let P=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;b=k+b;let z=0,q;for(;(q=P.exec(b))&&!p.destroyed;){$&&($.message=b.slice(z,q.index),U($));let[Oe,je,Eu]=q,Bi=Eu.split("] ["),Qo=Bi[0],xn=Bi[1];Bi.splice(0,2),$={timestamp:je,thread:Qo,level:xn,tags:Bi,message:""},z=q.index+Oe.length}k=b.slice(z)}),p.on("end",b=>{p.destroyed||$&&($.message=k.trim(),U($))}),p.resume();function U(b){let P,z,q;switch(!0){case(i&&c&&l):P=new Date(b.timestamp),z=new Date(u),q=new Date(_),b.level===o&&P>=z&&P<=q&&R<f?R++:b.level===o&&P>=z&&P<=q&&(Nn(b,E,O),R++,R===h&&p.destroy());break;case(i&&c):P=new Date(b.timestamp),z=new Date(u),b.level===o&&P>=z&&R<f?R++:b.level===o&&P>=z&&(Nn(b,E,O),R++,R===h&&p.destroy());break;case(i&&l):P=new Date(b.timestamp),q=new Date(_),b.level===o&&P<=q&&R<f?R++:b.level===o&&P<=q&&(Nn(b,E,O),R++,R===h&&p.destroy());break;case(c&&l):P=new Date(b.timestamp),z=new Date(u),q=new Date(_),P>=z&&P<=q&&R<f?R++:P>=z&&P<=q&&(Nn(b,E,O),R++,R===h&&p.destroy());break;case i:b.level===o&&R<f?R++:b.level===o&&(Nn(b,E,O),R++,R===h&&p.destroy());break;case c:P=new Date(b.timestamp),z=new Date(u),P>=z&&R<f?R++:P>=z&&R>=f&&(Nn(b,E,O),R++,R===h&&p.destroy());break;case l:P=new Date(b.timestamp),q=new Date(_),P<=q&&R<f?R++:P<=q&&R>=f&&(Nn(b,E,O),R++,R===h&&p.destroy());break;default:R<f?R++:(Nn(b,E,O),R++,R===h&&p.destroy())}}return a(U,"onLogMessage"),await JJ(p,"close"),O}a(s2,"readLog");function Nn(e,t,r){t==="desc"?n2(e,r):t==="asc"?i2(e,r):r.push(e)}a(Nn,"pushLineToResult");function n2(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(n2,"insertDescending");function i2(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(i2,"insertAscending")});var e_=m((dce,kw)=>{"use strict";var Fm=require("joi"),{string:jl,boolean:Fw,date:o2}=Fm.types(),a2=ve(),{validateSchemaExists:uce,validateTableExists:lce,validateSchemaName:_ce}=rs(),c2=A(),u2=Be(),Gw=Q();Gw.initSync();var l2=jl.invalid(Gw.get(c2.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(u2.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(),xw={operation:jl.valid("add_node","update_node"),node_name:l2,subscriptions:Fm.array().items({table:jl.optional(),schema:jl.required(),subscribe:Fw.required(),publish:Fw.required().custom(d2),start_time:o2.iso()}).min(1).required()};function _2(e){return a2.validateBySchema(e,Fm.object(xw))}a(_2,"addUpdateNodeValidator");function d2(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(d2,"checkForFalsy");kw.exports={addUpdateNodeValidator:_2,validation_schema:xw}});var $w=m((fce,Vw)=>{var E2=ve(),f2={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};Vw.exports=function(e){return E2.validateObject(e,f2)}});var xm=m((hce,Yw)=>{"use strict";var h2=A().OPERATIONS_ENUM,Gm=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=h2.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};Yw.exports=Gm});var Ww=m((Sce,Kw)=>{"use strict";var m2={OPERATION:"operation",REFRESH:"refresh"},km=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},Vm=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};Kw.exports={JWTTokens:km,TOKEN_TYPE_ENUM:m2,JWTRSAKeys:Vm}});var ic=m((Tce,Xw)=>{"use strict";var nc=require("jsonwebtoken"),$m=require("fs-extra"),Ym=V(),Ir=A(),{handleHDBError:Vt,hdb_errors:S2}=W(),{HTTP_STATUS_CODES:$t,AUTHENTICATION_ERROR_MSGS:Yt}=S2,sc=x(),Qw=ol(),Qm=br(),p2=Ar().update,T2=xm(),R2=Gs(),{UserEventMsg:g2}=Fr(),bn=Q();bn.initSync();var Km=require("path"),{JWTTokens:A2,JWTRSAKeys:O2,TOKEN_TYPE_ENUM:t_}=Ww(),N2=bn.get(Ir.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?bn.get(Ir.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",b2=bn.get(Ir.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?bn.get(Ir.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",r_="RS256",Wm;Xw.exports={createTokens:y2,validateOperationToken:w2,refreshOperationToken:I2,validateRefreshToken:Jw};async function y2(e){if(Ym.isEmpty(e)||typeof e!="object")throw Vt(new Error,Yt.INVALID_AUTH_OBJECT,$t.BAD_REQUEST,void 0,void 0,!0);if(Ym.isEmpty(e.username))throw Vt(new Error,Yt.USERNAME_REQUIRED,$t.BAD_REQUEST,void 0,void 0,!0);if(Ym.isEmpty(e.password))throw Vt(new Error,Yt.PASSWORD_REQUIRED,$t.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await Qm.findAndValidateUser(e.username,e.password),!t)throw Vt(new Error,Yt.INVALID_CREDENTIALS,$t.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw sc.error(E),Vt(new Error,Yt.INVALID_CREDENTIALS,$t.UNAUTHORIZED,void 0,void 0,!0)}let r=await s_(),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 zw(i,r.private_key,r.passphrase),c=await nc.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:b2,algorithm:r_,subject:t_.REFRESH}),u=Qw.hash(c),l=new T2(Ir.SYSTEM_SCHEMA_NAME,Ir.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),_,d;try{_=await p2(l)}catch(E){sc.error(E),d=E}if(d!==void 0||_.skipped_hashes.length>0)throw Vt(new Error,Yt.REFRESH_TOKEN_SAVE_FAILED,$t.INTERNAL_SERVER_ERROR);return R2.signalUserChange(new g2(process.pid)),new A2(o,c)}a(y2,"createTokens");async function zw(e,t,r){return await nc.sign(e,{key:t,passphrase:r},{expiresIn:N2,algorithm:r_,subject:t_.OPERATION})}a(zw,"signOperationToken");async function s_(){if(Wm===void 0)try{let e=Km.join(bn.getHdbBasePath(),Ir.LICENSE_KEY_DIR_NAME,Ir.JWT_ENUM.JWT_PASSPHRASE_NAME),t=Km.join(bn.getHdbBasePath(),Ir.LICENSE_KEY_DIR_NAME,Ir.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=Km.join(bn.getHdbBasePath(),Ir.LICENSE_KEY_DIR_NAME,Ir.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await $m.readFile(e)).toString(),n=(await $m.readFile(t)).toString(),i=(await $m.readFile(r)).toString();Wm=new O2(i,n,s)}catch(e){throw sc.error(e),Vt(new Error,Yt.NO_ENCRYPTION_KEYS,$t.INTERNAL_SERVER_ERROR)}return Wm}a(s_,"getJWTRSAKeys");async function I2(e){if(!e)throw Vt(new Error,Yt.INVALID_BODY,$t.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Vt(new Error,Yt.REFRESH_TOKEN_REQUIRED,$t.BAD_REQUEST,void 0,void 0,!0);await Jw(e.refresh_token);let t=await s_(),r=await nc.decode(e.refresh_token);return{operation_token:await zw({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(I2,"refreshOperationToken");async function w2(e){try{let t=await s_(),r=await nc.verify(e,t.public_key,{algorithms:r_,subject:t_.OPERATION});return await Qm.findAndValidateUser(r.username,void 0,!1)}catch(t){throw sc.warn(t),t.name&&t.name==="TokenExpiredError"?Vt(new Error,Yt.TOKEN_EXPIRED,$t.FORBIDDEN):Vt(new Error,Yt.INVALID_TOKEN,$t.UNAUTHORIZED)}}a(w2,"validateOperationToken");async function Jw(e){let t;try{let r=await s_(),s=await nc.verify(e,r.public_key,{algorithms:r_,subject:t_.REFRESH});t=await Qm.findAndValidateUser(s.username,void 0,!1)}catch(r){throw sc.warn(r),r.name&&r.name==="TokenExpiredError"?Vt(new Error,Yt.TOKEN_EXPIRED,$t.FORBIDDEN):Vt(new Error,Yt.INVALID_TOKEN,$t.UNAUTHORIZED)}if(!Qw.validate(t.refresh_token,e))throw Vt(new Error,Yt.INVALID_TOKEN,$t.UNAUTHORIZED);return t}a(Jw,"validateRefreshToken")});var zm=m((Ace,eC)=>{"use strict";var C2=$w(),ho=require("passport"),U2=require("passport-local").Strategy,D2=require("passport-http").BasicStrategy,L2=require("util"),M2=br(),jw=L2.callbackify(M2.findAndValidateUser),gce=rr(),P2=A(),Zw=ic();ho.use(new U2(function(e,t,r){jw(e,t,r)}));ho.use(new D2(function(e,t,r){jw(e,t,r)}));ho.serializeUser(function(e,t){t(null,e)});ho.deserializeUser(function(e,t){t(null,e)});function v2(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":ho.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===P2.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?Zw.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):Zw.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:ho.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(v2,"authorize");function B2(e,t){let r=C2(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(B2,"checkPermissions");eC.exports={authorize:v2,checkPermissions:B2}});var mo=m((Nce,tC)=>{"use strict";var Jm=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},Xm=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};tC.exports={Node:Jm,NodeSubscription:Xm}});var sC=m((yce,rC)=>{"use strict";var H2=A().OPERATIONS_ENUM,Zm=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=H2.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};rC.exports=Zm});var oc=m((wce,nC)=>{"use strict";var jm=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},eS=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)}};nC.exports={RemotePayloadObject:jm,RemotePayloadSubscription:eS}});var oC=m((Uce,iC)=>{"use strict";var tS=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}};iC.exports=tS});var uC=m((vce,cC)=>{"use strict";var q2=oC(),Lce=xe(),aC=ye(),F2=x(),{getSchemaPath:Mce,getTransactionAuditStorePath:Pce}=we(),{getDatabases:G2}=(de(),ee(Ne));cC.exports=x2;async function x2(e){let t=new q2;try{let r=G2()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await aC.environmentDataSize(schema_path,e.name),o=await aC.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){F2.warn(`unable to stat table dbi due to ${r}`)}return t}a(x2,"lmdbGetTableSize")});var _C=m((Hce,lC)=>{"use strict";var rS=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}};lC.exports=rS});var So=m((xce,hC)=>{"use strict";var k2=require("fs-extra"),V2=require("path"),Ut=require("systeminformation"),yn=x(),$2=it(),sS=Be(),i_=A(),Y2=uC(),fC=Qn(),{getThreadInfo:dC}=nt(),ES=Q();ES.initSync();var K2=_C(),{openEnvironment:Fce}=ye(),{getSchemaPath:Gce}=we(),{database:W2}=(de(),ee(Ne)),n_;hC.exports={getHDBProcessInfo:aS,getNetworkInfo:uS,getDiskInfo:cS,getMemoryInfo:oS,getCPUInfo:iS,getTimeInfo:nS,getSystemInformation:lS,systemInformation:Q2,getTableSize:_S,getMetrics:dS};function nS(){return Ut.time()}a(nS,"getTimeInfo");async function iS(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:l,..._}=await Ut.cpu();_.cpu_speed=await Ut.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:T,raw_currentload_user:p,cpus:R,...O}=await Ut.currentLoad();return O.cpus=[],R.forEach(k=>{let{raw_load:$,raw_load_idle:U,raw_load_irq:b,raw_load_nice:P,raw_load_system:z,raw_load_user:q,...Oe}=k;O.cpus.push(Oe)}),_.current_load=O,_}catch(e){return yn.error(`error in getCPUInfo: ${e}`),{}}}a(iS,"getCPUInfo");async function oS(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Ut.mem();return Object.assign(n,process.memoryUsage())}catch(e){return yn.error(`error in getMemoryInfo: ${e}`),{}}}a(oS,"getMemoryInfo");async function aS(){let e={core:[],clustering:[]};try{let t=await Ut.processes(),r;try{r=Number.parseInt(await k2.readFile(V2.join(ES.get(i_.CONFIG_PARAMS.ROOTPATH),i_.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===i_.NODE_ERROR_CODES.ENOENT)yn.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return yn.error(`error in getHDBProcessInfo: ${t}`),e}}a(aS,"getHDBProcessInfo");async function cS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Ut.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,...l}=await Ut.fsStats();return e.read_write=l,e.size=await Ut.fsSize(),e}catch(t){return yn.error(`error in getDiskInfo: ${t}`),e}}a(cS,"getDiskInfo");async function uS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Ut.networkInterfaceDefault(),e.latency=await Ut.inetChecksite("google.com"),(await Ut.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:l,ieee8021xState:_,carrier_changes:d,...E}=s;e.interfaces.push(E)}),(await Ut.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return yn.error(`error in getNetworkInfo: ${t}`),e}}a(uS,"getNetworkInfo");async function lS(){if(n_!==void 0)return n_;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Ut.osInfo();e=c;let u=await Ut.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,n_=e,n_}catch(t){return yn.error(`error in getSystemInformation: ${t}`),e}}a(lS,"getSystemInformation");async function _S(){let e=[],t=await fC.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await Y2(s));return e}a(_S,"getTableSize");async function dS(){let e=await fC.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let o=W2({database:r,table:n}).getStats();s[n]={puts:o.puts,deletes:o.deletes,txns:o.txns,pageFlushes:o.pageFlushes,writes:o.writes,pagesWritten:o.pagesWritten,timeDuringTxns:o.timeDuringTxns,timeStartTxns:o.timeStartTxns,timePageFlushes:o.timePageFlushes,timeSync:o.timeSync}}catch(i){yn.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(dS,"getMetrics");async function EC(){if(ES.get(i_.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await $2.getNATSReferences(),r=await t.streams.info(sS.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(sS.WORK_QUEUE_CONSUMER_NAMES.stream_name,sS.WORK_QUEUE_CONSUMER_NAMES.durable_name),n={ingest:{stream:{...r.state},consumer:{num_ack_pending:s._info.num_ack_pending,num_redelivered:s._info.num_redelivered,num_waiting:s._info.num_waiting,num_pending:s._info.num_pending}}};return r.config?.sources&&(n.ingest.stream.sources=r.config.sources),n}}a(EC,"getNatsStreamInfo");async function Q2(e){let t=new K2;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await lS(),t.time=nS(),t.cpu=await iS(),t.memory=await oS(),t.disk=await cS(),t.network=await uS(),t.harperdb_processes=await aS(),t.table_size=await _S(),t.metrics=await dS(),t.threads=await dC(),t.replication=await EC(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await lS();break;case"time":t.time=nS();break;case"cpu":t.cpu=await iS();break;case"memory":t.memory=await oS();break;case"disk":t.disk=await cS();break;case"network":t.network=await uS();break;case"harperdb_processes":t.harperdb_processes=await aS();break;case"table_size":t.table_size=await _S();break;case"database_metrics":case"metrics":t.metrics=await dS();break;case"threads":t.threads=await dC();break;case"replication":t.replication=await EC();break;default:break}return t}a(Q2,"systemInformation")});var fS=m((Yce,mC)=>{"use strict";var Vce=require("fs-extra"),$ce=x();mC.exports={version:z2,printVersion:X2,nodeVersion:J2};var In=Wa();function z2(){if(In)return In.version}a(z2,"version");function J2(){if(In&&In.engines&&In.engines["preferred-node"])return In.engines["preferred-node"]}a(J2,"nodeVersion");function X2(){In&&console.log(`HarperDB Version ${In.version}`)}a(X2,"printVersion")});var Vs=m((zce,RC)=>{"use strict";var Z2=Ar(),hS=V(),j2=require("util"),_i=A(),SC=Q();SC.initSync();var e3=zm(),pC=gr(),{Node:Wce,NodeSubscription:Qce}=mo(),t3=to(),r3=sC(),{RemotePayloadObject:s3,RemotePayloadSubscription:n3}=oc(),{handleHDBError:i3,hdb_errors:o3}=W(),{HTTP_STATUS_CODES:a3,HDB_ERROR_MSGS:c3}=o3,u3=os(),l3=So(),_3=fS(),{getDatabases:d3}=(de(),ee(Ne)),E3=j2.promisify(e3.authorize),f3=pC.searchByHash,h3=pC.searchByValue;RC.exports={authHeaderToUser:m3,isEmpty:S3,getNodeRecord:p3,upsertNodeRecord:T3,buildNodePayloads:R3,checkClusteringEnabled:g3,getAllNodeRecords:A3,getSystemInfo:O3,reverseSubscription:TC};async function m3(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await E3(t,null),e}a(m3,"authHeaderToUser");function S3(e){return e==null}a(S3,"isEmpty");async function p3(e){let t=new t3(_i.SYSTEM_SCHEMA_NAME,_i.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return f3(t)}a(p3,"getNodeRecord");async function T3(e){let t=new r3(_i.SYSTEM_SCHEMA_NAME,_i.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return Z2.upsert(t)}a(T3,"upsertNodeRecord");function TC(e){if(hS.isEmpty(e.subscribe)||hS.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(TC,"reverseSubscription");function R3(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:l}=c,_=hS.getTableHashAttribute(u,l),{subscribe:d,publish:E}=TC(c),f=d3()[u]?.[l],h=new n3(u,l,_,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);n.push(h)}return new s3(r,t,n,s)}a(R3,"buildNodePayloads");function g3(){if(!SC.get(_i.CONFIG_PARAMS.CLUSTERING_ENABLED))throw i3(new Error,c3.CLUSTERING_NOT_ENABLED,a3.BAD_REQUEST,void 0,void 0,!0)}a(g3,"checkClusteringEnabled");async function A3(){let e=new u3(_i.SYSTEM_SCHEMA_NAME,_i.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await h3(e))}a(A3,"getAllNodeRecords");async function O3(){let e=await l3.getSystemInformation();return{hdb_version:_3.version(),node_version:e.node_version,platform:e.platform}}a(O3,"getSystemInfo")});var mS=m((Xce,wC)=>{"use strict";var o_=it(),gC=V(),AC=Be(),OC=A(),a_=x(),NC=Wl(),N3=Ph(),{RemotePayloadObject:b3}=oc(),{handleHDBError:bC,hdb_errors:y3}=W(),{HTTP_STATUS_CODES:yC}=y3,{NodeSubscription:IC}=mo();wC.exports=I3;async function I3(e,t){let r;try{r=await o_.request(`${t}.${AC.REQUEST_SUFFIX}`,new b3(OC.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),a_.trace("Response from remote describe all request:",r)}catch(o){a_.error(`addNode received error from describe all request to remote node: ${o}`);let c=o_.requestErrorHandler(o,"add_node",t);throw bC(new Error,c,yC.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===AC.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw bC(new Error,o,yC.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:u}=o;if(c===OC.SYSTEM_SCHEMA_NAME){await o_.createLocalTableStream(c,u);let h=new IC(c,u,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let l=gC.doesSchemaExist(c),_=s[c]!==void 0,d=u?gC.doesTableExist(c,u):!0,E=u?s?.[c]?.[u]!==void 0:!0;if(!l&&!_||!d&&!E){n.push(o);continue}if(!l&&_&&(a_.trace(`addNode creating schema: ${c}`),await NC.createSchema({operation:"create_schema",schema:c})),!d&&E){a_.trace(`addNode creating table: ${u} in schema: ${c} with attributes ${JSON.stringify(s[c][u].attributes)}`);let h=new N3(c,u,s[c][u].hash_attribute);s[c][u].attributes&&(h.attributes=s[c][u].attributes),await NC.createTable(h)}await o_.createLocalTableStream(c,u);let f=new IC(c,u,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:n}}a(I3,"reviewSubscriptions")});var l_=m((jce,DC)=>{"use strict";var{handleHDBError:c_,hdb_errors:w3}=W(),{HTTP_STATUS_CODES:u_}=w3,{addUpdateNodeValidator:C3}=e_(),ac=x(),UC=A(),CC=Be(),U3=V(),SS=it(),cc=Vs(),D3=Q(),L3=mS(),{Node:M3,NodeSubscription:P3}=mo(),{broadcast:v3}=nt(),B3="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",H3="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",q3=D3.get(UC.CONFIG_PARAMS.CLUSTERING_NODENAME);DC.exports=F3;async function F3(e,t=!1){ac.trace("addNode called with:",e),cc.checkClusteringEnabled();let r=C3(e);if(r)throw c_(r,r.message,u_.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await cc.getNodeRecord(s);if(!U3.isEmptyOrZeroLength(d))throw c_(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,u_.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await L3(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=B3,o;let c=cc.buildNodePayloads(n,q3,UC.OPERATIONS_ENUM.ADD_NODE,await cc.getSystemInfo());ac.trace("addNode sending remote payload:",c);let u;try{u=await SS.request(`${s}.${CC.REQUEST_SUFFIX}`,c)}catch(d){ac.error(`addNode received error from request: ${d}`);let E=SS.requestErrorHandler(d,"add_node",s);throw c_(new Error,E,u_.INTERNAL_SERVER_ERROR,"error",E)}if(u.status===CC.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw c_(new Error,d,u_.INTERNAL_SERVER_ERROR,"error",d)}ac.trace(u);let l=[];for(let d=0,E=n.length;d<E;d++){let f=n[d];ac.trace("Add node updating work stream for node:",s,"subscriptions:",f),await SS.updateWorkStream(f,s),n[d].start_time===void 0&&delete n[d].start_time,l.push(new P3(f.schema,f.table,f.publish,f.subscribe))}let _=new M3(s,l,u.system_info);return await cc.upsertNodeRecord(_),v3({type:"nats_update"}),i.length>0?o.message=H3:o.message=`Successfully added '${s}' to manifest`,o}a(F3,"addNode")});var TS=m((tue,PC)=>{"use strict";var{handleHDBError:__,hdb_errors:G3}=W(),{HTTP_STATUS_CODES:d_}=G3,{addUpdateNodeValidator:x3}=e_(),uc=x(),MC=A(),LC=Be(),k3=V(),pS=it(),lc=Vs(),V3=Q(),{cloneDeep:$3}=require("lodash"),Y3=mS(),{NodeSubscription:K3}=mo(),{broadcast:W3}=nt(),Q3="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",z3="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",J3=V3.get(MC.CONFIG_PARAMS.CLUSTERING_NODENAME);PC.exports=X3;async function X3(e){uc.trace("updateNode called with:",e),lc.checkClusteringEnabled();let t=x3(e);if(t)throw __(t,t.message,d_.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=$3(await lc.getNodeRecord(r));if(k3.isEmptyOrZeroLength(s))throw __(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,d_.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await Y3(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=Q3,o;let c=lc.buildNodePayloads(n,J3,MC.OPERATIONS_ENUM.UPDATE_NODE,await lc.getSystemInfo());uc.trace("updateNode sending remote payload:",c);let u;try{u=await pS.request(`${r}.${LC.REQUEST_SUFFIX}`,c)}catch(l){uc.error(`updateNode received error from request: ${l}`);let _=pS.requestErrorHandler(l,"update_node",r);throw __(new Error,_,d_.INTERNAL_SERVER_ERROR,"error",_)}if(u.status===LC.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${u.message}`;throw __(new Error,l,d_.INTERNAL_SERVER_ERROR,"error",l)}uc.trace(u);for(let l=0,_=n.length;l<_;l++){let d=n[l];uc.trace(`updateNode updating work stream for node: ${r} subscription:`,d),await pS.updateWorkStream(d,r),n[l].start_time===void 0&&delete n[l].start_time}return await Z3(s[0],n,u.system_info),i.length>0?o.message=z3:o.message=`Successfully updated '${r}'`,o}a(X3,"updateNode");async function Z3(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,l=e.subscriptions.length;u<l;u++){let _=s.subscriptions[u];if(_.schema===o.schema&&_.table===o.table){_.publish=o.publish,_.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new K3(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await lc.upsertNodeRecord(s),W3({type:"nats_update"})}a(Z3,"updateNodeTable")});var FC=m((sue,qC)=>{"use strict";var HC=require("joi"),{string:vC}=HC.types(),j3=ve(),BC=A(),e4=Q(),t4=Be();qC.exports=r4;function r4(e){let t=vC.invalid(e4.get(BC.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(t4.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=HC.object({operation:vC.valid(BC.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return j3.validateBySchema(e,r)}a(r4,"removeNodeValidator")});var f_=m((iue,YC)=>{"use strict";var{handleHDBError:GC,hdb_errors:s4}=W(),{HTTP_STATUS_CODES:xC}=s4,n4=FC(),_c=x(),kC=Vs(),i4=V(),E_=A(),VC=Be(),$C=it(),o4=Q(),{RemotePayloadObject:a4}=oc(),{NodeSubscription:c4}=mo(),u4=Fa(),l4=jn(),{broadcast:_4}=nt(),d4=o4.get(E_.CONFIG_PARAMS.CLUSTERING_NODENAME);YC.exports=E4;async function E4(e){_c.trace("removeNode called with:",e),kC.checkClusteringEnabled();let t=n4(e);if(t)throw GC(t,t.message,xC.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await kC.getNodeRecord(r);if(i4.isEmptyOrZeroLength(s))throw GC(new Error,`Node '${r}' was not found.`,xC.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new a4(E_.OPERATIONS_ENUM.REMOVE_NODE,d4,[]),i,o=!1;try{i=await $C.request(`${r}.${VC.REQUEST_SUFFIX}`,n),_c.trace("Remove node reply from remote node:",r,i)}catch(u){_c.error("removeNode received error from request:",u),o=!0}for(let u=0,l=s.subscriptions.length;u<l;u++){let _=s.subscriptions[u];_c.trace(`Remove node removing subscription: ${_.schema}.${_.table} for node: ${r}`);let d=new c4(_.schema,_.table,!1,!1);await $C.updateWorkStream(d,r)}let c=new u4(E_.SYSTEM_SCHEMA_NAME,E_.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await l4.deleteRecord(c),_4({type:"nats_update"}),i?.status===VC.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(_c.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(E4,"removeNode")});var QC=m((aue,WC)=>{"use strict";var KC=require("joi"),{string:f4,array:h4}=KC.types(),m4=ve(),S4=e_();WC.exports=p4;function p4(e){let t=KC.object({operation:f4.valid("configure_cluster").required(),connections:h4.items(S4.validation_schema).required()});return m4.validateBySchema(e,t)}a(p4,"configureClusterValidator")});var RS=m((uue,jC)=>{"use strict";var T4=A(),h_=x(),R4=V(),g4=f_(),A4=l_(),zC=Vs(),O4=QC(),{handleHDBError:JC,hdb_errors:N4}=W(),{HTTP_STATUS_CODES:XC}=N4,b4="Configure cluster complete.",y4="Failed to configure the cluster. Check the logs for more details.",I4="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";jC.exports=w4;async function w4(e){h_.trace("configure cluster called with:",e),zC.checkClusteringEnabled();let t=O4(e);if(t)throw JC(t,t.message,XC.BAD_REQUEST,void 0,void 0,!0);let r=await zC.getAllNodeRecords(),s=[];for(let E=0,f=r.length;E<f;E++)s.push(ZC(g4,{operation:T4.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[E].name},r[E].name));let n=await Promise.allSettled(s);h_.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let E=0;E<o;E++){let f=e.connections[E];i.push(ZC(A4,f,f.node_name))}let c=await Promise.allSettled(i);h_.trace("All results from configure_cluster add node:",c);let u=[],l=[],_=!1,d=n.concat(c);for(let E=0,f=d.length;E<f;E++){let h=d[E];h.status==="rejected"&&(h_.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(_=!0);let T=h?.value?.result;typeof T=="string"&&T.includes("Successfully removed")||h.status==="rejected"||l.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(R4.isEmptyOrZeroLength(u))return{message:b4,connections:l};if(_)return{message:I4,failed_nodes:u,connections:l};throw JC(new Error,y4,XC.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(w4,"configureCluster");async function ZC(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(ZC,"functionWrapper")});var tU=m((_ue,eU)=>{"use strict";var m_=require("joi"),C4=ve(),{validateSchemaExists:U4,validateTableExists:D4,validateSchemaName:L4}=rs(),M4=m_.object({operation:m_.string().valid("purge_stream"),schema:m_.string().custom(U4).custom(L4).required(),table:m_.string().custom(D4).required()});function P4(e){return C4.validateBySchema(e,M4)}a(P4,"purgeStreamValidator");eU.exports=P4});var gS=m((Eue,rU)=>{"use strict";var{handleHDBError:v4,hdb_errors:B4}=W(),{HTTP_STATUS_CODES:H4}=B4,q4=tU(),F4=it(),G4=Vs();rU.exports=x4;async function x4(e){let t=q4(e);if(t)throw v4(t,t.message,H4.BAD_REQUEST,void 0,void 0,!0);G4.checkClusteringEnabled();let{schema:r,table:s}=e;return await F4.purgeTableStream(r,s),`Successfully purged table '${r}.${s}'`}a(x4,"purgeStream")});var NS=m((hue,cU)=>{"use strict";var OS=Vs(),k4=it(),iU=Q(),S_=A(),di=Be(),V4=V(),AS=x(),{RemotePayloadObject:$4}=oc(),{ErrorCode:sU}=require("nats"),nU=iU.get(S_.CONFIG_PARAMS.CLUSTERING_ENABLED),oU=iU.get(S_.CONFIG_PARAMS.CLUSTERING_NODENAME);cU.exports={clusterStatus:Y4,buildNodeStatus:aU};async function Y4(){let e={node_name:oU,is_enabled:nU,connections:[]};if(!nU)return e;let t=await OS.getAllNodeRecords();if(V4.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(aU(t[s],e.connections));return await Promise.allSettled(r),e}a(Y4,"clusterStatus");async function aU(e,t){let r=e.name,s=new $4(S_.OPERATIONS_ENUM.CLUSTER_STATUS,oU,void 0,await OS.getSystemInfo()),n,i,o=di.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await k4.request(di.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===di.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=di.CLUSTER_STATUS_STATUSES.CLOSED,AS.error(`Error getting node status from ${r} `,n))}catch(u){AS.warn(`Error getting node status from ${r}`,u),u.code===sU.NoResponders?o=di.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===sU.Timeout?o=di.CLUSTER_STATUS_STATUSES.TIMEOUT:o=di.CLUSTER_STATUS_STATUSES.CLOSED}let c=new K4(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!==S_.PRE_4_0_0_VERSION&&await OS.upsertNodeRecord(u)}catch(u){AS.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(aU,"buildNodeStatus");function K4(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(K4,"NodeStatusObject")});var yS=m((Sue,uU)=>{"use strict";var{handleHDBError:W4,hdb_errors:Q4}=W(),{HTTP_STATUS_CODES:z4}=Q4,J4=it(),X4=Vs(),bS=V(),p_=require("joi"),Z4=ve(),j4=2e3,eX=p_.object({timeout:p_.number().min(1),connected_nodes:p_.boolean(),routes:p_.boolean()});uU.exports=tX;async function tX(e){X4.checkClusteringEnabled();let t=Z4.validateBySchema(e,eX);if(t)throw W4(t,t.message,z4.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||bS.autoCastBoolean(s),o=n===void 0||bS.autoCastBoolean(n),c={nodes:[]},u=await J4.getServerList(r??j4),l={};if(i)for(let _=0,d=u.length;_<d;_++){let E=u[_].statsz;E&&(l[u[_].server.name]=E.routes)}for(let _=0,d=u.length;_<d;_++){if(u[_].statsz)continue;let E=u[_].server,f=u[_].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[_].response_time};i&&(h.connected_nodes=l[E.name]?l[E.name].map(T=>T.name.slice(0,-4)):[]),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(T=>({host:T.split(":")[0],port:bS.autoCast(T.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(tX,"clusterNetwork")});var EU=m((Tue,dU)=>{"use strict";var IS=require("joi"),lU=ve(),{route_constraints:_U}=Xf();dU.exports={setRoutesValidator:rX,deleteRoutesValidator:sX};function rX(e){let t=IS.object({server:IS.valid("hub","leaf").required(),routes:_U.required()});return lU.validateBySchema(e,t)}a(rX,"setRoutesValidator");function sX(e){let t=IS.object({routes:_U.required()});return lU.validateBySchema(e,t)}a(sX,"deleteRoutesValidator")});var CS=m((gue,SU)=>{"use strict";var Ei=Nr(),wS=V(),T_=A(),fU=EU(),{handleHDBError:hU,hdb_errors:nX}=W(),{HTTP_STATUS_CODES:mU}=nX,iX="cluster routes successfully set",oX="cluster routes successfully deleted";SU.exports={setRoutes:aX,getRoutes:cX,deleteRoutes:uX};function aX(e){let t=fU.setRoutesValidator(e);if(t)throw hU(t,t.message,mU.BAD_REQUEST,void 0,void 0,!0);let r=Ei.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 l=e.routes[c];l.port=wS.autoCast(l.port);let _=s.some(E=>E.host===l.host&&E.port===l.port),d=n.some(E=>E.host===l.host&&E.port===l.port);_||d?i.push(l):(s.push(l),o.push(l))}return e.server==="hub"?Ei.updateConfigValue(T_.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Ei.updateConfigValue(T_.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:iX,set:o,skipped:i}}a(aX,"setRoutes");function cX(){let e=Ei.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(cX,"getRoutes");function uX(e){let t=fU.deleteRoutesValidator(e);if(t)throw hU(t,t.message,mU.BAD_REQUEST,void 0,void 0,!0);let r=Ei.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let l=0,_=e.routes.length;l<_;l++){let d=e.routes[l],E=!1;for(let f=0,h=s.length;f<h;f++){let T=s[f];if(d.host===T.host&&d.port===T.port){s.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,T=n.length;h<T;h++){let p=n[h];if(d.host===p.host&&d.port===p.port){n.splice(h,1),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(s=wS.isEmptyOrZeroLength(s)?null:s,Ei.updateConfigValue(T_.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=wS.isEmptyOrZeroLength(n)?null:n,Ei.updateConfigValue(T_.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:oX,deleted:i,skipped:o}}a(uX,"deleteRoutes")});var TU=m((Oue,pU)=>{"use strict";var dc=require("alasql"),fi=require("recursive-iterator"),$r=x(),lX=V(),Ec=A(),US=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,dX(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=>Ec.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=>!Ec.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][Ec.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=_X(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(l=>({attribute_name:l.attribute}));let u=this.affected_attributes.get(i).get(o).filter(l=>!Ec.SEARCH_WILDCARDS.includes(l));c.forEach(({attribute_name:l})=>{let _=new dc.yy.Column({columnid:l});n.tableid&&(_.tableid=n.tableid),this.ast.columns.push(_),u.includes(l)||u.push(l)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function _X(e){return e.filter(t=>t[Ec.PERMS_CRUD_ENUM.READ])}a(_X,"filterReadRestrictedAttrs");function dX(e,t,r,s,n){EX(e,t,r,s,n)}a(dX,"interpretAST");function fc(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(fc,"addSchemaTableToMap");function EX(e,t,r,s,n){if(!e){$r.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof dc.yy.Insert?SX(e,t,r):e instanceof dc.yy.Select?fX(e,t,r,s,n):e instanceof dc.yy.Update?hX(e,t,r):e instanceof dc.yy.Delete?mX(e,t,r):$r.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(EX,"getRecordAttributesAST");function fX(e,t,r,s,n){if(!e){$r.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(lX.isEmptyOrZeroLength(i)){$r.error("No schema specified");return}e.from.forEach(c=>{fc(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),fc(c.table,t,r,s,n)});let o=new fi(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,l=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(l).has(u))if(r.has(u))u=r.get(u);else{$r.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(c.columnid)<0&&t.get(l).get(u).push(c.columnid)}if(e.where){let c=new fi(e.where),u=e.from[0].tableid;for(let{node:l}of c)if(l&&l.columnid){let _=l.tableid?l.tableid:u;if(!t.get(i).has(_))if(r.has(_))_=r.get(_);else{$r.info(`table specified as ${_} not found.`);continue}t.get(i).get(_).indexOf(l.columnid)<0&&t.get(i).get(_).push(l.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new fi(c.on);for(let{node:l}of u)if(l&&l.columnid){let _=l.tableid,d=n.get(_);if(!t.get(d).has(_))if(r.has(_))_=r.get(_);else{$r.info(`table specified as ${_} not found.`);continue}t.get(d).get(_).indexOf(l.columnid)<0&&t.get(d).get(_).push(l.columnid)}}),e.order){let c=new fi(e.order);for(let{node:u}of c)if(u&&u.columnid){let l=u.tableid,_=s.has(l)?s.get(l):i;if(l||(l=e.from[0].tableid),!t.get(_).has(l))if(r.has(l))l=r.get(l);else{$r.info(`table specified as ${l} not found.`);return}t.get(_).get(l).indexOf(u.columnid)<0&&t.get(_).get(l).push(u.columnid)}}}a(fX,"getSelectAttributes");function hX(e,t,r){if(!e){$r.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new fi(e.columns),n=e.table.databaseid;fc(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&DS(e.table.tableid,n,i.columnid,t,r)}a(hX,"getUpdateAttributes");function mX(e,t,r){if(!e){$r.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new fi(e.where),n=e.table.databaseid;fc(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&DS(e.table.tableid,n,i.columnid,t,r)}a(mX,"getDeleteAttributes");function SX(e,t,r){if(!e){$r.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new fi(e.columns),n=e.into.databaseid;fc(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&DS(e.into.tableid,n,i.columnid,t,r)}a(SX,"getInsertAttributes");function DS(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(DS,"pushAttribute");pU.exports=US});var PS=m((bue,OU)=>{var R_=Ca(),RU=require("chalk"),lr=x(),gU=require("prompt"),{promisify:pX}=require("util"),LS=A(),TX=require("fs-extra"),RX=require("path"),gX=V(),AX=fS(),AU=Q();AU.initSync();var OX=require("moment"),NX=pX(gU.get),bX=RX.join(AU.getHdbBasePath(),LS.LICENSE_KEY_DIR_NAME,LS.LICENSE_FILE_NAME,LS.LICENSE_FILE_NAME);OU.exports={getFingerprint:IX,setLicense:yX,parseLicense:MS,register:wX,getRegistrationInfo:UX};async function yX(e){if(e&&e.key&&e.company){try{lr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await MS(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw lr.error(r),lr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(yX,"setLicense");async function IX(){let e={};try{e=await R_.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw lr.error(r),lr.error(t),new Error(r)}return e}a(IX,"getFingerprint");async function MS(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");lr.info("Validating license input...");let r=R_.validateLicense(e,t);if(lr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(lr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(lr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{lr.info("writing license to disk"),await TX.writeFile(bX,JSON.stringify({license_key:e,company:t}))}catch(s){throw lr.error("Failed to write License"),s}return"Registration successful."}a(MS,"parseLicense");async function wX(){let e=await CX();return MS(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(wX,"register");async function CX(){let e=await R_.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:RU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:RU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{gU.start()}catch(s){lr.error(s)}let r;try{r=await NX(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(CX,"promptForRegistration");async function UX(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await R_.getLicense()}catch(r){throw lr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(gX.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=AX.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=OX.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(UX,"getRegistrationInfo")});var bU=m((Iue,NU)=>{"use strict";var DX=Be(),vS=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,l,_,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+DX.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:l,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:_,port:d,routes:E,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};NU.exports=vS});var wU=m((Cue,IU)=>{"use strict";var yU=Be(),BS=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+yU.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+yU.SERVER_SUFFIX.LEAF},this.tls={cert_file:l,key_file:_,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"}};IU.exports=BS});var UU=m((Due,CU)=>{"use strict";var HS=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};CU.exports=HS});var LU=m((Mue,DU)=>{"use strict";var LX=Be(),qS=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+LX.SERVER_SUFFIX.ADMIN,this.password=r}};DU.exports=qS});var xS=m((vue,vU)=>{"use strict";var hc=require("path"),N_=require("fs-extra"),MX=bU(),PX=wU(),vX=UU(),BX=LU(),FS=br(),po=V(),Kt=Nr(),O_=A(),g_=Be(),{CONFIG_PARAMS:Je}=O_,Sc=x(),b_=Q(),MU=vs(),GS=it(),mc="clustering",HX=1e4,PU=5;vU.exports={generateNatsConfig:qX,removeNatsConfig:FX};async function qX(e=!1,t=void 0){b_.initSync();let r=b_.get(Je.ROOTPATH),s=hc.join(r,mc,g_.PID_FILES.HUB),n=hc.join(r,mc,g_.PID_FILES.LEAF),i=Kt.getConfigFromFile(Je.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=hc.join(r,mc,g_.NATS_CONFIG_FILES.HUB_SERVER),c=hc.join(r,mc,g_.NATS_CONFIG_FILES.LEAF_SERVER),u=Kt.getConfigFromFile(Je.CLUSTERING_TLS_CERTIFICATE),l=Kt.getConfigFromFile(Je.CLUSTERING_TLS_PRIVATEKEY),_=Kt.getConfigFromFile(Je.CLUSTERING_TLS_CERT_AUTH),d=Kt.getConfigFromFile(Je.CLUSTERING_TLS_INSECURE),E=Kt.getConfigFromFile(Je.CLUSTERING_TLS_VERIFY),f=Kt.getConfigFromFile(Je.CLUSTERING_NODENAME),h=Kt.getConfigFromFile(Je.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await GS.checkNATSServerInstalled()||y_("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let T=await FS.listUsers(),p=Kt.getConfigFromFile(Je.CLUSTERING_USER),R=await FS.getClusterUser();(po.isEmpty(R)||R.active!==!0)&&y_(`Invalid cluster user '${p}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await A_(Je.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await A_(Je.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await A_(Je.CLUSTERING_HUBSERVER_NETWORK_PORT),await A_(Je.CLUSTERING_LEAFSERVER_NETWORK_PORT));let O=[],k=[];for(let[Oe,je]of T.entries())je.role.role===O_.ROLE_TYPES_ENUM.CLUSTER_USER&&je.active&&(O.push(new BX(je.username,MU.decrypt(je.hash))),k.push(new vX(je.username,MU.decrypt(je.hash))));let $=[],{hub_routes:U}=Kt.getClusteringRoutes();if(!po.isEmptyOrZeroLength(U))for(let Oe of U)$.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${Oe.host}:${Oe.port}`);let b=new MX(Kt.getConfigFromFile(Je.CLUSTERING_HUBSERVER_NETWORK_PORT),f,s,u,l,_,d,E,h,Kt.getConfigFromFile(Je.CLUSTERING_HUBSERVER_CLUSTER_NAME),Kt.getConfigFromFile(Je.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),$,O,k);_==null&&(delete b.tls.ca_file,delete b.leafnodes.tls.ca_file),t=po.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===O_.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await N_.writeJson(o,b),Sc.trace(`Hub server config written to ${o}`));let P=`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,z=`tls://${R.uri_encoded_name}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,q=new PX(Kt.getConfigFromFile(Je.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,n,i,[P],[z],O,k,u,l,_,d);_==null&&delete q.tls.ca_file,(t===void 0||t===O_.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await N_.writeJson(c,q),Sc.trace(`Leaf server config written to ${c}`))}a(qX,"generateNatsConfig");async function A_(e){let t=b_.get(e);return po.isEmpty(t)&&y_(`port undefined for '${e}'`),await po.isPortTaken(t)&&y_(`'${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(A_,"isPortAvailable");function y_(e){let t=`Error generating clustering config: ${e}`;Sc.error(t),console.error(t),process.exit(1)}a(y_,"generateNatsConfigError");async function FX(e){let{port:t,config_file:r}=GS.getServerConfig(e),{username:s,decrypt_hash:n}=await FS.getClusterUser(),i=0,o=500;for(;i<PU;){try{let l=await GS.createConnection(t,s,n,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){Sc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=PU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check the ${e} log for further details.`);await po.async_set_timeout(o*i)}let c="0".repeat(HX),u=hc.join(b_.get(Je.ROOTPATH),mc,r);await N_.writeFile(u,c),await N_.remove(u),Sc.notify(e,"started.")}a(FX,"removeNatsConfig")});var xU=m((Hue,GU)=>{"use strict";var _r=Q(),GX=Ca(),oe=A(),pc=Be(),$s=require("path"),{PACKAGE_ROOT:w_}=A(),BU=Q(),I_=V(),To="/dev/null",xX=$s.join(w_,"launchServiceScripts"),HU=$s.join(w_,"utility/scripts"),kX=$s.join(HU,oe.HDB_RESTART_SCRIPT),qU=$s.resolve(w_,"dependencies",`${process.platform}-${process.arch}`,pc.NATS_BINARY_NAME);function FU(){let t=GX.licenseSearch().ram_allocation||oe.RAM_ALLOCATION_ENUM.DEFAULT,r=oe.MEM_SETTING_KEY+t,s={[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return I_.noBootFile()&&(s[oe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=I_.getEnvCliRootPath()),{name:oe.PROCESS_DESCRIPTORS.HDB,script:oe.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:w_}}a(FU,"generateMainServerConfig");var VX=9930;function $X(){_r.initSync(!0);let e=_r.get(oe.CONFIG_PARAMS.ROOTPATH),t=$s.join(e,"clustering",pc.NATS_CONFIG_FILES.HUB_SERVER),r=$s.join(_r.get(oe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),oe.LOG_NAMES.HDB),s=BU.get(oe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=pc.LOG_LEVEL_FLAGS[_r.get(oe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==VX?"-"+s:""),script:qU,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=To,i.error_file=To),i}a($X,"generateNatsHubServerConfig");var YX=9940;function KX(){_r.initSync(!0);let e=_r.get(oe.CONFIG_PARAMS.ROOTPATH),t=$s.join(e,"clustering",pc.NATS_CONFIG_FILES.LEAF_SERVER),r=$s.join(_r.get(oe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),oe.LOG_NAMES.HDB),s=BU.get(oe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=pc.LOG_LEVEL_FLAGS[_r.get(oe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==YX?"-"+s:""),script:qU,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=To,i.error_file=To),i}a(KX,"generateNatsLeafServerConfig");function WX(){_r.initSync();let e=$s.join(_r.get(oe.CONFIG_PARAMS.LOGGING_ROOT),oe.LOG_NAMES.HDB),t={name:oe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:oe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:xX,autorestart:!1};return _r.get(oe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=To,t.error_file=To),t}a(WX,"generateClusteringUpgradeV4ServiceConfig");function QX(){let e={[oe.PROCESS_NAME_ENV_PROP]:oe.PROCESS_DESCRIPTORS.RESTART_HDB};return I_.noBootFile()&&(e[oe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=I_.getEnvCliRootPath()),{...{name:oe.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:HU},script:kX}}a(QX,"generateRestart");function zX(){return{apps:[FU()]}}a(zX,"generateAllServiceConfigs");GU.exports={generateAllServiceConfigs:zX,generateMainServerConfig:FU,generateRestart:QX,generateNatsHubServerConfig:$X,generateNatsLeafServerConfig:KX,generateClusteringUpgradeV4ServiceConfig:WX}});var rD=m(($ue,tD)=>{"use strict";var Re=A(),JX=V(),Tc=xS(),Rc=it(),ds=Be(),wn=xU(),C_=Q(),Ys=x(),XX=Vs(),{startWorker:kU,onMessageFromWorkers:ZX}=nt(),jX=So(),eZ=require("util"),$U=require("child_process"),{execFile:tZ}=$U,Fue=eZ.promisify($U.exec),Gue=require("systeminformation"),fe;tD.exports={enterPM2Mode:rZ,start:hi,stop:kS,reload:YU,restart:KU,list:VS,describe:QU,connect:Ks,kill:aZ,startAllServices:cZ,startService:$S,getUniqueServicesList:zU,restartAllServices:uZ,isServiceRegistered:JU,reloadStopStart:XU,restartHdb:WU,deleteProcess:iZ,startClusteringProcesses:jU,startClusteringThreads:eD,isHdbRestartRunning:oZ,isClusteringRunning:_Z,stopClustering:lZ,reloadClustering:dZ};var{PACKAGE_ROOT:xue}=A(),kue=A(),{loggerWithTag:Vue}=Ys,gc=!1;ZX(e=>{e.type==="restart"&&C_.initSync(!0)});function rZ(){gc=!0}a(rZ,"enterPM2Mode");function Ks(){return fe||(fe=require("pm2")),new Promise((e,t)=>{fe.connect((r,s)=>{Ys.setupConsoleLogging(),r&&t(r),e(s)})})}a(Ks,"connect");var Wt,sZ=10,VU;function hi(e){if(gc)return nZ(e);let t=tZ(e.script,e.args.split(" "),e);t.name=e.name,t.on("exit",n=>{let i=Wt.indexOf(t);i>-1&&Wt.splice(i,1),!VU&&n>0&&(e.restarts=(e.restarts||0)+1,e.restarts<sZ&&hi(e))});let r={serviceName:e.name.replace(/ /g,"-")};function s(n){let i=C_.get(Re.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),o=/\[\d+][^\[]+\[(\w+)]/g,c,u=0,l;for(;c=o.exec(n);){if(c.index&&ds.LOG_LEVEL_HIERARCHY[i]>=ds.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===ds.LOG_LEVELS.ERR||l===ds.LOG_LEVELS.WRN?Ys.OUTPUTS.STDERR:Ys.OUTPUTS.STDOUT;Ys.logCustomLevel(l||"info",E,r,n.slice(u,c.index).trim())}let[_,d]=c;u=c.index+_.length,l=ds.LOG_LEVELS[d]}if(ds.LOG_LEVEL_HIERARCHY[i]>=ds.LOG_LEVEL_HIERARCHY[l||"info"]){let _=l===ds.LOG_LEVELS.ERR||l===ds.LOG_LEVELS.WRN?Ys.OUTPUTS.STDERR:Ys.OUTPUTS.STDOUT;Ys.logCustomLevel(l||"info",_,r,n.slice(u).trim())}}if(a(s,"extractMessages"),t.stdout.on("data",s),t.stderr.on("data",s),t.unref(),!Wt){Wt=[];let n=a(()=>{VU=!0,Wt&&(Wt.map(i=>i.kill()),process.exit(0))},"kill_children");process.on("exit",n),process.on("SIGINT",n),process.on("SIGQUIT",n),process.on("SIGTERM",n)}Wt.push(t)}a(hi,"start");function nZ(e){return new Promise(async(t,r)=>{try{await Ks()}catch(s){r(s)}fe.start(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(nZ,"startWithPM2");function kS(e){if(!gc){for(let t of Wt||[])t.name===e&&(Wt.splice(Wt.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ks()}catch(s){r(s)}fe.stop(e,async(s,n)=>{s&&(fe.disconnect(),r(s)),fe.delete(e,(i,o)=>{i&&(fe.disconnect(),r(s)),fe.disconnect(),t(o)})})})}a(kS,"stop");function YU(e){return new Promise(async(t,r)=>{try{await Ks()}catch(s){r(s)}fe.reload(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(YU,"reload");function KU(e){if(!gc)for(let t of Wt||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ks()}catch(s){r(s)}fe.restart(e,(s,n)=>{fe.disconnect(),t(n)})})}a(KU,"restart");function iZ(e){return new Promise(async(t,r)=>{try{await Ks()}catch(s){r(s)}fe.delete(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(iZ,"deleteProcess");async function WU(){await hi(wn.generateRestart())}a(WU,"restartHdb");async function oZ(){let e=await VS();for(let t in e)if(e[t].name===Re.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(oZ,"isHdbRestartRunning");function VS(){return new Promise(async(e,t)=>{try{await Ks()}catch(r){t(r)}fe.list((r,s)=>{r&&(fe.disconnect(),t(r)),fe.disconnect(),e(s)})})}a(VS,"list");function QU(e){return new Promise(async(t,r)=>{try{await Ks()}catch(s){r(s)}fe.describe(e,(s,n)=>{s&&(fe.disconnect(),r(s)),fe.disconnect(),t(n)})})}a(QU,"describe");function aZ(){if(!gc){for(let e of Wt||[])e.kill();Wt=[];return}return new Promise(async(e,t)=>{try{await Ks()}catch(r){t(r)}fe.killDaemon((r,s)=>{r&&(fe.disconnect(),t(r)),fe.disconnect(),e(s)})})}a(aZ,"kill");async function cZ(){try{await jU(),await eD(),await hi(wn.generateAllServiceConfigs())}catch(e){throw fe.disconnect(),e}}a(cZ,"startAllServices");async function $S(e){try{let t;switch(e=e.toLowerCase(),e){case Re.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=wn.generateMainServerConfig();break;case Re.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=wn.generateNatsIngestServiceConfig();break;case Re.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=wn.generateNatsReplyServiceConfig();break;case Re.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=wn.generateNatsHubServerConfig(),await hi(t),await Tc.removeNatsConfig(e);return;case Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=wn.generateNatsLeafServerConfig(),await hi(t),await Tc.removeNatsConfig(e);return;case Re.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=wn.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await hi(t)}catch(t){throw fe.disconnect(),t}}a($S,"startService");async function zU(){try{let e=await VS(),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 fe.disconnect(),e}}a(zU,"getUniqueServicesList");async function uZ(e=[]){try{let t=!1,r=await zU();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===Re.PROCESS_DESCRIPTORS.HDB?t=!0:await KU(o))}t&&await XU(Re.PROCESS_DESCRIPTORS.HDB)}catch(t){throw fe.disconnect(),t}}a(uZ,"restartAllServices");async function JU(e){if(Wt?.find(r=>r.name===e))return!0;let t=await jX.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(JU,"isServiceRegistered");async function XU(e){let t=e===Re.PROCESS_DESCRIPTORS.HDB?C_.get(Re.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):C_.get(Re.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await QU(e),s=JX.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await kS(e),await $S(e)):e===Re.PROCESS_DESCRIPTORS.HDB?await WU():await YU(e)}a(XU,"reloadStopStart");var ZU;async function jU(){for(let e in Re.CLUSTERING_PROCESSES){let t=Re.CLUSTERING_PROCESSES[e];await $S(t)}}a(jU,"startClusteringProcesses");async function eD(){ZU=kU(Re.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Re.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Rc.createWorkQueueStream(ds.WORK_QUEUE_CONSUMER_NAMES),await Rc.updateIngestStreamConsumer(),await Rc.updateLocalStreams();let e=await XX.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Re.PRE_4_0_0_VERSION){Ys.info("Starting clustering upgrade 4.0.0 process"),kU(Re.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(eD,"startClusteringThreads");async function lZ(){for(let e in Re.CLUSTERING_PROCESSES)if(e!==Re.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Re.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await ZU.terminate();else{let t=Re.CLUSTERING_PROCESSES[e];await kS(t)}}a(lZ,"stopClustering");async function _Z(){for(let e in Re.CLUSTERING_PROCESSES){let t=Re.CLUSTERING_PROCESSES[e];if(await JU(t)===!1)return!1}return!0}a(_Z,"isClusteringRunning");async function dZ(){await Tc.generateNatsConfig(!0),await Rc.reloadNATSHub(),await Rc.reloadNATSLeaf(),await Tc.removeNatsConfig(Re.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Tc.removeNatsConfig(Re.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(dZ,"reloadClustering")});var XS=m((Kue,cD)=>{"use strict";var EZ=require("minimist"),{isMainThread:WS,parentPort:iD}=require("worker_threads"),He=A(),{PROCESS_DESCRIPTORS_VALIDATE:Ac}=He,Es=x(),QS=V(),U_=xS(),Ro=it(),YS=Be(),oD=Nr(),hs=rD(),sD=So(),fZ=yE(),{restartWorkers:D_,onMessageByType:hZ}=nt(),{handleHDBError:mZ,hdb_errors:SZ}=W(),{HTTP_STATUS_CODES:pZ}=SZ,L_=Q();L_.initSync();var Oc=`Restarting HarperDB. This may take up to ${He.RESTART_TIMEOUT_MS/1e3} seconds.`,TZ="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",nD="Clustering is not enabled so cannot be restarted",RZ="Invalid service",mi,Yr;cD.exports={restart:aD,restartService:zS};WS&&hZ(He.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?zS({service:e.workerType}):aD({operation:"restart"})});async function aD(e){Yr=Object.keys(e).length===0,mi=await hs.isServiceRegistered(He.HDB_PROC_DESCRIPTOR);let t=EZ(process.argv);if(t.service){await zS(t);return}if(Yr&&!mi){console.error(TZ);return}if(Yr&&console.log(Oc),mi){hs.enterPM2Mode(),Es.notify(Oc);let r=fZ(Object.keys(He.CONFIG_PARAM_MAP),!0);return QS.isEmptyOrZeroLength(Object.keys(r))||oD.updateConfigValue(void 0,void 0,r,!0,!0),AZ(),Oc}return WS?(Es.notify(Oc),await JS(),setTimeout(()=>{D_()},50)):iD.postMessage({type:He.ITC_EVENT_TYPES.RESTART}),Oc}a(aD,"restart");async function zS(e){let{service:t}=e;if(He.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw mZ(new Error,RZ,pZ.BAD_REQUEST,void 0,void 0,!0);if(mi=await hs.isServiceRegistered(He.HDB_PROC_DESCRIPTOR),!WS)return iD.postMessage({type:He.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Ac.clustering:if(!L_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=nD;break}Yr&&console.log("Restarting clustering"),Es.notify("Restarting clustering"),await JS();break;case Ac.clustering_config:case Ac["clustering config"]:if(!L_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=nD;break}Yr&&console.log("Restarting clustering_config"),Es.notify("Restarting clustering_config"),await hs.reloadClustering();break;case"custom_functions":case"custom functions":case Ac.harperdb:case Ac.http_workers:if(Yr&&!mi){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}Yr&&console.log("Restarting http_workers"),Es.notify("Restarting http_workers"),mi?await hs.restart(He.HDB_PROC_DESCRIPTOR):setTimeout(()=>{D_("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(Es.error(r),Yr&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(zS,"restartService");async function gZ(){await Ro.publishToStream(`${YS.SUBJECT_PREFIXES.TXN}.${YS.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,YS.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ro.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(gZ,"postDummyNatsMsg");async function AZ(){await JS(),await hs.restart(He.HDB_PROC_DESCRIPTOR),await QS.async_set_timeout(2e3),L_.get(He.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await KS(),Yr&&(await Ro.closeConnection(),process.exit(0))}a(AZ,"restartPM2Mode");async function JS(){if(!oD.getConfigFromFile(He.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await sD.getHDBProcessInfo()).clustering.length===0)Es.trace("Clustering not running, restart will start clustering services"),await U_.generateNatsConfig(!0),await hs.startClusteringProcesses(),await hs.startClusteringThreads(),await KS(),Yr&&await Ro.closeConnection();else{await gZ(),await U_.generateNatsConfig(!0),mi?(Es.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await hs.restart(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await hs.restart(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await sD.getHDBProcessInfo()).clustering.forEach(n=>{Es.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await QS.async_set_timeout(3e3),await KS(),await Ro.updateLocalStreams(),Yr&&await Ro.closeConnection(),Es.trace("Restart clustering restarting ingest and reply service threads");let t=D_(He.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=D_(He.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(JS,"restartClustering");async function KS(){await U_.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await U_.removeNatsConfig(He.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(KS,"removeNatsConfig")});var TD=m((zue,pD)=>{"use strict";var Que=require("lodash"),Qt=A(),{handleHDBError:uD,hdb_errors:OZ}=W(),{HDB_ERROR_MSGS:NZ,HTTP_STATUS_CODES:bZ}=OZ,ZS=x();pD.exports={getRolePermissions:IZ};var Si=Object.create(null),yZ=a(e=>({key:e,perms:{}}),"perms_template_obj"),ED=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),fD=a((e=!1,t=!1,r=!1,s=!1)=>({[Qt.PERMS_CRUD_ENUM.READ]:e,[Qt.PERMS_CRUD_ENUM.INSERT]:t,[Qt.PERMS_CRUD_ENUM.UPDATE]:r,[Qt.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),jS=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...fD(t,r,s,n)}),"table_perms_template"),lD=a((e,t=fD())=>({attribute_name:e,describe:SD(t),[Nc]:t[Nc],[ep]:t[ep],[tp]:t[tp]}),"attr_perms_template"),_D=a((e,t=!1)=>({attribute_name:e,describe:t,[Nc]:t}),"timestamp_attr_perms_template"),{READ:Nc,INSERT:ep,UPDATE:tp}=Qt.PERMS_CRUD_ENUM,hD=Object.values(Qt.PERMS_CRUD_ENUM),mD=[Nc,ep,tp];function IZ(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[Qt.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(Si[t]&&Si[t].key===s)return Si[t].perms;let n=wZ(e,r);return Si[t]?Si[t].key=s:Si[t]=yZ(s),Si[t].perms=n,n}catch(r){if(!e[Qt.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Qt.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Qt.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 ZS.error(s),ZS.debug(r),uD(new Error,NZ.OUTDATED_PERMS_TRANSLATION_ERROR,bZ.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
9
|
+
${r.stack}`;throw ZS.error(s),uD(new Error)}}}a(IZ,"getRolePermissions");function wZ(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[Qt.SYSTEM_SCHEMA_NAME]=s[Qt.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]=CZ(t[i]);return}r[i]=ED(),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],l=UZ(c,u);r[i].describe||hD.forEach(_=>{l[_]&&(r[i].describe=!0)}),r[i].tables[o]=l}else r[i].tables[o]=jS()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=jS()})}),r}a(wZ,"translateRolePermissions");function CZ(e){let t=ED(!0);return Object.keys(e).forEach(r=>{t.tables[r]=jS(!0,!0,!0,!0,!0)}),t}a(CZ,"createStructureUserPermissions");function UZ(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}=_,E=_;return Qt.TIME_STAMP_NAMES.includes(d)&&(E=_D(d,_[Nc])),l[d]=E,l},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=lD(o);return t.attributes.forEach(({attribute:l})=>{if(i[l]){let _=i[l];_.describe=SD(_),n.attribute_permissions.push(_),c||DZ(_,u)}else if(l!==o){let _;Qt.TIME_STAMP_NAMES.includes(l)?_=_D(l):_=lD(l),n.attribute_permissions.push(_)}}),c||n.attribute_permissions.push(u),n.describe=dD(n),n}else return e.describe=dD(e),e}a(UZ,"getTableAttrPerms");function dD(e){return hD.filter(t=>e[t]).length>0}a(dD,"getSchemaTableDescribePerm");function SD(e){return mD.filter(t=>e[t]).length>0}a(SD,"getAttributeDescribePerm");function DZ(e,t){mD.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(DZ,"checkForHashPerms")});var RD={};Ye(RD,{Resources:()=>M_,keyArrayToString:()=>go,resetResources:()=>LZ,resources:()=>Cn});function LZ(){return Cn=new M_}function go(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var M_,Cn,bc=Se(()=>{$n();M_=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 l=2;for(;(l=c.indexOf("/",l))>-1;){let _=this.get(c.slice(0,l));_&&(_.hasSubPaths=!0),l+=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&&(n.relativeURL="")),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 Ke(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(LZ,"resetResources");a(go,"keyArrayToString")});var gD={};Ye(gD,{Headers:()=>pi});var pi,P_=Se(()=>{pi=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]}append(t,r,s){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase(),i=super.get(n);if(i){let o=i[1];s?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var yc={};Ye(yc,{authentication:()=>ID,login:()=>xZ,logout:()=>kZ,start:()=>GZ});async function ID(e,t){let r=e.headers,s=r.authorization,n=r.cookie,i=r.origin,o=[];if(i){let f=e.isOperationsServer?BZ?vZ:[]:PZ?MZ:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h={"Access-Control-Allow-Methods":"POST, GET, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Accept, Content-Type, Authorization","Access-Control-Allow-Origin":i};return v_&&(h["Access-Control-Allow-Credentials"]="true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),v_&&o.push("Access-Control-Allow-Credentials","true")}}let c,u;if(v_){let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(f);if(h>=0){let T=n.indexOf(";",h),p=n.indexOf("=",h);c=n.slice(p+1,T===-1?n.length:T),u=await OD.get(c)}e.session=u||(u={})}e.user=null;let l=a((f,h,T)=>{let p=new q_.AuthAuditLog(f,h,Rt.AUTH_AUDIT_TYPES.AUTHENTICATION,e.headers["x-forwarded-for"]??e.ip,e.method,e.pathname);p.auth_strategy=T,c&&(p.session_id=c),e.headers.referer&&(p.referer=e.headers.referer),e.headers.origin&&(p.origin=e.headers.origin),h===Rt.AUTH_AUDIT_STATUS.SUCCESS?AD.notify(p):AD.error(p)},"authAuditLog"),_;if(s){if(_=Ao.get(s),!_){let[f,h]=s.split(" "),T,p;try{switch(f){case"Basic":[T,p]=atob(h).split(":"),_=T||p?await tt.auth(T,p):null;break;case"Bearer":try{_=await(0,H_.validateOperationToken)(h)}catch(R){if(R.message==="invalid token")try{return await(0,H_.validateRefreshToken)(h),{status:-1}}catch{throw R}}break}}catch(R){return FZ&&(Ao.get(h)||(Ao.set(h,h),l(T,Rt.AUTH_AUDIT_STATUS.FAILURE,f))),{status:401,body:Ws({error:R.message},e)}}Ao.set(s,_),qZ&&l(_.username,Rt.AUTH_AUDIT_STATUS.SUCCESS,f)}e.user=_}else u?.user?e.user=await tt.auth(u.user,null,!1):HZ&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")&&(e.user=_=await(0,B_.getSuperUser)());v_&&(e.session.update=function(f){if(!c){c=(0,bD.v4)();let T=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${c}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",T):d?.headers?.set&&d.headers.set("Set-Cookie",T)}return f.id=c,OD.put(f)},e.login=async function(f,h){e.user=await tt.auth(f,h),e.session.update({user:e.user.username})},(_&&!u||u?.user?.username!==_?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let d=await t(e);if(!d)return d;d.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&Cn.loginPath?(d.status=302,d.headers.set("Location",Cn.loginPath(e))):d.headers.set("WWW-Authenticate","Basic"));let E=o.length;if(E>0){let f=d.headers;f||(d.headers=f=new pi);for(let h=0;h<E;){let T=o[h++];f.set(T,o[h++])}}return o=null,d}function GZ({server:e,port:t}){e.request(ID,{port:t||"all"}),ND||(ND=!0,setInterval(()=>{Ao=new Map},wr.get(Rt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),yD.user.addListener(()=>{Ao=new Map}))}async function xZ(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 kZ(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var B_,H_,bD,wr,Rt,q_,yD,AD,MZ,PZ,vZ,BZ,OD,v_,HZ,qZ,FZ,Ao,ND,F_=Se(()=>{B_=C(br());Pr();bc();H_=C(ic());de();bD=require("uuid"),wr=C(Q()),Rt=C(A()),q_=C(x());Oo();yD=C(Da());P_();AD=(0,q_.loggerWithTag)("auth-event");wr.initSync();MZ=wr.get(Rt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),PZ=wr.get(Rt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS),vZ=wr.get(Rt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),BZ=wr.get(Rt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS);tt.auth=B_.findAndValidateUser;OD=rt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),v_=wr.get(Rt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,HZ=wr.get(Rt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??!0,qZ=wr.get(Rt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,FZ=wr.get(Rt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,Ao=new Map;a(ID,"authentication");a(GZ,"start");a(xZ,"login");a(kZ,"logout")});var PD=m((ole,MD)=>{"use strict";var he=require("joi"),wD=require("fs-extra"),CD=require("path"),zs=ve(),UD=Q(),DD=A(),LD=x(),{hdb_errors:VZ}=W(),{HDB_ERROR_MSGS:Dt}=VZ,Qs=/^[a-zA-Z0-9-_]+$/;MD.exports={getDropCustomFunctionValidator:YZ,setCustomFunctionValidator:KZ,addComponentValidator:JZ,dropCustomFunctionProjectValidator:XZ,packageComponentValidator:ZZ,deployComponentValidator:jZ,setComponentFileValidator:WZ,getComponentFileValidator:zZ,dropComponentFileValidator:QZ};function G_(e,t,r){try{let s=UD.get(DD.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=CD.join(s,t);return wD.existsSync(n)?e?t:r.message(Dt.PROJECT_EXISTS):e?r.message(Dt.NO_PROJECT):t}catch(s){return LD.error(s),r.message(Dt.VALIDATION_ERR)}}a(G_,"checkProjectExists");function Ic(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Ic,"checkFilePath");function $Z(e,t,r,s){try{let n=UD.get(DD.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=CD.join(n,e,t,r+".js");return wD.existsSync(i)?r:s.message(Dt.NO_FILE)}catch(n){return LD.error(n),s.message(Dt.VALIDATION_ERR)}}a($Z,"checkFileExists");function YZ(e){let t=he.object({project:he.string().pattern(Qs).custom(G_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),type:he.string().valid("helpers","routes").required(),file:he.string().pattern(Qs).custom($Z.bind(null,e.project,e.type)).custom(Ic).required().messages({"string.pattern.base":Dt.BAD_FILE_NAME})});return zs.validateBySchema(e,t)}a(YZ,"getDropCustomFunctionValidator");function KZ(e){let t=he.object({project:he.string().pattern(Qs).custom(G_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),type:he.string().valid("helpers","routes").required(),file:he.string().custom(Ic).required(),function_content:he.string().required()});return zs.validateBySchema(e,t)}a(KZ,"setCustomFunctionValidator");function WZ(e){let t=he.object({project:he.string().pattern(Qs).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),file:he.string().custom(Ic).required(),payload:he.string().optional(),encoding:he.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return zs.validateBySchema(e,t)}a(WZ,"setComponentFileValidator");function QZ(e){let t=he.object({project:he.string().pattern(Qs).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),file:he.string().custom(Ic).optional()});return zs.validateBySchema(e,t)}a(QZ,"dropComponentFileValidator");function zZ(e){let t=he.object({project:he.string().required(),file:he.string().custom(Ic).required(),encoding:he.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return zs.validateBySchema(e,t)}a(zZ,"getComponentFileValidator");function JZ(e){let t=he.object({project:he.string().pattern(Qs).custom(G_.bind(null,!1)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME})});return zs.validateBySchema(e,t)}a(JZ,"addComponentValidator");function XZ(e){let t=he.object({project:he.string().pattern(Qs).custom(G_.bind(null,!0)).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME})});return zs.validateBySchema(e,t)}a(XZ,"dropCustomFunctionProjectValidator");function ZZ(e){let t=he.object({project:he.string().pattern(Qs).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),skip_node_modules:he.boolean()});return zs.validateBySchema(e,t)}a(ZZ,"packageComponentValidator");function jZ(e){let t=he.object({project:he.string().pattern(Qs).required().messages({"string.pattern.base":Dt.BAD_PROJECT_NAME}),payload:he.string().optional().messages({"string.pattern.base":Dt.BAD_PACKAGE}),package:he.string().optional()});return zs.validateBySchema(e,t)}a(jZ,"deployComponentValidator")});var ip=m((cle,HD)=>{"use strict";var be=require("fs-extra"),rp=require("fast-glob"),me=require("path"),vD=require("tar-fs"),ej=require("uuid").v4,sp=require("normalize-path"),ms=PD(),gt=x(),Ie=A(),$e=Q(),x_=Nr(),tj=V(),{PACKAGE_ROOT:rj}=A(),{handleHDBError:ot,hdb_errors:sj}=W(),{HDB_ERROR_MSGS:Un,HTTP_STATUS_CODES:at}=sj,nj=me.join(rj,"application-template"),np=me.join($e.get(Ie.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function BD(){let e=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw ot(new Error,Un.NOT_ENABLED,at.BAD_REQUEST,void 0,void 0,!0)}a(BD,"isCFEnabled");function ij(){gt.trace("getting custom api status");let e={};try{e={is_enabled:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw ot(new Error,Un.FUNCTION_STATUS,at.INTERNAL_SERVER_ERROR,gt.ERR,t)}return e}a(ij,"customFunctionsStatus");function oj(){gt.trace("getting custom api endpoints");let e={},t=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{rp.sync(sp(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:rp.sync(sp(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:rp.sync(sp(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw ot(new Error,Un.GET_FUNCTIONS,at.INTERNAL_SERVER_ERROR,gt.ERR,r)}return e}a(oj,"getCustomFunctions");function aj(e){e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=ms.getDropCustomFunctionValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);gt.trace("getting custom api endpoint file content");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=me.join(r,s,n,i+".js");try{return be.readFileSync(o,{encoding:"utf8"})}catch(c){throw ot(new Error,Un.GET_FUNCTION,at.INTERNAL_SERVER_ERROR,gt.ERR,c)}}a(aj,"getCustomFunction");function cj(e){BD(),e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=ms.setCustomFunctionValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);gt.trace("setting custom function file content");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return be.outputFileSync(me.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw ot(new Error,Un.SET_FUNCTION,at.INTERNAL_SERVER_ERROR,gt.ERR,c)}}a(cj,"setCustomFunction");function uj(e){e.project&&(e.project=me.parse(e.project).name),e.file&&(e.file=me.parse(e.file).name);let t=ms.getDropCustomFunctionValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);gt.trace("dropping custom function file");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return be.unlinkSync(me.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw ot(new Error,Un.DROP_FUNCTION,at.INTERNAL_SERVER_ERROR,gt.ERR,o)}}a(uj,"dropCustomFunction");function lj(e){BD(),e.project&&(e.project=me.parse(e.project).name);let t=ms.addComponentValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);gt.trace("adding component");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=me.join(r,s);return be.mkdirSync(n,{recursive:!0}),be.copySync(nj,n),`Successfully added project: ${s}`}catch(n){throw ot(new Error,Un.ADD_FUNCTION,at.INTERNAL_SERVER_ERROR,gt.ERR,n)}}a(lj,"addComponent");function _j(e){e.project&&(e.project=me.parse(e.project).name);let t=ms.dropCustomFunctionProjectValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);gt.trace("dropping custom function project");let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=$e.get(Ie.CONFIG_PARAMS.APPS);if(!tj.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 x_.updateConfigValue(Ie.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=me.join(r,s);return be.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw ot(new Error,Un.DROP_FUNCTION_PROJECT,at.INTERNAL_SERVER_ERROR,gt.ERR,i)}}a(_j,"dropCustomFunctionProject");async function dj(e){e.project&&(e.project=me.parse(e.project).name);let t=ms.packageComponentValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;gt.trace("packaging component",s);let n;try{n=await be.realpath(me.join(r,s))}catch(u){if(u.code!==Ie.NODE_ERROR_CODES.ENOENT)throw u;try{n=await be.realpath(me.join($e.get(Ie.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(l){if(l.code===Ie.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await be.ensureDir(np);let i=me.join(np,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(me.join(n,"node_modules"))}),vD.pack(n,o).pipe(be.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=be.readFileSync(i,{encoding:"base64"});return await be.remove(i),{project:s,payload:c}}a(dj,"packageComponent");async function Ej(e){e.project&&(e.project=me.parse(e.project).name);let t=ms.deployComponentValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);let r=$e.get(Ie.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,package:i}=e;if(gt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");if(n){let o=me.join(r,s);i="file:"+o,await be.ensureDir(o);let c,u;do c=me.join(np,ej()+".tar"),u=await be.pathExists(c);while(u);await be.outputFile(c,n,{encoding:"base64"});let l=be.createReadStream(c);l.pipe(vD.extract(o)),await new Promise(_=>l.on("end",_)),await be.unlink(c)}return x_.updateConfigValue(`${s}_package`,i,void 0,!1,!1,!0),`Successfully deployed: ${s}`}a(Ej,"deployComponent");async function fj(){let e=x_.getConfiguration(),t=[];for(let s in e)if(e[s]?.package){if(e[s].package.startsWith("file:"))continue;t.push(Object.assign(e[s],{name:s}))}let r=a(async(s,n)=>{let i=await be.readdir(s,{withFileTypes:!0});for(let o of i){let c=o.name;if(c.startsWith(".")||c==="node_modules")continue;let u=me.join(s,c);if(await o.isDirectory()){let l={name:c,entries:[]};n.entries.push(l),await r(u,l)}else{let l=await be.stat(u),_={name:me.basename(c),mtime:l.mtime,size:l.size};n.entries.push(_)}}return n},"walk_dir");return r($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),{name:$e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT).split(me.sep).slice(-1).pop(),entries:t})}a(fj,"getComponents");async function hj(e){let t=ms.getComponentFileValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{return await be.readFile(me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),e.project,e.file),r)}catch(s){throw s.code===Ie.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${me.join(e.project,e.file)}'`):s}}a(hj,"getComponentFile");async function mj(e){let t=ms.setComponentFileValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),e.project,e.file);return e.payload!==void 0?(await be.ensureFile(s),await be.outputFile(s,e.payload,r)):await be.ensureDir(s),"Successfully set component: "+e.file}a(mj,"setComponentFile");async function Sj(e){let t=ms.dropComponentFileValidator(e);if(t)throw ot(t,t.message,at.BAD_REQUEST);let r=e.file?me.join(e.project,e.file):e.project,s=me.join($e.get(Ie.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),r);return await be.pathExists(s)&&await be.remove(s),x_.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(Sj,"dropComponent");HD.exports={customFunctionsStatus:ij,getCustomFunctions:oj,getCustomFunction:aj,setCustomFunction:cj,dropCustomFunction:uj,addComponent:lj,dropCustomFunctionProject:_j,packageComponent:dj,deployComponent:Ej,getComponents:fj,getComponentFile:hj,setComponentFile:mj,dropComponent:Sj}});var op=m((lle,FD)=>{"use strict";var Ss=require("joi"),qD=ve();FD.exports={readTransactionLogValidator:pj,deleteTransactionLogsBeforeValidator:Tj};function pj(e){let t=Ss.object({schema:Ss.string().required(),table:Ss.string().required(),from:Ss.date().timestamp(),to:Ss.date().timestamp(),limit:Ss.number().min(1)});return qD.validateBySchema(e,t)}a(pj,"readTransactionLogValidator");function Tj(e){let t=Ss.object({schema:Ss.string().required(),table:Ss.string().required(),timestamp:Ss.date().timestamp().required()});return qD.validateBySchema(e,t)}a(Tj,"deleteTransactionLogsBeforeValidator")});var V_=m((dle,$D)=>{"use strict";var ap=A(),k_=it(),GD=V(),xD=Q(),kD=vs(),{handleHDBError:No,hdb_errors:Rj}=W(),{HTTP_STATUS_CODES:bo}=Rj,{readTransactionLogValidator:gj,deleteTransactionLogsBeforeValidator:Aj}=op(),VD="This operation relies on clustering and cannot run with it disable.",Oj="Logs successfully deleted from transaction log.",Nj="All logs successfully deleted from transaction log.";$D.exports={readTransactionLog:bj,deleteTransactionLogsBefore:yj};async function*bj(e){let t=gj(e);if(t)throw No(t,t.message,bo.BAD_REQUEST,void 0,void 0,!0);if(!xD.get(ap.CONFIG_PARAMS.CLUSTERING_ENABLED))throw No(new Error,VD,bo.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=GD.checkSchemaTableExist(r,s);if(n)throw No(new Error,n,bo.NOT_FOUND,void 0,void 0,!0);let i=kD.createNatsTableStreamName(r,s),o=await k_.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 l={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===ap.OPERATIONS_ENUM.DELETE&&(l.hash_values=c?.entry?.hash_values),yield l}}a(bj,"readTransactionLog");async function yj(e){let t=Aj(e);if(t)throw No(t,t.message,bo.BAD_REQUEST,void 0,void 0,!0);if(!xD.get(ap.CONFIG_PARAMS.CLUSTERING_ENABLED))throw No(new Error,VD,bo.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=GD.checkSchemaTableExist(r,s);if(i)throw No(new Error,i,bo.NOT_FOUND,void 0,void 0,!0);let o=kD.createNatsTableStreamName(r,s),{jsm:c}=await k_.getNATSReferences(),u=await k_.getStreamInfo(o),l=new Date(u.state.first_ts).getTime();if(n<=l)return`No transactions exist before: ${n}`;let _=Oj,d,E=new Date(u.state.last_ts).getTime();return n>E?(d=u.state.last_seq+1,_=Nj):d=(await k_.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),_}a(yj,"deleteTransactionLogsBefore")});var W_=m((fle,XD)=>{"use strict";var $_=require("joi"),Y_=require("path"),YD=require("fs-extra"),{exec:Ij}=require("child_process"),wj=require("util"),KD=wj.promisify(Ij),wc=A(),{handleHDBError:yo,hdb_errors:Cj}=W(),{HTTP_STATUS_CODES:Io}=Cj,Uc=Q(),Uj=ve(),Cc=x();Uc.initSync();var cp=Uc.get(wc.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),WD="npm install --omit=dev --json",Dj=`${WD} --dry-run`;XD.exports={installModules:vj,auditModules:Bj,installAllRootModules:Lj,uninstallRootModule:Mj,linkHarperdb:Pj};async function Lj(e=!1){await K_(),await Dc(e?"npm install --ignore-scripts":"npm install",Uc.get(wc.CONFIG_PARAMS.ROOTPATH))}a(Lj,"installAllRootModules");async function Mj(e){await Dc(`npm uninstall ${e}`,Uc.get(wc.CONFIG_PARAMS.ROOTPATH))}a(Mj,"uninstallRootModule");async function Pj(){await K_(),await Dc(`npm link ${wc.PACKAGE_ROOT}`,Uc.get(wc.CONFIG_PARAMS.ROOTPATH))}a(Pj,"linkHarperdb");async function Dc(e,t=void 0){let{stdout:r,stderr:s}=await KD(e,{cwd:t});if(s&&!s.includes("Debugger listening"))throw new Error(s.replace(`
|
|
10
|
+
`,""));return Cc.trace(r,s),r.replace(`
|
|
11
|
+
`,"")}a(Dc,"runCommand");async function vj(e){Cc.info(`starting installModules for request: ${e}`);let t=JD(e);if(t)throw yo(t,t.message,Io.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?Dj:WD;await K_(),await zD(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 l=Y_.join(cp,u),_,d=null;try{let{stdout:E,stderr:f}=await KD(n,{cwd:l});_=E?E.replace(`
|
|
12
12
|
`,""):null,d=f?f.replace(`
|
|
13
|
-
`,""):null}catch(E){E.stderr?i[u].npm_error=
|
|
14
|
-
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(VD,"parseNPMStdErr");async function Uj(e){yc.info(`starting auditModules for request: ${e}`);let t=YD(e);if(t)throw No(t,t.message,bo.BAD_REQUEST);let{projects:r}=e;await V_(),await $D(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=k_.join(np,o);s[o]={npm_output:null,npm_error:null};try{let u=await wc("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=VD(u.stderr)}}return yc.info(`finished auditModules with response ${s}`),s}a(Uj,"auditModules");async function V_(){try{return await wc("npm -v"),!0}catch{throw No(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",bo.BAD_REQUEST,void 0,void 0,!0)}}a(V_,"checkNPMInstalled");async function $D(e){if(!Array.isArray(e)||e.length===0)throw No(new Error,"projects argument must be an array with at least 1 element",bo.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=k_.join(np,i.toString());if(!await GD.pathExists(o)){t.push(i);continue}let u=k_.join(o,"package.json");await GD.pathExists(u)||r.push(i)}if(t.length>0)throw No(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,bo.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw No(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,bo.BAD_REQUEST,void 0,void 0,!0)}a($D,"checkProjectPaths");function YD(e){let t=x_.object({projects:x_.array().min(1).items(x_.string()).required(),dry_run:x_.boolean().default(!1)});return Nj.validateBySchema(e,t)}a(YD,"modulesValidator")});var QD=m((ole,WD)=>{"use strict";var ip=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}};WD.exports=ip});var JD=m((cle,zD)=>{"use strict";var op=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};zD.exports=op});var cp=m((lle,ZD)=>{"use strict";var XD=QD(),Dj=JD(),{HDB_ERROR_MSGS:Lj}=rr(),ap=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=Lj.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 XD(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new Dj(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 XD(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}};ZD.exports=ap});var Q_=m((dle,fL)=>{"use strict";var up=Rr(),Y_=Tr(),wr=Yl(),Dc=Wn(),lp=Zn(),Mj=Am(),Pj=Tw(),Lc=Or(),K_=Dm(),ot=F(),vj=Pm(),Bj=c_(),Hj=hS(),qj=d_(),Fj=mS(),Gj=SS(),xj=RS(),kj=AS(),_p=bS(),zs=x(),Vj=hU(),dp=US(),tL=WS(),Ir=g(),rL=hD(),$j=ho(),sL=rc(),nL=(B_(),te(Oc)),iL=Ar(),dr=tp(),Yj=require("alasql"),oL=G_(),aL=$_(),cL=cp(),{handleHDBError:zt,hdb_errors:uL}=W(),{HDB_ERROR_MSGS:At,HTTP_STATUS_CODES:Cc}=uL,P=new Map,lL="delete",Un="insert",Js="read",Si="update",Uc="describe",jD=Dc.describeSchema.name,eL=Dc.describeTable.name,_L={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},Kj="catchup",Wj="handleGetJob",Qj="handleGetJobsByStartDate",W_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},zj=[wr.createTable.name,wr.createAttribute.name,wr.dropTable.name,wr.dropAttribute.name],dL={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},q=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};P.set(up.insert.name,new q(!1,[Un]));P.set(up.update.name,new q(!1,[Si]));P.set(up.upsert.name,new q(!1,[Un,Si]));P.set(Y_.searchByConditions.name,new q(!1,[Js]));P.set(Y_.searchByHash.name,new q(!1,[Js]));P.set(Y_.searchByValue.name,new q(!1,[Js]));P.set(Y_.search.name,new q(!1,[Js]));P.set(wr.createSchema.name,new q(!0,[]));P.set(wr.createTable.name,new q(!0,[]));P.set(wr.createAttribute.name,new q(!1,[Un]));P.set(wr.dropSchema.name,new q(!0,[]));P.set(wr.dropTable.name,new q(!0,[]));P.set(wr.dropAttribute.name,new q(!0,[]));P.set(Dc.describeSchema.name,new q(!1,[Js]));P.set(Dc.describeTable.name,new q(!1,[Js]));P.set(lp.deleteRecord.name,new q(!1,[lL]));P.set(Lc.addUser.name,new q(!0,[]));P.set(Lc.alterUser.name,new q(!0,[]));P.set(Lc.dropUser.name,new q(!0,[]));P.set(Lc.listUsersExternal.name,new q(!0,[]));P.set(K_.listRoles.name,new q(!0,[]));P.set(K_.addRole.name,new q(!0,[]));P.set(K_.alterRole.name,new q(!0,[]));P.set(K_.dropRole.name,new q(!0,[]));P.set(vj.name,new q(!0,[]));P.set(Bj.name,new q(!0,[]));P.set(Hj.name,new q(!0,[]));P.set(qj.name,new q(!0,[]));P.set(Fj.name,new q(!0,[]));P.set(Gj.name,new q(!0,[]));P.set(_p.setRoutes.name,new q(!0,[]));P.set(_p.getRoutes.name,new q(!0,[]));P.set(_p.deleteRoutes.name,new q(!0,[]));P.set(iL.setConfiguration.name,new q(!0,[]));P.set(xj.clusterStatus.name,new q(!0,[]));P.set(kj.name,new q(!0,[]));P.set(dp.getFingerprint.name,new q(!0,[]));P.set(dp.setLicense.name,new q(!0,[]));P.set(lp.deleteFilesBefore.name,new q(!0,[]));P.set(lp.deleteAuditLogsBefore.name,new q(!0,[]));P.set(tL.restart.name,new q(!0,[]));P.set(tL.restartService.name,new q(!0,[]));P.set(Mj.name,new q(!0,[]));P.set(Pj.name,new q(!0,[Js]));P.set($j.systemInformation.name,new q(!0,[]));P.set(iL.getConfiguration.name,new q(!0,[]));P.set(oL.readTransactionLog.name,new q(!0,[]));P.set(oL.deleteTransactionLogsBefore.name,new q(!0,[]));P.set(aL.installModules.name,new q(!0,[]));P.set(aL.auditModules.name,new q(!0,[]));P.set(sL.createTokens.name,new q(!1,[]));P.set(sL.refreshOperationToken.name,new q(!1,[]));P.set(nL.login.name,new q(!1,[]));P.set(nL.logout.name,new q(!1,[]));P.set(dr.customFunctionsStatus.name,new q(!0,[]));P.set(dr.getCustomFunctions.name,new q(!0,[]));P.set(dr.getComponents.name,new q(!0,[]));P.set(dr.getComponentFile.name,new q(!0,[]));P.set(dr.setComponentFile.name,new q(!0,[]));P.set(dr.dropComponent.name,new q(!0,[]));P.set(dr.getCustomFunction.name,new q(!0,[]));P.set(dr.setCustomFunction.name,new q(!0,[]));P.set(dr.dropCustomFunction.name,new q(!0,[]));P.set(dr.addComponent.name,new q(!0,[]));P.set(dr.dropCustomFunctionProject.name,new q(!0,[]));P.set(dr.packageComponent.name,new q(!0,[]));P.set(dr.deployComponent.name,new q(!0,[]));P.set(dp.getRegistrationInfo.name,new q(!1,[]));P.set(Lc.userInfo.name,new q(!1,[]));P.set(Dc.describeAll.name,new q(!1,[]));P.set(Wj,new q(!1,[]));P.set(Qj,new q(!0,[]));P.set(Kj,new q(!0,[]));P.set(W_.CSV_DATA_LOAD,new q(!1,[Un,Si]));P.set(W_.CSV_URL_LOAD,new q(!1,[Un,Si]));P.set(W_.CSV_FILE_LOAD,new q(!1,[Un,Si]));P.set(W_.IMPORT_FROM_S3,new q(!1,[Un,Si]));P.set(dL.EXPORT_TO_S3,new q(!0,[]));P.set(dL.EXPORT_LOCAL,new q(!0,[]));P.set(Ir.VALID_SQL_OPS_ENUM.DELETE,new q(!1,[lL]));P.set(Ir.VALID_SQL_OPS_ENUM.SELECT,new q(!1,[Js]));P.set(Ir.VALID_SQL_OPS_ENUM.INSERT,new q(!1,[Un]));P.set(Ir.VALID_SQL_OPS_ENUM.UPDATE,new q(!1,[Si]));fL.exports={verifyPerms:Xj,verifyPermsAst:Jj,verifyBulkLoadAttributePerms:jj};function Jj(e,t,r){if(zs.isEmptyOrZeroLength(e))throw ot.info("verify_perms_ast has an empty user parameter"),zt(new Error);if(zs.isEmptyOrZeroLength(t))throw ot.info("verify_perms_ast has an empty user parameter"),zt(new Error);if(zs.isEmptyOrZeroLength(r))throw ot.info("verify_perms_ast has a null operation parameter"),zt(new Error);try{let s=new cL,n=new Vj(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw ot.info("No schemas defined in verifyPermsAst(), will not continue."),zt(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&_L[r])throw zt(new Error,At.DROP_SYSTEM,Cc.FORBIDDEN);if(c&&!u)return null;let l=rL.getRolePermissions(t.role);t.role.permission=l,!c&&e instanceof Yj.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(l));for(let d=0;d<i.length;d++){let E=n.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let _=EL(t,r,o,s);return _||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=n.getAttributesBySchemaTableName(E,d[f]),T=fp(t.role.permission,E,d[f]);Ep(h,T,r,d[f],E,s)}}),s.getPermsResponse())}catch(s){throw zt(s)}}a(Jj,"verifyPermsAst");function Xj(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw ot.info("null required parameter in verifyPerms"),zt(new Error,At.DEFAULT_INVALID_REQUEST,Cc.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new cL;if(zs.isEmptyOrZeroLength(e.hdb_user.role)||zs.isEmptyOrZeroLength(e.hdb_user.role.permission))return ot.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(At.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,l=e.hdb_user.role.permission.structure_user,_=o.has(Ir.SYSTEM_SCHEMA_NAME)||n===Ir.SYSTEM_SCHEMA_NAME;if(_&&_L[r])throw zt(new Error,At.DROP_SYSTEM,Cc.FORBIDDEN);if(u&&!_||l===!0&&(r===wr.createSchema.name||r===wr.dropSchema.name))return null;if(zj.indexOf(r)>=0&&(l===!0||Array.isArray(l)))return l===!0||l.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=rL.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===jD||r===eL){if(n===Ir.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(At.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===jD&&(!d[n]||!d[n][Uc]))return c.handleInvalidItem(At.SCHEMA_NOT_FOUND(n));if(r===eL&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][Uc]))return c.handleInvalidItem(At.TABLE_NOT_FOUND(n,i))}}let E=EL(e.hdb_user,r,o,c,s);if(E)return E;if(P.get(r)&&P.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&Ir.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let T=[],S=d[n].tables[i];S[Ir.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(O=>O[Ir.PERMS_CRUD_ENUM.READ]).forEach(O=>{T.push(O.attribute_name)}):T=global.hdb_schema[n][i].attributes.map(y=>y.attribute),e.get_attributes=T)}let f=Zj(e),h=fp(e.hdb_user.role.permission,n,i);return Ep(f,h,r,i,n,c,s),c.getPermsResponse()}a(Xj,"verifyPerms");function EL(e,t,r,s,n){if(zs.arrayHasEmptyValues([e,t,r]))throw ot.info("hasPermissions has an invalid parameter"),zt(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||P.get(t).requires_su))return null;if(!P.get(t))throw ot.info(`operation ${t} not found.`),zt(new Error,At.OP_NOT_FOUND(t),Cc.BAD_REQUEST);if(P.get(t)&&P.get(t).requires_su)return ot.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(At.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][Uc]===!1){s.addInvalidItem(At.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(At.SCHEMA_NOT_FOUND(u));continue}let l=r.get(u);for(let _ of l){let d=o[u].tables[_];if(!d||d[Uc]===!1)s.addInvalidItem(At.TABLE_NOT_FOUND(u,_));else try{let E=[],f=P.get(t).perms;!zs.isEmpty(n)&&f.includes(n)&&(f=[n]);for(let h=0;h<f.length;h++){let T=f[h],S=d[T];(S==null||S===!1)&&(ot.info(`Required ${T} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),E.push(T))}E.length>0&&s.addUnauthorizedTable(u,_,E)}catch(E){let f=At.UNKNOWN_OP_AUTH_ERROR(t,u,_);throw ot.error(f),ot.error(E),zt(uL.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?s.getPermsResponse():null}a(EL,"hasPermissions");function Ep(e,t,r,s,n,i,o){if(!e||!t)throw ot.info("no attributes specified in checkAttributePerms."),zt(new Error);let c=P.get(r).perms;if(!c||c==="")throw ot.info(`no permissions found for ${r} in checkAttributePerms().`),zt(new Error);if(zs.isEmptyOrZeroLength(t))return ot.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let _ of e){let d=t.get(_);if(d){if(d[Uc]===!1){i.addInvalidItem(At.ATTR_NOT_FOUND(n,s,_),n,s);continue}if(c)for(let E of c){if(Ir.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Js)throw zt(new Error,At.SYSTEM_TIMESTAMP_PERMS_ERR,Cc.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(At.ATTR_NOT_FOUND(n,s,_),n,s)}let l=Object.keys(u);l.length>0&&i.addUnauthorizedAttributes(l,n,s,u)}a(Ep,"checkAttributePerms");function Zj(e){let t=new Set;try{if(e.action)return t;if(e.operation===Ir.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){ot.info(r)}return t}a(Zj,"getRecordAttributes");function fp(e,t,r){let s=new Map;if(zs.isEmpty(e))return ot.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{ot.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(fp,"getAttributePermissions");function jj(e,t,r,s,n,i,o){let c=new Set(i),u=fp(e,s,n);Ep(c,u,t,n,s,o,r)}a(jj,"verifyBulkLoadAttributePerms")});var J_=m((fle,TL)=>{"use strict";TL.exports={evaluateSQL:d5,processAST:pL,convertSQLToAST:SL,checkASTPermissions:mL};var e5=Rr(),hL=require("util"),t5=hL.callbackify(e5.insert),r5=Tr().search,s5=mI().update,n5=hL.callbackify(s5),i5=pI().convertDelete,Dn=require("alasql"),o5=Q_(),z_=F(),a5=wl(),c5=x(),Mc=g(),{hdb_errors:u5,handleHDBError:hp}=W(),{HTTP_STATUS_CODES:mp}=u5;a5(Dn);var l5=403,_5="There was a problem performing this insert. Please check the logs and try again.",Sp=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function d5(e,t){let r=e.parsed_sql_object;if(!r){r=SL(e.sql);let s,n=r.ast.statements[0];if(n instanceof Dn.yy.Insert?s=n.into.databaseid:n instanceof Dn.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Dn.yy.Update||n instanceof Dn.yy.Delete?s=n.table.databaseid:z_.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Dn.yy.Select)&&c5.isEmptyOrZeroLength(s))return t("No schema specified",null)}pL(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(d5,"evaluateSQL");function mL(e,t){let r;try{r=o5.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(mL,"checkASTPermissions");function SL(e){let t=new Sp;if(!e)throw hp(new Error,"The 'sql' parameter is missing from the request body",mp.BAD_REQUEST);try{let r=e.trim(),s=Dn.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
15
|
-
`);throw s[1]?hp(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,mp.BAD_REQUEST):hp(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",mp.BAD_REQUEST)}return t}a(SL,"convertSQLToAST");function pL(e,t,r){try{let s=E5;if(!e.bypass_auth&&!t.permissions_checked){let i=mL(e,t);if(i&&i.length>0)return r(l5,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Mc.VALID_SQL_OPS_ENUM.SELECT:s=r5,n=t.ast.statements[0];break;case Mc.VALID_SQL_OPS_ENUM.INSERT:s=f5;break;case Mc.VALID_SQL_OPS_ENUM.UPDATE:s=n5;break;case Mc.VALID_SQL_OPS_ENUM.DELETE:s=i5;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(pL,"processAST");function E5(e,t){z_.info(e),t("unknown sql statement")}a(E5,"nullFunction");function f5({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=h5(i,e.values)}catch(o){return r(o)}t5(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){z_.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(f5,"convertInsert");function h5(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]]=Dn.compile(`SELECT ${n.toString()} AS [${Mc.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw z_.error(r),new Error(_5)}}a(h5,"createDataObjects")});var pp=m((mle,gL)=>{"use strict";var{S3:m5,GetObjectCommand:S5}=require("@aws-sdk/client-s3");gL.exports={getFileStreamFromS3:p5,getS3AuthObj:RL};async function p5(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await RL(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new S5(r))).Body}a(p5,"getFileStreamFromS3");function RL(e,t,r){return new m5({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(RL,"getS3AuthObj")});var X_=m((ple,DL)=>{"use strict";var NL=Tr(),T5=J_(),R5=pp(),{AsyncParser:g5,Transform:A5}=require("json2csv"),vc=require("stream"),Er=x(),Tp=require("fs-extra"),O5=require("path"),Cr=F(),{promisify:bL}=require("util"),Pc=x(),{handleHDBError:Je,hdb_errors:N5}=W(),{HDB_ERROR_MSGS:Jt,HTTP_STATUS_CODES:Xe}=N5,{streamAsJSON:b5}=JE(),{Upload:y5}=require("@aws-sdk/lib-storage"),AL=["search_by_value","search_by_hash","sql"],OL=["json","csv"],yL="json",IL="csv",I5="Successfully exported JSON locally.",w5="Successfully exported CSV locally.",C5=1e3,U5=NL.searchByHash,D5=NL.searchByValue,L5=bL(T5.evaluateSQL),M5=bL(vc.finished);DL.exports={export_to_s3:H5,export_local:P5,toCsvStream:wL};async function P5(e){Cr.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=CL(e);if(!Er.isEmpty(t))throw Cr.error(t),Je(new Error,t,Xe.BAD_REQUEST,void 0,void 0,!0);if(Er.isEmpty(e.path))throw Cr.error(Jt.MISSING_VALUE("path")),Je(new Error,Jt.MISSING_VALUE("path"),Xe.BAD_REQUEST,void 0,void 0,!0);let r=(Er.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(O5.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Er.buildFolderPath(e.path,r);await v5(e.path);let n=await UL(e);return await B5(s,e.format,n)}a(P5,"export_local");async function v5(e){if(Cr.trace("in confirmPath"),Er.isEmptyOrZeroLength(e))throw Je(new Error,`Invalid path: ${e}`,Xe.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Tp.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,Cr.error(s),Je(new Error,s,Xe.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 Cr.error(r),Je(new Error,r,Xe.BAD_REQUEST,void 0,void 0,!0)}return!0}a(v5,"confirmPath");async function B5(e,t,r){if(Cr.trace("in saveToLocal"),Pc.isEmptyOrZeroLength(e))throw Je(new Error,Jt.INVALID_VALUE("file_path"),Xe.BAD_REQUEST,void 0,void 0,!0);if(Pc.isEmptyOrZeroLength(t))throw Je(new Error,Jt.INVALID_VALUE("Source format"),Xe.BAD_REQUEST,void 0,void 0,!0);if(Pc.isEmpty(r))throw Je(new Error,Jt.NOT_FOUND("Data"),Xe.BAD_REQUEST,void 0,void 0,!0);if(t===yL){let s=Tp.createWriteStream(e);return b5(r).pipe(s),await M5(s),{message:I5,path:e}}else if(t===IL){let s=Tp.createWriteStream(e),n=vc.Readable.from(r),i={},o={objectMode:!0};return await new g5(i,o).fromInput(n).toOutput(s).promise(!1),{message:w5,path:e}}throw Je(new Error,Jt.INVALID_VALUE("format"),Xe.BAD_REQUEST)}a(B5,"saveToLocal");async function H5(e){if(!e.s3||Object.keys(e.s3).length===0)throw Je(new Error,Jt.MISSING_VALUE("S3 object"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Je(new Error,Jt.MISSING_VALUE("aws_access_key_id"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Je(new Error,Jt.MISSING_VALUE("aws_secret_access_key"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.bucket))throw Je(new Error,Jt.MISSING_VALUE("bucket"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.key))throw Je(new Error,Jt.MISSING_VALUE("key"),Xe.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.region))throw Je(new Error,Jt.MISSING_VALUE("region"),Xe.BAD_REQUEST);let t=CL(e);if(!Er.isEmpty(t))throw Je(new Error,t,Xe.BAD_REQUEST);Cr.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await UL(e)}catch(u){throw Cr.error(u),u}let s,n=await R5.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new vc.PassThrough;if(e.format===IL){i=e.s3.key+".csv";let u=wL(r);u.on("error",l=>{throw l}),u.pipe(o)}else if(e.format===yL){i=e.s3.key+".json";let u=new vc.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let l=r.length,_="";for(let[d,E]of r.entries()){let f=d===l-1?JSON.stringify(E):JSON.stringify(E)+",";_+=f,d!==0&&d%C5===0&&(u.push(_),_="")}_.length!==0&&u.push(_),u.push("]"),u.push(null)}else throw Je(new Error,Jt.INVALID_VALUE("format"),Xe.BAD_REQUEST);return new y5({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(H5,"export_to_s3");function wL(e){let t=vc.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),r={},s={objectMode:!0},n=new A5(r,s);return t.pipe(n)}a(wL,"toCsvStream");function CL(e){if(Cr.trace("in exportCoreValidation"),Er.isEmpty(e.format))return"format missing";if(OL.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${OL.join(", ")}`;let t=e.search_operation.operation;if(Er.isEmpty(t))return"search_operation.operation missing";if(AL.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${AL.join(", ")}`}a(CL,"exportCoreValidation");async function UL(e){Cr.trace("in getRecords");let t,r;if(Pc.isEmpty(e.search_operation)||Pc.isEmptyOrZeroLength(e.search_operation.operation))throw Je(new Error,Jt.INVALID_VALUE("Search operation"),Xe.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=D5;break;case"search_by_hash":t=U5;break;case"sql":t=L5;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Cr.error(r),Je(new Error,r,Xe.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(UL,"getRecords")});var HL={};Ze(HL,{contentTypes:()=>vL,findBestSerializer:()=>td,getDeserializer:()=>yo,registerContentHandlers:()=>gp,serialize:()=>Ap,serializeMessage:()=>Ks});function q5(e){try{return e?.[0]===123?JSON.parse(e):e}catch{return e}}function gp(e){e.register(G5,{serializers:[{regex:/^application\/json$/,serializer:Z_.streamAsJSON},{regex:/^application\/cbor$/,serializer:function(t){return new pi.EncoderStream(Bc).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?ed.Readable.from((0,ms.encodeIter)(t,Bc)):(0,ms.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Rp.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,ms.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,pi.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function td(e){let t=e.headers.accept,r,s=0,n,i,o=t?t.toLowerCase().split(/\s*,\s*/):[];for(let c of o){let[u,...l]=c.split(/\s*;\s*/),_=1,d={q:1};for(let f of l){let h=f.indexOf("=");d[f.substring(0,h)]=f.substring(h+1)}_=+d.q;let E=dt.get(u);if(E){let f=(E.q||1)*_;f>s&&(r=E,n=E.type||u,s=f,i=d)}}if(!r){if(t)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(dt.keys()).join(", "))}};r=dt.get("application/json"),n="application/json"}return{serializer:r,type:n,parameters:i}}function Ap(e,t,r){let s=t.headers["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null&&(r.headers["Content-Type"]=e.contentType,r.headers.Vary="Accept-Encoding",n=e.data),e instanceof Uint8Array)r.headers["Content-Type"]="application/octet-stream",r.headers.Vary="Accept-Encoding",n=e;else{let i=td(t);if(r.headers.Vary="Accept, Accept-Encoding",r.headers["Content-Type"]=i.type,e[Symbol.iterator]&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e);return s&&(r.headers["Content-Encoding"]="br",o=o.pipe((0,j_.createBrotliCompress)({}))),o}n=i.serializer.serialize(e)}return s?(r.headers["Content-Encoding"]="br",new Promise((i,o)=>(0,j_.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ks(e,t){if(e?.contentType!=null&&e.data!=null)return e;let r=t.serialize;if(r)return r(e);let s=td(t);return r=t.serialize=s.serializer.serialize,r(e)}function x5(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 yo(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=dt.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=dt.get(e)?.deserialize||ML(e,s);return o=>x5(o).then(i)}return dt.get(e)?.deserialize||ML(e,s)}function ML(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=>({contentType:e,data:r})}function k5(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 Z_,Rp,ms,pi,j_,ed,PL,Bc,dt,vL,LL,BL,F5,G5,go=pe(()=>{Z_=D(JE()),Rp=D(X_()),ms=require("msgpackr"),pi=require("cbor-x"),j_=require("zlib"),ed=require("stream");Us();PL=require("../../index"),Bc={useRecords:!1,useToJSON:!0};ht.contentType=function(e,t){dt.set(e,t)};dt=new Map,vL=dt;(0,PL._assignPackageExport)("contentTypes",vL);dt.set("application/json",{serializeStream:Z_.streamAsJSON,serialize:JSON.stringify,deserialize:JSON.parse,q:.8});LL=new pi.Encoder(Bc);dt.set("application/cbor",{serializeStream(e){return new pi.EncoderStream(Bc).end(e)},serialize:LL.encode,deserialize:LL.decode,q:1});dt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?ed.Readable.from((0,ms.encodeIter)(e,Bc)):(0,ms.pack)(e)},serialize:ms.pack,deserialize:ms.unpack,q:.9});dt.set("text/csv",{serializeStream(e){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Rp.toCsvStream)(e)},q:.1});dt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});dt.set("text/event-stream",{serializeStream:function(e){return ed.Readable.from(k5(e,this.serialize))},serialize:function(e){if(e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
13
|
+
`,""):null}catch(E){E.stderr?i[u].npm_error=QD(E.stderr):i[u].npm_error=E.message;continue}try{i[u].npm_output=JSON.parse(_)}catch{i[u].npm_output=_}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return Cc.info(`finished installModules with response ${i}`),i}a(vj,"installModules");function QD(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
|
|
14
|
+
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(QD,"parseNPMStdErr");async function Bj(e){Cc.info(`starting auditModules for request: ${e}`);let t=JD(e);if(t)throw yo(t,t.message,Io.BAD_REQUEST);let{projects:r}=e;await K_(),await zD(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=Y_.join(cp,o);s[o]={npm_output:null,npm_error:null};try{let u=await Dc("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=QD(u.stderr)}}return Cc.info(`finished auditModules with response ${s}`),s}a(Bj,"auditModules");async function K_(){try{return await Dc("npm -v"),!0}catch{throw yo(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Io.BAD_REQUEST,void 0,void 0,!0)}}a(K_,"checkNPMInstalled");async function zD(e){if(!Array.isArray(e)||e.length===0)throw yo(new Error,"projects argument must be an array with at least 1 element",Io.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=Y_.join(cp,i.toString());if(!await YD.pathExists(o)){t.push(i);continue}let u=Y_.join(o,"package.json");await YD.pathExists(u)||r.push(i)}if(t.length>0)throw yo(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Io.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw yo(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Io.BAD_REQUEST,void 0,void 0,!0)}a(zD,"checkProjectPaths");function JD(e){let t=$_.object({projects:$_.array().min(1).items($_.string()).required(),dry_run:$_.boolean().default(!1)});return Uj.validateBySchema(e,t)}a(JD,"modulesValidator")});var jD=m((mle,ZD)=>{"use strict";var up=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}};ZD.exports=up});var tL=m((ple,eL)=>{"use strict";var lp=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};eL.exports=lp});var dp=m((Rle,sL)=>{"use strict";var rL=jD(),Hj=tL(),{HDB_ERROR_MSGS:qj}=rr(),_p=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=qj.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 rL(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new Hj(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 rL(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}};sL.exports=_p});var X_=m((Ale,TL)=>{"use strict";var Ep=Ar(),Q_=gr(),Ur=Wl(),Pc=Qn(),fp=jn(),Fj=ym(),Gj=Aw(),vc=br(),z_=vm(),ct=x(),xj=qm(),kj=l_(),Vj=TS(),$j=f_(),Yj=RS(),Kj=gS(),Wj=NS(),Qj=yS(),hp=CS(),Js=V(),zj=TU(),mp=PS(),oL=XS(),Cr=A(),aL=TD(),Jj=So(),cL=ic(),uL=(F_(),ee(yc)),lL=Nr(),dr=ip(),Xj=require("alasql"),_L=V_(),dL=W_(),EL=dp(),{handleHDBError:zt,hdb_errors:fL}=W(),{HDB_ERROR_MSGS:At,HTTP_STATUS_CODES:Lc}=fL,M=new Map,hL="delete",Dn="insert",Xs="read",Ti="update",Mc="describe",nL=Pc.describeSchema.name,iL=Pc.describeTable.name,mL={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},Zj="catchup",jj="handleGetJob",e5="handleGetJobsByStartDate",J_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},t5=[Ur.createTable.name,Ur.createAttribute.name,Ur.dropTable.name,Ur.dropAttribute.name],SL={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},H=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};M.set(Ep.insert.name,new H(!1,[Dn]));M.set(Ep.update.name,new H(!1,[Ti]));M.set(Ep.upsert.name,new H(!1,[Dn,Ti]));M.set(Q_.searchByConditions.name,new H(!1,[Xs]));M.set(Q_.searchByHash.name,new H(!1,[Xs]));M.set(Q_.searchByValue.name,new H(!1,[Xs]));M.set(Q_.search.name,new H(!1,[Xs]));M.set(Ur.createSchema.name,new H(!0,[]));M.set(Ur.createTable.name,new H(!0,[]));M.set(Ur.createAttribute.name,new H(!1,[Dn]));M.set(Ur.dropSchema.name,new H(!0,[]));M.set(Ur.dropTable.name,new H(!0,[]));M.set(Ur.dropAttribute.name,new H(!0,[]));M.set(Pc.describeSchema.name,new H(!1,[Xs]));M.set(Pc.describeTable.name,new H(!1,[Xs]));M.set(fp.deleteRecord.name,new H(!1,[hL]));M.set(vc.addUser.name,new H(!0,[]));M.set(vc.alterUser.name,new H(!0,[]));M.set(vc.dropUser.name,new H(!0,[]));M.set(vc.listUsersExternal.name,new H(!0,[]));M.set(z_.listRoles.name,new H(!0,[]));M.set(z_.addRole.name,new H(!0,[]));M.set(z_.alterRole.name,new H(!0,[]));M.set(z_.dropRole.name,new H(!0,[]));M.set(xj.name,new H(!0,[]));M.set(kj.name,new H(!0,[]));M.set(Vj.name,new H(!0,[]));M.set($j.name,new H(!0,[]));M.set(Yj.name,new H(!0,[]));M.set(Kj.name,new H(!0,[]));M.set(hp.setRoutes.name,new H(!0,[]));M.set(hp.getRoutes.name,new H(!0,[]));M.set(hp.deleteRoutes.name,new H(!0,[]));M.set(lL.setConfiguration.name,new H(!0,[]));M.set(Wj.clusterStatus.name,new H(!0,[]));M.set(Qj.name,new H(!0,[]));M.set(mp.getFingerprint.name,new H(!0,[]));M.set(mp.setLicense.name,new H(!0,[]));M.set(fp.deleteFilesBefore.name,new H(!0,[]));M.set(fp.deleteAuditLogsBefore.name,new H(!0,[]));M.set(oL.restart.name,new H(!0,[]));M.set(oL.restartService.name,new H(!0,[]));M.set(Fj.name,new H(!0,[]));M.set(Gj.name,new H(!0,[Xs]));M.set(Jj.systemInformation.name,new H(!0,[]));M.set(lL.getConfiguration.name,new H(!0,[]));M.set(_L.readTransactionLog.name,new H(!0,[]));M.set(_L.deleteTransactionLogsBefore.name,new H(!0,[]));M.set(dL.installModules.name,new H(!0,[]));M.set(dL.auditModules.name,new H(!0,[]));M.set(cL.createTokens.name,new H(!1,[]));M.set(cL.refreshOperationToken.name,new H(!1,[]));M.set(uL.login.name,new H(!1,[]));M.set(uL.logout.name,new H(!1,[]));M.set(dr.customFunctionsStatus.name,new H(!0,[]));M.set(dr.getCustomFunctions.name,new H(!0,[]));M.set(dr.getComponents.name,new H(!0,[]));M.set(dr.getComponentFile.name,new H(!0,[]));M.set(dr.setComponentFile.name,new H(!0,[]));M.set(dr.dropComponent.name,new H(!0,[]));M.set(dr.getCustomFunction.name,new H(!0,[]));M.set(dr.setCustomFunction.name,new H(!0,[]));M.set(dr.dropCustomFunction.name,new H(!0,[]));M.set(dr.addComponent.name,new H(!0,[]));M.set(dr.dropCustomFunctionProject.name,new H(!0,[]));M.set(dr.packageComponent.name,new H(!0,[]));M.set(dr.deployComponent.name,new H(!0,[]));M.set(mp.getRegistrationInfo.name,new H(!1,[]));M.set(vc.userInfo.name,new H(!1,[]));M.set(Pc.describeAll.name,new H(!1,[]));M.set(jj,new H(!1,[]));M.set(e5,new H(!0,[]));M.set(Zj,new H(!0,[]));M.set(J_.CSV_DATA_LOAD,new H(!1,[Dn,Ti]));M.set(J_.CSV_URL_LOAD,new H(!1,[Dn,Ti]));M.set(J_.CSV_FILE_LOAD,new H(!1,[Dn,Ti]));M.set(J_.IMPORT_FROM_S3,new H(!1,[Dn,Ti]));M.set(SL.EXPORT_TO_S3,new H(!0,[]));M.set(SL.EXPORT_LOCAL,new H(!0,[]));M.set(Cr.VALID_SQL_OPS_ENUM.DELETE,new H(!1,[hL]));M.set(Cr.VALID_SQL_OPS_ENUM.SELECT,new H(!1,[Xs]));M.set(Cr.VALID_SQL_OPS_ENUM.INSERT,new H(!1,[Dn]));M.set(Cr.VALID_SQL_OPS_ENUM.UPDATE,new H(!1,[Ti]));TL.exports={verifyPerms:s5,verifyPermsAst:r5,verifyBulkLoadAttributePerms:i5};function r5(e,t,r){if(Js.isEmptyOrZeroLength(e))throw ct.info("verify_perms_ast has an empty user parameter"),zt(new Error);if(Js.isEmptyOrZeroLength(t))throw ct.info("verify_perms_ast has an empty user parameter"),zt(new Error);if(Js.isEmptyOrZeroLength(r))throw ct.info("verify_perms_ast has a null operation parameter"),zt(new Error);try{let s=new EL,n=new zj(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw ct.info("No schemas defined in verifyPermsAst(), will not continue."),zt(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&mL[r])throw zt(new Error,At.DROP_SYSTEM,Lc.FORBIDDEN);if(c&&!u)return null;let l=aL.getRolePermissions(t.role);t.role.permission=l,!c&&e instanceof Xj.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(l));for(let d=0;d<i.length;d++){let E=n.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let _=pL(t,r,o,s);return _||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=n.getAttributesBySchemaTableName(E,d[f]),T=pp(t.role.permission,E,d[f]);Sp(h,T,r,d[f],E,s)}}),s.getPermsResponse())}catch(s){throw zt(s)}}a(r5,"verifyPermsAst");function s5(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw ct.info("null required parameter in verifyPerms"),zt(new Error,At.DEFAULT_INVALID_REQUEST,Lc.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new EL;if(Js.isEmptyOrZeroLength(e.hdb_user.role)||Js.isEmptyOrZeroLength(e.hdb_user.role.permission))return ct.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(At.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,l=e.hdb_user.role.permission.structure_user,_=o.has(Cr.SYSTEM_SCHEMA_NAME)||n===Cr.SYSTEM_SCHEMA_NAME;if(_&&mL[r])throw zt(new Error,At.DROP_SYSTEM,Lc.FORBIDDEN);if(u&&!_||l===!0&&(r===Ur.createSchema.name||r===Ur.dropSchema.name))return null;if(t5.indexOf(r)>=0&&(l===!0||Array.isArray(l)))return l===!0||l.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=aL.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===nL||r===iL){if(n===Cr.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(At.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===nL&&(!d[n]||!d[n][Mc]))return c.handleInvalidItem(At.SCHEMA_NOT_FOUND(n));if(r===iL&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][Mc]))return c.handleInvalidItem(At.TABLE_NOT_FOUND(n,i))}}let E=pL(e.hdb_user,r,o,c,s);if(E)return E;if(M.get(r)&&M.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&Cr.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let T=[],p=d[n].tables[i];p[Cr.PERMS_CRUD_ENUM.READ]&&(p.attribute_permissions.length>0?p.attribute_permissions.filter(O=>O[Cr.PERMS_CRUD_ENUM.READ]).forEach(O=>{T.push(O.attribute_name)}):T=global.hdb_schema[n][i].attributes.map(R=>R.attribute),e.get_attributes=T)}let f=n5(e),h=pp(e.hdb_user.role.permission,n,i);return Sp(f,h,r,i,n,c,s),c.getPermsResponse()}a(s5,"verifyPerms");function pL(e,t,r,s,n){if(Js.arrayHasEmptyValues([e,t,r]))throw ct.info("hasPermissions has an invalid parameter"),zt(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||M.get(t).requires_su))return null;if(!M.get(t))throw ct.info(`operation ${t} not found.`),zt(new Error,At.OP_NOT_FOUND(t),Lc.BAD_REQUEST);if(M.get(t)&&M.get(t).requires_su)return ct.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(At.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][Mc]===!1){s.addInvalidItem(At.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(At.SCHEMA_NOT_FOUND(u));continue}let l=r.get(u);for(let _ of l){let d=o[u].tables[_];if(!d||d[Mc]===!1)s.addInvalidItem(At.TABLE_NOT_FOUND(u,_));else try{let E=[],f=M.get(t).perms;!Js.isEmpty(n)&&f.includes(n)&&(f=[n]);for(let h=0;h<f.length;h++){let T=f[h],p=d[T];(p==null||p===!1)&&(ct.info(`Required ${T} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),E.push(T))}E.length>0&&s.addUnauthorizedTable(u,_,E)}catch(E){let f=At.UNKNOWN_OP_AUTH_ERROR(t,u,_);throw ct.error(f),ct.error(E),zt(fL.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?s.getPermsResponse():null}a(pL,"hasPermissions");function Sp(e,t,r,s,n,i,o){if(!e||!t)throw ct.info("no attributes specified in checkAttributePerms."),zt(new Error);let c=M.get(r).perms;if(!c||c==="")throw ct.info(`no permissions found for ${r} in checkAttributePerms().`),zt(new Error);if(Js.isEmptyOrZeroLength(t))return ct.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let _ of e){let d=t.get(_);if(d){if(d[Mc]===!1){i.addInvalidItem(At.ATTR_NOT_FOUND(n,s,_),n,s);continue}if(c)for(let E of c){if(Cr.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Xs)throw zt(new Error,At.SYSTEM_TIMESTAMP_PERMS_ERR,Lc.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(At.ATTR_NOT_FOUND(n,s,_),n,s)}let l=Object.keys(u);l.length>0&&i.addUnauthorizedAttributes(l,n,s,u)}a(Sp,"checkAttributePerms");function n5(e){let t=new Set;try{if(e.action)return t;if(e.operation===Cr.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){ct.info(r)}return t}a(n5,"getRecordAttributes");function pp(e,t,r){let s=new Map;if(Js.isEmpty(e))return ct.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{ct.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(pp,"getAttributePermissions");function i5(e,t,r,s,n,i,o){let c=new Set(i),u=pp(e,s,n);Sp(c,u,t,n,s,o,r)}a(i5,"verifyBulkLoadAttributePerms")});var j_=m((Nle,NL)=>{"use strict";NL.exports={evaluateSQL:p5,processAST:OL,convertSQLToAST:AL,checkASTPermissions:gL};var o5=Ar(),RL=require("util"),a5=RL.callbackify(o5.insert),c5=gr().search,u5=TI().update,l5=RL.callbackify(u5),_5=gI().convertDelete,Ln=require("alasql"),d5=X_(),Z_=x(),E5=Dl(),f5=V(),Bc=A(),{hdb_errors:h5,handleHDBError:Tp}=W(),{HTTP_STATUS_CODES:Rp}=h5;E5(Ln);var m5=403,S5="There was a problem performing this insert. Please check the logs and try again.",gp=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function p5(e,t){let r=e.parsed_sql_object;if(!r){r=AL(e.sql);let s,n=r.ast.statements[0];if(n instanceof Ln.yy.Insert?s=n.into.databaseid:n instanceof Ln.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Ln.yy.Update||n instanceof Ln.yy.Delete?s=n.table.databaseid:Z_.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Ln.yy.Select)&&f5.isEmptyOrZeroLength(s))return t("No schema specified",null)}OL(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(p5,"evaluateSQL");function gL(e,t){let r;try{r=d5.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(gL,"checkASTPermissions");function AL(e){let t=new gp;if(!e)throw Tp(new Error,"The 'sql' parameter is missing from the request body",Rp.BAD_REQUEST);try{let r=e.trim(),s=Ln.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
15
|
+
`);throw s[1]?Tp(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Rp.BAD_REQUEST):Tp(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Rp.BAD_REQUEST)}return t}a(AL,"convertSQLToAST");function OL(e,t,r){try{let s=T5;if(!e.bypass_auth&&!t.permissions_checked){let i=gL(e,t);if(i&&i.length>0)return r(m5,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Bc.VALID_SQL_OPS_ENUM.SELECT:s=c5,n=t.ast.statements[0];break;case Bc.VALID_SQL_OPS_ENUM.INSERT:s=R5;break;case Bc.VALID_SQL_OPS_ENUM.UPDATE:s=l5;break;case Bc.VALID_SQL_OPS_ENUM.DELETE:s=_5;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(OL,"processAST");function T5(e,t){Z_.info(e),t("unknown sql statement")}a(T5,"nullFunction");function R5({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=g5(i,e.values)}catch(o){return r(o)}a5(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Z_.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(R5,"convertInsert");function g5(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]]=Ln.compile(`SELECT ${n.toString()} AS [${Bc.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw Z_.error(r),new Error(S5)}}a(g5,"createDataObjects")});var Ap=m((yle,yL)=>{"use strict";var{S3:A5,GetObjectCommand:O5}=require("@aws-sdk/client-s3");yL.exports={getFileStreamFromS3:N5,getS3AuthObj:bL};async function N5(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await bL(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new O5(r))).Body}a(N5,"getFileStreamFromS3");function bL(e,t,r){return new A5({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(bL,"getS3AuthObj")});var ed=m((wle,BL)=>{"use strict";var CL=gr(),b5=j_(),y5=Ap(),{AsyncParser:I5,Transform:w5}=require("json2csv"),qc=require("stream"),Er=V(),Op=require("fs-extra"),C5=require("path"),Dr=x(),{promisify:UL}=require("util"),Hc=V(),{handleHDBError:Xe,hdb_errors:U5}=W(),{HDB_ERROR_MSGS:Jt,HTTP_STATUS_CODES:Ze}=U5,{streamAsJSON:D5}=ef(),{Upload:L5}=require("@aws-sdk/lib-storage"),IL=["search_by_value","search_by_hash","sql"],wL=["json","csv"],DL="json",LL="csv",M5="Successfully exported JSON locally.",P5="Successfully exported CSV locally.",v5=1e3,B5=CL.searchByHash,H5=CL.searchByValue,q5=UL(b5.evaluateSQL),F5=UL(qc.finished);BL.exports={export_to_s3:V5,export_local:G5,toCsvStream:ML};async function G5(e){Dr.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=PL(e);if(!Er.isEmpty(t))throw Dr.error(t),Xe(new Error,t,Ze.BAD_REQUEST,void 0,void 0,!0);if(Er.isEmpty(e.path))throw Dr.error(Jt.MISSING_VALUE("path")),Xe(new Error,Jt.MISSING_VALUE("path"),Ze.BAD_REQUEST,void 0,void 0,!0);let r=(Er.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(C5.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Er.buildFolderPath(e.path,r);await x5(e.path);let n=await vL(e);return await k5(s,e.format,n)}a(G5,"export_local");async function x5(e){if(Dr.trace("in confirmPath"),Er.isEmptyOrZeroLength(e))throw Xe(new Error,`Invalid path: ${e}`,Ze.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Op.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,Dr.error(s),Xe(new Error,s,Ze.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 Dr.error(r),Xe(new Error,r,Ze.BAD_REQUEST,void 0,void 0,!0)}return!0}a(x5,"confirmPath");async function k5(e,t,r){if(Dr.trace("in saveToLocal"),Hc.isEmptyOrZeroLength(e))throw Xe(new Error,Jt.INVALID_VALUE("file_path"),Ze.BAD_REQUEST,void 0,void 0,!0);if(Hc.isEmptyOrZeroLength(t))throw Xe(new Error,Jt.INVALID_VALUE("Source format"),Ze.BAD_REQUEST,void 0,void 0,!0);if(Hc.isEmpty(r))throw Xe(new Error,Jt.NOT_FOUND("Data"),Ze.BAD_REQUEST,void 0,void 0,!0);if(t===DL){let s=Op.createWriteStream(e);return D5(r).pipe(s),await F5(s),{message:M5,path:e}}else if(t===LL){let s=Op.createWriteStream(e),n=qc.Readable.from(r),i={},o={objectMode:!0};return await new I5(i,o).fromInput(n).toOutput(s).promise(!1),{message:P5,path:e}}throw Xe(new Error,Jt.INVALID_VALUE("format"),Ze.BAD_REQUEST)}a(k5,"saveToLocal");async function V5(e){if(!e.s3||Object.keys(e.s3).length===0)throw Xe(new Error,Jt.MISSING_VALUE("S3 object"),Ze.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Xe(new Error,Jt.MISSING_VALUE("aws_access_key_id"),Ze.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Xe(new Error,Jt.MISSING_VALUE("aws_secret_access_key"),Ze.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.bucket))throw Xe(new Error,Jt.MISSING_VALUE("bucket"),Ze.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.key))throw Xe(new Error,Jt.MISSING_VALUE("key"),Ze.BAD_REQUEST);if(Er.isEmptyOrZeroLength(e.s3.region))throw Xe(new Error,Jt.MISSING_VALUE("region"),Ze.BAD_REQUEST);let t=PL(e);if(!Er.isEmpty(t))throw Xe(new Error,t,Ze.BAD_REQUEST);Dr.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await vL(e)}catch(u){throw Dr.error(u),u}let s,n=await y5.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new qc.PassThrough;if(e.format===LL){i=e.s3.key+".csv";let u=ML(r);u.on("error",l=>{throw l}),u.pipe(o)}else if(e.format===DL){i=e.s3.key+".json";let u=new qc.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let l=r.length,_="";for(let[d,E]of r.entries()){let f=d===l-1?JSON.stringify(E):JSON.stringify(E)+",";_+=f,d!==0&&d%v5===0&&(u.push(_),_="")}_.length!==0&&u.push(_),u.push("]"),u.push(null)}else throw Xe(new Error,Jt.INVALID_VALUE("format"),Ze.BAD_REQUEST);return new L5({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(V5,"export_to_s3");function ML(e){let t=qc.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),r={},s={objectMode:!0},n=new w5(r,s);return t.pipe(n)}a(ML,"toCsvStream");function PL(e){if(Dr.trace("in exportCoreValidation"),Er.isEmpty(e.format))return"format missing";if(wL.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${wL.join(", ")}`;let t=e.search_operation.operation;if(Er.isEmpty(t))return"search_operation.operation missing";if(IL.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${IL.join(", ")}`}a(PL,"exportCoreValidation");async function vL(e){Dr.trace("in getRecords");let t,r;if(Hc.isEmpty(e.search_operation)||Hc.isEmptyOrZeroLength(e.search_operation.operation))throw Xe(new Error,Jt.INVALID_VALUE("Search operation"),Ze.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=H5;break;case"search_by_hash":t=B5;break;case"sql":t=q5;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Dr.error(r),Xe(new Error,r,Ze.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(vL,"getRecords")});var kL={};Ye(kL,{contentTypes:()=>GL,findBestSerializer:()=>nd,getDeserializer:()=>wo,registerContentHandlers:()=>bp,serialize:()=>yp,serializeMessage:()=>Ws});function $5(e){try{return e?.[0]===123?JSON.parse(e):e}catch{return e}}function bp(e){e.register(K5,{serializers:[{regex:/^application\/json$/,serializer:td.streamAsJSON},{regex:/^application\/cbor$/,serializer:function(t){return new Ri.EncoderStream(Fc).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?sd.Readable.from((0,ps.encodeIter)(t,Fc)):(0,ps.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Np.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,ps.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,Ri.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function nd(e){let t=e.headers.accept,r,s=0,n,i,o=t?t.toLowerCase().split(/\s*,\s*/):[];for(let c of o){let[u,...l]=c.split(/\s*;\s*/),_=1,d={q:1};for(let f of l){let h=f.indexOf("=");d[f.substring(0,h)]=f.substring(h+1)}_=+d.q;let E=Et.get(u);if(E){let f=(E.q||1)*_;f>s&&(r=E,n=E.type||u,s=f,i=d)}}if(!r){if(t)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(Et.keys()).join(", "))}};r=Et.get("application/json"),n="application/json"}return{serializer:r,type:n,parameters:i}}function yp(e,t,r){let s=t.headers["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),e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=nd(t);if(r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),e[Symbol.iterator]&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e);return s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,rd.createBrotliCompress)({}))),o}n=i.serializer.serialize(e)}return s?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,rd.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ws(e,t){if(e?.contentType!=null&&e.data!=null)return e;let r=t.serialize;if(r)return r(e);let s=nd(t);return r=t.serialize=s.serializer.serialize,r(e)}function W5(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 wo(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=Et.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=Et.get(e)?.deserialize||qL(e,s);return o=>W5(o).then(i)}return Et.get(e)?.deserialize||qL(e,s)}function qL(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=>({contentType:e,data:r})}function Q5(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 td,Np,ps,Ri,rd,sd,FL,Fc,Et,GL,HL,xL,Y5,K5,Oo=Se(()=>{td=C(ef()),Np=C(ed()),ps=require("msgpackr"),Ri=require("cbor-x"),rd=require("zlib"),sd=require("stream");Pr();FL=require("../../index"),Fc={useRecords:!1,useToJSON:!0};tt.contentType=function(e,t){Et.set(e,t)};Et=new Map,GL=Et;(0,FL._assignPackageExport)("contentTypes",GL);Et.set("application/json",{serializeStream:td.streamAsJSON,serialize:JSON.stringify,deserialize:JSON.parse,q:.8});HL=new Ri.Encoder(Fc);Et.set("application/cbor",{serializeStream(e){return new Ri.EncoderStream(Fc).end(e)},serialize:HL.encode,deserialize:HL.decode,q:1});Et.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?sd.Readable.from((0,ps.encodeIter)(e,Fc)):(0,ps.pack)(e)},serialize:ps.pack,deserialize:ps.unpack,q:.9});Et.set("text/csv",{serializeStream(e){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Np.toCsvStream)(e)},q:.1});Et.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});Et.set("text/event-stream",{serializeStream:function(e){return sd.Readable.from(Q5(e,this.serialize))},serialize:function(e){if(e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
16
16
|
`),e.data){let r=e.data;typeof r=="object"&&(r=JSON.stringify(r)),t+="data: "+r+`
|
|
17
17
|
`}return e.id&&(t+="id: "+e.id+`
|
|
18
18
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
19
19
|
`),t+`
|
|
20
20
|
`}else return"data: "+e+`
|
|
21
21
|
|
|
22
|
-
`},q:.8});dt.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()}});BL={type:"application/json",serializeStream:Z_.streamAsJSON,serialize:JSON.stringify,deserialize:q5,q:.8};dt.set("*/*",BL);dt.set("",BL);a(q5,"tryJSONParse");a(gp,"registerContentHandlers");F5=require("fastify-plugin"),G5=F5(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=td(s.raw);n.type(c),n.serializer(o.serializeStream||o.serialize)}),r()},{name:"content-type-negotiation"});a(td,"findBestSerializer");a(Ap,"serialize");a(Ks,"serializeMessage");a(x5,"streamToBuffer");a(yo,"getDeserializer");a(ML,"deserializerUnknownType");a(k5,"transformIterable")});var yp={};Ze(yp,{start:()=>Y5});async function $5(e,t){let r=e.headers.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Cu(e);let s=performance.now(),n;try{let i=new bp;e.responseHeaders=i;let o=e.url.slice(1),c=Np.getMatch(o);if(!c)return t(e);let u={url:c.relativeURL},l=c.Resource,_=await Ye(e,()=>{if(r==="POST"||r==="PUT"||r==="PATCH"||r==="QUERY")try{e.data=yo(e.headers["content-type"],!0)(e.body)}catch(T){throw new Hc.ClientError(T,400)}switch(e.authorize=!0,r){case"GET":case"HEAD":return l.get(u,e);case"POST":return l.post(u,e.data,e);case"PUT":return l.put(u,e.data,e);case"DELETE":return l.delete(u,e);case"PATCH":return l.patch(u,e.data,e);case"OPTIONS":i.Allow="GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACe, QUERY, COPY, MOVE";return;case"CONNECT":return l.connect(u,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(u,e.data,e);case"COPY":return l.copy(u,e.headers.destination,e);case"MOVE":return l.move(u,e.headers.destination,e);case"BREW":throw new Hc.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Hc.ServerError(`Method ${r} is not recognized`,501)}}),d=performance.now()-s,E=200,f;if(_==null)E=r==="GET"||r==="HEAD"?404:204;else if(f=e?.lastModified){V5[0]=f;let T=String.fromCharCode(34,(Ot[0]&63)+62,(Ot[0]>>6)+(Ot[1]<<2&63)+62,(Ot[1]>>4)+(Ot[2]<<4&63)+62,(Ot[2]>>2)+62,(Ot[3]&63)+62,(Ot[3]>>6)+(Ot[4]<<2&63)+62,(Ot[4]>>4)+(Ot[5]<<4&63)+62,(Ot[5]>>2)+62,(Ot[6]&63)+62,(Ot[6]>>6)+(Ot[7]<<2&63)+62,34),S=e.headers["if-none-match"];S&&T==S?(_?.onDone&&_.onDone(),E=304,_=void 0):i.ETag=T}e.createdResource&&(E=201),e.newLocation&&(i.Location=e.newLocation);let h={status:E,headers:i,body:void 0};return i["Server-Timing"]=`db;dur=${d.toFixed(2)}`,ai(d,"TTFB",n,r),vl(E<400,"success",n,r),_!==void 0&&(h.body=Ap(_,e,h),r==="HEAD"&&(h.body=void 0)),h}catch(i){let o=performance.now()-s;ai(o,"TTFB",n,r),vl(!1,"success",n,r),i.http_resp_code||console.error(i);let c={};return i.http_resp_code===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),c.Allow=i.allow.map(u=>u.toUpperCase()).join(", "))),{status:i.http_resp_code||500,headers:c,body:Ks(i.toString(),e)}}}function Y5(e){if(qL)return;qL=!0,Np=e.resources,e.server.http(async(r,s)=>{if(!r.isWebSocket)return $5(r,s)}),e.server.ws(async(r,s,n)=>{FL++,Op||(setTimeout(()=>{console.log("connection count",FL,"mem",Math.round(process.memoryUsage().heapUsed/1e6)),Op=!1},1e3),Op=!0),t(s);let i=new Jr;r.on("error",console.error);let o;r.on("message",a(function(d){o||(o=yo(s.headers["content-type"]));let E=o(d);i.push(E)},"message"));let c;r.on("close",()=>{i.emit("close"),c&&c.return()}),await n;let u,l=await Np.call(s.pathname.slice(1),s,(_,d)=>(u=!0,_.connect(i)));if(!u)r.send(Ks(`No resource was found to handle ${s.pathname}`,s));else{c=l[Symbol.asyncIterator]();let _;for(;!(_=await c.next()).done;)r.send(Ks(_.value,s))}r.close()});function t(r){let s=r.pathname,n=s.lastIndexOf(".");if(n>-1){let i=s.slice(n+1),o=EXTENSION_TYPES[i];o&&(r.headers.accept=o)}}a(t,"startRequest")}var Hc,Ot,V5,qL,Np,FL,Op,bp,GL=pe(()=>{go();ro();Hc=D(W());Uu();aa();Vn();Ot=new Uint8Array(8),V5=new Float64Array(Ot.buffer,0,1);a($5,"http");FL=0;a(Y5,"start");bp=class{static{a(this,"Headers")}set(t,r){this[t]=r}}});var Ip=m((Cle,xL)=>{var{recordAction:rd,recordActionBinary:K5}=(ro(),te(Bl)),W5=require("fastify-plugin"),Q5=200;xL.exports=W5(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.context.config,l,_,d;u.isOperation?(l=s.body?.operation,_="operation"):(l=u.url,_="fastify-route",d=u.method),rd(o,"TTFB",l,d,_),K5(n.raw.statusCode<400,"success",l,d,_);let E=Q5;i?.pipe?(i.on("data",h=>{E+=h.length}),i.on("end",()=>{rd(performance.now()-c,"transfer",l,d,_),rd(E,"bytes-sent",l,d,_)})):(E+=i?.length||0,rd(E,"bytes-sent",l,d,_));let f=o.toFixed(3);n.header("Server-Timing",`db;dur=${f}`)}),r()},{name:"hdb-request-time"})});var Dp=m((Ule,KL)=>{var ad=require("clone"),cd=ve(),z5=x(),id=g(),J5=F(),sd=require("fs"),wp=require("joi"),{string:od}=wp.types(),{hdb_errors:X5,handleHDBError:qc}=W(),{HDB_ERROR_MSGS:Z5,HTTP_STATUS_CODES:nd}=X5,{common_validators:Io}=ts(),kL=1e9,VL=" is required",j5=["insert","update","upsert"],Cp={database:{presence:!1,format:Io.schema_format,length:Io.schema_length},schema:{presence:!1,format:Io.schema_format,length:Io.schema_length},table:{presence:!0,format:Io.schema_format,length:Io.schema_length},action:{inclusion:{within:j5,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},e8={schema:od.required(),table:od.required(),action:od.valid("insert","update","upsert")},{AWS_ACCESS_KEY:t8,AWS_SECRET:r8,AWS_BUCKET:s8,AWS_FILE_KEY:n8,REGION:i8}=id.S3_BUCKET_AUTH_KEYS,o8={s3:{presence:!0},[`s3.${t8}`]:{presence:!0,type:"String"},[`s3.${r8}`]:{presence:!0,type:"String"},[`s3.${s8}`]:{presence:!0,type:"String"},[`s3.${n8}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${i8}`]:{presence:!0,type:"String"}},$L=ad(Cp);$L.data.presence={message:VL};var YL=ad(Cp);YL.file_path.presence={message:VL};var a8=Object.assign(ad(Cp),o8),Up=ad(e8);Up.csv_url=od.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Up.passthrough_headers=wp.object();function c8(e){let t=cd.validateObject(e,$L);return ud(e,t)}a(c8,"dataObject");function u8(e){let t=cd.validateBySchema(e,wp.object(Up));return ud(e,t)}a(u8,"urlObject");function l8(e){let t=cd.validateObject(e,YL);return ud(e,t)}a(l8,"fileObject");function _8(e){let t=cd.validateObject(e,a8);return ud(e,t)}a(_8,"s3FileObject");function ud(e,t){if(!t){let r=z5.checkGlobalSchemaTable(e.schema,e.table);if(r)return qc(new Error,r,nd.BAD_REQUEST);if(e.operation===id.OPERATIONS_ENUM.CSV_FILE_LOAD){try{sd.accessSync(e.file_path,sd.constants.R_OK|sd.constants.F_OK)}catch(s){return s.code===id.NODE_ERROR_CODES.ENOENT?qc(s,`No such file or directory ${s.path}`,nd.BAD_REQUEST):s.code===id.NODE_ERROR_CODES.EACCES?qc(s,`Permission denied ${s.path}`,nd.BAD_REQUEST):qc(s)}try{let s=sd.statSync(e.file_path).size;if(s>kL)return qc(new Error,Z5.MAX_FILE_SIZE_ERR(s,kL),nd.BAD_REQUEST)}catch(s){J5.error(s),console.error(s)}}}return t}a(ud,"postValidateChecks");KL.exports={dataObject:c8,urlObject:u8,fileObject:l8,s3FileObject:_8}});var Lp=m((Lle,WL)=>{"use strict";var Fc=F(),ld=g();async function d8(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===ld.OPERATIONS_ENUM.INSERT||t.operation===ld.OPERATIONS_ENUM.UPDATE||t.operation===ld.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===ld.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(Fc.info(i.message),i):i.http_resp_msg?(Fc.error(`Error calling operation: ${e.name}`),Fc.error(i.http_resp_msg),i):(Fc.error(`Error calling operation: ${e.name}`),Fc.error(i),i)}}a(d8,"callOperationFunctionAsAwait");WL.exports={callOperationFunctionAsAwait:d8}});var zL=m((Ple,QL)=>{"use strict";var Mp=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}},Pp=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};QL.exports={BulkLoadFileObject:Mp,BulkLoadDataObject:Pp}});var XL=m((Ble,JL)=>{"use strict";var vp=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};JL.exports=vp});var xp=m((kle,fM)=>{"use strict";var _d=Rr(),Ed=Dp(),E8=require("needle"),Yr=g(),qle=Be(),wo=x(),{handleHDBError:qe,hdb_errors:oM}=W(),{HTTP_STATUS_CODES:Nt,HDB_ERROR_MSGS:at,CHECK_LOGS_WRAPPER:Ri}=oM,Co=F(),Bp=require("papaparse");wo.promisifyPapaParse();var Kr=require("fs-extra"),f8=require("path"),{chain:ZL}=require("stream-chain"),jL=require("stream-json/streamers/StreamArray"),eM=require("stream-json/utils/Batch"),tM=require("stream-chain/utils/comp"),{finished:rM}=require("stream"),h8=Q(),aM=Lp(),m8=pp(),{BulkLoadFileObject:qp,BulkLoadDataObject:S8}=zL(),Fp=cp(),{verifyBulkLoadAttributePerms:cM}=Q_(),Fle=XL(),Gle=st(),xle=Ps(),{databases:p8}=(de(),te(Ne)),{coerceType:T8}=(fd(),te(kp)),sM="No records parsed from csv file.",Ti=`${h8.get("HDB_ROOT")}/tmp`,{schema_regex:R8}=ts(),nM=1024*1024*2,iM=5e3,g8={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};fM.exports={csvDataLoad:A8,csvURLLoad:O8,csvFileLoad:N8,importFromS3:b8};async function A8(e,t){let r=Ed.dataObject(e);if(r)throw qe(r,r.message,Nt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=_M(e.schema,e.table),i=Bp.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Hp.bind(null,n),dynamicTyping:!1}),o=new Fp;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&cM(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 qe(new Error,c,Nt.BAD_REQUEST,void 0,void 0,!0);let u=new S8(e.action,e.schema,e.table,i.data);return s=await aM.callOperationFunctionAsAwait(dM,u,null),s.message===sM?sM:EM(s.records,s.number_written)}catch(n){throw gi(n)}}a(A8,"csvDataLoad");async function O8(e){let t=Ed.urlObject(e);if(t)throw qe(t,t.message,Nt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${Ti}/${r}`;try{await y8(e,r)}catch(n){throw Co.error(at.DOWNLOAD_FILE_ERR(r)+" - "+n),qe(n,Ri(at.DOWNLOAD_FILE_ERR(r)))}try{let n=new qp(this.job_operation_function.name,e.action,e.schema,e.table,s,Yr.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Gp(n);return await dd(s),i}catch(n){throw await dd(s),gi(n)}}a(O8,"csvURLLoad");async function N8(e){let t=Ed.fileObject(e);if(t)throw qe(t,t.message,Nt.BAD_REQUEST,void 0,void 0,!0);let r=new qp(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Yr.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Gp(r)}catch(s){throw gi(s)}}a(N8,"csvFileLoad");async function b8(e){let t=Ed.s3FileObject(e);if(t)throw qe(t,t.message,Nt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=f8.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${Ti}/${n}`;let i=new qp(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await I8(n,e);let o=await Gp(i);return await dd(r),o}catch(s){throw await dd(r),gi(s)}}a(b8,"importFromS3");async function y8(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await E8("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 qe(s,n,s.statusCode,Yr.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}C8(r,e.csv_url),await w8(t,r.raw)}a(y8,"downloadCSVFile");async function I8(e,t){try{let r=`${Ti}/${e}`;await Kr.mkdirp(Ti),await Kr.writeFile(`${Ti}/${e}`,"",{flag:"a+"});let s=await Kr.createWriteStream(r),n=await m8.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(){Co.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Co.error(at.S3_DOWNLOAD_ERR+" - "+r),qe(r,Ri(at.S3_DOWNLOAD_ERR))}}a(I8,"downloadFileFromS3");async function w8(e,t){try{await Kr.mkdirp(Ti),await Kr.writeFile(`${Ti}/${e}`,t)}catch(r){throw Co.error(at.WRITE_TEMP_FILE_ERR),qe(r,Ri(at.DEFAULT_BULK_LOAD_ERR))}}a(w8,"writeFileToTempFolder");async function dd(e){if(e)try{await Kr.access(e),await Kr.unlink(e)}catch{Co.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(dd,"deleteTempFile");function C8(e,t){if(e.statusCode!==oM.HTTP_STATUS_CODES.OK)throw qe(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Nt.BAD_REQUEST);if(!g8[e.headers["content-type"]])throw qe(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Nt.BAD_REQUEST);if(!e.raw)throw qe(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Nt.BAD_REQUEST)}a(C8,"validateURLResponse");async function Gp(e){try{let t;switch(e.file_type){case Yr.VALID_S3_FILE_TYPES.CSV:t=await U8(e);break;case Yr.VALID_S3_FILE_TYPES.JSON:t=await D8(e);break;default:throw qe(new Error,at.DEFAULT_BULK_LOAD_ERR,Nt.BAD_REQUEST,Yr.LOG_LEVELS.ERROR,at.INVALID_FILE_EXT_ERR(e))}return EM(t.records,t.number_written)}catch(t){throw gi(t)}}a(Gp,"fileLoad");async function uM(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 _d.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&cM(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=qe(c);r(u)}}a(uM,"validateChunk");async function lM(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;wo.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!wo.isEmpty(c)&&!wo.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(l=>c.add(l))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await aM.callOperationFunctionAsAwait(dM,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=qe(c,Ri(at.INSERT_CSV_ERR),Nt.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,at.INSERT_CSV_ERR+" - "+c);r(u)}}a(lM,"insertChunk");async function U8(e){let t={records:0,number_written:0},r=_M(e.schema,e.table);try{let s=new Fp,n=Kr.createReadStream(e.file_path,{highWaterMark:nM});n.setEncoding("utf8"),await Bp.parsePromise(n,uM.bind(null,e,s),Hp.bind(null,r));let i=s.getPermsResponse();if(i)throw qe(new Error,i,Nt.BAD_REQUEST);return n=Kr.createReadStream(e.file_path,{highWaterMark:nM}),n.setEncoding("utf8"),await Bp.parsePromise(n,lM.bind(null,e,t),Hp.bind(null,r)),n.destroy(),t}catch(s){throw qe(s,Ri(at.PAPA_PARSE_ERR),Nt.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,at.PAPA_PARSE_ERR+s)}}a(U8,"callPapaParse");function _M(e,t){let r=p8[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>T8(i,n));return s}a(_M,"createTransformMap");function Hp(e,t,r){let s=e.get(r);return s?s(t):wo.autoCast(t)}a(Hp,"typeFunction");async function D8(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Fp,n=ZL([Kr.createReadStream(e.file_path,{encoding:"utf-8"}),jL.withParser(),c=>c.value,new eM({batchSize:iM}),tM(async c=>{await uM(e,s,r,c)})]);await new Promise((c,u)=>{rM(n,l=>{l?u(l):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw qe(new Error,i,Nt.BAD_REQUEST);let o=ZL([Kr.createReadStream(e.file_path,{encoding:"utf-8"}),jL.withParser(),c=>c.value,new eM({batchSize:iM}),tM(async c=>{await lM(e,t,r,c)})]);return await new Promise((c,u)=>{rM(o,l=>{l?u(l):c()}),o.resume()}),t}catch(s){throw qe(s,Ri(at.INSERT_JSON_ERR),Nt.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,at.INSERT_JSON_ERR+s)}}a(D8,"insertJson");async function dM(e){let t={};try{e.data&&e.data.length>0&&L8(e.data[0])?t=await M8(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Co.info(t.message))}catch(r){throw gi(r)}return t}a(dM,"callBulkFileLoad");function L8(e){let t=Object.keys(e);for(let r of t)if(!R8.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(L8,"validateColumnNames");async function M8(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=_d.insert;break;case"update":i=_d.update;break;case"upsert":i=_d.upsert;break;default:throw qe(new Error,at.INVALID_ACTION_PARAM_ERR(s),Nt.BAD_REQUEST,Yr.LOG_LEVELS.ERROR,at.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 _=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][_])>=0&&e.splice(d,1)}let u=wo.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw gi(o)}}a(M8,"bulkFileLoad");function EM(e,t){return`successfully loaded ${t} of ${e} records`}a(EM,"buildResponseMsg");function gi(e){return qe(e,Ri(at.DEFAULT_BULK_LOAD_ERR),Nt.INTERNAL_SERVER_ERROR,Yr.LOG_LEVELS.ERROR,at.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(gi,"buildTopLevelErrMsg")});var mM=m(($le,hM)=>{"use strict";var Vp=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};hM.exports=Vp});var TM=m((Kle,pM)=>{"use strict";var P8=g(),SM=require("moment"),v8=require("uuid").v4,$p=class{static{a(this,"JobObject")}constructor(){this.id=v8(),this.type=void 0,this.start_datetime=SM().valueOf(),this.created_datetime=SM().valueOf(),this.end_datetime=void 0,this.status=P8.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};pM.exports=$p});var Yp=m((Qle,bM)=>{"use strict";var B8=require("uuid").v4,AM=Rr(),OM=Tr(),H8=is(),q8=ji(),F8=mM(),Fe=g(),G8=TM(),x8=Hm(),Ur=F(),k8=Ta(),Uo=x(),{promisify:V8}=require("util"),Ai=require("moment"),$8=J_(),hd=Dp(),RM=Bf(),{deleteTransactionLogsBeforeValidator:Y8}=rp(),{handleHDBError:K8,hdb_errors:W8}=W(),{HTTP_STATUS_CODES:Q8}=W8,gM=OM.searchByValue,z8=OM.searchByHash,J8=AM.insert,X8=V8($8.evaluateSQL),Z8=AM.update;bM.exports={addJob:t6,updateJob:s6,handleGetJob:j8,handleGetJobsByStartDate:e6,getJobById:NM};async function j8(e){try{let t=await NM(e.id);return Uo.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 Ur.error("There was an error getting job",t),new Error(r)}}a(j8,"handleGetJob");async function e6(e){try{let t=await r6(e);if(Ur.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=Ai(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Ai(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 Ur.error(r),new Error(r)}}a(e6,"handleGetJobsByStartDate");async function t6(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Uo.isEmptyOrZeroLength(e.operation)){let _="job parameter is invalid";return Ur.info(_),t.error=_,t}if(!Fe.JOB_TYPE_ENUM[e.operation])return Ur.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case Fe.OPERATIONS_ENUM.CSV_FILE_LOAD:s=hd.fileObject(e);break;case Fe.OPERATIONS_ENUM.CSV_URL_LOAD:s=hd.urlObject(e);break;case Fe.OPERATIONS_ENUM.CSV_DATA_LOAD:s=hd.dataObject(e);break;case Fe.OPERATIONS_ENUM.IMPORT_FROM_S3:s=hd.s3FileObject(e);break;case Fe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Fe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=RM(e,"date");break;case Fe.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=RM(e,"timestamp");break;case Fe.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=Y8(e);break;default:break}if(s)throw K8(s,s.message,Q8.BAD_REQUEST,void 0,void 0,!0);let n=new G8;n.type=e.operation===Fe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Fe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new H8(Fe.SYSTEM_SCHEMA_NAME,Fe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await gM(i))}catch(_){let d=`There was an error inserting a new job: ${_}`;return Ur.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=B8();try{o=await gM(i)}catch(_){let d=`There was an error inserting a new job: ${_}`;return Ur.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Ur.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new k8(Fe.SYSTEM_SCHEMA_NAME,Fe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),l;try{l=await J8(u)}catch(_){return Ur.error(`There was an error inserting a job for job type: ${e.operation} -- ${_}`),t.success=!1,t}if(l.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let _=`Created a job with type ${n.type} and id ${n.id}`;t.message=_,t.createdJob=n,t.success=!0,Ur.trace(_)}return t}a(t6,"addJob");async function r6(e){let t=Ai(e.from_date,Ai.ISO_8601),r=Ai(e.to_date,Ai.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 F8(s,e.hdb_user);try{return await X8(n)}catch(i){throw Ur.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(r6,"getJobsInDateRange");async function NM(e){if(Uo.isEmptyOrZeroLength(e))return Uo.errorizeMessage("Invalid job ID specified.");let t=new q8(Fe.SYSTEM_SCHEMA_NAME,Fe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await z8(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return Ur.error(s),Uo.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(NM,"getJobById");async function s6(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Uo.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Fe.JOB_STATUS_ENUM.COMPLETE||e.status===Fe.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Ai().valueOf());let t=new x8(Fe.SYSTEM_SCHEMA_NAME,Fe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Z8(t),r}a(s6,"updateJob")});var DM=m((Jle,UM)=>{"use strict";var yM=x(),Xt=g(),n6=require("moment"),md=xp(),Sd=F(),IM=Yp(),wM=X_(),CM=Zn(),i6=rt(),o6=G_(),Kp=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function a6(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(yM.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(yM.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Xt.JOB_TYPE_ENUM.csv_file_load:await Xs(e,md.csvFileLoad);break;case Xt.JOB_TYPE_ENUM.csv_url_load:await Xs(e,md.csvURLLoad);break;case Xt.JOB_TYPE_ENUM.csv_data_load:await Xs(e,md.csvDataLoad);break;case Xt.JOB_TYPE_ENUM.import_from_s3:await Xs(e,md.importFromS3);break;case Xt.JOB_TYPE_ENUM.empty_trash:break;case Xt.JOB_TYPE_ENUM.export_local:await Xs(e,wM.export_local);break;case Xt.JOB_TYPE_ENUM.export_to_s3:await Xs(e,wM.export_to_s3);break;case Xt.JOB_TYPE_ENUM.delete_files_before:case Xt.JOB_TYPE_ENUM.delete_records_before:await Xs(e,CM.deleteFilesBefore);break;case Xt.JOB_TYPE_ENUM.delete_audit_logs_before:await Xs(e,CM.deleteAuditLogsBefore);break;case Xt.JOB_TYPE_ENUM.delete_transaction_logs_before:await Xs(e,o6.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(a6,"parseMessage");async function Xs(e,t){try{e.job.status=Xt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=n6().valueOf(),await IM.updateJob(e.job),await c6(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):Sd.error(`There was an error running ${t.name} job with id ${e.job.id}`),Sd.error(s),e.job.message=s,e.job.status=Xt.JOB_STATUS_ENUM.ERROR;try{await IM.updateJob(e.job)}catch(n){throw Sd.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Xs,"runJob");async function c6(e){Sd.trace("launching job thread:",e),i6.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Xt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(c6,"launchJobThread");UM.exports={parseMessage:a6,RunnerMessage:Kp}});var MM=m((Zle,LM)=>{"use strict";var Wp=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};LM.exports=Wp});var JM=m((e_e,Zp)=>{"use strict";var gd=Tr(),Jp=J_(),pd=xp(),Zs=Yl(),Td=Wn(),xc=Zn(),u6=Am(),Gc=Or(),Rd=Dm(),bt=tp(),ct=F(),l6=Pm(),_6=c_(),d6=hS(),E6=d_(),f6=mS(),h6=SS(),m6=RS(),S6=AS(),Qp=bS(),PM=X_(),p6=Q_(),Xp=Yp(),I=g(),{hdb_errors:Vc,handleHDBError:kc}=W(),{HTTP_STATUS_CODES:vM}=Vc,zp=US(),BM=WS(),YM=require("util"),Do=Rr(),T6=_n(),R6=ho(),HM=DM(),qM=rc(),FM=(B_(),te(Oc)),GM=Ar(),xM=G_(),kM=$_(),{setServerUtilities:g6}=(fd(),te(kp)),{CONTEXT:A6}=(Xr(),te(GE)),{_assignPackageExport:O6}=require("../../index"),{transformReq:N6}=x(),b6=Lp(),VM=gd.searchByHash,y6=gd.searchByValue,I6=YM.promisify(gd.search),w6=YM.promisify(Jp.evaluateSQL),C6={[I.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[I.OPERATIONS_ENUM.CREATE_TABLE]:!0,[I.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[I.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[I.OPERATIONS_ENUM.DROP_TABLE]:!0,[I.OPERATIONS_ENUM.DROP_SCHEMA]:!0},B=MM();async function KM(e,t){try{if(e.body.operation!=="read_log"&&(ct.log_level===I.LOG_LEVELS.INFO||ct.log_level===I.LOG_LEVELS.DEBUG||ct.log_level===I.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;ct.info(o)}}catch(s){ct.error(s)}let r=await b6.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return C6[e.body.operation]&&T6.setSchemaDataToGlobal(s=>{s&&ct.error(s)}),r}a(KM,"processLocalTransaction");var $M=D6();Zp.exports={chooseOperation:WM,getOperationFunction:QM,operation:zM,processLocalTransaction:KM};g6(Zp.exports);function WM(e){let t;try{t=QM(e)}catch(n){throw ct.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=Jp.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=Jp.checkASTPermissions(e,i);if(o)throw ct.error(`${vM.FORBIDDEN} from operation ${e.operation}`),ct.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),kc(new Error,o,Vc.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==I.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==I.OPERATIONS_ENUM.LOGIN&&e.operation!==I.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=p6.verifyPerms(i,n);if(o)throw ct.error(`${vM.FORBIDDEN} from operation ${e.operation}`),ct.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),kc(new Error,o,Vc.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw kc(n,"There was an error when trying to choose an operation path")}return r}a(WM,"chooseOperation");function QM(e){if(ct.trace(`getOperationFunction with operation: ${e.operation}`),$M.has(e.operation))return $M.get(e.operation);throw kc(new Error,Vc.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Vc.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(QM,"getOperationFunction");O6("operation",zM);function zM(e,t){e.hdb_user=this[A6]?.user,e.bypass_auth=!t;let r=WM(e);return KM({body:e},r)}a(zM,"operation");async function U6(e){ct.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[I.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case I.OPERATIONS_ENUM.INSERT:o=await Do.insert(i);break;case I.OPERATIONS_ENUM.UPDATE:o=await Do.update(i);break;case I.OPERATIONS_ENUM.UPSERT:o=await Do.upsert(i);break;case I.OPERATIONS_ENUM.DELETE:o=await xc.deleteRecord(i);break;default:ct.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){ct.info("Invalid operation in transaction"),ct.error(o)}}a(U6,"catchup");async function Ss(e){N6(e);let t,r;try{r=await Xp.addJob(e),t=r.createdJob,ct.info("addJob result",r);let s=new HM.RunnerMessage(t,e);return await HM.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 ct.error(n),kc(s,n)}}a(Ss,"executeJob");function D6(){let e=new Map;return e.set(I.OPERATIONS_ENUM.INSERT,new B(Do.insert)),e.set(I.OPERATIONS_ENUM.UPDATE,new B(Do.update)),e.set(I.OPERATIONS_ENUM.UPSERT,new B(Do.upsert)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new B(gd.searchByConditions)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_HASH,new B(VM)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_ID,new B(VM)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_VALUE,new B(y6)),e.set(I.OPERATIONS_ENUM.SEARCH,new B(I6)),e.set(I.OPERATIONS_ENUM.SQL,new B(w6)),e.set(I.OPERATIONS_ENUM.CSV_DATA_LOAD,new B(Ss,pd.csvDataLoad)),e.set(I.OPERATIONS_ENUM.CSV_FILE_LOAD,new B(Ss,pd.csvFileLoad)),e.set(I.OPERATIONS_ENUM.CSV_URL_LOAD,new B(Ss,pd.csvURLLoad)),e.set(I.OPERATIONS_ENUM.IMPORT_FROM_S3,new B(Ss,pd.importFromS3)),e.set(I.OPERATIONS_ENUM.CREATE_SCHEMA,new B(Zs.createSchema)),e.set(I.OPERATIONS_ENUM.CREATE_DATABASE,new B(Zs.createSchema)),e.set(I.OPERATIONS_ENUM.CREATE_TABLE,new B(Zs.createTable)),e.set(I.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new B(Zs.createAttribute)),e.set(I.OPERATIONS_ENUM.DROP_SCHEMA,new B(Zs.dropSchema)),e.set(I.OPERATIONS_ENUM.DROP_DATABASE,new B(Zs.dropSchema)),e.set(I.OPERATIONS_ENUM.DROP_TABLE,new B(Zs.dropTable)),e.set(I.OPERATIONS_ENUM.DROP_ATTRIBUTE,new B(Zs.dropAttribute)),e.set(I.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new B(Td.describeSchema)),e.set(I.OPERATIONS_ENUM.DESCRIBE_DATABASE,new B(Td.describeSchema)),e.set(I.OPERATIONS_ENUM.DESCRIBE_TABLE,new B(Td.describeTable)),e.set(I.OPERATIONS_ENUM.DESCRIBE_ALL,new B(Td.describeAll)),e.set(I.OPERATIONS_ENUM.DELETE,new B(xc.deleteRecord)),e.set(I.OPERATIONS_ENUM.ADD_USER,new B(Gc.addUser)),e.set(I.OPERATIONS_ENUM.ALTER_USER,new B(Gc.alterUser)),e.set(I.OPERATIONS_ENUM.DROP_USER,new B(Gc.dropUser)),e.set(I.OPERATIONS_ENUM.LIST_USERS,new B(Gc.listUsersExternal)),e.set(I.OPERATIONS_ENUM.LIST_ROLES,new B(Rd.listRoles)),e.set(I.OPERATIONS_ENUM.ADD_ROLE,new B(Rd.addRole)),e.set(I.OPERATIONS_ENUM.ALTER_ROLE,new B(Rd.alterRole)),e.set(I.OPERATIONS_ENUM.DROP_ROLE,new B(Rd.dropRole)),e.set(I.OPERATIONS_ENUM.USER_INFO,new B(Gc.userInfo)),e.set(I.OPERATIONS_ENUM.READ_LOG,new B(l6)),e.set(I.OPERATIONS_ENUM.ADD_NODE,new B(_6)),e.set(I.OPERATIONS_ENUM.UPDATE_NODE,new B(d6)),e.set(I.OPERATIONS_ENUM.REMOVE_NODE,new B(E6)),e.set(I.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new B(f6)),e.set(I.OPERATIONS_ENUM.PURGE_STREAM,new B(h6)),e.set(I.OPERATIONS_ENUM.SET_CONFIGURATION,new B(GM.setConfiguration)),e.set(I.OPERATIONS_ENUM.CLUSTER_STATUS,new B(m6.clusterStatus)),e.set(I.OPERATIONS_ENUM.CLUSTER_NETWORK,new B(S6)),e.set(I.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new B(Qp.setRoutes)),e.set(I.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new B(Qp.getRoutes)),e.set(I.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new B(Qp.deleteRoutes)),e.set(I.OPERATIONS_ENUM.EXPORT_TO_S3,new B(Ss,PM.export_to_s3)),e.set(I.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new B(Ss,xc.deleteFilesBefore)),e.set(I.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new B(Ss,xc.deleteFilesBefore)),e.set(I.OPERATIONS_ENUM.EXPORT_LOCAL,new B(Ss,PM.export_local)),e.set(I.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new B(Xp.handleGetJobsByStartDate)),e.set(I.OPERATIONS_ENUM.GET_JOB,new B(Xp.handleGetJob)),e.set(I.OPERATIONS_ENUM.GET_FINGERPRINT,new B(zp.getFingerprint)),e.set(I.OPERATIONS_ENUM.SET_LICENSE,new B(zp.setLicense)),e.set(I.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new B(zp.getRegistrationInfo)),e.set(I.OPERATIONS_ENUM.RESTART,new B(BM.restart)),e.set(I.OPERATIONS_ENUM.RESTART_SERVICE,new B(BM.restartService)),e.set(I.OPERATIONS_ENUM.CATCHUP,new B(U6)),e.set(I.OPERATIONS_ENUM.SYSTEM_INFORMATION,new B(R6.systemInformation)),e.set(I.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new B(Ss,xc.deleteAuditLogsBefore)),e.set(I.OPERATIONS_ENUM.READ_AUDIT_LOG,new B(u6)),e.set(I.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new B(qM.createTokens)),e.set(I.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new B(qM.refreshOperationToken)),e.set(I.OPERATIONS_ENUM.LOGIN,new B(FM.login)),e.set(I.OPERATIONS_ENUM.LOGOUT,new B(FM.logout)),e.set(I.OPERATIONS_ENUM.GET_CONFIGURATION,new B(GM.getConfiguration)),e.set(I.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new B(bt.customFunctionsStatus)),e.set(I.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new B(bt.getCustomFunctions)),e.set(I.OPERATIONS_ENUM.GET_COMPONENT_FILE,new B(bt.getComponentFile)),e.set(I.OPERATIONS_ENUM.GET_COMPONENTS,new B(bt.getComponents)),e.set(I.OPERATIONS_ENUM.SET_COMPONENT_FILE,new B(bt.setComponentFile)),e.set(I.OPERATIONS_ENUM.DROP_COMPONENT,new B(bt.dropComponent)),e.set(I.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new B(bt.getCustomFunction)),e.set(I.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new B(bt.setCustomFunction)),e.set(I.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new B(bt.dropCustomFunction)),e.set(I.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new B(bt.addComponent)),e.set(I.OPERATIONS_ENUM.ADD_COMPONENT,new B(bt.addComponent)),e.set(I.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new B(bt.dropCustomFunctionProject)),e.set(I.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new B(bt.packageComponent)),e.set(I.OPERATIONS_ENUM.PACKAGE_COMPONENT,new B(bt.packageComponent)),e.set(I.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new B(bt.deployComponent)),e.set(I.OPERATIONS_ENUM.DEPLOY_COMPONENT,new B(bt.deployComponent)),e.set(I.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new B(xM.readTransactionLog)),e.set(I.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new B(Ss,xM.deleteTransactionLogsBefore)),e.set(I.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new B(kM.installModules)),e.set(I.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new B(kM.auditModules)),e.set(I.OPERATIONS_ENUM.GET_BACKUP,new B(Zs.getBackup)),e}a(D6,"initializeOperationFunctionMap")});var Od=m((r_e,jM)=>{"use strict";var jp=g(),L6=x(),$c=F(),{handleHDBError:eT,hdb_errors:Ad}=W(),{isMainThread:M6}=require("worker_threads"),{Readable:P6}=require("stream"),XM=require("os"),v6=require("util"),B6=Ym(),H6=v6.promisify(B6.authorize),ZM=JM(),{Gzip:q6}=require("zlib");function F6(e){let t=`Found an uncaught exception with message: ${e.message}. ${XM.EOL}Stack: ${e.stack} ${XM.EOL}Terminating ${M6?"HDB":"thread"}.`;console.error(t),$c.fatal(t),process.exit(1)}a(F6,"handleServerUncaughtException");function G6(e,t,r){if($c[e.logLevel||"error"](e),e.http_resp_code)return typeof e.http_resp_msg!="object"?r.code(e.http_resp_code).send({error:e.http_resp_msg||e.message}):r.code(e.http_resp_code).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:Ad.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(G6,"serverErrorHandler");function x6(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=eT(new Error,"Invalid JSON.",Ad.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(L6.isEmpty(e.body.operation)){let s=eT(new Error,"Request body must include an 'operation' property.",Ad.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(x6,"reqBodyValidationHandler");function k6(e,t,r){let s;e.body.operation!==jp.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==jp.OPERATIONS_ENUM.LOGIN&&e.body.operation!==jp.OPERATIONS_ENUM.LOGOUT?H6(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{$c.warn(n),$c.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(eT(n,i,Ad.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(k6,"authHandler");async function V6(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=ZM.chooseOperation(e.body);let n=await ZM.processLocalTransaction(e,s);if(n instanceof P6&&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(new q6))}return n}catch(n){throw $c.error(n),n}}a(V6,"handlePostRequest");jM.exports={authHandler:k6,handlePostRequest:V6,handleServerUncaughtException:F6,serverErrorHandler:G6,reqBodyValidationHandler:x6}});var sP=m((n_e,rP)=>{"use strict";var $6=require("fastify-plugin"),{handlePostRequest:eP,authHandler:Y6,reqBodyValidationHandler:K6}=Od();async function W6(e){e.decorate("hdbCore",{preValidation:[K6,Y6],request:t=>tP(eP(t)),requestWithoutAuthentication:t=>tP(eP(t,!0))})}a(W6,"hdbCore");async function tP(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(tP,"convertAsyncIterators");rP.exports=$6(W6)});var iP=m((o_e,nP)=>{"use strict";var tT=require("fs"),Lo=Q();Lo.initSync();var{CONFIG_PARAMS:Yc}=g(),Q6=1024*1024*1024;function z6(e){let t=Lo.get(Yc.CUSTOMFUNCTIONS_NETWORK_TIMEOUT),r=Lo.get(Yc.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT),s={bodyLimit:Q6,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0};if(e){let n=Lo.get(Yc.CUSTOMFUNCTIONS_TLS_PRIVATEKEY),i=Lo.get(Yc.CUSTOMFUNCTIONS_TLS_CERTIFICATE),o=Lo.get(Yc.OPERATIONSAPI_TLS_CERT_AUTH);s.https={allowHTTP1:!0,key:tT.readFileSync(`${n}`),cert:tT.readFileSync(i)+(o?`
|
|
22
|
+
`},q:.8});Et.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()}});xL={type:"application/json",serializeStream:td.streamAsJSON,serialize:JSON.stringify,deserialize:$5,q:.8};Et.set("*/*",xL);Et.set("",xL);a($5,"tryJSONParse");a(bp,"registerContentHandlers");Y5=require("fastify-plugin"),K5=Y5(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=nd(s.raw);n.type(c),n.serializer(o.serializeStream||o.serialize)}),r()},{name:"content-type-negotiation"});a(nd,"findBestSerializer");a(yp,"serialize");a(Ws,"serializeMessage");a(W5,"streamToBuffer");a(wo,"getDeserializer");a(qL,"deserializerUnknownType");a(Q5,"transformIterable")});var Cp={};Ye(Cp,{start:()=>X5});async function J5(e,t){let r=e.headers.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Mu(e);let s=performance.now(),n,i=new pi;try{e.responseHeaders=i;let o=e.url.slice(1),c=wp.getMatch(o);if(!c)return t(e);let u={url:c.relativeURL},l=c.Resource,_=await Ke(e,()=>{if(r==="POST"||r==="PUT"||r==="PATCH"||r==="QUERY")try{e.data=wo(e.headers["content-type"],!0)(e.body)}catch(R){throw new Gc.ClientError(R,400)}switch(e.authorize=!0,r){case"GET":case"HEAD":return l.get(u,e);case"POST":return l.post(u,e.data,e);case"PUT":return l.put(u,e.data,e);case"DELETE":return l.delete(u,e);case"PATCH":return l.patch(u,e.data,e);case"OPTIONS":i.set("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return l.connect(u,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(u,e.data,e);case"COPY":return l.copy(u,e.headers.destination,e);case"MOVE":return l.move(u,e.headers.destination,e);case"BREW":throw new Gc.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Gc.ServerError(`Method ${r} is not recognized`,501)}}),d=performance.now()-s,E=200,f;if(_==null)E=r==="GET"||r==="HEAD"?404:204;else if(f=e?.lastModified){z5[0]=f;let R=String.fromCharCode(34,(Ot[0]&63)+62,(Ot[0]>>6)+(Ot[1]<<2&63)+62,(Ot[1]>>4)+(Ot[2]<<4&63)+62,(Ot[2]>>2)+62,(Ot[3]&63)+62,(Ot[3]>>6)+(Ot[4]<<2&63)+62,(Ot[4]>>4)+(Ot[5]<<4&63)+62,(Ot[5]>>2)+62,(Ot[6]&63)+62,(Ot[6]>>6)+(Ot[7]<<2&63)+62,34),O=e.headers["if-none-match"];O&&R==O?(_?.onDone&&_.onDone(),E=304,_=void 0):i.set("ETag",R)}e.createdResource&&(E=201),e.newLocation&&i.set("Location",e.newLocation);let h={status:E,headers:i,body:void 0},T=`db;dur=${d.toFixed(2)}`,p=_?.wasLoadedFromSource?.();return p!==void 0&&(p?T+=", miss":f&&i.set("Age",Math.round((Date.now()-f)/1e3))),i.append("Server-Timing",T,!0),ls(d,"TTFB",n,r),no(E<400,"success",n,r),_!==void 0&&(h.body=yp(_,e,h),r==="HEAD"&&(h.body=void 0)),h}catch(o){let c=performance.now()-s;return ls(c,"TTFB",n,r),no(!1,"success",n,r),o.statusCode||console.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.set("Allow",o.allow.map(u=>u.toUpperCase()).join(", ")))),{status:o.statusCode||500,headers:i,body:Ws(o.toString(),e)}}}function X5(e){if(VL)return;VL=!0,wp=e.resources,e.server.http(async(r,s)=>{if(!r.isWebSocket)return J5(r,s)}),e.server.ws(async(r,s,n)=>{$L++,Ip||(setTimeout(()=>{console.log("connection count",$L,"mem",Math.round(process.memoryUsage().heapUsed/1e6)),Ip=!1},1e3),Ip=!0),t(s);let i=new Xr;r.on("error",console.error);let o;r.on("message",a(function(d){o||(o=wo(s.headers["content-type"]));let E=o(d);i.push(E)},"message"));let c;r.on("close",()=>{i.emit("close"),c&&c.return()}),await n;let u,l=await wp.call(s.pathname.slice(1),s,(_,d)=>(u=!0,_.connect(i)));if(!u)r.send(Ws(`No resource was found to handle ${s.pathname}`,s));else{c=l[Symbol.asyncIterator]();let _;for(;!(_=await c.next()).done;)r.send(Ws(_.value,s))}r.close()});function t(r){let s=r.pathname,n=s.lastIndexOf(".");if(n>-1){let i=s.slice(n+1),o=EXTENSION_TYPES[i];o&&(r.headers.accept=o)}}a(t,"startRequest")}var Gc,Ot,z5,VL,wp,$L,Ip,YL=Se(()=>{Oo();ci();Gc=C(W());Pu();ua();$n();P_();Ot=new Uint8Array(8),z5=new Float64Array(Ot.buffer,0,1);a(J5,"http");$L=0;a(X5,"start")});var Up=m((Gle,KL)=>{var{recordAction:id,recordActionBinary:Z5}=(ci(),ee(ql)),j5=require("fastify-plugin"),e8=200;KL.exports=j5(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.context.config,l,_,d;u.isOperation?(l=s.body?.operation,_="operation"):(l=u.url,_="fastify-route",d=u.method),id(o,"TTFB",l,d,_),Z5(n.raw.statusCode<400,"success",l,d,_);let E=e8;i?.pipe?(i.on("data",h=>{E+=h.length}),i.on("end",()=>{id(performance.now()-c,"transfer",l,d,_),id(E,"bytes-sent",l,d,_)})):(E+=i?.length||0,id(E,"bytes-sent",l,d,_));let f=o.toFixed(3);n.header("Server-Timing",`db;dur=${f}`)}),r()},{name:"hdb-request-time"})});var Pp=m((xle,XL)=>{var ld=require("clone"),_d=ve(),t8=V(),cd=A(),r8=x(),od=require("fs"),Dp=require("joi"),{string:ud}=Dp.types(),{hdb_errors:s8,handleHDBError:xc}=W(),{HDB_ERROR_MSGS:n8,HTTP_STATUS_CODES:ad}=s8,{common_validators:Co}=rs(),WL=1e9,QL=" is required",i8=["insert","update","upsert"],Lp={database:{presence:!1,format:Co.schema_format,length:Co.schema_length},schema:{presence:!1,format:Co.schema_format,length:Co.schema_length},table:{presence:!0,format:Co.schema_format,length:Co.schema_length},action:{inclusion:{within:i8,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},o8={schema:ud.required(),table:ud.required(),action:ud.valid("insert","update","upsert")},{AWS_ACCESS_KEY:a8,AWS_SECRET:c8,AWS_BUCKET:u8,AWS_FILE_KEY:l8,REGION:_8}=cd.S3_BUCKET_AUTH_KEYS,d8={s3:{presence:!0},[`s3.${a8}`]:{presence:!0,type:"String"},[`s3.${c8}`]:{presence:!0,type:"String"},[`s3.${u8}`]:{presence:!0,type:"String"},[`s3.${l8}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${_8}`]:{presence:!0,type:"String"}},zL=ld(Lp);zL.data.presence={message:QL};var JL=ld(Lp);JL.file_path.presence={message:QL};var E8=Object.assign(ld(Lp),d8),Mp=ld(o8);Mp.csv_url=ud.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Mp.passthrough_headers=Dp.object();function f8(e){let t=_d.validateObject(e,zL);return dd(e,t)}a(f8,"dataObject");function h8(e){let t=_d.validateBySchema(e,Dp.object(Mp));return dd(e,t)}a(h8,"urlObject");function m8(e){let t=_d.validateObject(e,JL);return dd(e,t)}a(m8,"fileObject");function S8(e){let t=_d.validateObject(e,E8);return dd(e,t)}a(S8,"s3FileObject");function dd(e,t){if(!t){let r=t8.checkGlobalSchemaTable(e.schema,e.table);if(r)return xc(new Error,r,ad.BAD_REQUEST);if(e.operation===cd.OPERATIONS_ENUM.CSV_FILE_LOAD){try{od.accessSync(e.file_path,od.constants.R_OK|od.constants.F_OK)}catch(s){return s.code===cd.NODE_ERROR_CODES.ENOENT?xc(s,`No such file or directory ${s.path}`,ad.BAD_REQUEST):s.code===cd.NODE_ERROR_CODES.EACCES?xc(s,`Permission denied ${s.path}`,ad.BAD_REQUEST):xc(s)}try{let s=od.statSync(e.file_path).size;if(s>WL)return xc(new Error,n8.MAX_FILE_SIZE_ERR(s,WL),ad.BAD_REQUEST)}catch(s){r8.error(s),console.error(s)}}}return t}a(dd,"postValidateChecks");XL.exports={dataObject:f8,urlObject:h8,fileObject:m8,s3FileObject:S8}});var vp=m((Vle,ZL)=>{"use strict";var kc=x(),Ed=A();async function p8(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===Ed.OPERATIONS_ENUM.INSERT||t.operation===Ed.OPERATIONS_ENUM.UPDATE||t.operation===Ed.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===Ed.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(kc.info(i.message),i):i.http_resp_msg?(kc.error(`Error calling operation: ${e.name}`),kc.error(i.http_resp_msg),i):(kc.error(`Error calling operation: ${e.name}`),kc.error(i),i)}}a(p8,"callOperationFunctionAsAwait");ZL.exports={callOperationFunctionAsAwait:p8}});var eM=m((Yle,jL)=>{"use strict";var Bp=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}},Hp=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};jL.exports={BulkLoadFileObject:Bp,BulkLoadDataObject:Hp}});var rM=m((Wle,tM)=>{"use strict";var qp=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};tM.exports=qp});var $p=m((jle,TM)=>{"use strict";var fd=Ar(),md=Pp(),T8=require("needle"),Kr=A(),zle=Be(),Uo=V(),{handleHDBError:qe,hdb_errors:_M}=W(),{HTTP_STATUS_CODES:Nt,HDB_ERROR_MSGS:ut,CHECK_LOGS_WRAPPER:Ai}=_M,Do=x(),Fp=require("papaparse");Uo.promisifyPapaParse();var Wr=require("fs-extra"),R8=require("path"),{chain:sM}=require("stream-chain"),nM=require("stream-json/streamers/StreamArray"),iM=require("stream-json/utils/Batch"),oM=require("stream-chain/utils/comp"),{finished:aM}=require("stream"),g8=Q(),dM=vp(),A8=Ap(),{BulkLoadFileObject:xp,BulkLoadDataObject:O8}=eM(),kp=dp(),{verifyBulkLoadAttributePerms:EM}=X_(),Jle=rM(),Xle=it(),Zle=vs(),{databases:N8}=(de(),ee(Ne)),{coerceType:b8}=(Sd(),ee(Yp)),cM="No records parsed from csv file.",gi=`${g8.get("HDB_ROOT")}/tmp`,{schema_regex:y8}=rs(),uM=1024*1024*2,lM=5e3,I8={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};TM.exports={csvDataLoad:w8,csvURLLoad:C8,csvFileLoad:U8,importFromS3:D8};async function w8(e,t){let r=md.dataObject(e);if(r)throw qe(r,r.message,Nt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=mM(e.schema,e.table),i=Fp.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Gp.bind(null,n),dynamicTyping:!1}),o=new kp;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&EM(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 qe(new Error,c,Nt.BAD_REQUEST,void 0,void 0,!0);let u=new O8(e.action,e.schema,e.table,i.data);return s=await dM.callOperationFunctionAsAwait(SM,u,null),s.message===cM?cM:pM(s.records,s.number_written)}catch(n){throw Oi(n)}}a(w8,"csvDataLoad");async function C8(e){let t=md.urlObject(e);if(t)throw qe(t,t.message,Nt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${gi}/${r}`;try{await L8(e,r)}catch(n){throw Do.error(ut.DOWNLOAD_FILE_ERR(r)+" - "+n),qe(n,Ai(ut.DOWNLOAD_FILE_ERR(r)))}try{let n=new xp(this.job_operation_function.name,e.action,e.schema,e.table,s,Kr.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Vp(n);return await hd(s),i}catch(n){throw await hd(s),Oi(n)}}a(C8,"csvURLLoad");async function U8(e){let t=md.fileObject(e);if(t)throw qe(t,t.message,Nt.BAD_REQUEST,void 0,void 0,!0);let r=new xp(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Kr.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Vp(r)}catch(s){throw Oi(s)}}a(U8,"csvFileLoad");async function D8(e){let t=md.s3FileObject(e);if(t)throw qe(t,t.message,Nt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=R8.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${gi}/${n}`;let i=new xp(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await M8(n,e);let o=await Vp(i);return await hd(r),o}catch(s){throw await hd(r),Oi(s)}}a(D8,"importFromS3");async function L8(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await T8("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 qe(s,n,s.statusCode,Kr.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}v8(r,e.csv_url),await P8(t,r.raw)}a(L8,"downloadCSVFile");async function M8(e,t){try{let r=`${gi}/${e}`;await Wr.mkdirp(gi),await Wr.writeFile(`${gi}/${e}`,"",{flag:"a+"});let s=await Wr.createWriteStream(r),n=await A8.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(){Do.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Do.error(ut.S3_DOWNLOAD_ERR+" - "+r),qe(r,Ai(ut.S3_DOWNLOAD_ERR))}}a(M8,"downloadFileFromS3");async function P8(e,t){try{await Wr.mkdirp(gi),await Wr.writeFile(`${gi}/${e}`,t)}catch(r){throw Do.error(ut.WRITE_TEMP_FILE_ERR),qe(r,Ai(ut.DEFAULT_BULK_LOAD_ERR))}}a(P8,"writeFileToTempFolder");async function hd(e){if(e)try{await Wr.access(e),await Wr.unlink(e)}catch{Do.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(hd,"deleteTempFile");function v8(e,t){if(e.statusCode!==_M.HTTP_STATUS_CODES.OK)throw qe(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Nt.BAD_REQUEST);if(!I8[e.headers["content-type"]])throw qe(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Nt.BAD_REQUEST);if(!e.raw)throw qe(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Nt.BAD_REQUEST)}a(v8,"validateURLResponse");async function Vp(e){try{let t;switch(e.file_type){case Kr.VALID_S3_FILE_TYPES.CSV:t=await B8(e);break;case Kr.VALID_S3_FILE_TYPES.JSON:t=await H8(e);break;default:throw qe(new Error,ut.DEFAULT_BULK_LOAD_ERR,Nt.BAD_REQUEST,Kr.LOG_LEVELS.ERROR,ut.INVALID_FILE_EXT_ERR(e))}return pM(t.records,t.number_written)}catch(t){throw Oi(t)}}a(Vp,"fileLoad");async function fM(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 fd.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&EM(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=qe(c);r(u)}}a(fM,"validateChunk");async function hM(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;Uo.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!Uo.isEmpty(c)&&!Uo.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(l=>c.add(l))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await dM.callOperationFunctionAsAwait(SM,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=qe(c,Ai(ut.INSERT_CSV_ERR),Nt.INTERNAL_SERVER_ERROR,Kr.LOG_LEVELS.ERROR,ut.INSERT_CSV_ERR+" - "+c);r(u)}}a(hM,"insertChunk");async function B8(e){let t={records:0,number_written:0},r=mM(e.schema,e.table);try{let s=new kp,n=Wr.createReadStream(e.file_path,{highWaterMark:uM});n.setEncoding("utf8"),await Fp.parsePromise(n,fM.bind(null,e,s),Gp.bind(null,r));let i=s.getPermsResponse();if(i)throw qe(new Error,i,Nt.BAD_REQUEST);return n=Wr.createReadStream(e.file_path,{highWaterMark:uM}),n.setEncoding("utf8"),await Fp.parsePromise(n,hM.bind(null,e,t),Gp.bind(null,r)),n.destroy(),t}catch(s){throw qe(s,Ai(ut.PAPA_PARSE_ERR),Nt.INTERNAL_SERVER_ERROR,Kr.LOG_LEVELS.ERROR,ut.PAPA_PARSE_ERR+s)}}a(B8,"callPapaParse");function mM(e,t){let r=N8[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>b8(i,n));return s}a(mM,"createTransformMap");function Gp(e,t,r){let s=e.get(r);return s?s(t):Uo.autoCast(t)}a(Gp,"typeFunction");async function H8(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new kp,n=sM([Wr.createReadStream(e.file_path,{encoding:"utf-8"}),nM.withParser(),c=>c.value,new iM({batchSize:lM}),oM(async c=>{await fM(e,s,r,c)})]);await new Promise((c,u)=>{aM(n,l=>{l?u(l):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw qe(new Error,i,Nt.BAD_REQUEST);let o=sM([Wr.createReadStream(e.file_path,{encoding:"utf-8"}),nM.withParser(),c=>c.value,new iM({batchSize:lM}),oM(async c=>{await hM(e,t,r,c)})]);return await new Promise((c,u)=>{aM(o,l=>{l?u(l):c()}),o.resume()}),t}catch(s){throw qe(s,Ai(ut.INSERT_JSON_ERR),Nt.INTERNAL_SERVER_ERROR,Kr.LOG_LEVELS.ERROR,ut.INSERT_JSON_ERR+s)}}a(H8,"insertJson");async function SM(e){let t={};try{e.data&&e.data.length>0&&q8(e.data[0])?t=await F8(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Do.info(t.message))}catch(r){throw Oi(r)}return t}a(SM,"callBulkFileLoad");function q8(e){let t=Object.keys(e);for(let r of t)if(!y8.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(q8,"validateColumnNames");async function F8(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=fd.insert;break;case"update":i=fd.update;break;case"upsert":i=fd.upsert;break;default:throw qe(new Error,ut.INVALID_ACTION_PARAM_ERR(s),Nt.BAD_REQUEST,Kr.LOG_LEVELS.ERROR,ut.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 _=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][_])>=0&&e.splice(d,1)}let u=Uo.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Oi(o)}}a(F8,"bulkFileLoad");function pM(e,t){return`successfully loaded ${t} of ${e} records`}a(pM,"buildResponseMsg");function Oi(e){return qe(e,Ai(ut.DEFAULT_BULK_LOAD_ERR),Nt.INTERNAL_SERVER_ERROR,Kr.LOG_LEVELS.ERROR,ut.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Oi,"buildTopLevelErrMsg")});var gM=m((t_e,RM)=>{"use strict";var Kp=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};RM.exports=Kp});var NM=m((s_e,OM)=>{"use strict";var G8=A(),AM=require("moment"),x8=require("uuid").v4,Wp=class{static{a(this,"JobObject")}constructor(){this.id=x8(),this.type=void 0,this.start_datetime=AM().valueOf(),this.created_datetime=AM().valueOf(),this.end_datetime=void 0,this.status=G8.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};OM.exports=Wp});var Qp=m((i_e,UM)=>{"use strict";var k8=require("uuid").v4,IM=Ar(),wM=gr(),V8=os(),$8=to(),Y8=gM(),Fe=A(),K8=NM(),W8=xm(),Lr=x(),Q8=Aa(),Lo=V(),{promisify:z8}=require("util"),Ni=require("moment"),J8=j_(),pd=Pp(),bM=Gf(),{deleteTransactionLogsBeforeValidator:X8}=op(),{handleHDBError:Z8,hdb_errors:j8}=W(),{HTTP_STATUS_CODES:e6}=j8,yM=wM.searchByValue,t6=wM.searchByHash,r6=IM.insert,s6=z8(J8.evaluateSQL),n6=IM.update;UM.exports={addJob:a6,updateJob:u6,handleGetJob:i6,handleGetJobsByStartDate:o6,getJobById:CM};async function i6(e){try{let t=await CM(e.id);return Lo.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 Lr.error("There was an error getting job",t),new Error(r)}}a(i6,"handleGetJob");async function o6(e){try{let t=await c6(e);if(Lr.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=Ni(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Ni(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 Lr.error(r),new Error(r)}}a(o6,"handleGetJobsByStartDate");async function a6(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Lo.isEmptyOrZeroLength(e.operation)){let _="job parameter is invalid";return Lr.info(_),t.error=_,t}if(!Fe.JOB_TYPE_ENUM[e.operation])return Lr.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case Fe.OPERATIONS_ENUM.CSV_FILE_LOAD:s=pd.fileObject(e);break;case Fe.OPERATIONS_ENUM.CSV_URL_LOAD:s=pd.urlObject(e);break;case Fe.OPERATIONS_ENUM.CSV_DATA_LOAD:s=pd.dataObject(e);break;case Fe.OPERATIONS_ENUM.IMPORT_FROM_S3:s=pd.s3FileObject(e);break;case Fe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Fe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=bM(e,"date");break;case Fe.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=bM(e,"timestamp");break;case Fe.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=X8(e);break;default:break}if(s)throw Z8(s,s.message,e6.BAD_REQUEST,void 0,void 0,!0);let n=new K8;n.type=e.operation===Fe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Fe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new V8(Fe.SYSTEM_SCHEMA_NAME,Fe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await yM(i))}catch(_){let d=`There was an error inserting a new job: ${_}`;return Lr.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=k8();try{o=await yM(i)}catch(_){let d=`There was an error inserting a new job: ${_}`;return Lr.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Lr.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new Q8(Fe.SYSTEM_SCHEMA_NAME,Fe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),l;try{l=await r6(u)}catch(_){return Lr.error(`There was an error inserting a job for job type: ${e.operation} -- ${_}`),t.success=!1,t}if(l.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let _=`Created a job with type ${n.type} and id ${n.id}`;t.message=_,t.createdJob=n,t.success=!0,Lr.trace(_)}return t}a(a6,"addJob");async function c6(e){let t=Ni(e.from_date,Ni.ISO_8601),r=Ni(e.to_date,Ni.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 Y8(s,e.hdb_user);try{return await s6(n)}catch(i){throw Lr.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(c6,"getJobsInDateRange");async function CM(e){if(Lo.isEmptyOrZeroLength(e))return Lo.errorizeMessage("Invalid job ID specified.");let t=new $8(Fe.SYSTEM_SCHEMA_NAME,Fe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await t6(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return Lr.error(s),Lo.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(CM,"getJobById");async function u6(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Lo.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Fe.JOB_STATUS_ENUM.COMPLETE||e.status===Fe.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Ni().valueOf());let t=new W8(Fe.SYSTEM_SCHEMA_NAME,Fe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await n6(t),r}a(u6,"updateJob")});var BM=m((a_e,vM)=>{"use strict";var DM=V(),Xt=A(),l6=require("moment"),Td=$p(),Rd=x(),LM=Qp(),MM=ed(),PM=jn(),_6=nt(),d6=V_(),zp=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function E6(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(DM.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(DM.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Xt.JOB_TYPE_ENUM.csv_file_load:await Zs(e,Td.csvFileLoad);break;case Xt.JOB_TYPE_ENUM.csv_url_load:await Zs(e,Td.csvURLLoad);break;case Xt.JOB_TYPE_ENUM.csv_data_load:await Zs(e,Td.csvDataLoad);break;case Xt.JOB_TYPE_ENUM.import_from_s3:await Zs(e,Td.importFromS3);break;case Xt.JOB_TYPE_ENUM.empty_trash:break;case Xt.JOB_TYPE_ENUM.export_local:await Zs(e,MM.export_local);break;case Xt.JOB_TYPE_ENUM.export_to_s3:await Zs(e,MM.export_to_s3);break;case Xt.JOB_TYPE_ENUM.delete_files_before:case Xt.JOB_TYPE_ENUM.delete_records_before:await Zs(e,PM.deleteFilesBefore);break;case Xt.JOB_TYPE_ENUM.delete_audit_logs_before:await Zs(e,PM.deleteAuditLogsBefore);break;case Xt.JOB_TYPE_ENUM.delete_transaction_logs_before:await Zs(e,d6.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(E6,"parseMessage");async function Zs(e,t){try{e.job.status=Xt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=l6().valueOf(),await LM.updateJob(e.job),await f6(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):Rd.error(`There was an error running ${t.name} job with id ${e.job.id}`),Rd.error(s),e.job.message=s,e.job.status=Xt.JOB_STATUS_ENUM.ERROR;try{await LM.updateJob(e.job)}catch(n){throw Rd.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Zs,"runJob");async function f6(e){Rd.trace("launching job thread:",e),_6.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Xt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(f6,"launchJobThread");vM.exports={parseMessage:E6,RunnerMessage:zp}});var qM=m((u_e,HM)=>{"use strict";var Jp=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};HM.exports=Jp});var tP=m((__e,tT)=>{"use strict";var Nd=gr(),jp=j_(),gd=$p(),js=Wl(),Ad=Qn(),$c=jn(),h6=ym(),Vc=br(),Od=vm(),bt=ip(),lt=x(),m6=qm(),S6=l_(),p6=TS(),T6=f_(),R6=RS(),g6=gS(),A6=NS(),O6=yS(),Xp=CS(),FM=ed(),N6=X_(),eT=Qp(),I=A(),{hdb_errors:Kc,handleHDBError:Yc}=W(),{HTTP_STATUS_CODES:GM}=Kc,Zp=PS(),xM=XS(),JM=require("util"),Mo=Ar(),b6=dn(),y6=So(),kM=BM(),VM=ic(),$M=(F_(),ee(yc)),YM=Nr(),KM=V_(),WM=W_(),{setServerUtilities:I6}=(Sd(),ee(Yp)),{CONTEXT:w6}=(Zr(),ee($E)),{_assignPackageExport:C6}=require("../../index"),{transformReq:U6}=V(),D6=vp(),QM=Nd.searchByHash,L6=Nd.searchByValue,M6=JM.promisify(Nd.search),P6=JM.promisify(jp.evaluateSQL),v6={[I.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[I.OPERATIONS_ENUM.CREATE_TABLE]:!0,[I.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[I.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[I.OPERATIONS_ENUM.DROP_TABLE]:!0,[I.OPERATIONS_ENUM.DROP_SCHEMA]:!0},B=qM();async function XM(e,t){try{if(e.body.operation!=="read_log"&&(lt.log_level===I.LOG_LEVELS.INFO||lt.log_level===I.LOG_LEVELS.DEBUG||lt.log_level===I.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;lt.info(o)}}catch(s){lt.error(s)}let r=await D6.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return v6[e.body.operation]&&b6.setSchemaDataToGlobal(s=>{s&<.error(s)}),r}a(XM,"processLocalTransaction");var zM=H6();tT.exports={chooseOperation:ZM,getOperationFunction:jM,operation:eP,processLocalTransaction:XM};I6(tT.exports);function ZM(e){let t;try{t=jM(e)}catch(n){throw lt.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=jp.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=jp.checkASTPermissions(e,i);if(o)throw lt.error(`${GM.FORBIDDEN} from operation ${e.operation}`),lt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),Yc(new Error,o,Kc.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==I.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==I.OPERATIONS_ENUM.LOGIN&&e.operation!==I.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=N6.verifyPerms(i,n);if(o)throw lt.error(`${GM.FORBIDDEN} from operation ${e.operation}`),lt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),Yc(new Error,o,Kc.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw Yc(n,"There was an error when trying to choose an operation path")}return r}a(ZM,"chooseOperation");function jM(e){if(lt.trace(`getOperationFunction with operation: ${e.operation}`),zM.has(e.operation))return zM.get(e.operation);throw Yc(new Error,Kc.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Kc.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(jM,"getOperationFunction");C6("operation",eP);function eP(e,t){e.hdb_user=this[w6]?.user,e.bypass_auth=!t;let r=ZM(e);return XM({body:e},r)}a(eP,"operation");async function B6(e){lt.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[I.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case I.OPERATIONS_ENUM.INSERT:o=await Mo.insert(i);break;case I.OPERATIONS_ENUM.UPDATE:o=await Mo.update(i);break;case I.OPERATIONS_ENUM.UPSERT:o=await Mo.upsert(i);break;case I.OPERATIONS_ENUM.DELETE:o=await $c.deleteRecord(i);break;default:lt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){lt.info("Invalid operation in transaction"),lt.error(o)}}a(B6,"catchup");async function Ts(e){U6(e);let t,r;try{r=await eT.addJob(e),t=r.createdJob,lt.info("addJob result",r);let s=new kM.RunnerMessage(t,e);return await kM.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw lt.error(n),Yc(s,n)}}a(Ts,"executeJob");function H6(){let e=new Map;return e.set(I.OPERATIONS_ENUM.INSERT,new B(Mo.insert)),e.set(I.OPERATIONS_ENUM.UPDATE,new B(Mo.update)),e.set(I.OPERATIONS_ENUM.UPSERT,new B(Mo.upsert)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new B(Nd.searchByConditions)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_HASH,new B(QM)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_ID,new B(QM)),e.set(I.OPERATIONS_ENUM.SEARCH_BY_VALUE,new B(L6)),e.set(I.OPERATIONS_ENUM.SEARCH,new B(M6)),e.set(I.OPERATIONS_ENUM.SQL,new B(P6)),e.set(I.OPERATIONS_ENUM.CSV_DATA_LOAD,new B(Ts,gd.csvDataLoad)),e.set(I.OPERATIONS_ENUM.CSV_FILE_LOAD,new B(Ts,gd.csvFileLoad)),e.set(I.OPERATIONS_ENUM.CSV_URL_LOAD,new B(Ts,gd.csvURLLoad)),e.set(I.OPERATIONS_ENUM.IMPORT_FROM_S3,new B(Ts,gd.importFromS3)),e.set(I.OPERATIONS_ENUM.CREATE_SCHEMA,new B(js.createSchema)),e.set(I.OPERATIONS_ENUM.CREATE_DATABASE,new B(js.createSchema)),e.set(I.OPERATIONS_ENUM.CREATE_TABLE,new B(js.createTable)),e.set(I.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new B(js.createAttribute)),e.set(I.OPERATIONS_ENUM.DROP_SCHEMA,new B(js.dropSchema)),e.set(I.OPERATIONS_ENUM.DROP_DATABASE,new B(js.dropSchema)),e.set(I.OPERATIONS_ENUM.DROP_TABLE,new B(js.dropTable)),e.set(I.OPERATIONS_ENUM.DROP_ATTRIBUTE,new B(js.dropAttribute)),e.set(I.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new B(Ad.describeSchema)),e.set(I.OPERATIONS_ENUM.DESCRIBE_DATABASE,new B(Ad.describeSchema)),e.set(I.OPERATIONS_ENUM.DESCRIBE_TABLE,new B(Ad.describeTable)),e.set(I.OPERATIONS_ENUM.DESCRIBE_ALL,new B(Ad.describeAll)),e.set(I.OPERATIONS_ENUM.DELETE,new B($c.deleteRecord)),e.set(I.OPERATIONS_ENUM.ADD_USER,new B(Vc.addUser)),e.set(I.OPERATIONS_ENUM.ALTER_USER,new B(Vc.alterUser)),e.set(I.OPERATIONS_ENUM.DROP_USER,new B(Vc.dropUser)),e.set(I.OPERATIONS_ENUM.LIST_USERS,new B(Vc.listUsersExternal)),e.set(I.OPERATIONS_ENUM.LIST_ROLES,new B(Od.listRoles)),e.set(I.OPERATIONS_ENUM.ADD_ROLE,new B(Od.addRole)),e.set(I.OPERATIONS_ENUM.ALTER_ROLE,new B(Od.alterRole)),e.set(I.OPERATIONS_ENUM.DROP_ROLE,new B(Od.dropRole)),e.set(I.OPERATIONS_ENUM.USER_INFO,new B(Vc.userInfo)),e.set(I.OPERATIONS_ENUM.READ_LOG,new B(m6)),e.set(I.OPERATIONS_ENUM.ADD_NODE,new B(S6)),e.set(I.OPERATIONS_ENUM.UPDATE_NODE,new B(p6)),e.set(I.OPERATIONS_ENUM.REMOVE_NODE,new B(T6)),e.set(I.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new B(R6)),e.set(I.OPERATIONS_ENUM.PURGE_STREAM,new B(g6)),e.set(I.OPERATIONS_ENUM.SET_CONFIGURATION,new B(YM.setConfiguration)),e.set(I.OPERATIONS_ENUM.CLUSTER_STATUS,new B(A6.clusterStatus)),e.set(I.OPERATIONS_ENUM.CLUSTER_NETWORK,new B(O6)),e.set(I.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new B(Xp.setRoutes)),e.set(I.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new B(Xp.getRoutes)),e.set(I.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new B(Xp.deleteRoutes)),e.set(I.OPERATIONS_ENUM.EXPORT_TO_S3,new B(Ts,FM.export_to_s3)),e.set(I.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new B(Ts,$c.deleteFilesBefore)),e.set(I.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new B(Ts,$c.deleteFilesBefore)),e.set(I.OPERATIONS_ENUM.EXPORT_LOCAL,new B(Ts,FM.export_local)),e.set(I.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new B(eT.handleGetJobsByStartDate)),e.set(I.OPERATIONS_ENUM.GET_JOB,new B(eT.handleGetJob)),e.set(I.OPERATIONS_ENUM.GET_FINGERPRINT,new B(Zp.getFingerprint)),e.set(I.OPERATIONS_ENUM.SET_LICENSE,new B(Zp.setLicense)),e.set(I.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new B(Zp.getRegistrationInfo)),e.set(I.OPERATIONS_ENUM.RESTART,new B(xM.restart)),e.set(I.OPERATIONS_ENUM.RESTART_SERVICE,new B(xM.restartService)),e.set(I.OPERATIONS_ENUM.CATCHUP,new B(B6)),e.set(I.OPERATIONS_ENUM.SYSTEM_INFORMATION,new B(y6.systemInformation)),e.set(I.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new B(Ts,$c.deleteAuditLogsBefore)),e.set(I.OPERATIONS_ENUM.READ_AUDIT_LOG,new B(h6)),e.set(I.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new B(VM.createTokens)),e.set(I.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new B(VM.refreshOperationToken)),e.set(I.OPERATIONS_ENUM.LOGIN,new B($M.login)),e.set(I.OPERATIONS_ENUM.LOGOUT,new B($M.logout)),e.set(I.OPERATIONS_ENUM.GET_CONFIGURATION,new B(YM.getConfiguration)),e.set(I.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new B(bt.customFunctionsStatus)),e.set(I.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new B(bt.getCustomFunctions)),e.set(I.OPERATIONS_ENUM.GET_COMPONENT_FILE,new B(bt.getComponentFile)),e.set(I.OPERATIONS_ENUM.GET_COMPONENTS,new B(bt.getComponents)),e.set(I.OPERATIONS_ENUM.SET_COMPONENT_FILE,new B(bt.setComponentFile)),e.set(I.OPERATIONS_ENUM.DROP_COMPONENT,new B(bt.dropComponent)),e.set(I.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new B(bt.getCustomFunction)),e.set(I.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new B(bt.setCustomFunction)),e.set(I.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new B(bt.dropCustomFunction)),e.set(I.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new B(bt.addComponent)),e.set(I.OPERATIONS_ENUM.ADD_COMPONENT,new B(bt.addComponent)),e.set(I.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new B(bt.dropCustomFunctionProject)),e.set(I.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new B(bt.packageComponent)),e.set(I.OPERATIONS_ENUM.PACKAGE_COMPONENT,new B(bt.packageComponent)),e.set(I.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new B(bt.deployComponent)),e.set(I.OPERATIONS_ENUM.DEPLOY_COMPONENT,new B(bt.deployComponent)),e.set(I.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new B(KM.readTransactionLog)),e.set(I.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new B(Ts,KM.deleteTransactionLogsBefore)),e.set(I.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new B(WM.installModules)),e.set(I.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new B(WM.auditModules)),e.set(I.OPERATIONS_ENUM.GET_BACKUP,new B(js.getBackup)),e}a(H6,"initializeOperationFunctionMap")});var yd=m((E_e,nP)=>{"use strict";var rT=A(),q6=V(),Wc=x(),{handleHDBError:sT,hdb_errors:bd}=W(),{isMainThread:F6}=require("worker_threads"),{Readable:G6}=require("stream"),rP=require("os"),x6=require("util"),k6=zm(),V6=x6.promisify(k6.authorize),sP=tP(),{Gzip:$6}=require("zlib");function Y6(e){let t=`Found an uncaught exception with message: ${e.message}. ${rP.EOL}Stack: ${e.stack} ${rP.EOL}Terminating ${F6?"HDB":"thread"}.`;console.error(t),Wc.fatal(t),process.exit(1)}a(Y6,"handleServerUncaughtException");function K6(e,t,r){if(Wc[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:bd.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(K6,"serverErrorHandler");function W6(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=sT(new Error,"Invalid JSON.",bd.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(q6.isEmpty(e.body.operation)){let s=sT(new Error,"Request body must include an 'operation' property.",bd.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(W6,"reqBodyValidationHandler");function Q6(e,t,r){let s;e.body.operation!==rT.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==rT.OPERATIONS_ENUM.LOGIN&&e.body.operation!==rT.OPERATIONS_ENUM.LOGOUT?V6(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{Wc.warn(n),Wc.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(sT(n,i,bd.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(Q6,"authHandler");async function z6(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=sP.chooseOperation(e.body);let n=await sP.processLocalTransaction(e,s);if(n instanceof G6&&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(new $6))}return n}catch(n){throw Wc.error(n),n}}a(z6,"handlePostRequest");nP.exports={authHandler:Q6,handlePostRequest:z6,handleServerUncaughtException:Y6,serverErrorHandler:K6,reqBodyValidationHandler:W6}});var cP=m((h_e,aP)=>{"use strict";var J6=require("fastify-plugin"),{handlePostRequest:iP,authHandler:X6,reqBodyValidationHandler:Z6}=yd();async function j6(e){e.decorate("hdbCore",{preValidation:[Z6,X6],request:t=>oP(iP(t,response)),requestWithoutAuthentication:(t,r)=>oP(iP(t,r,!0))})}a(j6,"hdbCore");async function oP(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(oP,"convertAsyncIterators");aP.exports=J6(j6)});var lP=m((S_e,uP)=>{"use strict";var nT=require("fs"),Po=Q();Po.initSync();var{CONFIG_PARAMS:Qc}=A(),e9=1024*1024*1024;function t9(e){let t=Po.get(Qc.CUSTOMFUNCTIONS_NETWORK_TIMEOUT),r=Po.get(Qc.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT),s={bodyLimit:e9,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0};if(e){let n=Po.get(Qc.CUSTOMFUNCTIONS_TLS_PRIVATEKEY),i=Po.get(Qc.CUSTOMFUNCTIONS_TLS_CERTIFICATE),o=Po.get(Qc.OPERATIONSAPI_TLS_CERT_AUTH);s.https={allowHTTP1:!0,key:nT.readFileSync(`${n}`),cert:nT.readFileSync(i)+(o?`
|
|
23
23
|
|
|
24
|
-
`+tT.readFileSync(o):"")},s.http2=!0}return s}a(z6,"getServerOptions");nP.exports=z6});var cP=m((c_e,aP)=>{"use strict";var rT=Q();rT.initSync();var{CONFIG_PARAMS:oP}=g();function J6(){let e=rT.get(oP.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=rT.get(oP.CUSTOMFUNCTIONS_NETWORK_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(J6,"getCORSOptions");aP.exports=J6});var _P=m((l_e,lP)=>{"use strict";var uP=Q();uP.initSync();var X6=g();function Z6(){return uP.get(X6.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}a(Z6,"getHeaderTimeoutConfig");lP.exports=Z6});var iT={};Ze(iT,{customFunctionsServer:()=>t9,handleFile:()=>e9,ready:()=>n9});async function e9(e,t,r,s){if(!js){let c=sT.get(nT.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS);js=NP(c),ht.http((await js).server)}let n=await js,i=(0,EP.dirname)(r),o=t.replace(/\/routes\/.*/g,"");o.startsWith("/")&&(o=o.slice(1)),dP.has(i)||(dP.add(i),n.register(s9(i,o)))}async function t9(){try{Ue.info("In Custom Functions Fastify server"+process.cwd()),Ue.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ue.debug(`Custom Functions server process ${process.pid} starting up.`),await r9();let e=sT.get(nT.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=e&&(e===!0||e.toUpperCase()===TRUE_COMPARE_VAL),r;try{r=js=await NP(t)}catch(s){throw Ue.error(`Custom Functions buildServer error: ${s}`),s}try{await r.ready()}catch(s){throw Ue.error(`Custom Functions server.ready() error: ${s}`),s}r.server.cantCleanupProperly=!0}catch(e){Ue.error(`Custom Functions ${process.pid} Error: ${e}`),Ue.error(e),process.exit(1)}}async function r9(){try{Ue.info("Custom Functions starting configuration."),await TP.setUsersToGlobal(),Ue.info("Custom Functions completed configuration.")}catch(e){Ue.error(e)}}function s9(e,t){return async function(r){try{Ue.info("Custom Functions starting buildRoutes"),Ue.trace("Loading fastify routes folder "+e),(0,fP.existsSync)(e)&&r.register(pP.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ue.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?Ue.error(n.message):n&&Ue.error(n),o()})}catch(s){Ue.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function NP(e){Ue.info("Custom Functions starting buildServer.");let t=(0,RP.default)(e),r=(0,hP.default)(t);r.server.headersTimeout=(0,AP.default)(),r.setErrorHandler(OP.serverErrorHandler);let s=(0,gP.default)();return s&&r.register(mP.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(SP.default),await r.register(j6),await r.after(),gp(r),Ue.info("Custom Functions completed buildServer."),r}function n9(){if(js)return js.then?js.then(e=>e.ready()):js.ready()}var EP,fP,hP,mP,SP,pP,sT,nT,Ue,j6,TP,RP,gP,AP,OP,js,dP,bP=pe(()=>{EP=require("path"),fP=require("fs"),hP=D(require("fastify")),mP=D(require("@fastify/cors")),SP=D(Ip()),pP=D(require("@fastify/autoload")),sT=D(Q()),nT=D(g()),Ue=D(F()),j6=D(sP()),TP=D(Or()),RP=D(iP()),gP=D(cP()),AP=D(_P()),OP=D(Od());go();Us();dP=new Set;a(e9,"handleFile");a(t9,"customFunctionsServer");a(r9,"setUp");a(s9,"buildRouteFolder");a(NP,"buildServer");a(n9,"ready")});var oT={};Ze(oT,{start:()=>i9});function i9(e){let t=e.root;return{handleFile(r,s,n){IP||(IP=!0,e.server.http(async(i,o)=>{if(!i.isWebSocket){let c=yP.get(i.pathname);if(c)return{handlesHeaders:!0,body:(0,wP.default)(i,c)}}return o(i)},{runFirst:!0})),t&&(s.startsWith("/"+t)?s=s.slice(t.length+1):s.startsWith(t)&&(s=s.slice(t.length))),yP.set(s,n)}}}var wP,yP,IP,CP=pe(()=>{wP=D(require("send")),yP=new Map;a(i9,"start")});function c9(e,t=1,r){if(aT++,(0,Oi.startWorker)("server/threads/threadServer.js",{name:yd.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(l){l.type===yd.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});a9.push(n),await n,Mo.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=bd.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=Mo.indexOf(s);o>-1&&Mo.splice(o,1)}if(a(i,"removeWorker"),Po){let o=Po;Po=[];for(let c of o)PP[c.localPort](c)}}}),r){let s=setInterval(()=>{cT?cT=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Oi.shutdownWorkers)(),aT=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function vP(e=0,t){if(typeof e=="string")try{(0,Id.existsSync)(e)&&(0,Id.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=u9:r=l9(t):r=uT;let s=(0,LP.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData},PP[e]=i=>{cT=!0,r(i,(o,c)=>{if(!o){UP?(UP.deliverSocket(i,e,c),i.resume()):aT>0?(Po.length===0&&setTimeout(()=>{Po.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(),Po.push(i)):(console.log("start up a dynamic thread to handle request"),c9(0));return}o.requests++,i._handle.fd>=0?o.postMessage({port:e,fd:i._handle.fd,data:c}):f9(i,o,e)})}).listen(e);s.on("error",i=>{console.error("Error in socket server",i)}),process.env._UNREF_SERVER&&s.unref();let n=$a();return MP.info(`HarperDB ${n.version} Server running on port ${e}`),s}function uT(e,t){let r,s=0;for(let n of Mo){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=Nd)return Nd=i,t(r);s=i}Nd=0,t(r)}function u9(e,t){let r=e.remoteAddress,s=vo.get(r),n=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=n,t(s.worker);uT(e,i=>{vo.set(r,{worker:i,lastUsed:n}),t(i)})}function l9(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){s.on("data",i=>{s._handle.readStop();let c=i.toString("latin1").match(t)?.[1],u=vo.get(c),l=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=l,n(u.worker);uT(s,_=>{vo.set(c,{worker:_,lastUsed:l}),n(_,i)})})}a(r,"findByHeaderAffinity")}function d9(){Nd=0;for(let e of Mo)e.expectedIdle=e.recentELU.idle+_9,e.requests=1;Mo.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function f9(e,t,r){let s=E9++;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(),bd.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")),bd.delete(s)),n.event=="destroy"&&(e.destroy(),bd.delete(s))})}var Oi,LP,yd,MP,Id,o9,Mo,Po,PP,UP,aT,a9,cT,Nd,DP,vo,_9,bd,E9,BP=pe(()=>{Oi=D(rt()),LP=require("net"),yd=D(g()),MP=D(F()),Id=require("fs"),{isMainThread:o9}=require("worker_threads"),Mo=[],Po=[],PP=[],aT=0,a9=[];o9&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&console.error("uncaughtException",e)});a(c9,"startHTTPWorker");a(vP,"startSocketServer");Nd=0;a(uT,"findMostIdleWorker");DP=36e5,vo=new Map;a(u9,"findByRemoteAddressAffinity");a(l9,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of vo)r.lastUsed+DP<e&&vo.delete(t)},DP).unref();_9=1e3;a(d9,"updateWorkerIdleness");(0,Oi.setMonitorListener)(d9);bd=new Map,E9=1;a(f9,"proxySocket")});var xP=m((g_e,GP)=>{"use strict";var h9=require("cluster"),Wr=Q();Wr.initSync();var qP=g(),p_e=require("util"),en=F(),lT=require("fs"),m9=require("fastify"),T_e=$a(),S9=require("@fastify/cors"),p9=require("@fastify/compress"),T9=require("@fastify/static"),R9=Ip(),g9=require("path"),{PACKAGE_ROOT:A9}=g(),O9=_n(),N9=x(),b9=Or(),y9=ya(),{server:I9}=(Us(),te(Lu)),{authHandler:w9,handlePostRequest:C9,serverErrorHandler:U9,reqBodyValidationHandler:D9}=Od(),R_e=require("net"),{registerContentHandlers:L9}=(go(),te(HL)),M9=1024*1024*1024,FP="TRUE",{HDB_SETTINGS_NAMES:bi,CONFIG_PARAMS:P9}=qP,v9=bi.CORS_ENABLED_KEY,B9="CORS_ACCESSLIST",H9=bi.SERVER_TIMEOUT_KEY,q9=bi.SERVER_KEEP_ALIVE_TIMEOUT_KEY,F9=bi.SERVER_HEADERS_TIMEOUT_KEY,G9=bi.PRIVATE_KEY_KEY,x9=bi.CERT_KEY,k9=bi.HTTP_SECURE_ENABLED_KEY,Ni;GP.exports={hdbServer:HP,start:HP};async function HP(e){try{en.info("In Fastify server"+process.cwd()),en.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),en.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=h9.isMaster,await V9();let t=Wr.get(k9),r=t&&(t===!0||t.toUpperCase()===FP);Ni=$9(r),await Ni.ready(),e||(e={}),e.isOperationsServer=!0,Ni.server.cantCleanupProperly=!0;try{I9.http(Ni.server,e),Ni.server.closeIdleConnections||await Ni.listen({port:0,host:"::"})}catch(s){throw Ni.close(),en.error(s),en.error(`Error configuring ${server_type} server`),s}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),en.fatal(t),process.exit(1)}}a(HP,"operationsServer");async function V9(){en.trace("Configuring HarperDB process."),O9.setSchemaDataToGlobal(),await b9.setUsersToGlobal(),await y9.getLicense()}a(V9,"setUp");function $9(e){en.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Y9(e),r=m9(t);r.server.headersTimeout=W9(),r.setErrorHandler(U9);let s=K9();s&&r.register(S9,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,l){r.server.emit("unhandled",u.raw,l.raw)}),c()}),r.register(R9),r.register(p9),r.register(T9,{root:g9.join(A9,"docs")}),L9(r);let n=Wr.get(qP.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!N9.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.callNotFound()}),r.post("/",{preValidation:[D9,w9],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),C9(i,o)}),r.get("/health",()=>"HarperDB is running."),en.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a($9,"buildServer");function Y9(e){let t=Wr.get(H9),r=Wr.get(q9),s={bodyLimit:M9,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1};if(e){let n=Wr.get(G9),i=Wr.get(x9),o=Wr.get(P9.OPERATIONSAPI_TLS_CERT_AUTH),c={allowHTTP1:!0,key:lT.readFileSync(n),cert:lT.readFileSync(i)+(o?`
|
|
24
|
+
`+nT.readFileSync(o):"")},s.http2=!0}return s}a(t9,"getServerOptions");uP.exports=t9});var EP=m((T_e,dP)=>{"use strict";var iT=Q();iT.initSync();var{CONFIG_PARAMS:_P}=A();function r9(){let e=iT.get(_P.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=iT.get(_P.CUSTOMFUNCTIONS_NETWORK_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(r9,"getCORSOptions");dP.exports=r9});var mP=m((g_e,hP)=>{"use strict";var fP=Q();fP.initSync();var s9=A();function n9(){return fP.get(s9.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}a(n9,"getHeaderTimeoutConfig");hP.exports=n9});var cT={};Ye(cT,{customFunctionsServer:()=>a9,handleFile:()=>o9,ready:()=>l9});async function o9(e,t,r,s){if(!en){let c=oT.get(aT.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS);en=CP(c),tt.http((await en).server)}let n=await en,i=(0,pP.dirname)(r),o=t.replace(/\/routes\/.*/g,"");o.startsWith("/")&&(o=o.slice(1)),SP.has(i)||(SP.add(i),n.register(u9(i,o)))}async function a9(){try{Ue.info("In Custom Functions Fastify server"+process.cwd()),Ue.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ue.debug(`Custom Functions server process ${process.pid} starting up.`),await c9();let e=oT.get(aT.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=e&&(e===!0||e.toUpperCase()===TRUE_COMPARE_VAL),r;try{r=en=await CP(t)}catch(s){throw Ue.error(`Custom Functions buildServer error: ${s}`),s}try{await r.ready()}catch(s){throw Ue.error(`Custom Functions server.ready() error: ${s}`),s}r.server.cantCleanupProperly=!0}catch(e){Ue.error(`Custom Functions ${process.pid} Error: ${e}`),Ue.error(e),process.exit(1)}}async function c9(){try{Ue.info("Custom Functions starting configuration."),await NP.setUsersToGlobal(),Ue.info("Custom Functions completed configuration.")}catch(e){Ue.error(e)}}function u9(e,t){return async function(r){try{Ue.info("Custom Functions starting buildRoutes"),Ue.trace("Loading fastify routes folder "+e),(0,TP.existsSync)(e)&&r.register(OP.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ue.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?Ue.error(n.message):n&&Ue.error(n),o()})}catch(s){Ue.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function CP(e){Ue.info("Custom Functions starting buildServer.");let t=(0,bP.default)(e),r=(0,RP.default)(t);r.server.headersTimeout=(0,IP.default)(),r.setErrorHandler(wP.serverErrorHandler);let s=(0,yP.default)();return s&&r.register(gP.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(AP.default),await r.register(i9),await r.after(),bp(r),Ue.info("Custom Functions completed buildServer."),r}function l9(){if(en)return en.then?en.then(e=>e.ready()):en.ready()}var pP,TP,RP,gP,AP,OP,oT,aT,Ue,i9,NP,bP,yP,IP,wP,en,SP,UP=Se(()=>{pP=require("path"),TP=require("fs"),RP=C(require("fastify")),gP=C(require("@fastify/cors")),AP=C(Up()),OP=C(require("@fastify/autoload")),oT=C(Q()),aT=C(A()),Ue=C(x()),i9=C(cP()),NP=C(br()),bP=C(lP()),yP=C(EP()),IP=C(mP()),wP=C(yd());Oo();Pr();SP=new Set;a(o9,"handleFile");a(a9,"customFunctionsServer");a(c9,"setUp");a(u9,"buildRouteFolder");a(CP,"buildServer");a(l9,"ready")});var uT={};Ye(uT,{start:()=>_9});function _9(e){let t=e.root;return{handleFile(r,s,n){LP||(LP=!0,e.server.http(async(i,o)=>{if(!i.isWebSocket){let c=DP.get(i.pathname);if(c)return{handlesHeaders:!0,body:(0,MP.default)(i,c)}}return o(i)},{runFirst:!0})),t&&(s.startsWith("/"+t)?s=s.slice(t.length+1):s.startsWith(t)&&(s=s.slice(t.length))),DP.set(s,n)}}}var MP,DP,LP,PP=Se(()=>{MP=C(require("send")),DP=new Map;a(_9,"start")});function f9(e,t=1,r){if(lT++,(0,bi.startWorker)("server/threads/threadServer.js",{name:Cd.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(l){l.type===Cd.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});E9.push(n),await n,vo.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=wd.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=vo.indexOf(s);o>-1&&vo.splice(o,1)}if(a(i,"removeWorker"),Bo){let o=Bo;Bo=[];for(let c of o)qP[c.localPort](c)}}}),r){let s=setInterval(()=>{_T?_T=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,bi.shutdownWorkers)(),lT=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function FP(e=0,t){if(typeof e=="string")try{(0,Dd.existsSync)(e)&&(0,Dd.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=h9:r=m9(t):r=dT;let s=(0,HP.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData},qP[e]=i=>{_T=!0,r(i,(o,c)=>{if(!o){vP?(vP.deliverSocket(i,e,c),i.resume()):lT>0?(Bo.length===0&&setTimeout(()=>{Bo.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(),Bo.push(i)):(console.log("start up a dynamic thread to handle request"),f9(0));return}o.requests++;let u=i._handle.fd;Ud.trace("Socket",u,"from",i.remoteAddress," routed to worker",o.threadId),u>=0?o.postMessage({port:e,fd:u,data:c}):R9(i,o,e)})}).listen(e);s.on("error",i=>{console.error("Error in socket server",i)}),process.env._UNREF_SERVER&&s.unref();let n=Wa();return Ud.info(`HarperDB ${n.version} Server running on port ${e}`),s}function dT(e,t){let r,s=0;for(let n of vo){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=Id)return Id=i,t(r);s=i}Id=0,t(r)}function h9(e,t){let r=e.remoteAddress,s=Ho.get(r),n=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=n,t(s.worker);dT(e,i=>{Ho.set(r,{worker:i,lastUsed:n}),t(i)})}function m9(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){s.on("data",i=>{s._handle.readStop();let c=i.toString("latin1").match(t)?.[1],u=Ho.get(c),l=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=l,n(u.worker);dT(s,_=>{Ho.set(c,{worker:_,lastUsed:l}),n(_,i)})})}a(r,"findByHeaderAffinity")}function p9(){Id=0;for(let e of vo)e.expectedIdle=e.recentELU.idle+S9,e.requests=1;vo.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function R9(e,t,r){let s=T9++;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(),wd.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")),wd.delete(s)),n.event=="destroy"&&(e.destroy(),wd.delete(s))})}var bi,HP,Cd,Ud,Dd,d9,vo,Bo,qP,vP,lT,E9,_T,Id,BP,Ho,S9,wd,T9,GP=Se(()=>{bi=C(nt()),HP=require("net"),Cd=C(A()),Ud=C(x()),Dd=require("fs"),{isMainThread:d9}=require("worker_threads"),vo=[],Bo=[],qP=[],lT=0,E9=[];d9&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&console.error("uncaughtException",e)});a(f9,"startHTTPWorker");a(FP,"startSocketServer");Id=0;a(dT,"findMostIdleWorker");BP=36e5,Ho=new Map;a(h9,"findByRemoteAddressAffinity");a(m9,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ho)r.lastUsed+BP<e&&Ho.delete(t)},BP).unref();S9=1e3;a(p9,"updateWorkerIdleness");(0,bi.setMonitorListener)(p9);wd=new Map,T9=1;a(R9,"proxySocket")});var YP=m((L_e,$P)=>{"use strict";var g9=require("cluster"),Qr=Q();Qr.initSync();var kP=A(),C_e=require("util"),tn=x(),ET=require("fs"),A9=require("fastify"),U_e=Wa(),O9=require("@fastify/cors"),N9=require("@fastify/compress"),b9=require("@fastify/static"),y9=Up(),I9=require("path"),{PACKAGE_ROOT:w9}=A(),C9=dn(),U9=V(),D9=br(),L9=Ca(),{server:M9}=(Pr(),ee(da)),{authHandler:P9,handlePostRequest:v9,serverErrorHandler:B9,reqBodyValidationHandler:H9}=yd(),D_e=require("net"),{registerContentHandlers:q9}=(Oo(),ee(kL)),F9=1024*1024*1024,VP="TRUE",{HDB_SETTINGS_NAMES:Ii,CONFIG_PARAMS:G9}=kP,x9=Ii.CORS_ENABLED_KEY,k9="CORS_ACCESSLIST",V9=Ii.SERVER_TIMEOUT_KEY,$9=Ii.SERVER_KEEP_ALIVE_TIMEOUT_KEY,Y9=Ii.SERVER_HEADERS_TIMEOUT_KEY,K9=Ii.PRIVATE_KEY_KEY,W9=Ii.CERT_KEY,Q9=Ii.HTTP_SECURE_ENABLED_KEY,yi;$P.exports={hdbServer:xP,start:xP};async function xP(e){try{tn.info("In Fastify server"+process.cwd()),tn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),tn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=g9.isMaster,await z9();let t=Qr.get(Q9),r=t&&(t===!0||t.toUpperCase()===VP);yi=J9(r),await yi.ready(),e||(e={}),e.isOperationsServer=!0,yi.server.cantCleanupProperly=!0;try{M9.http(yi.server,e),yi.server.closeIdleConnections||await yi.listen({port:0,host:"::"})}catch(s){throw yi.close(),tn.error(s),tn.error(`Error configuring ${server_type} server`),s}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),tn.fatal(t),process.exit(1)}}a(xP,"operationsServer");async function z9(){tn.trace("Configuring HarperDB process."),C9.setSchemaDataToGlobal(),await D9.setUsersToGlobal(),await L9.getLicense()}a(z9,"setUp");function J9(e){tn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=X9(e),r=A9(t);r.server.headersTimeout=j9(),r.setErrorHandler(B9);let s=Z9();s&&r.register(O9,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,l){r.server.emit("unhandled",u.raw,l.raw)}),c()}),r.register(y9),r.register(N9),r.register(b9,{root:I9.join(w9,"docs")}),q9(r);let n=Qr.get(kP.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!U9.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.callNotFound()}),r.post("/",{preValidation:[H9,P9],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),v9(i,o)}),r.get("/health",()=>"HarperDB is running."),tn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(J9,"buildServer");function X9(e){let t=Qr.get(V9),r=Qr.get($9),s={bodyLimit:F9,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1};if(e){let n=Qr.get(K9),i=Qr.get(W9),o=Qr.get(G9.OPERATIONSAPI_TLS_CERT_AUTH),c={allowHTTP1:!0,key:ET.readFileSync(n),cert:ET.readFileSync(i)+(o?`
|
|
25
25
|
|
|
26
|
-
`+lT.readFileSync(o):"")};s.http2=!0,s.https=c}return s}a(Y9,"getServerOptions");function K9(){let e=Wr.get(v9),t=Wr.get(B9),r;return e&&(e===!0||e.toUpperCase()===FP)&&(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(K9,"getCORSOpts");function W9(){return Wr.get(F9)}a(W9,"getHeaderTimeoutConfig")});var jP=m((b_e,ZP)=>{"use strict";var{decode:Q9}=require("msgpackr"),{isMainThread:z9,parentPort:J9,threadId:O_e}=require("worker_threads"),_T=st(),Bo=Be(),X9=g(),Kc=F(),kP=Q(),YP=g();rt();var Z9=Ps(),{recordAction:j9,recordActionBinary:e7}=(ro(),te(Bl)),{publishToStream:t7}=_T,N_e={durable:Bo.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Bo.WORK_QUEUE_CONSUMER_NAMES.deliver_group},r7,s7,n7,KP,WP;ZP.exports={initialize:QP,workQueueListener:XP,setSubscription:i7,setIgnoreOrigin:a7,getDatabaseSubscriptions:o7};async function QP(){WP=!0,Kc.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await _T.getNATSReferences();r7=e,s7=e.info.server_name,n7=t,KP=r}a(QP,"initialize");var Cd=new Map;function i7(e,t,r){let s=Cd.get(e);s||Cd.set(e,s=new Map),s.set(t,r),WP||QP().then(XP)}a(i7,"setSubscription");function o7(){return Cd}a(o7,"getDatabaseSubscriptions");var zP;function a7(e){zP=e}a(a7,"setIgnoreOrigin");var JP=100,VP=new Array(JP),wd=0;async function XP(){let t=await(await KP.consumers.get(Bo.WORK_QUEUE_CONSUMER_NAMES.stream_name,Bo.WORK_QUEUE_CONSUMER_NAMES.durable_name)).consume();for await(let r of t)await VP[wd],VP[wd]=c7(r).catch(s=>{Kc.error(s)}),++wd>=JP&&(wd=0)}a(XP,"workQueueListener");z9||J9.on("message",async e=>{let{type:t}=e;t===YP.ITC_EVENT_TYPES.SHUTDOWN&&_T.closeConnection()});async function c7(e){let t=Q9(e.data);j9(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let n=e.headers.get(Bo.MSG_HEADERS.ORIGIN)===kP.get(X9.CONFIG_PARAMS.CLUSTERING_NODENAME)&&!zP;if(e7(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}try{let{operation:i,schema:o,next:c,table:u,records:l,hash_values:_,__origin:d}=t;Kc.trace("processing message:",i,o,u,(l?"records: "+l.map(y=>y.id):"")+(_?"ids: "+_:""),"with sequence:",e.seq),Kc.trace(`messageProcessor nats msg id: ${e.headers.get(Bo.MSG_HEADERS.NATS_MSG_ID)}`);let E;l||(l=_);let{timestamp:f,user:h,node_name:T}=d||{},S=Cd.get(o)?.get(u);if(!S)throw new Error("Missing table for replication message",u);if(i==="define_schema")t.type=i,S.send(t);else if(l.length===1&&!c)S.send({type:$P(i),value:l[0],id:_?.[0],timestamp:f,table:u,onCommit:E,user:h,nodeName:T});else{let y=l.map((O,H)=>({type:$P(i),value:O,id:_?.[H],table:u}));for(;c;)y.push({type:c.operation,value:c.record,id:c.id,table:c.table}),c=c.next;S.send({type:"transaction",writes:y,table:u,timestamp:f,onCommit:E,user:h,nodeName:T})}kP.get(YP.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&t7(e.subject.split(".").slice(0,-1).join("."),Z9.createNatsTableStreamName(o,u),e.headers,e.data)}catch(i){Kc.error(i)}e.ack()}a(c7,"messageProcessor");function $P(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a($P,"convertOperation")});var ST={};Ze(ST,{disableNATS:()=>l7,setNATSReplicator:()=>dT,start:()=>u7});function u7(){Dd.default.get(Ld.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&d7()}function l7(e=!0){nv=e}function d7(){if(nv)return;let e=Gr(),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];dT(n,r,i)}}pT((r,s)=>{dT(r.tableName,r.databaseName,r),s&&ov(r)}),!ev&&(ev=!0)}function dT(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.Source?.isNATSReplicator)return;let s;r.sourcedFrom(class extends ft{static{a(this,"NATSReplicator")}put(o){let c;return s?.put&&(!s.put.reliesOnPrototype||s.prototype.put)&&(c=s.put(this[ie],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[ie],record:o},c)}delete(){let o;return s?.delete&&(!s.delete.reliesOnPrototype||s.prototype.delete)&&(o=s.delete(this[ie],this.getContext())),n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[ie]},o)}publish(o){let c;return s?.publish&&(!s.publish.reliesOnPrototype||s.prototype.publish)&&(c=s.publish(this[ie],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[ie],record:o},c)}invalidate(o){if(n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[ie]}),s?.invalidate&&(!s.invalidate.reliesOnPrototype||s.prototype.invalidate))return s.invalidate(this[ie],this.getContext())}static defineSchema(o){ov(o)}static mergeSource(o,c){return s=o,s?.get&&(!s.get.reliesOnPrototype||s.prototype.get)&&(c.replicationSource?this.get=async(u,l)=>{let _=await s.get(u,l);return _&&n(l).addWrite(t,{operation:"put",table:e,id:u,record:_}),_}:this.get=(u,l)=>s.get(u,l)),this}static subscribe(){let o=new Jr;return(0,tv.setSubscription)(t,e,o),o}static subscribeOnThisThread(o){return o<_7}static isNATSReplicator=!0});function n(i){let o=i?.transaction?.nats;return o||(i?.transaction?(i.transaction.push(o=i.transaction.nats=new Ud(i.transaction,i)),o.user=i.user):o=iv),o}a(n,"getNATSTransaction")}function ov(e){let t=Dd.default.get(Ld.default.CONFIG_PARAMS.CLUSTERING_NODENAME);(0,fT.publishToStream)(`${hT.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,mT.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 fT,hT,mT,tv,rv,Dd,Ld,sv,nv,_7,iv,ev,Ud,ET,av=pe(()=>{de();Xr();fT=D(st()),hT=D(Be()),mT=D(Ps());aa();tv=D(jP()),rv=D(vt()),Dd=D(Q()),Ld=D(g()),sv=D(F());a(u7,"start");a(l7,"disableNATS");_7=2;a(d7,"assignReplicationSource");a(dT,"setNATSReplicator");a(ov,"publishSchema");Ud=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r,s){let n=this.writes_by_db.get(t);if(n||this.writes_by_db.set(t,n=[]),s?.then)return s.then(()=>n.push(r));n.push(r)}commit(t){let r=Dd.default.get(Ld.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,l;for(let _ of i){let d=_.table,E=_.operation=="put"?"upsert":_.operation;u||(sv.trace(`Sending transaction event ${E}`),l=u={operation:E,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(_.record),c.push(_.id)):l=l.next={operation:E,table:d,id:_.id,record:_.record}}s.push((0,fT.publishToStream)(`${hT.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,mT.createNatsTableStreamName)(n,u.table),void 0,u))}return Promise.all(s)}},ET=class extends Ud{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,rv.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit()}};iv=new ET});async function uv({clientId:e,user:t,listener:r,clean:s}){let n;if(e&&!s){let i=await TT.getResource(e,{});n=new gT(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await TT.get(e);i&&i.delete()}n=new Pd(e,t)}return n}function RT(){return Md++,Md>65500&&(Md=1),Md}var cv,Wc,TT,Md,Pd,gT,lv=pe(()=>{de();Ac();cv=D(vt()),Wc=D(F());Vn();TT=et({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"}]}}]});a(uv,"getSession");Md=1;a(RT,"getNextMessageId");Pd=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,omitCurrent:i,startTime:o}=t,c=n.indexOf("?"),u,l;if(c>-1?(u=n.slice(c),l=n.slice(0,c)):l=n,!l)throw new Error("No topic provided");let _=!1,d;if((l.endsWith("+")||l.endsWith("#"))&&(_=!0,l.endsWith("+")&&(d=!0),l=l.slice(0,l.length-1)),l.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");if(l.indexOf("#")>-1||l.indexOf("+")>-1)throw new Error("Only trailing wildcards are supported");let E=this.subscriptions.find(O=>O.topic===n);E&&(E.end(),this.subscriptions.splice(this.subscriptions.indexOf(E),1));let f={search:u,user:this.user,startTime:o,omitCurrent:i,isCollection:_,shallowWildcard:d,url:""},h=wn.getMatch(l);if(!h)throw new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);f.url=h.relativeURL;let T=h.path,S=h.Resource,y=await Ye(f,async()=>{let O=await S.subscribe(f);if(!O)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!O[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let H of O)try{let Y;if(H.type&&H.type!=="put"&&H.type!=="delete"&&H.type!=="message"||s&&!s(H))continue;r?(H.topic=n,Y=this.needsAcknowledge(H)):Y=RT();let A=H.id;Array.isArray(A)&&(A=To(A)),A==null&&(A=""),this.listener(T+"/"+A,H.value,Y,t)}catch(Y){(0,Wc.warn)(Y)}})(),O});return y.topic=n,y.qos=t.qos,this.subscriptions.push(y),y}resume(){}needsAcknowledge(t){return RT()}acknowledge(t){}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);r&&r.end()}async publish(t,r){let{topic:s,retain:n}=t;t.data=r,t.user=this.user;let i=wn.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`);t.url=i.relativeURL;let o=i.Resource;return Ye(t,()=>n?r===void 0?o.delete(t,t):o.put(t,t.data,t):o.publish(t,t.data,t))}setListener(t){this.listener=t}disconnect(){for(let t of this.subscriptions)t.end();this.subscriptions=[]}},gT=class extends Pd{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=RT();return this.awaitingAcks.set(r,{topic:t.topic,timestamp:t.timestamp}),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t);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,Wc.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,cv.getNextMonotonicTime)()),(0,Wc.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),TT.put(this.sessionRecord)),t.qos}}});var NT={};Ze(NT,{start:()=>f7});async function f7({server:e,port:t,webSocket:r,securePort:s,requireAuthentication:n}){let i=e.mqtt={requireAuthentication:n};r&&e.ws((o,c,u)=>{if(o.protocol==="mqtt"){let{onMessage:l,onClose:_}=Ev(o,(d,E)=>{if(o.send(d),E&&o._socket.writableNeedDrain)return new Promise(f=>this._socket.once("drain",f))},c,Promise.resolve(u).then(()=>c?.user),i);o.on("message",l),o.on("close",_),o.on("error",d=>{(0,tn.info)("WebSocket error",d)})}},{subProtocol:"mqtt"}),(t||s)&&e.socket(async o=>{let c;E7&&o.remoteAddress.includes("127.0.0.1")&&(c=await(0,fv.getSuperUser)());let{onMessage:u,onClose:l}=Ev(o,_=>o.write(_),null,c,i);o.on("data",u),o.on("close",l),o.on("error",_=>{(0,tn.info)("Socket error",_)})},{port:t,securePort:s})}function Ev(e,t,r,s,n){dv||(dv=!0,lm(_=>{_.push({metric:"mqtt-connections",connections:AT})})),AT++;let i,o={protocolVersion:4},c=(0,vd.parser)({protocolVersion:5});function u(_){c.parse(_)}a(u,"onMessage");function l(){AT--,i?.disconnect()}return a(l,"onClose"),c.on("packet",async _=>{s?.then&&(s=await s),i?.then&&await i;try{switch(_.cmd){case"connect":if(o.protocolVersion=_.protocolVersion,_.username)try{s=await ht.auth(_.username,_.password.toString()),(0,OT.get)(rn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&_v.notify({username:s.username,status:rn.AUTH_AUDIT_STATUS.SUCCESS,type:rn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,OT.get)(rn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&_v.error({username:s.username,status:rn.AUTH_AUDIT_STATUS.FAILURE,type:rn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),d({cmd:"connack",reasonCode:134,returnCode:134})}if(!s&&n.requireAuthentication)return d({cmd:"connack",reasonCode:134,returnCode:134});try{n.authorizeClient?.(_,s),i=uv({user:s,..._}),i=await i}catch(O){return(0,tn.error)(O),d({cmd:"connack",reasonCode:O.code||128,returnCode:O.code||128})}d({cmd:"connack",sessionPresent:i.sessionWasPresent,reasonCode:0,returnCode:0}),i.setListener((O,H,Y,A)=>{try{let w=O.indexOf("/",1),G=w>0?O.slice(0,w):O;d({cmd:"publish",topic:O,payload:E(H),messageId:Y||Math.floor(Math.random()*1e8),qos:A.qos},G)}catch(w){(0,tn.error)(w),i?.disconnect()}}),i.sessionWasPresent&&await i.resume();break;case"subscribe":let f=[];for(let O of _.subscriptions){let H;try{H=(await i.addSubscription(O,O.qos>=1)).qos||0}catch(Y){(0,tn.error)(Y),H=128}f.push(H)}await i.committed,d({cmd:"suback",granted:f,messageId:_.messageId});break;case"unsubscribe":for(let O of _.unsubscriptions)i.removeSubscription(O);d({cmd:"unsuback",messageId:_.messageId});break;case"pubrel":d({cmd:"pubcomp",messageId:_.messageId,reasonCode:0});return;case"publish":let h=_.qos===2?"pubrec":"puback",T=e.deserialize||(e.deserialize=yo(r?.headers["content-type"])),S=_.payload?.length>0?T(_.payload):void 0,y;try{y=await i.publish(_,S)}catch(O){console.warn(O),_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:128},_.topic)}_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:y===!1?144:0},_.topic);break;case"pubrec":d({cmd:"pubrel",messageId:_.messageId,reasonCode:0});break;case"pubcomp":case"puback":i.acknowledge(_.messageId);break;case"pingreq":d({cmd:"pingresp"});break;case"disconnect":i?.disconnect(),e.close?e.close():e.end();break}}catch(f){console.error(f),d({cmd:"disconnect"})}function d(f,h){let T=(0,vd.generate)(f,o);t(T),ai(T.length,"bytes-sent",h,f.cmd,"mqtt")}a(d,"sendPacket");function E(f){return r?Ks(f,r):JSON.stringify(f)}a(E,"serialize")}),{onMessage:u,onClose:l}}var vd,fv,OT,rn,tn,_v,E7,dv,AT,hv=pe(()=>{vd=require("mqtt-packet");lv();fv=D(Or());go();ro();Us();OT=D(Q()),rn=D(g()),tn=D(F()),_v=(0,tn.loggerWithTag)("auth-event"),E7=!0;a(f7,"start");AT=0;a(Ev,"onSocket")});var bv={};Ze(bv,{loadComponent:()=>Bd,loadComponentDirectories:()=>Nv});function Nv(e,t){t&&(yT=t),e&&(IT=e);let r=[];if((0,ps.existsSync)(bT)){let n=(0,ps.readdirSync)(bT,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Dr.join)(bT,o);r.push(Bd(c,yT,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(Bd(s,yT,s)),Promise.all(r).then(()=>{Ov=!0})}async function Bd(e,t,r,s,n){if(!Sv.has(e)){Sv.set(e,!0),n&&(IT=n);try{let i,o=(0,Dr.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,ps.existsSync)(o)?i=(0,pv.parseDocument)((0,ps.readFileSync)(o,"utf8"),{simpleKeys:!0}).toJSON():i=p7;let c=[];for(let u in i){let l=i[u];if(!l)continue;let _,d=l.package;if(d){let E=e,f;for(;!(0,ps.existsSync)(f=(0,Dr.join)(E,"node_modules",u));)if(E=(0,Dr.dirname)(E),E.length<(0,Av.getHdbBasePath)().length){f=null;break}if(f)_=await Bd(f,t,r,!1);else throw new Error(`Unable to find package ${u}:${d}`)}else _=S7[u];if(_)try{c.push(_);let E=a(S=>(S.origin=r,et(S)),"ensureTable"),f=l.network||(l.port||l.securePort)&&l,h=f?.securePort||f?.https&&f.port,T=!f?.https&&f?.port;if(Qc.isMainThread&&(_=await _.startOnMainThread?.({server:ht,ensureTable:E,port:T,securePort:h,resources:t,...l})||_,s&&f))for(let S of[T,h])try{if(+S&&!mv.includes(S)){mv.push(S);let y=wT.get(CT.CONFIG_PARAMS.HTTP_SESSION_AFFINITY);vP(S,y)}}catch(y){console.error("Error listening on socket",S,y,u)}if(t.isWorker&&(_=await _.start?.({server:ht,ensureTable:E,port:T,securePort:h,resources:t,...l})||_),IT.set(_,!0),_.handleFile&&l.files){if(l.files.includes(".."))throw(0,gv.handleHDBError)("Can not reference parent directories");let S=(0,Dr.join)(e,l.files);for(let y of await(0,Tv.default)(S,{onlyFiles:!1,objectMode:!0})){let{path:O,dirent:H}=y,Y=(0,Dr.relative)(e,O),A=(0,Dr.basename)(e),w=l.path||"/";w=w.startsWith("/")?w:w.startsWith("./")?"/"+A+w.slice(2):w==="."?"/"+A:"/"+A+"/"+w,w+=(w.endsWith("/")?"":"/")+Y;try{if(H.isFile()){let G=await m7(O);Qc.isMainThread&&await _.setupFile?.(G,w,O,t),t.isWorker&&await _.handleFile?.(G,w,O,t)}else Qc.isMainThread&&await _.setupDirectory?.(w,O,t),t.isWorker&&await _.handleDirectory?.(w,O,t)}catch(G){console.error(`Could not load ${H.isFile()?"file":"directory"} ${O} using ${l.module} for application ${e}`,G),t.set(l.path||"/",new zc(G))}}}}catch(E){console.error(`Could not load component ${u} for application ${e}`,E),t.set(l.path||"/",new zc(E),null,!0)}}if(Qc.isMainThread&&!Ov&&(0,Rv.watchDir)(e,async()=>Nv()),i.extensionModule)return await Mu((0,Dr.join)(e,i.extensionModule))}catch(i){console.error(`Could not load application directory ${e}`,i),t.set("",new zc(i))}}}var ps,Dr,Qc,pv,wT,CT,Tv,Rv,gv,Av,h7,m7,bT,IT,Ov,yT,S7,p7,mv,Sv,zc,yv=pe(()=>{ps=require("fs"),Dr=require("path"),Qc=require("worker_threads"),pv=require("yaml"),wT=D(Q()),CT=D(g());Lg();Bg();Hg();GL();bP();CP();Tv=D(require("fast-glob")),Rv=D(rt());$E();Us();gv=D(W());Xr();de();BP();Av=D(Q()),h7=D(xP());B_();av();hv();({readFile:m7}=ps.promises),bT=wT.get(CT.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),IT=new Map;a(Nv,"loadComponentDirectories");S7={REST:yp,graphqlSchema:VE,jsResource:KE,fastifyRoutes:iT,login:QE,static:oT,operationsApi:h7,customFunctions:{},clustering:ST,authentication:Oc,mqtt:NT},p7={REST:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}},mv=[],Sv=new Map;a(Bd,"loadComponent");zc=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 Lv=m((j_e,Dv)=>{"use strict";var Fd=require("fs-extra"),UT=require("path"),Hd=F(),Iv=x(),qd=g(),Uv=Q(),T7=Ar();Dv.exports=R7;async function R7(){let e=g7(),t=Uv.get(qd.CONFIG_PARAMS.ROOTPATH),r=UT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+qd.PACKAGE_ROOT}},n=UT.join(t,"node_modules");await Fd.ensureDir(n);let i,o=!0,c=!1;try{i=await Fd.readJson(r)}catch(u){if(Iv.isEmptyOrZeroLength(e))return;if(u.code!==qd.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!Iv.isEmptyOrZeroLength(e)){for(let{name:u,package:l}of e){let _=await wv(l);s.dependencies[u]=_+l}if(!o){Hd.notify("Installing components"),await Cv(r,s);return}for(let{name:u,package:l}of e){let _=i.dependencies[u],d=await wv(l);if(_===void 0||_!==d+l){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(Hd.notify("Removing component",u),c=!0);c&&(Hd.notify("Updating components."),await Cv(r,s))}a(R7,"installComponents");function g7(){let e=T7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(g7,"getComponentsConfig");async function wv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":UT.extname(e)||await Fd.pathExists(e)?"file:":"github:"}a(wv,"getPkgPrefix");async function Cv(e,t){Hd.trace("npm installing components package.json",t),await Fd.writeFile(e,JSON.stringify(t,null," ")),await $_().installAllRootModules(Uv.get(qd.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}a(Cv,"installPackages")});var LT=m((tde,Pv)=>{var{isMainThread:Mv}=require("worker_threads"),{getTables:A7}=(de(),te(Ne)),{loadComponentDirectories:O7,loadComponent:N7}=(yv(),te(bv)),{resetResources:b7}=(Ac(),te(mD)),y7=Lv(),I7=Ar(),{dirname:w7}=require("path"),{getConnection:C7}=st(),U7=Q(),D7=g(),DT=new Map;async function L7(e=!1){!Mv&&U7.get(D7.CONFIG_PARAMS.CLUSTERING_ENABLED)&&C7(),Mv&&await y7();let t=b7();A7(),t.isWorker=e,await N7(w7(I7.getConfigFilePath()),t,"hdb",!0,DT),await O7(DT,t);let r=[];for(let[s]of DT)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(L7,"loadRootComponents");Pv.exports.loadRootComponents=L7});var rt=m((nde,Pn)=>{"use strict";var{Worker:M7,MessageChannel:P7,parentPort:Ts,isMainThread:HT,threadId:v7,workerData:Jc}=require("worker_threads"),{PACKAGE_ROOT:B7}=g(),{join:Hv,isAbsolute:H7,extname:xd}=require("path"),{server:q7}=(Us(),te(Lu)),{watch:F7,readdir:G7}=require("fs/promises"),{totalmem:vv}=require("os"),qT=g(),yi=F(),sde=g(),{randomBytes:x7}=require("crypto"),k7=1024*1024,Mn=[],Ln=[],V7=50,qv=1e4,$7="restart",Fv="request_thread_info",Gv="resource_report",xv="thread_info",kv="added-port",Y7="ack",MT;Pn.exports={startWorker:PT,restartWorkers:FT,shutdownWorkers:z7,workers:Mn,setMonitorListener:see,onMessageFromWorkers:J7,onMessageByType:X7,broadcast:Z7,broadcastWithAcknowledgement:eee,setChildListenerByType:Q7,getWorkerIndex:$v,getTicketKeys:Yv,setMainIsWorker:K7,restartNumber:Jc?.restartNumber||1};var Vv;function $v(){return Jc?Jc.workerIndex:Vv?0:void 0}a($v,"getWorkerIndex");function K7(e){Vv=e}a(K7,"setMainIsWorker");var Gd;function Yv(){return Gd||(Gd=HT?x7(48):Jc.ticketKeys,Gd)}a(Yv,"getTicketKeys");Object.defineProperty(q7,"workerIndex",{get(){return $v()}});var Kv={[Fv](e,t){tee(t)},[Gv](e,t){ree(t,e)}};function PT(e,t={}){let r=process.constrainedMemory?.()||vv();r=Math.min(r,vv());let s=Math.max(Math.floor(r/k7/(1+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>7,16),64),i=[];for(let c of Ln){let{port1:u,port2:l}=new P7;c.postMessage({type:kv,port:u},[u]),i.push(l)}xd(e)||(e+=".js");let o=new M7(H7(e)?e:Hv(B7,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:i,workerIndex:t.workerIndex,name:t.name,restartNumber:Pn.exports.restartNumber,ticketKeys:Yv()},transferList:i},t));return Vd(o,!0),o.unexpectedRestarts=t.unexpectedRestarts||0,o.startCopy=()=>{PT(e,t)},o.on("error",c=>{console.error("Worker error:",c),yi.error("Worker error:",c)}),o.on("exit",c=>{Mn.splice(Mn.indexOf(o),1),!o.wasShutdown&&t.autoRestart!==!1&&(o.unexpectedRestarts<V7?(t.unexpectedRestarts=o.unexpectedRestarts+1,PT(e,t)):yi.error(`Thread has been restarted ${o.restarts} times and will not be restarted`))}),o.on("message",c=>{Kv[c.type]?.(c,o)}),Mn.push(o),iee(),t.onStarted&&t.onStarted(o),o.name=t.name,o}a(PT,"startWorker");var W7=[qT.THREAD_TYPES.HTTP];async function FT(e=null,t=2,r=!0){if(HT){if(r){let{loadRootComponents:n}=LT();await n()}Pn.exports.restartNumber++,t<1&&(t=t*Mn.length);let s=[];for(let n of Mn.slice(0)){if(e&&n.name!==e||n.wasShutdown)continue;n.postMessage({restartNumber:Pn.exports.restartNumber,type:qT.ITC_EVENT_TYPES.SHUTDOWN}),n.wasShutdown=!0,n.emit("shutdown",{});let i=W7.indexOf(n.name)>-1,o=new Promise(c=>{let u=setTimeout(()=>n.terminate(),qv*2).unref();n.on("exit",()=>{clearTimeout(u),s.splice(s.indexOf(o)),!i&&r&&n.startCopy(),c()})});s.push(o),i&&r&&(n.startCopy(),s.length>=t&&await Promise.race(s))}await Promise.all(s)}else Ts.postMessage({type:$7,workerType:e})}a(FT,"restartWorkers");function Q7(e,t){Kv[e]=t}a(Q7,"setChildListenerByType");function z7(e){return FT(e,1/0,!1)}a(z7,"shutdownWorkers");var Wv=[];function J7(e){Wv.push(e)}a(J7,"onMessageFromWorkers");var vT=new Map;function X7(e,t){let r=vT.get(e);r||vT.set(e,r=[]),r.push(t)}a(X7,"onMessageByType");function Z7(e){for(let t of Ln)try{t.postMessage(e)}catch(r){yi.error("Unable to send message to worker",r)}}a(Z7,"broadcast");var kd=new Map,j7=1;function eee(e){return new Promise(t=>{let r=0;for(let s of Ln)try{let n=j7++,i=a(()=>{kd.delete(n),--r===0&&t(),s!==Ts&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,kd.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of kd)o.port===s&&o()})),s.postMessage(e),r++}catch(n){yi.error("Unable to send message to worker",n)}r===0&&t()})}a(eee,"broadcastWithAcknowledgement");function tee(e){e.postMessage({type:xv,workers:Qv()})}a(tee,"sendThreadInfo");function Qv(){let e=Date.now();return Mn.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(Qv,"getChildWorkerInfo");function ree(e,t){e.resources=t,e.resources.updated=Date.now()}a(ree,"recordResourceReport");var BT;function see(e){BT=e}a(see,"setMonitorListener");var nee=1e3,Bv=!1;function iee(){Bv||(Bv=!0,setInterval(()=>{for(let e of Mn){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}BT&&BT()},nee).unref())}a(iee,"startMonitoring");var oee=1e3;if(Ts){Vd(Ts);for(let e of Jc.addPorts)Vd(e);setInterval(()=>{let e=process.memoryUsage();Ts.postMessage({type:Gv,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},oee).unref(),MT=a(()=>new Promise((e,t)=>{Ts.on("message",r),Ts.postMessage({type:Fv});function r(s){s.type===xv&&(Ts.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else MT=Qv;Pn.exports.getThreadInfo=MT;function Vd(e,t){Ln.push(e),e.on("message",r=>{if(r.type===kv)Vd(r.port);else if(r.type===Y7){let s=kd.get(r.id);s&&s()}else{for(let n of Wv)n(r,e);let s=vT.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){yi.error(i)}}}).on("close",()=>{Ln.splice(Ln.indexOf(e),1)}).on("exit",()=>{Ln.splice(Ln.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(Vd,"addPort");if(HT){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await G7(s,{withFileTypes:!0}))i.isDirectory()&&r(Hv(s,i.name));for await(let{filename:i}of F7(s,{persistent:!1}))(xd(i)===".ts"||xd(i)===".js"||xd(i)===".graphql")&&(t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await FT(),yi.info("Reloaded HarperDB components")},100))},"watch_dir");Pn.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else Ts.on("message",async e=>{let{type:t}=e;t===qT.ITC_EVENT_TYPES.SHUTDOWN&&(Pn.exports.restartNumber=e.restartNumber,Ts.unref(),setTimeout(()=>{yi.warn("Thread did not voluntarily terminate",v7),process.exit(0)},qv).unref())})});function $T(e){let t=e.auditStore=e.openDB(jv.AUDIT_STORE_NAME,cee);t.rootStore=e;let r=[];return t.addDeleteRemovalCallback=function(s,n){return r[s]=n,{remove(){delete r[s]}}},(0,tB.getWorkerIndex)()===0&&e.on("aftercommit",()=>{xT||(xT=setTimeout(()=>{if(xT=null,t.rootStore.status!=="closed")for(let{key:s,value:n}of t.getRange({start:[0,0],end:[Date.now()-zv,0]})){if((n[0]&15)===VT){let i=s[1];r[i]?.(s[2])}t.remove(s)}},zv/10).unref())}),t}function Kd(e,t,r){let s=nB[r.type],n=3;if(t?t.length>80?(s|=$d,n=(0,sn.writeKey)(t,Rs,e?14:6),GT.setUint16(2,n)):(n=(0,sn.writeKey)(t,Rs,e?11:3),Rs[1]=n):Rs[1]=0,e){s|=sB;let i=s&$d?6:3;GT.setFloat64(i,e),t||(n=i+8)}return Rs[0]=s,s&$d?GT.setUint16(4,0):Rs[2]=0,r.value?Buffer.concat([Rs.slice(0,n),r.value]):Rs.subarray(0,n)}function vn(e,t){let r=e[0],s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)),n=r&$d,i=n?6:3,o;r&sB&&(o=s.getFloat64(i),i+=8);let c;n?c=s.getUint16(2):c=e[1];let u=r&kT?t.decoder.decode(e.subarray(c||i)):void 0;return{type:nB[r&7],value:u,lastVersion:o,get user(){return c?(0,sn.readKey)(e,i,c):void 0}}}var sn,Yd,jv,eB,tB,rB,Rs,GT,aee,cee,zv,xT,kT,Jv,VT,Xv,Zv,$d,sB,nB,Xc=pe(()=>{sn=require("ordered-binary"),Yd=D(Q()),jv=D(xe()),eB=D(g()),tB=D(rt()),rB=D(x());(0,Yd.initSync)();Rs=Buffer.alloc(1024),GT=new DataView(Rs.buffer,Rs.byteOffset,1024),aee={writeKey(e,t,r){if(Array.isArray(e)){let s=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength));return s.setFloat64(r,e[0]),s.setUint32(r+8,e[1]),(0,sn.writeKey)(e[2],t,r+12)}else return(0,sn.writeKey)(e,t,r)},readKey(e,t,r){if(e[t]>40){let s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength));return[s.getFloat64(t),s.getUint32(t+8),(0,sn.readKey)(e,t+12,r)]}else return(0,sn.readKey)(e,t,r)}},cee={encoding:"binary",keyEncoder:aee},zv=(0,rB.convertToMS)((0,Yd.get)(eB.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,xT=null;a($T,"openAuditStore");kT=16,Jv=1,VT=2,Xv=3,Zv=4,$d=128,sB=64,nB={put:Jv|kT,[Jv]:"put",delete:VT,[VT]:"delete",message:Xv|kT,[Xv]:"message",invalidate:Zv,[Zv]:"invalidate"};a(Kd,"createAuditEntry");a(vn,"readAuditEntry")});var YT,Ii,uee,Zc,Wd,iB=pe(()=>{YT=D(vt());Xc();Ii=Symbol("completion"),uee=100,Zc=class{static{a(this,"DatabaseTransaction")}writes=[];hasWrittenTime;username;lmdbDb;auditStore;readTxn;constructor(t,r,s){this.lmdbDb=t,this.username=r?.username,this.auditStore=s}getReadTxn(){return this.readTxn||(this.readTxn=this.lmdbDb.useReadTransaction())}resetReadSnapshot(){this.readTxn&&(this.readTxn.done(),this.readTxn=null)}addWrite(t){this.writes.push(t)}validate(){for(let t of this.writes||[])t.validate?.()}commit(t=(0,YT.getNextMonotonicTime)(),r=!0,s=0){this.resetReadSnapshot();let n,i=[],o=0,c;this.hasWrittenTime=!1;let u=a(_=>{let d=_.commit(t,s);if(d&&(d[Ii]&&(i||(i=[]),i.push(d[Ii])),c=_.store,this.auditStore)){d.user=this.username,d.lastVersion=_.lastVersion,d.newTxnTime&&!this.hasWrittenTime&&(t=d.newTxnTime),this.hasWrittenTime=!0;let E=[t,_.store.tableId,_.key];_.invalidated&&(E.invalidated=!0),this.auditStore.put(E,Kd(_.lastVersion,this.username,d))}},"doWrite"),l=a(()=>{let _=this.writes[o++];if(_)if(_.key){let d=_.store.getEntry(_.key),E=s===0&&_.lastVersion!==void 0?_.lastVersion:_.lastVersion=d?.version??null,f=_.store.ifVersion(_.key,E,l);n=n||f}else l();else for(let d of this.writes)u(d)},"nextCondition");return this.writes.length<uee>>s?l():(s=1,n=this.writes[0].store.transaction(()=>{for(let _ of this.writes)u(_);return!0})),n?.then(_=>_?(c&&i.push(c.flushed),Promise.all(i).then(()=>(this.writes=[],{txnTime:t}))):this.commit(t,r,s+1))}abort(){this.resetReadSnapshot(),this.writes=[]}},Wd=class extends Zc{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit(this.timestamp)}get timestamp(){return this._timestamp||(this._timestamp=(0,YT.getNextMonotonicTime)())}getReadTxn(){}}});function uB(e,t,r,s,n){let i=e.primaryStore.env.path,o=e.primaryStore.tableId;qo||((0,wi.onMessageByType)(aB,d=>{let E=d.auditIds;WT(d.path,E,d.txnId)}),(0,wi.onMessageByType)(cB,d=>{(0,gs.trace)("confirming to proceed with txn",d.txnId)}),qo=Object.create(null));let c=qo[i]||(qo[i]=[]);c.auditStore=e.auditStore;let u=c[o];u||(u=c[o]=new Map,u.envs=c,u.tableId=o,u.store=e.primaryStore),t=To(t);let l=new KT(r);l.startTime=s,n&&(l.includeDescendants=n);let _=u.get(t);return _?_.push(l):(u.set(t,_=[l]),_.tables=u,_.key=t),l.subscriptions=_,l}function WT(e,t,r,s){if(!qo)return;let n=qo[e];if(n){if(Ho&&Ho+1!==r){(0,gs.trace)("Waiting to ensure latest txn id",Ho,"proceeds",r,s);let i=(async()=>{for(let[o,c]of Qd)o<r&&((0,gs.trace)("Txn",r,"waiting for txn",o),await c);if(Ho+1!==r){await(0,wi.broadcastWithAcknowledgement)({type:cB,txnId:r});for(let[o,c]of Qd)o<r&&((0,gs.trace)("Txn",r,"waiting for txn",o),await c)}Qd.delete(r),(0,gs.trace)("Proceeding with txn id",r),Ho=r-1,WT(e,t,r,s)})();return Qd.set(r,i),i}(0,gs.trace)("Notifying with txn id",r,s),Ho=r;try{n.auditStore.resetReadTxn()}catch(i){throw i.message+=" in "+e,i}e:for(let i of t){let[o,c,u]=i,l=n[c];if(!l)continue;(0,oB.writeKey)(i,_ee,0);let _=i[3];_&&(i.length=3);let d,E=To(u),f;do{let h=l.get(E);if(h){for(let S of h)if(!(f&&!S.includeDescendants)){if(S.startTime>=o){(0,gs.info)("omitting",u,S.startTime,o);continue}try{if(S.crossThreads===!1&&!s)continue;if(d===void 0){let y=n.auditStore.get(i);if(!y||(d=vn(y,l.store),d.type!=="message"&&l.store.getEntry(i[2])?.version!==i[0])||_&&d.type!=="invalidate")continue e}S.listener(u,d,o)}catch(y){console.error(y),(0,gs.info)(y)}}}if(E==null)break;let T=E.lastIndexOf?.("/",E.length-2);T>-1?E=E.slice(0,T+1):E=null,f=!0}while(!0)}}}function lB(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",({next:i,last:o,txnId:c})=>{let u,l=[];if(t)do{if(i.flag&lee)continue;let _;i.meta&&i.meta.store===t&&(_=i.meta.key)&&(typeof _[2]=="symbol"&&(_[2]=null),_.invalidated&&(_[3]=!0),l.push(_))}while(i!=o&&(i=i.next));l.length!==0&&((0,wi.broadcast)({type:aB,path:n,auditIds:l,txnId:c,start:u}),WT(n,l,c,!0))})}}var gs,wi,oB,aB,cB,lee,qo,_ee,KT,Ho,Qd,_B=pe(()=>{gs=D(F()),wi=D(rt()),oB=require("ordered-binary");aa();Ac();Xc();aB="transaction",cB="transaction-await",lee=67108864,_ee=Buffer.alloc(4096);a(uB,"addSubscription");KT=class extends Jr{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t}end(){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]}}}toJSON(){return{name:"subscription"}}},Qd=new Map;a(WT,"notifyFromTransactionData");a(lB,"listenToCommits")});var kp={};Ze(kp,{coerceType:()=>zd,makeTable:()=>Xd,setServerUtilities:()=>mee});function Xd(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:l,dbisDB:_}=e,{expirationMS:d,audit:E,trackDeletes:f}=e,{attributes:h}=e;h||(h=[]),lB(i,u);let T=0,S,y,O={},H,Y,A,w;for(let z of h)(z.assignCreatedTime||z.name==="__createdtime__")&&(H=z),(z.assignUpdatedTime||z.name==="__updatedtime__")&&(Y=z),z.expiresAt&&(A=z),z.isPrimaryKey&&(O=z);let G;E&&ER();class k extends ft{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=h;static expirationTimer;static createdTimeProperty=H;static updatedTimeProperty=Y;static dbisDB=_;static schemaDefined=l;static sourcedFrom(p,N){if(N&&(this.sourceOptions=N,N.expiration&&this.setTTLExpiration(N.expiration)),this.Source)if(this.Source.mergeSource)this.Source=this.Source.mergeSource(p,this.sourceOptions);else if(p.mergeSource)this.Source=p.mergeSource(this.Source,this.sourceOptions);else throw new Error("Can not assign multiple sources to a table with no source providing a (static) mergeSource method");else this.Source=p;return(async()=>{let L=!1,b=a(async C=>{let v=C.value,U=C.table?Pe[c][C.table]:k;if(c===Qr.SYSTEM_SCHEMA_NAME&&(C.table===Qr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||C.table===Qr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!0),C.id===void 0&&(C.id=v[U.primaryKey],C.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(C));let M=await U.getResource(C.id,C,jc);switch(C.type){case"put":return M._writeUpdate(v,jc);case"delete":return M._writeDelete(jc);case"publish":return M._writePublish(v,jc);case"invalidate":return M.invalidate(jc);default:Di.error("Unknown operation",C.type,C.id)}},"writeUpdate");try{let C=p.subscribe&&(!p.subscribe.reliesOnPrototype||p.prototype.subscribe);C&&f==null&&(f=!0);let v=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Ui.getWorkerIndex)()):(0,Ui.getWorkerIndex)()===0,U=C&&v&&await p.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(U)for await(let M of U)try{if(!(M.type==="transaction"?M.writes[0]:M)){console.error("Bad subscription event");continue}let J=Ye(M,()=>{if(M.type==="transaction"){let Z=[];for(let K of M.writes){K[Oe]=M;try{Z.push(b(K))}catch(re){throw re.message+=" writing "+JSON.stringify(K)+" of event "+JSON.stringify(M),re}}return Promise.all(Z)}else if(M.type==="define_schema"){let Z=this.attributes.slice(0),K;for(let re of M.attributes)Z.find(De=>De.name===re.name)||(Z.push(re),K=!0);K&&(et({table:n,database:c,attributes:Z,origin:"cluster"}),ru.signalSchemaChange(new su.SchemaEventMsg(process.pid,Qr.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return b(M)});M.onCommit&&(J?.then&&L&&ru.signalUserChange(new su.UserEventMsg(process.pid)),J?.then?J.then(M.onCommit):M.onCommit())}catch(V){console.error("error in subscription handler",V)}}catch(C){console.error(C)}})(),this}static getResource(p,N,L){let b=super.getResource(p,N,L);if(p!=null)try{if(b.hasOwnProperty(ce))return b;let C=b._txnForRequest();if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let v,U,V={transaction:C?.getReadTxn()},J;return ut(p,N,V,(Z,K)=>{K?U(K):(b[ce]=Z?.value,b[Zt]=Z?.version,J=!0,v?.(b))}),J?b:new Promise((Z,K)=>{v=Z,U=K})}catch(C){throw C.message.includes("Unable to serialize object")&&(C.message+=": "+JSON.stringify(p)),C}return b}static setTTLExpiration(p){(0,Ui.getWorkerIndex)()===0&&(d=p*1e3,this.expirationTimer&&clearInterval(this.expirationTimer),this.expirationTimer=setInterval(()=>{if(this.primaryStore.rootStore.status!=="open")return clearInterval(this.expirationTimer);for(let{key:N,value:L,version:b}of this.primaryStore.getRange({start:!1,versions:!0}))b<Date.now()-d&&b>0&&L?.__invalidated__==null&&k.evict(N,L,b)},d).unref())}static enableAuditing(){E=!0,ER(),k.audit=!0}static coerceId(p){return p===""?null:zd(p,O)}static async dropTable(){if(delete Pe[c][n],c===o){for(let p in r)_.remove(k.tableName+"/"+p),r[p].drop();_.remove(k.tableName+"/"),i.drop(),await _.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));ru.signalSchemaChange(new su.SchemaEventMsg(process.pid,Qr.OPERATIONS_ENUM.DROP_TABLE,c,n))}static Source;static get(p,N){return p&&typeof p=="object"&&!Array.isArray(p)&&p.url===""?{recordCount:this.getRecordCount(),records:"./",name:n,database:c,attributes:h}:super.get(p,N)}get(p){if(typeof p=="string")return this.getProperty(p);if(this[Cs])return this.search(p);if(p?.property)return this.getProperty(p.property);if(this.doesExist()||this[Oe]?.hasOwnProperty("returnNonexistent")&&this[Oe].returnNonexistent)return this}static allowRead(p,N){if(!p)return!1;let L=p.role.permission;if(L.super_user)return!0;if(L[n]?.read){let b=L[n].attribute_permissions;if(b){N||(N={});let C=N.select;if(C){let v=QT(b,"read");N.select=C.filter(U=>v[U])}else N.select=b.filter(v=>v.read).map(v=>v.attribute_name);return N}else return!0}}allowUpdate(p,N,L){if(!p)return!1;let b=p.role.permission;if(b.super_user)return!0;if(b[n]?.update){let C=b[n].attribute_permissions;if(C){let v=QT(C,"update");for(let U in N)if(!v[U])return!1;if(L)for(let U of C){let M=U.attribute_name;!U.update&&!(M in N)&&(N[M]=this.getProperty(M))}}else return!0}}allowCreate(p,N){return this.allowUpdate(p,{})}static allowCreate(p,N){if(!p)return!1;let L=p.role.permission;if(L.super_user)return!0;if(L[n]?.insert){let b=L[n].attribute_permissions;if(b){let C=QT(b,"insert");for(let v in N)if(!C[v])return!1}else return!0}}static allowDelete(p){if(!p)return!1;let N=p.role.permission;if(N.super_user||N[n]?.delete)return!0}update(p,N){if(!this._txnForRequest())throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let b;if(typeof p=="object"&&p){if(N)for(let C in this[ce])p[C]===void 0&&(p[C]=void 0);b=this[Et],b&&(p=Object.assign(b,p)),this[Et]=b=p}return!this[ce]&&t&&!(b||(b=this[Et]))?.[t]&&(b||(b=this[Et]=Object.create(null)),b[t]=this[ie]),this._writeUpdate(this),this}invalidate(p){this._txnForRequest().addWrite({key:this[ie],store:i,invalidated:!0,lastVersion:this[Zt],nodeName:this[Oe]?.nodeName,commit:(L,b)=>{if(b)return;let C={__invalidated__:L};for(let V in r)C[V]=this.getProperty(V);let v=k.Source,U,M=this[ie];return p?.isNotification||v?.invalidate&&(!v.invalidate.reliesOnPrototype||v.prototype.invalidate)&&(U=v.invalidate(M,this)),i.put(this[ie],C,L),{type:E&&"invalidate",[Ii]:U}}})}static evict(p,N,L){let b=this.Source;if(b?.get&&(!b.get.reliesOnPrototype||b.prototype.get)){let C;if(!N){let v=i.getEntry(p);if(!v)return;N=v.value,L=v.version}if(N)for(let v in r)C||(C={__invalidated__:0}),C[v]=N[v];return C?i.put(p,C,L,L):i.remove(p,L)}else return i.remove(p,L)}lock(){throw new Error("Not yet implemented")}static operation(p,N){return p.table||=n,p.schema||=c,TB.operation(p,N)}async put(p){this.update(p,!0)}_writeUpdate(p,N){let L=this._txnForRequest();if(this[ie]===void 0)throw new Error("Can not save record without an id");let b=this[ce],C,v,U=this[ie];b||(this[ce]={}),L.addWrite({key:U,store:i,lastVersion:this[Zt],nodeName:this[Oe]?.nodeName,validate:()=>{this.validate(p)},commit:(M,V)=>{let J;if(V){if(C)return;let K=i.getEntry(U);b=K?.value;let re=this[Oe];re&&K?.version>(re.lastModified||0)&&(re.lastModified=K.version)}if(!v){if(v=!0,N?.isNotification)p=ua(p);else{if(p[fB]&&(C=!Nu(p),C))return;t&&p[t]!==U&&(p[t]=U),Y&&(p[Y.name]=Y.type==="Date"?new Date(M):Y.type==="String"?new Date(M).toISOString():M),H&&(b?p[H.name]=b[H.name]:p[H.name]=H.type==="Date"?new Date(M):H.type==="String"?new Date(M).toISOString():M),p=ua(p);let K=k.Source;K?.put&&(!K.put.reliesOnPrototype||K.prototype.put)&&(J=K.put(U,p,this))}if(p[ce])throw new Error("Can not assign a record with a record property");this[ce]=p}if(Di.trace("Checking timestamp for put",U,this[Zt]>M,this[Zt],M),this[Zt]>M)return E&&{type:"put",value:i.encoder.encode(p)};let Z=i.encoder.encode(p);return i.put(this[ie],(0,Fo.asBinary)(Z),M),ge(this[ie],b,p),b===null&&!V&&Gn(-1),{type:E&&"put",value:Z,[Ii]:J}}})}async delete(p){return typeof p=="string"?this.deleteProperty(p):this[ce]?this._writeDelete(p):!1}_writeDelete(p){let N=this._txnForRequest(),L,b=this[ie],C;return N.addWrite({key:b,store:i,lastVersion:this[Zt],nodeName:this[Oe]?.nodeName,commit:(v,U)=>{let M=this[ce];if(U){let V=i.getEntry(b);M=V?.value;let J=this[Oe];J&&V?.version>(J.lastModified||0)&&(J.lastModified=V.version)}if(!L&&(L=!0,!p?.isNotification)){let V=k.Source;V?.delete&&(!V.delete.reliesOnPrototype||V.prototype.delete)&&(C=V.delete(b,this))}if(!(this[Zt]>v))return ge(this[ie],M),Di.trace("Write delete entry",E||f,v),E||f?(i.put(this[ie],null,v),E||dR(),U||Gn(1)):i.remove(this[ie]),{type:E&&"delete",[Ii]:C}}}),!0}search(p){let N=this._txnForRequest();if(!p)throw new Error("No query provided");let L=p.reverse===!0,b=p.conditions;b?b.length===void 0&&(b=Array.from(b)):b=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this[ie]&&(b=[{attribute:null,comparator:"prefix",value:this[ie]}].concat(b));for(let K of b){let re=K[0]??K.attribute,De=re==null?O:h.find(on=>on.name==re);if(De)De.type&&(K[1]===void 0?K.value=C(K.value,De):K[1]=C(K[1],De));else if(re!=null)throw(0,Ci.handleHDBError)(new Error,`${re} is not a defined attribute`,404)}function C(K,re){return Array.isArray(K)?K.map(De=>zd(De,re)):zd(K,re)}a(C,"coerceTypedValues"),b.length>1&&(b=(0,SB.sortBy)(b,K=>{if(K.estimated_count===void 0){let re=K.comparator||K.search_type;if(re===eu.SEARCH_TYPES.EQUALS){let De=K[0]??K.attribute;if(De==null||De===t)K.estimated_count=1;else{let on=r[De];K.estimated_count=on?on.getValuesCount(K[1]??K.value):1/0}}else re===eu.SEARCH_TYPES.CONTAINS||re===eu.SEARCH_TYPES.ENDS_WITH||re==="ne"?K.estimated_count=1/0:re===eu.SEARCH_TYPES.STARTS_WITH||re==="prefix"?K.estimated_count=Eee:K.estimated_count=dee}return K.estimated_count}));let v=N.getReadTxn();v.use();let U=p.select,M=b[0],V;if(!M)V=i.getRange(L?{end:!1,reverse:!0,transaction:v,lazy:U?.length<4}:{start:!1,transaction:v,lazy:U?.length<4}).map(({value:K})=>K?new Promise(re=>setImmediate(()=>re(K))):Fo.SKIP);else{let K=BE(M,v,L,k,p.allowFullScan);if(!p.operator||p.operator.toLowerCase()==="and"){let re=b.slice(1).map(HE);V=Z(K,re)}else{for(let De=1;De<b.length;De++){let on=b[De],EE=BE(on,v,L,k,p.allowFullScan);K=K.concat(EE)}let re=new Set;K=K.filter(De=>re.has(De)?!1:(re.add(De),!0)),V=Z(K)}}(p.offset||p.limit!==void 0)&&(V=V.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0)),V.onDone=()=>{v.done()};let J=this[Oe];function Z(K,re){let De=re?.length,on={transaction:v,lazy:De>0||U?.length<4,alwaysPrefetch:!0};return K.map(EE=>new Promise(fE=>ut(EE,J,on,WB=>{let hE=WB?.value;if(!hE)return fE(Fo.SKIP);for(let mE=0;mE<De;mE++)if(!re[mE](hE))return fE(Fo.SKIP);fE(hE)})))}return a(Z,"idsToRecords"),V}async subscribe(p){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||et({table:n,database:c,schemaDefined:l,attributes:h,audit:!0});let N=uB(k,this[ie]??null,function(v,U,M){try{this.send({id:v,timestamp:M,...U})}catch(V){console.error(V)}},p.startTime,this[Cs]),L=this[ie],b=p.previousCount;b>1e3&&(b=1e3);let C=p.startTime;if(this[Cs]){if(C){if(b)throw new Ci.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:v,value:U}of u.getRange({start:[C,Number.MAX_SAFE_INTEGER]})){let[M,V,J]=v;if(v.length>3&&(J=v.slice(2)),V!==s)continue;let Z=vn(U,i);(L==null||mB(L,J))&&N.send({id:J,timestamp:M,...Z}),N.startTime=M}}else if(b){let v=[];for(let{key:U,value:M}of u.getRange({start:"z",end:!1,reverse:!0}))try{let[V,J,Z]=U;if(U.length>3&&(Z=U.slice(2)),J!==s)continue;if(L==null||mB(L,Z)){let K=vn(M,i);if(v.push({id:Z,timestamp:V,...K}),--b<=0)break}}catch(V){Di.error("Error getting history entry",U,V)}for(let U=v.length;U>0;)N.send(v[--U]);v[0]&&(N.startTime=v[0].timestamp)}else if(!p.omitCurrent)for(let{key:v,value:U,version:M}of i.getRange({start:L??!1,end:L==null?void 0:[L,pB.MAXIMUM_KEY],versions:!0}))U&&N.send({id:v,timestamp:M,value:U})}else{b&&!C&&(C=0);let v=this[Zt];if(C<v){let U=[],M=v;do{let V=[M,s,L],J=u.get(V);if(J){p.omitCurrent=!0;let Z=vn(J,i);U.push({id:L,timestamp:M,...Z}),M=Z.lastVersion}else break;b&&b--}while(M>C&&b!==0);for(let V=U.length;V>0;)N.send(U[--V]);N.startTime=v}!p.omitCurrent&&this.doesExist()&&N.send({id:L,timestamp:this[Zt],value:this})}return p.listener&&N.on("data",p.listener),N}doesExist(){return!!this[ce]}async publish(p,N){this._writePublish(p,N)}_writePublish(p,N){let L=this._txnForRequest(),b=this[ie]||null,C,v;L.addWrite({store:i,key:b,lastVersion:this[Zt],nodeName:this[Oe]?.nodeName,validate:()=>{this.validate(p)},commit:(U,M)=>{if(this.validate(p),!v&&(v=!0,!N?.isNotification)){let Z=k.Source;Z?.publish&&(!Z.publish.reliesOnPrototype||Z.prototype.publish)&&(C=Z.publish(b,p,this))}let V=M>0?i.get(b):this[ce];V===void 0&&!M&&(E||f)&&(E||dR(),Gn(1));let J={type:"message",value:i.encoder.encode(p),[Ii]:C};return!L.hasWrittenTime&&this[Zt]>U&&(U=J.newTxnTime=this[Zt]+.001),i.put(b,V??null,U),J}})}_txnForRequest(){let p=this[Oe],N=p?.transaction;if(N){let L;return(L=N?.find(b=>b.lmdbDb?.path===i.path))||N.push(L=new Zc(i,p.user,u)),L}else return new Wd(i,p.user,u)}validate(p){let N;for(let L=0,b=h.length;L<b;L++){let C=h[L];if(C.type){let v=p[C.name];if(v!=null)switch(C.type){case"Int":case"Float":(typeof v!="number"||C.type==="Int"&&v!==Math.floor(v))&&(N||(N=[])).push(`Property ${C.name} must be an ${C.type==="Int"?"integer":"number"}`);break;case"ID":typeof v=="string"||v?.length>0&&v.every?.(U=>typeof U=="string")||(N||(N=[])).push(`Property ${C.name} must be a string, number, or an array (of strings and numbers)`);break;case"String":typeof v!="string"&&(N||(N=[])).push(`Property ${C.name} must be a string`)}}C.required&&p[C.name]==null&&(N||(N=[])).push(`Property ${C.name} is required`)}if(N)throw new Ci.ClientError(N.join(". "))}getUpdatedTime(){return this[Zt]}static async addAttributes(p){let N=h.slice(0);for(let L of p){if(!L.name)throw new Ci.ClientError("Attribute name is required");if(L.name.match(/[`/]/))throw new Ci.ClientError("Attribute names cannot include backticks or forward slashes");N.push(L)}return et({table:n,database:c,schemaDefined:l,attributes:N}),k.indexingOperation}static async removeAttributes(p){let N=h.filter(L=>!p.includes(L.name));return et({table:n,database:c,schemaDefined:l,attributes:N}),k.indexingOperation}static getRecordCount(){let p=0;for(let{key:N,value:L}of i.getRange({end:!1}))p++,N[0]?.description==="deletions"&&(p+=L||0);return i.getStats().entryCount-p}static updatedAttributes(){yu(this,this)}static async deleteHistory(p=0){let N;for(let{key:L,value:b}of u.getRange({start:[0,0],end:[p,0]})){await new Promise(M=>setImmediate(M));let[C,v,U]=L;L.length>3&&(U=L.slice(2)),v===s&&(N=i.remove(U))}await N}static async*getHistory(p=0,N=1/0){for(let{key:L,value:b}of u.getRange({start:[p,0],end:[N,0]})){await new Promise(V=>setImmediate(V));let[C,v,U]=L;if(L.length>3&&(U=L.slice(2)),v!==s)continue;let M=vn(b,i);M.id=U,M.timestamp=C,yield M}}static async getHistoryOfRecord(p){let N=[],L=i.getEntry(p);if(!L)return N;let b=L.version,C=0;do{await new Promise(M=>setImmediate(M));let v=[b,s,p],U=u.get(v);if(U){let M=vn(U,i);M.timestamp=b,N.push(M),b=M.lastVersion}else break}while(C<1e3);return N.reverse()}static cleanup(){G?.remove()}}k.updatedAttributes();let X=k.prototype;return X[fB]=!0,d&&k.setTTLExpiration(d/1e3),A&&KB(),k;function ge(z,p,N){let L;for(let b in r){let C=r[b],v=C.isIndexing,U=N?.[b],M=p?.[b];if(U===M&&!v)continue;L=!0;let V=(0,tu.getIndexedValues)(M);if(V){dB&&C.prefetch(V.map(J=>({key:J,value:z})),hB);for(let J=0,Z=V.length;J<Z;J++)C.remove(V[J],z)}if(V=(0,tu.getIndexedValues)(U),V){dB&&C.prefetch(V.map(J=>({key:J,value:z})),hB);for(let J=0,Z=V.length;J<Z;J++)C.put(V[J],z)}}return L}a(ge,"updateIndices");function ut(z,p,N,L){let b=a(()=>{let C=N.transaction;if(C?.isDone)throw new Error("Invalid read transaction");let v;C&&!C.hasRunLoadRecord&&(v=!0,C.hasRunLoadRecord=!0);let U;try{U=i.getEntry(z,N)}catch(Z){throw Z.message+=". The read txn is "+JSON.stringify(C)+" first loadRecord: "+v,console.error(Z),console.error("reader list",i.readerList()),console.error("reader check",i.readerCheck()),console.error("reader list",i.readerList()),Z}let M,V,J;if(U?(p&&U?.version>(p.lastModified||0)&&(p.lastModified=U.version),V=U.version,M=U.value,(V<0||!M||typeof M.__invalidated__=="number"||d&&V<Date.now()-d)&&(J=!0)):J=!0,J&&!N?.allowInvalidated){let Z=k.Source;if(Z&&Z.get&&(!Z.get.reliesOnPrototype||Z.prototype.get))return Ko(z,M,V,p).then(re=>{if(re?.value?.[ce])throw new Error("Can not assign a record with a record property");L(re)},re=>{L(null,re)})}if(U?.value?.[ce])throw new Error("Can not assign a record with a record property");L(U)},"whenPrefetched");if(!N.alwaysPrefetch&&(z==null||i.cache?.get(z)))return b();i.prefetch([z],b)}a(ut,"loadRecord");function Pi(){w=new Set,(0,Ui.onMessageByType)("transaction",z),i.on("aftercommit",z);function z(){for(let p of w)p()}a(z,"onCommit")}a(Pi,"setupCommitListeners");async function Ko(z,p=null,N,L){if(N<0){let U;return w||Pi(),await new Promise(M=>{let V,J=a(()=>{if(U=i.getEntry(z),!U||U.version>0){if(clearTimeout(V),w.delete(J),typeof U?.value?.__invalidated__=="number")return M(Ko(z,U.value,U.version,L));M(U)}},"listener");w.add(J),V=setTimeout(()=>{w.delete(J),M(Ko(z,U?.value,void 0,L))},1e4).unref()})}let b=p?.__invalidated__,C=-(N||1);i.put(z,p,C,N);let v={transaction:L?.transaction};try{let U=await k.Source.get(z,v),M=v.lastModified||N;(!M||d&&M<Date.now()-d)&&(M=(0,tu.getNextMonotonicTime)());let J=ge(z,p,U)&&N||b>0;return U?(t&&(U[t]=z),typeof U.toJSON=="function"&&(U=U.toJSON()),i.put(z,U,M,C)):i.remove(z,C),J&&E&&u.put([M,s,z],Kd(b,null,U?{type:"put",value:i.encoder.encode(U)}:{type:"delete"})),{version:M,value:U}}catch(U){throw i.put(z,p,N,C),U}}a(Ko,"getFromSource");function Gn(z){T||(T=i.get([EB,zT.threadId])||0),T+=z,y||(y=setTimeout(()=>{y=null,i.rootStore.status==="open"&&i.put([EB,zT.threadId],T)},50))}a(Gn,"recordDeletion");function dR(){S||(S=setTimeout(()=>{if(S=null,i.rootStore.status==="open"){for(let{key:z,value:p}of i.getRange({start:!0}))if(p===null){let N=i.getEntry(z);N?.value===null&&i.remove(z,N.version),Gn(-1)}}},k.getRecordCount()*100+hee).unref())}a(dR,"enqueueDeletionCleanup");function ER(){G=u?.addDeleteRemovalCallback(s,z=>{let p=i.getEntry(z);p?.value===null&&i.remove(z,p.version),Gn(-1)})}a(ER,"addDeleteRemoval");function KB(){(0,Ui.getWorkerIndex)()===0&&setInterval(async()=>{try{let z=A.name,p=r[z];if(!p)throw new Error(`expiresAt attribute ${A} must be indexed`);for(let{value:N}of p.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let L=i.getEntry(N);L.value?.[z]<Date.now()&&k.evict(N,L.value,L.version),await new Promise(b=>setImmediate(b))}}catch(z){Di.error("Error in evicting old records",z)}},fee).unref()}a(KB,"runRecordExpirationEviction")}function QT(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 hB(){}function mee(e){TB=e}function zd(e,t){let r=t?.type;return e===null?e:r==="Int"?parseInt(e):r==="Float"?parseFloat(e):r==="Date"?(typeof e!="number"&&!See.test(e)&&(e+="Z"),new Date(e)):r?e:(0,Jd.autoCast)(e)}function mB(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}var Qr,Fo,tu,SB,zT,eu,nu,Ci,ru,su,Di,pB,Ui,Jd,TB,dee,Eee,fee,dB,EB,Zt,fB,yde,jc,hee,See,fd=pe(()=>{Qr=D(g()),Fo=require("lmdb"),tu=D(vt()),SB=require("lodash"),zT=require("worker_threads");Xr();iB();eu=D(xe()),nu=D(Q());_B();Ci=D(W()),ru=D(Fs()),su=D(qr());de();Uu();Di=D(F());wu();Vn();pB=require("ordered-binary"),Ui=D(rt());Xc();Jd=D(x()),dee=1e8,Eee=1e7,fee=6e4;nu.initSync();dB=nu.get(Qr.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),EB=Symbol.for("deletions"),Zt=Symbol.for("version"),fB=Symbol.for("incremental-update"),yde=Symbol("source-resource"),jc={isNotification:!0,allowInvalidated:!0},hee=(0,Jd.convertToMS)(nu.get(Qr.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(Xd,"makeTable");a(QT,"attributesAsObject");a(hB,"noop");a(mee,"setServerUtilities");See=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(zd,"coerceType");a(mB,"isDescendantId")});var Ne={};Ze(Ne,{database:()=>Ga,databases:()=>Pe,dropDatabase:()=>Jh,dropTableMeta:()=>Oee,getDatabases:()=>Gr,getTables:()=>pee,onUpdatedTable:()=>pT,readMetaDb:()=>iu,resetDatabases:()=>Tee,table:()=>et,tables:()=>sr});function pee(){return tE||Gr(),sr||{}}function Gr(){if(tE)return Pe;tE=!0,Vo=new Map;let e=(0,yt.getHdbBasePath)()&&(0,Me.join)((0,yt.getHdbBasePath)(),jt.DATABASES_DIR_NAME),t=(0,yt.get)(jt.CONFIG_PARAMS.SCHEMAS)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,yt.get)(jt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,fr.existsSync)(e)?e:(0,Me.join)((0,yt.getHdbBasePath)(),jt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,fr.existsSync)(e))for(let r of(0,fr.readdirSync)(e,{withFileTypes:!0})){let s=(0,Me.basename)(r.name,".mdb");r.isFile()&&(0,Me.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&iu((0,Me.join)(e,r.name),null,s)}if((0,fr.existsSync)((0,ko.getBaseSchemaPath)())){for(let r of(0,fr.readdirSync)((0,ko.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,Me.join)((0,ko.getBaseSchemaPath)(),r.name),n=(0,Me.join)((0,ko.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,fr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,Me.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Me.join)(n,i.name);iu((0,Me.join)(s,i.name),(0,Me.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,fr.existsSync)(n))for(let o of(0,fr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,Me.extname)(o.name).toLowerCase()===".mdb"&&iu((0,Me.join)(n,o.name),(0,Me.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,Me.join)(c.path,(0,Me.basename)(o+".mdb"));(0,fr.existsSync)(u)&&iu(u,o,r,null,!0)}}for(let r in Pe){let s=Vo.get(r);if(s){let n=Pe[r];r.includes("delete")&&Le.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Le.trace(`delete table class ${i}`),delete n[i])}else if(delete Pe[r],r==="data"){for(let n in sr)delete sr[n];delete sr[rE]}}return Vo=null,Pe}}function Tee(){tE=!1;for(let[,e]of Bn)e.needsDeletion=!0;Gr();for(let[e,t]of Bn)t.needsDeletion&&!e.endsWith("system.mdb")&&(console.log("closing database",e),t.close().then(()=>console.log("closed database",e)),Bn.delete(e));return Pe}function iu(e,t,r=ZT,s,n){let i=new JT.default(e,!1);e.includes("delete")&&Le.trace(`reading meta data from ${e}`);try{let o=Bn.get(e);o?o.needsDeletion=!1:(o=(0,Zd.open)(i),Bn.set(e,o));let c=new Li.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(Go.INTERNAL_DBIS_NAME,c)),l=o.auditStore;l||(s?(0,fr.existsSync)(s)&&(i.path=s,l=(0,Zd.open)(i),l.isLegacy=!0):l=$T(o));let _=OB(r),d=_[rE],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[T,S]=f.toString().split("/");e.includes("delete")&&Le.trace(`read key ${f}`),S===""?S=h.name:S||(S=T,T=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(T);let y=E.get(T);y||E.set(T,y={attributes:[]}),(S==null||h.is_hash_attribute)&&(y.primary=h),S!=null&&y.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:T,primary:S}=h;if(!S){for(let X of T)if(X.is_hash_attribute||X.isPrimaryKey){S=X;break}if(!S)throw new Error(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(T)}`)}let y=_[f],O={},H=[],Y,A,w=typeof S.audit=="boolean"?S.audit:(0,yt.get)(jt.CONFIG_PARAMS.LOGGING_AUDITLOG),G=S.trackDeletes,k=S.expiration;if(y)O=y.indices,H=y.attributes,y.schemaVersion++;else{Y=S.tableId,Y?Y>=(u.get(xo)||0)&&u.putSync(xo,Y+1):(S.tableId=Y=u.get(xo),Y||(Y=1),u.putSync(xo,Y+1),u.putSync(S.key,S));let X=new Li.default(!S.is_hash_attribute,S.is_hash_attribute);Le.trace(`openDB ${S.key} from ${r}`),A=o.openDB(S.key,X),A.rootStore=o,A.tableId=Y}for(let X of T){X.attribute=X.name;try{if(!X.is_hash_attribute&&(X.indexed||X.attribute&&!X.name)){if(!O[X.name]){let ut=new Li.default(!X.is_hash_attribute,X.is_hash_attribute);Le.trace(`openDB ${X.key} from ${r}`),O[X.name]=o.openDB(X.key,ut)}let ge=H.find(ut=>ut.name===X.name);ge?H.splice(H.indexOf(ge),1,X):H.push(X)}}catch(ge){Le.error("Error trying to update attribute",X,H,O,ge)}}if(!y){Le.trace(`creating table class ${f}`,Object.keys(_)),y=NB(_,f,Xd({primaryStore:A,auditStore:l,audit:w,expirationMS:k&&k*1e3,trackDeletes:G,tableName:f,tableId:Y,primaryKey:S.name,databasePath:n?r+"/"+f:r,databaseName:r,indices:O,attributes:T,schemaDefined:S.schemaDefined,dbisDB:u})),y.schemaVersion=1;for(let X of jT)X(y)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function OB(e){let t=Pe[e];if(t||(e==="data"?t=Pe[e]=sr:e==="system"?Object.defineProperty(Pe,"system",{value:t=Object.create(null),configurable:!0}):t=Pe[e]=Object.create(null)),Vo&&!Vo.has(e)){let r=new Set;t[rE]=r,Vo.set(e,r)}return t}function NB(e,t,r){return e[t]=r,r}function Ga({database:e,table:t}){e||(e=ZT),Gr();let r=OB(e),s=(0,Me.join)((0,yt.getHdbBasePath)(),jt.DATABASES_DIR_NAME),n=t&&(0,yt.get)(jt.CONFIG_PARAMS.SCHEMAS)?.[e]?.tables?.[t]?.path;s=n||(0,yt.get)(jt.CONFIG_PARAMS.SCHEMAS)?.[e]?.path||process.env.STORAGE_PATH||(0,yt.get)(jt.CONFIG_PARAMS.STORAGE_PATH)||((0,fr.existsSync)(s)?s:(0,Me.join)((0,yt.getHdbBasePath)(),jt.LEGACY_DATABASES_DIR_NAME));let i=(0,Me.join)(s,(n?t:e)+".mdb"),o=Bn.get(i);if(!o){let c=new JT.default(i,!1);o=(0,Zd.open)(c),Bn.set(i,o)}return o}async function Jh(e){if(!Pe[e])throw new Error("Schema does not exist");let t=Pe[e];for(let r in t){let n=t[r].primaryStore.rootStore;Bn.delete(n.path),n.status==="open"&&(await n.close(),await RB.remove(n.path))}if(e==="data"){for(let r in sr)delete sr[r];delete sr[rE]}delete Pe[e]}function et({table:e,database:t,expiration:r,attributes:s,audit:n,trackDeletes:i,schemaDefined:o,origin:c}){t||(t=ZT);let u=Ga({database:t,table:e}),l=Pe[t],_=l?.[e];if(u.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let d,E,f,h;o==null&&(o=!0);let T=new Li.default(!1);for(let A of s)A.attribute?(A.name=A.attribute,A.indexed=!0):A.attribute=A.name,A.expiresAt&&(A.indexed=!0);let S,y;if(_){if(Le.trace(`${e} table already exists`),d=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);_.attributes.splice(0,_.attributes.length,...s)}else{let A=u.auditStore;A||(A=$T(u)),E=s.find(X=>X.isPrimaryKey)||{},d=E.name,E.is_hash_attribute=!0,E.schemaDefined=o,i&&(E.trackDeletes=!0),n=E.audit=typeof n=="boolean"?n:(0,yt.get)(jt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(E.expiration=r),c&&(E.origins?E.origins.includes(c)||E.origins.push(c):E.origins=[c]),Le.trace(`${e} table loading, opening primary store`);let w=new Li.default(!1,!0),G=e+"/";Le.trace(`openDB ${G} from ${t}`);let k=u.openDB(G,w);k.rootStore=u,Le.trace(`openDB ${Go.INTERNAL_DBIS_NAME} from ${t}`),h=u.dbisDb=u.openDB(Go.INTERNAL_DBIS_NAME,T),k.tableId=h.get(xo),k.tableId||(k.tableId=1),h.putSync(xo,k.tableId+1),E.tableId=k.tableId,_=NB(l,e,Xd({primaryStore:k,auditStore:A,audit:n,trackDeletes:i,expirationMS:r&&r*1e3,primaryKey:d,tableName:e,tableId:k.tableId,databasePath:t,databaseName:t,indices:{},attributes:s,schemaDefined:o,dbisDB:h})),_.schemaVersion=1,S=!0,Y(),h.put(G,E)}Le.trace(`${e} table loading, getting stored attributes`),f=_.indices,h||Le.trace(`openDB ${Go.INTERNAL_DBIS_NAME} from ${t}`),h=h||(u.dbisDb=u.openDB(Go.INTERNAL_DBIS_NAME,T)),_.dbisDB=h;let O=[];for(let{key:A,value:w}of h.getRange({start:!0})){let[G,k]=A.toString().split("/");if(k===""&&(k=w.name),k){if(G!==e)continue}else k=G;if(!s.find(ge=>ge.name===k)?.indexed&&w.indexed&&!w.isPrimaryKey){Y(),S=!0,h.remove(A);let ge=_.indices[G];ge&&O.push(ge)}}Le.trace(`${e} table loading, comparing atributes`);let H=[];try{for(let A of s||[]){let w=e+"/"+(A.name||"");Object.defineProperty(A,"key",{value:w,configurable:!0});let G=h.get(w);if(A.isPrimaryKey){if(n===!0&&!_.audit){_.enableAuditing(),G||(w=e+"/",G=h.get(w));let X=Object.assign({},G,{audit:!0});S=!0,Y(),h.put(w,X)}continue}G?.attribute&&!G.name&&(G.indexed=!0);let k=!G||G.type!==A.type||G.indexed!==A.indexed||JSON.stringify(G.attributes)!==JSON.stringify(A.attributes)||JSON.stringify(G.elements)!==JSON.stringify(A.elements);if(A.indexed){let X=new Li.default(!0,!1);Le.trace(`openDB ${w} from ${t}`);let ge=u.openDB(w,X);(k||G.indexingPID&&G.indexingPID!==process.pid||G.restartNumber<ou.workerData?.restartNumber)&&(S=!0,Y(),G=h.get(w),(k||G.indexingPID&&G.indexingPID!==process.pid||G.restartNumber<ou.workerData?.restartNumber)&&(S=!0,A.lastIndexedKey=G?.lastIndexedKey||!1,A.indexingPID=process.pid,ge.isIndexing=!0,Object.defineProperty(A,"dbi",{value:ge}),H.push(A)),h.put(w,A)),f[A.name]=ge}else k&&(S=!0,Y(),h.put(w,A))}}finally{y&&y()}if(S&&(_.schemaVersion++,_.updatedAttributes()),Le.trace(`${e} table loading, running index`),H.length>0||O.length>0?_.indexingOperation=Aee(_,H,O):S&&jd.signalSchemaChange(new eE.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=c,S)for(let A of jT)A(_,c!=="cluster");return r&&_.setTTLExpiration(+r),Le.trace(`${e} table loaded`),_;function Y(){y||u.transactionSync(()=>({then(A){y=A}}))}a(Y,"startTxn")}async function Aee(e,t,r){try{let s=e.schemaVersion;await jd.signalSchemaChange(new eE.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:l,value:_,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(_){if(u++,n=e.primaryStore.ifVersion(l,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,T=(0,gB.getIndexedValues)(_[h]);if(T)for(let S=0,y=T.length;S<y;S++)f.dbi.put(T[S],l)}}),n.then(()=>u--,E=>{u--,Le.error(E)}),ou.workerData&&ou.workerData.restartNumber!==AB.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=l,e.dbisDB.put(E.key,E);if(i)return}u>Ree?await n:u>gee&&await new Promise(E=>setImmediate(E))}for(let l of t)delete l.lastIndexedKey,delete l.indexingPID,l.dbi.isIndexing=!1,n=e.dbisDB.put(l.key,l)}await n,await jd.signalSchemaChange(new eE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Le.error("Error in indexing",s)}}function Oee({table:e,database:t}){let r=Ga({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 pT(e){jT.push(e)}var yt,Go,Zd,Me,fr,ko,Li,JT,jt,RB,XT,gB,jd,eE,ou,Le,AB,ZT,rE,sr,Pe,xo,jT,tE,Bn,Vo,Ree,gee,de=pe(()=>{yt=D(Q()),Go=D(xe()),Zd=require("lmdb"),Me=require("path"),fr=require("fs"),ko=D(we());fd();Li=D(vu()),JT=D(Hu()),jt=D(g()),RB=D(require("fs-extra")),XT=require("../../index"),gB=D(vt()),jd=D(Fs()),eE=D(qr()),ou=require("worker_threads"),Le=D(F()),AB=D(rt());Xc();ZT="data",rE=Symbol("defined-tables");(0,yt.initSync)();sr=Object.create(null),Pe=Object.create(null);(0,XT._assignPackageExport)("databases",Pe);(0,XT._assignPackageExport)("tables",sr);xo=Symbol.for("next-table-id"),jT=[],Bn=new Map;a(pee,"getTables");a(Gr,"getDatabases");a(Tee,"resetDatabases");a(iu,"readMetaDb");a(OB,"ensureDB");a(NB,"setTable");a(Ga,"database");a(Jh,"dropDatabase");a(et,"table");Ree=1e3,gee=10;a(Aee,"runIndexing");a(Oee,"dropTableMeta");a(pT,"onUpdatedTable")});var x=m((vde,qB)=>{"use strict";var Hn=require("path"),CB=require("fs-extra"),er=F(),bB=require("fs-extra"),sE=require("os"),Nee=require("net"),bee=require("recursive-iterator"),Ge=g(),yee=KR(),yB=require("papaparse"),nE=require("moment"),{inspect:Iee}=require("util"),IB=require("is-number"),Pde=require("lodash"),wee=require("minimist"),Cee=require("https"),Uee=require("http"),{hdb_errors:iE}=W(),Dee=/^((\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)))$/,UB=require("util").promisify(setTimeout),Lee=100,Mee=5,Pee="",vee=4,wB={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};qB.exports={isEmpty:hr,isEmptyOrZeroLength:As,arrayHasEmptyValues:qee,arrayHasEmptyOrZeroLengthValues:Fee,buildFolderPath:Gee,isBoolean:DB,errorizeMessage:Bee,stripFileExtension:kee,autoCast:Vee,autoCastJSON:LB,autoCastJSONDeep:tR,removeDir:$ee,compareVersions:Yee,isCompatibleDataVersion:Kee,escapeRawValue:Wee,unescapeValue:Qee,stringifyProps:zee,timeoutPromise:Xee,isClusterOperation:jee,getClusterUser:tte,checkGlobalSchemaTable:ete,getHomeDir:PB,getPropsFilePath:Jee,promisifyPapaParse:rte,removeBOM:vB,createEventPromise:ste,checkProcessRunning:nte,checkSchemaTableExist:ite,checkSchemaExists:BB,checkTableExists:HB,getStartOfTomorrowInSeconds:ote,getLimitKey:ate,isObject:xee,isNotEmptyAndHasValue:Hee,autoCasterIsNumberCheck:MB,backtickASTSchemaItems:cte,isPortTaken:Zee,createForkArgs:ute,autoCastBoolean:lte,async_set_timeout:UB,getTableHashAttribute:_te,doesSchemaExist:dte,doesTableExist:Ete,stringifyObj:fte,ms_to_time:hte,changeExtension:mte,getEnvCliRootPath:rR,noBootFile:Ste,httpRequest:pte,transformReq:Tte,convertToMS:Rte,PACKAGE_ROOT:Ge.PACKAGE_ROOT};function Bee(e){return e instanceof Error?e:new Error(e)}a(Bee,"errorizeMessage");function hr(e){return e==null}a(hr,"isEmpty");function Hee(e){return!hr(e)&&(e||e===0||e===""||DB(e))}a(Hee,"isNotEmptyAndHasValue");function As(e){return hr(e)||e.length===0||e.size===0}a(As,"isEmptyOrZeroLength");function qee(e){if(hr(e))return!0;for(let t=0;t<e.length;t++)if(hr(e[t]))return!0;return!1}a(qee,"arrayHasEmptyValues");function Fee(e){if(As(e))return!0;for(let t=0;t<e.length;t++)if(As(e[t]))return!0;return!1}a(Fee,"arrayHasEmptyOrZeroLengthValues");function Gee(...e){try{return e.join(Hn.sep)}catch{console.error(e)}}a(Gee,"buildFolderPath");function DB(e){return hr(e)?!1:e===!0||e===!1}a(DB,"isBoolean");function xee(e){return hr(e)?!1:typeof e=="object"}a(xee,"isObject");function kee(e){return As(e)?Pee:e.slice(0,-vee)}a(kee,"stripFileExtension");function Vee(e){return hr(e)||e===""||typeof e!="string"?e:wB[e]!==void 0?wB[e]:MB(e)===!0?Number(e):Dee.test(e)?new Date(e):e}a(Vee,"autoCast");function LB(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(LB,"autoCastJSON");function tR(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=tR(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=tR(r);s!==r&&(e[t]=s)}return e}else return LB(e)}a(tR,"autoCastJSONDeep");function MB(e){if(e.startsWith("0.")&&IB(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&IB(e))}a(MB,"autoCasterIsNumberCheck");async function $ee(e){if(As(e))throw new Error(`Directory path: ${e} does not exist`);try{await bB.emptyDir(e),await bB.remove(e)}catch(t){throw er.error(`Error removing files in ${e} -- ${t}`),t}}a($ee,"removeDir");function Yee(e,t){if(As(e)){er.info("Invalid current version sent as parameter.");return}if(As(t)){er.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 l=0;l<u;l++)if(r=parseInt(o[l],10)-parseInt(c[l],10),r)return r;return o.length-c.length}a(Yee,"compareVersions");function Kee(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(Kee,"isCompatibleDataVersion");function Wee(e){if(hr(e))return e;let t=String(e);return t==="."?Ge.UNICODE_PERIOD:t===".."?Ge.UNICODE_PERIOD+Ge.UNICODE_PERIOD:t.replace(Ge.FORWARD_SLASH_REGEX,Ge.UNICODE_FORWARD_SLASH)}a(Wee,"escapeRawValue");function Qee(e){if(hr(e))return e;let t=String(e);return t===Ge.UNICODE_PERIOD?".":t===Ge.UNICODE_PERIOD+Ge.UNICODE_PERIOD?"..":String(e).replace(Ge.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Qee,"unescapeValue");function zee(e,t){if(hr(e))return er.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+sE.EOL}!As(s)&&s[0]===";"?r+=" "+s+n+sE.EOL:As(s)||(r+=s+"="+n+sE.EOL)}catch{er.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(zee,"stringifyProps");function PB(){let e;try{e=sE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(PB,"getHomeDir");function Jee(){let e=Hn.join(PB(),Ge.HDB_HOME_DIR_NAME,Ge.BOOT_PROPS_FILE_NAME);return CB.existsSync(e)||(e=Hn.join(__dirname,"../","hdb_boot_properties.file")),e}a(Jee,"getPropsFilePath");function Xee(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(Xee,"timeoutPromise");async function Zee(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=Nee.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(Zee,"isPortTaken");function jee(e){try{return Ge.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){er.error(`Error checking operation against cluster ops ${t}`)}return!1}a(jee,"isClusterOperation");function ete(e,t){let r=(de(),te(Ne)).getDatabases();if(!r[e])return iE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return iE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(ete,"checkGlobalSchemaTable");function tte(e,t){if(hr(t)){er.warn("No CLUSTERING_USER defined, clustering disabled");return}if(hr(e)||As(e)){er.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){er.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){er.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(tte,"getClusterUser");function rte(){yB.parsePromise=function(e,t,r){return new Promise(function(s,n){yB.parse(e,{header:!0,transformHeader:vB,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(rte,"promisifyPapaParse");function vB(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(vB,"removeBOM");function ste(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;er.info(`Got cluster status event response: ${Iee(n)}`);try{i.cancel()}catch{er.error("Error trying to cancel timeout.")}s(n)})})}a(ste,"createEventPromise");async function nte(e){let t=!0,r=0;do await UB(Lee*r++),(await yee.findPs(e)).length>0&&(t=!1);while(t&&r<Mee);if(t)throw new Error(`process ${e} was not started`)}a(nte,"checkProcessRunning");function ite(e,t){let r=BB(e);if(r)return r;let s=HB(e,t);if(s)return s}a(ite,"checkSchemaTableExist");function BB(e){let{getDatabases:t}=(de(),te(Ne));if(!t()[e])return iE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(BB,"checkSchemaExists");function HB(e,t){let{getDatabases:r}=(de(),te(Ne));if(!r()[e][t])return iE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(HB,"checkTableExists");function ote(){let e=nE().utc().add(1,Ge.MOMENT_DAYS_TAG).startOf(Ge.MOMENT_DAYS_TAG).unix(),t=nE().utc().unix();return e-t}a(ote,"getStartOfTomorrowInSeconds");function ate(){return nE().utc().format("DD-MM-YYYY")}a(ate,"getLimitKey");function cte(e){try{let t=new bee(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){er.error("Got an error back ticking items."),er.error(t)}}a(cte,"backtickASTSchemaItems");function ute(e){return[e]}a(ute,"createForkArgs");function lte(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(lte,"autoCastBoolean");function _te(e,t){let{getDatabases:r}=(de(),te(Ne)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(_te,"getTableHashAttribute");function dte(e){let{getDatabases:t}=(de(),te(Ne));return t()[e]!==void 0}a(dte,"doesSchemaExist");function Ete(e,t){let{getDatabases:r}=(de(),te(Ne));return r()[e]?.[t]!==void 0}a(Ete,"doesTableExist");function fte(e){try{return JSON.stringify(e)}catch{return e}}a(fte,"stringifyObj");function hte(e){let t=nE.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(hte,"ms_to_time");function mte(e,t){let r=Hn.basename(e,Hn.extname(e));return Hn.join(Hn.dirname(e),r+t)}a(mte,"changeExtension");function rR(){if(process.env[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=wee(process.argv);if(e[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(rR,"getEnvCliRootPath");var eR;function Ste(){if(eR)return eR;let e=rR();rR()&&CB.pathExistsSync(Hn.join(e,Ge.HDB_CONFIG_FILE))&&(eR=!0)}a(Ste,"noBootFile");function pte(e,t){let r;return e.protocol==="http:"?r=Uee:r=Cee,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(pte,"httpRequest");function Tte(e){if(!e.schema&&!e.database){e.schema=Ge.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Tte,"transformReq");function Rte(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(Rte,"convertToMS")});var Q=m((Hde,xB)=>{"use strict";var sR=require("fs-extra"),zr=require("path"),FB=require("os"),gte=require("properties-reader"),au=F(),Mi=x(),ee=g(),oE=Ar(),Ate="Error initializing environment manager",aE="BOOT_PROPS_FILE_PATH",GB=!1,Ote={[ee.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},nn={};xB.exports={BOOT_PROPS_FILE_PATH:aE,getHdbBasePath:Nte,setHdbBasePath:bte,get:yte,initSync:wte,setProperty:Ee,initTestEnvironment:Cte};function Nte(){return nn[ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Nte,"getHdbBasePath");function bte(e){nn[ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(bte,"setHdbBasePath");function yte(e){let t=oE.getConfigValue(e);return t===void 0?nn[e]:t}a(yte,"get");function Ee(e,t){Ote[e]&&(nn[e]=t),oE.updateConfigObject(e,t)}a(Ee,"setProperty");function Ite(){let e;try{e=Mi.getPropsFilePath(),sR.accessSync(e,sR.constants.F_OK|sR.constants.R_OK),GB=!0;let t=gte(e);return nn[ee.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ee.HDB_SETTINGS_NAMES.INSTALL_USER),nn[ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),nn[aE]=e,!0}catch{return au.trace(`Environment manager found no properties file at ${e}`),!1}}a(Ite,"doesPropFileExist");function wte(e=!1){try{(GB||Ite()||Mi.noBootFile())&&(oE.initConfig(e),nn[ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=oE.getConfigValue(ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){au.error(Ate),au.error(t),console.error(t),process.exit(1)}}a(wte,"initSync");function Cte(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=zr.join(__dirname,"../../","unitTests");nn[aE]=zr.join(u,"hdb_boot_properties.file"),Ee(ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,zr.join(u,"settings.test")),Ee(ee.HDB_SETTINGS_NAMES.INSTALL_USER,FB.userInfo()?FB.userInfo().username:void 0),Ee(ee.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,zr.join(u,"envDir","utility","keys","privateKey.pem")),Ee(ee.HDB_SETTINGS_NAMES.CERT_KEY,zr.join(u,"envDir","utility","keys","certificate.pem")),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,zr.join(u,"envDir","utility","keys","privateKey.pem")),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,zr.join(u,"envDir","utility","keys","certificate.pem")),Ee(ee.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ee(ee.HDB_SETTINGS_NAMES.LOG_PATH_KEY,zr.join(u,"envDir","log")),Ee(ee.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ee(ee.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ee(ee.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ee(ee.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,zr.join(u,"envDir")),Ee(ee.CONFIG_PARAMS.STORAGE_PATH,zr.join(u,"envDir")),Ee(ee.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Mi.isEmpty(n)?!0:n),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Mi.isEmpty(n)?!0:n),Ee(ee.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ee(ee.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Mi.isEmpty(i)?!1:i),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Mi.isEmpty(i)?!1:i),Ee(ee.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ee(ee.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ee(ee.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ee(ee.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ee(ee.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,zr.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ee(ee.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Mi.isEmpty(c)?!1:c),o&&(Ee("CORS_ACCESSLIST",o),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(Ee(ee.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(Ee(ee.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(Ee(ee.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ee(ee.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${aE}. Please check your boot props and settings files`;au.fatal(r),au.error(t)}}a(Cte,"initTestEnvironment")});var Wte=m(dE=>{var{isMainThread:Ute,parentPort:uu,threadId:Dte}=require("worker_threads"),{Socket:Lte}=require("net"),{createServer:Mte,IncomingMessage:Pte}=require("http"),{createServer:vte}=require("https"),{readFileSync:$o}=require("fs"),cE=F(),Os=Q(),Yo=g(),{server:_E}=(Us(),te(Lu)),{WebSocketServer:Bte}=require("ws"),{createServer:Hte}=require("tls"),{getTicketKeys:qte}=rt();process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:Fde,CONFIG_PARAMS:Gde}=Yo;Os.initSync();var Fn={};dE.registerServer=lR;dE.httpServer=_R;dE.deliverSocket=uR;_E.http=_R;_E.request=Vte;_E.socket=$te;_E.ws=Yte;var nR=[],iR=[],Fte,cu={},uE={},Gte=[],oR=[];Ute||LT().loadRootComponents(!0).then(()=>{uu.on("message",e=>{let{port:t,fd:r,data:s}=e;if(r)uR(r,t,s);else if(e.requestId)xte(e);else if(e.type===Yo.ITC_EVENT_TYPES.SHUTDOWN)for(let n in Fn){let i=Fn[n];i.close?.(()=>{setTimeout(()=>{i.cantCleanupProperly||cE.warn("Had to forcefully exit the thread",Dte),process.exit(0)},i.cantCleanupProperly?2500:5e3).unref()}),i.closeIdleConnections?.()}}).ref(),uu.postMessage({type:Yo.ITC_EVENT_TYPES.CHILD_STARTED})});function uR(e,t,r){let s=e?.read?e:new Lte({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),n=Fn[t];if(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):(cE.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(uR,"deliverSocket");var kB=new Map;function xte(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=kB.get(n),r){case"connection":i=uR(void 0,t),kB.set(n,i),i.write=(c,u,l)=>(uu.postMessage({requestId:n,event:"data",data:c.toString("latin1")}),l&&l(),!0),i.end=(c,u,l)=>(uu.postMessage({requestId:n,event:"end",data:c?.toString("latin1")}),l&&l(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),uu.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(xte,"proxyRequest");function lR(e,t){+t||(t=parseInt(Os.get(Yo.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10));let r=Fn[t];if(r){let s=r.lastServer||r;s.off("unhandled",VB),s.on("unhandled",(n,i)=>{e.cantCleanupProperly&&(r.cantCleanupProperly=!0),e.emit("request",n,i)}),r.lastServer=e}else Fn[t]=e;e.on("unhandled",VB)}a(lR,"registerServer");function $B(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=[{port:parseInt(Os.get(Yo.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10),secure:Os.get(Yo.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}]),t}a($B,"getPorts");function _R(e,t){for(let{port:r,secure:s}of $B(t))YB(r,s,t?.isOperationsServer),typeof e=="function"?oR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):lR(e,r),uE[r]=aR(oR,r),Fte=aR(Gte,r)}a(_R,"httpServer");function YB(e,t,r){if(!cu[e]){let s={};if(t){let n=r?"operationsapi":"customfunctions",i=Os.get(n+"_tls_privatekey"),o=Os.get(n+"_tls_certificate"),c=Os.get(n+"_tls_certificateauthority");s={key:$o(i),cert:$o(o)+(c?`
|
|
26
|
+
`+ET.readFileSync(o):"")};s.http2=!0,s.https=c}return s}a(X9,"getServerOptions");function Z9(){let e=Qr.get(x9),t=Qr.get(k9),r;return e&&(e===!0||e.toUpperCase()===VP)&&(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(Z9,"getCORSOpts");function j9(){return Qr.get(Y9)}a(j9,"getHeaderTimeoutConfig")});var sv=m((B_e,rv)=>{"use strict";var{decode:e7}=require("msgpackr"),{isMainThread:t7,parentPort:r7,threadId:P_e}=require("worker_threads"),fT=it(),qo=Be(),s7=A(),zc=x(),KP=Q(),zP=A();nt();var n7=vs(),{recordAction:i7,recordActionBinary:o7}=(ci(),ee(ql)),{publishToStream:a7}=fT,v_e={durable:qo.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:qo.WORK_QUEUE_CONSUMER_NAMES.deliver_group},c7,u7,l7,JP,XP;rv.exports={initialize:ZP,workQueueListener:tv,setSubscription:_7,setIgnoreOrigin:E7,getDatabaseSubscriptions:d7};async function ZP(){XP=!0,zc.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await fT.getNATSReferences();c7=e,u7=e.info.server_name,l7=t,JP=r}a(ZP,"initialize");var Md=new Map;function _7(e,t,r){let s=Md.get(e);s||Md.set(e,s=new Map),s.set(t,r),XP||ZP().then(tv)}a(_7,"setSubscription");function d7(){return Md}a(d7,"getDatabaseSubscriptions");var jP;function E7(e){jP=e}a(E7,"setIgnoreOrigin");var ev=100,WP=new Array(ev),Ld=0;async function tv(){let t=await(await JP.consumers.get(qo.WORK_QUEUE_CONSUMER_NAMES.stream_name,qo.WORK_QUEUE_CONSUMER_NAMES.durable_name)).consume();for await(let r of t)await WP[Ld],WP[Ld]=f7(r).catch(s=>{zc.error(s)}),++Ld>=ev&&(Ld=0)}a(tv,"workQueueListener");t7||r7.on("message",async e=>{let{type:t}=e;t===zP.ITC_EVENT_TYPES.SHUTDOWN&&fT.closeConnection()});async function f7(e){let t=e7(e.data);i7(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let n=e.headers.get(qo.MSG_HEADERS.ORIGIN)===KP.get(s7.CONFIG_PARAMS.CLUSTERING_NODENAME)&&!jP;if(o7(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}try{let{operation:i,schema:o,next:c,table:u,records:l,hash_values:_,__origin:d}=t;zc.trace("processing message:",i,o,u,(l?"records: "+l.map(R=>R.id):"")+(_?"ids: "+_:""),"with sequence:",e.seq),zc.trace(`messageProcessor nats msg id: ${e.headers.get(qo.MSG_HEADERS.NATS_MSG_ID)}`);let E;l||(l=_);let{timestamp:f,user:h,node_name:T}=d||{},p=Md.get(o)?.get(u);if(!p)throw new Error("Missing table for replication message",u);if(i==="define_schema")t.type=i,p.send(t);else if(l.length===1&&!c)p.send({type:QP(i),value:l[0],id:_?.[0],timestamp:f,table:u,onCommit:E,user:h,nodeName:T});else{let R=l.map((O,k)=>({type:QP(i),value:O,id:_?.[k],table:u}));for(;c;)R.push({type:c.operation,value:c.record,id:c.id,table:c.table}),c=c.next;p.send({type:"transaction",writes:R,table:u,timestamp:f,onCommit:E,user:h,nodeName:T})}KP.get(zP.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&a7(e.subject.split(".").slice(0,-1).join("."),n7.createNatsTableStreamName(o,u),e.headers,e.data)}catch(i){zc.error(i)}e.ack()}a(f7,"messageProcessor");function QP(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(QP,"convertOperation")});var RT={};Ye(RT,{disableNATS:()=>m7,setNATSReplicator:()=>hT,start:()=>h7});function h7(){vd.default.get(Bd.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&p7()}function m7(e=!0){cv=e}function p7(){if(cv)return;let e=xr(),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];hT(n,r,i)}}gT((r,s)=>{hT(r.tableName,r.databaseName,r),s&&lv(r)}),!nv&&(nv=!0)}function hT(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.Source?.isNATSReplicator)return;let s;r.sourcedFrom(class extends ht{static{a(this,"NATSReplicator")}put(o){let c;return s?.put&&(!s.put.reliesOnPrototype||s.prototype.put)&&(c=s.put(this[ae],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[ae],record:o},c)}delete(){let o;return s?.delete&&(!s.delete.reliesOnPrototype||s.prototype.delete)&&(o=s.delete(this[ae],this.getContext())),n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[ae]},o)}publish(o){let c;return s?.publish&&(!s.publish.reliesOnPrototype||s.prototype.publish)&&(c=s.publish(this[ae],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[ae],record:o},c)}invalidate(o){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[ae]})}static defineSchema(o){lv(o)}static mergeSource(o,c){return s=o,s?.get&&(!s.get.reliesOnPrototype||s.prototype.get)&&(c?.replicationSource?this.get=async(u,l)=>{let _=await s.get(u,l);return _&&n(l).addWrite(t,{operation:"put",table:e,id:u,record:_}),_}:this.get=(u,l)=>s.get(u,l)),this}static subscribe(){let o=new Xr;return(0,iv.setSubscription)(t,e,o),o}static subscribeOnThisThread(o){return o<S7}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0});function n(i){let o=i?.transaction?.nats;return o||(i?.transaction?(i.transaction.push(o=i.transaction.nats=new Pd(i.transaction,i)),o.user=i.user):o=uv),o}a(n,"getNATSTransaction")}function lv(e){let t=vd.default.get(Bd.default.CONFIG_PARAMS.CLUSTERING_NODENAME);(0,ST.publishToStream)(`${pT.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,TT.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 ST,pT,TT,iv,ov,vd,Bd,av,cv,S7,uv,nv,Pd,mT,_v=Se(()=>{de();Zr();ST=C(it()),pT=C(Be()),TT=C(vs());ua();iv=C(sv()),ov=C(vt()),vd=C(Q()),Bd=C(A()),av=C(x());a(h7,"start");a(m7,"disableNATS");S7=2;a(p7,"assignReplicationSource");a(hT,"setNATSReplicator");a(lv,"publishSchema");Pd=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r,s){let n=this.writes_by_db.get(t);if(n||this.writes_by_db.set(t,n=[]),s?.then)return s.then(()=>n.push(r));n.push(r)}commit(t){let r=vd.default.get(Bd.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,l;for(let _ of i){let d=_.table,E=_.operation=="put"?"upsert":_.operation;u||(av.trace(`Sending transaction event ${E}`),l=u={operation:E,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(_.record),c.push(_.id)):l=l.next={operation:E,table:d,id:_.id,record:_.record}}s.push((0,ST.publishToStream)(`${pT.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,TT.createNatsTableStreamName)(n,u.table),void 0,u))}return Promise.all(s)}},mT=class extends Pd{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,ov.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit()}};uv=new mT});async function Ev({clientId:e,user:t,listener:r,clean:s}){let n;if(e&&!s){let i=await AT.getResource(e,{});n=new NT(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await AT.get(e);i&&i.delete()}n=new qd(e,t)}return n}function OT(){return Hd++,Hd>65500&&(Hd=1),Hd}var dv,Jc,AT,Hd,qd,NT,fv=Se(()=>{de();bc();dv=C(vt()),Jc=C(x());$n();AT=rt({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"}]}}]});a(Ev,"getSession");Hd=1;a(OT,"getNextMessageId");qd=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,omitCurrent:i,startTime:o}=t,c=n.indexOf("?"),u,l;if(c>-1?(u=n.slice(c),l=n.slice(0,c)):l=n,!l)throw new Error("No topic provided");let _=!1,d;if((l.endsWith("+")||l.endsWith("#"))&&(_=!0,l.endsWith("+")&&(d=!0),l=l.slice(0,l.length-1)),l.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");if(l.indexOf("#")>-1||l.indexOf("+")>-1)throw new Error("Only trailing wildcards are supported");let E=this.subscriptions.find(O=>O.topic===n);E&&(E.end(),this.subscriptions.splice(this.subscriptions.indexOf(E),1));let f={search:u,user:this.user,startTime:o,omitCurrent:i,isCollection:_,shallowWildcard:d,url:""},h=Cn.getMatch(l);if(!h)throw new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);f.url=h.relativeURL;let T=h.path,p=h.Resource,R=await Ke(f,async()=>{let O=await p.subscribe(f);if(!O)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!O[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let k of O)try{let $;if(k.type&&k.type!=="put"&&k.type!=="delete"&&k.type!=="message"||s&&!s(k))continue;r?(k.topic=n,$=this.needsAcknowledge(k)):$=OT();let U=k.id;Array.isArray(U)&&(U=go(U)),U==null&&(U=""),this.listener(T+"/"+U,k.value,$,t)}catch($){(0,Jc.warn)($)}})(),O});return R.topic=n,R.qos=t.qos,this.subscriptions.push(R),R}resume(){}needsAcknowledge(t){return OT()}acknowledge(t){}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);r&&r.end()}async publish(t,r){let{topic:s,retain:n}=t;t.data=r,t.user=this.user;let i=Cn.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`);t.url=i.relativeURL;let o=i.Resource;return Ke(t,()=>n?r===void 0?o.delete(t,t):o.put(t,t.data,t):o.publish(t,t.data,t))}setListener(t){this.listener=t}disconnect(){for(let t of this.subscriptions)t.end();this.subscriptions=[]}},NT=class extends qd{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=OT();return this.awaitingAcks.set(r,{topic:t.topic,timestamp:t.timestamp}),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t);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,Jc.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,dv.getNextMonotonicTime)()),(0,Jc.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),AT.put(this.sessionRecord)),t.qos}}});var IT={};Ye(IT,{start:()=>R7});async function R7({server:e,port:t,webSocket:r,securePort:s,requireAuthentication:n}){let i=e.mqtt={requireAuthentication:n};r&&e.ws((o,c,u)=>{if(o.protocol==="mqtt"){let{onMessage:l,onClose:_}=Sv(o,(d,E)=>{if(o.send(d),E&&o._socket.writableNeedDrain)return new Promise(f=>this._socket.once("drain",f))},c,Promise.resolve(u).then(()=>c?.user),i);o.on("message",l),o.on("close",_),o.on("error",d=>{(0,rn.info)("WebSocket error",d)})}},{subProtocol:"mqtt"}),(t||s)&&e.socket(async o=>{let c;T7&&o.remoteAddress.includes("127.0.0.1")&&(c=await(0,pv.getSuperUser)());let{onMessage:u,onClose:l}=Sv(o,_=>o.write(_),null,c,i);o.on("data",u),o.on("close",l),o.on("error",_=>{(0,rn.info)("Socket error",_)})},{port:t,securePort:s})}function Sv(e,t,r,s,n){mv||(mv=!0,fm(_=>{_.push({metric:"mqtt-connections",connections:bT})})),bT++;let i,o={protocolVersion:4},c=(0,Fd.parser)({protocolVersion:5});function u(_){c.parse(_)}a(u,"onMessage");function l(){bT--,i?.disconnect()}return a(l,"onClose"),c.on("packet",async _=>{s?.then&&(s=await s),i?.then&&await i;try{switch(_.cmd){case"connect":if(o.protocolVersion=_.protocolVersion,_.username)try{s=await tt.auth(_.username,_.password.toString()),(0,yT.get)(sn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&hv.notify({username:s.username,status:sn.AUTH_AUDIT_STATUS.SUCCESS,type:sn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,yT.get)(sn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&hv.error({username:s.username,status:sn.AUTH_AUDIT_STATUS.FAILURE,type:sn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),d({cmd:"connack",reasonCode:134,returnCode:134})}if(!s&&n.requireAuthentication)return d({cmd:"connack",reasonCode:134,returnCode:134});try{n.authorizeClient?.(_,s),i=Ev({user:s,..._}),i=await i}catch(O){return(0,rn.error)(O),d({cmd:"connack",reasonCode:O.code||128,returnCode:O.code||128})}d({cmd:"connack",sessionPresent:i.sessionWasPresent,reasonCode:0,returnCode:0}),i.setListener((O,k,$,U)=>{try{let b=O.indexOf("/",1),P=b>0?O.slice(0,b):O;d({cmd:"publish",topic:O,payload:E(k),messageId:$||Math.floor(Math.random()*1e8),qos:U.qos},P)}catch(b){(0,rn.error)(b),i?.disconnect()}}),i.sessionWasPresent&&await i.resume();break;case"subscribe":let f=[];for(let O of _.subscriptions){let k;try{k=(await i.addSubscription(O,O.qos>=1)).qos||0}catch($){(0,rn.error)($),k=128}f.push(k)}await i.committed,d({cmd:"suback",granted:f,messageId:_.messageId});break;case"unsubscribe":for(let O of _.unsubscriptions)i.removeSubscription(O);d({cmd:"unsuback",messageId:_.messageId});break;case"pubrel":d({cmd:"pubcomp",messageId:_.messageId,reasonCode:0});return;case"publish":let h=_.qos===2?"pubrec":"puback",T=e.deserialize||(e.deserialize=wo(r?.headers["content-type"])),p=_.payload?.length>0?T(_.payload):void 0,R;try{R=await i.publish(_,p)}catch(O){console.warn(O),_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:128},_.topic)}_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:R===!1?144:0},_.topic);break;case"pubrec":d({cmd:"pubrel",messageId:_.messageId,reasonCode:0});break;case"pubcomp":case"puback":i.acknowledge(_.messageId);break;case"pingreq":d({cmd:"pingresp"});break;case"disconnect":i?.disconnect(),e.close?e.close():e.end();break}}catch(f){console.error(f),d({cmd:"disconnect"})}function d(f,h){let T=(0,Fd.generate)(f,o);t(T),ls(T.length,"bytes-sent",h,f.cmd,"mqtt")}a(d,"sendPacket");function E(f){return r?Ws(f,r):JSON.stringify(f)}a(E,"serialize")}),{onMessage:u,onClose:l}}var Fd,pv,yT,sn,rn,hv,T7,mv,bT,Tv=Se(()=>{Fd=require("mqtt-packet");fv();pv=C(br());Oo();ci();Pr();yT=C(Q()),sn=C(A()),rn=C(x()),hv=(0,rn.loggerWithTag)("auth-event"),T7=!0;a(R7,"start");bT=0;a(Sv,"onSocket")});var Cv={};Ye(Cv,{loadComponent:()=>Gd,loadComponentDirectories:()=>wv});function wv(e,t){t&&(CT=t),e&&(UT=e);let r=[];if((0,Rs.existsSync)(wT)){let n=(0,Rs.readdirSync)(wT,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Mr.join)(wT,o);r.push(Gd(c,CT,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(Gd(s,CT,s)),Promise.all(r).then(()=>{Iv=!0})}async function Gd(e,t,r,s,n){if(!gv.has(e)){gv.set(e,!0),n&&(UT=n);try{let i,o=(0,Mr.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Rs.existsSync)(o)?i=(0,Av.parseDocument)((0,Rs.readFileSync)(o,"utf8"),{simpleKeys:!0}).toJSON():i=N7;let c=[];for(let u in i){let l=i[u];if(!l)continue;let _,d=l.package;if(d){let E=e,f;for(;!(0,Rs.existsSync)(f=(0,Mr.join)(E,"node_modules",u));)if(E=(0,Mr.dirname)(E),E.length<(0,yv.getHdbBasePath)().length){f=null;break}if(f)_=await Gd(f,t,r,!1);else throw new Error(`Unable to find package ${u}:${d}`)}else _=O7[u];if(_)try{c.push(_);let E=a(p=>(p.origin=r,rt(p)),"ensureTable"),f=l.network||(l.port||l.securePort)&&l,h=f?.securePort||f?.https&&f.port,T=!f?.https&&f?.port;if(Xc.isMainThread&&(_=await _.startOnMainThread?.({server:tt,ensureTable:E,port:T,securePort:h,resources:t,...l})||_,s&&f))for(let p of[T,h])try{if(+p&&!Rv.includes(p)){Rv.push(p);let R=DT.get(LT.CONFIG_PARAMS.HTTP_SESSION_AFFINITY);FP(p,R)}}catch(R){console.error("Error listening on socket",p,R,u)}if(t.isWorker&&(_=await _.start?.({server:tt,ensureTable:E,port:T,securePort:h,resources:t,...l})||_),UT.set(_,!0),_.handleFile&&l.files){if(l.files.includes(".."))throw(0,bv.handleHDBError)("Can not reference parent directories");let p=(0,Mr.join)(e,l.files);for(let R of await(0,Ov.default)(p,{onlyFiles:!1,objectMode:!0})){let{path:O,dirent:k}=R,$=(0,Mr.relative)(e,O),U=(0,Mr.basename)(e),b=l.path||"/";b=b.startsWith("/")?b:b.startsWith("./")?"/"+U+b.slice(2):b==="."?"/"+U:"/"+U+"/"+b,b+=(b.endsWith("/")?"":"/")+$;try{if(k.isFile()){let P=await A7(O);Xc.isMainThread&&await _.setupFile?.(P,b,O,t),t.isWorker&&await _.handleFile?.(P,b,O,t)}else Xc.isMainThread&&await _.setupDirectory?.(b,O,t),t.isWorker&&await _.handleDirectory?.(b,O,t)}catch(P){console.error(`Could not load ${k.isFile()?"file":"directory"} ${O} using ${l.module} for application ${e}`,P),t.set(l.path||"/",new Zc(P))}}}}catch(E){console.error(`Could not load component ${u} for application ${e}`,E),t.set(l.path||"/",new Zc(E),null,!0)}}if(Xc.isMainThread&&!Iv&&(0,Nv.watchDir)(e,async()=>wv()),i.extensionModule)return await Bu((0,Mr.join)(e,i.extensionModule))}catch(i){console.error(`Could not load application directory ${e}`,i),t.set("",new Zc(i))}}}var Rs,Mr,Xc,Av,DT,LT,Ov,Nv,bv,yv,g7,A7,wT,UT,Iv,CT,O7,N7,Rv,gv,Zc,Uv=Se(()=>{Rs=require("fs"),Mr=require("path"),Xc=require("worker_threads"),Av=require("yaml"),DT=C(Q()),LT=C(A());vg();Fg();Gg();YL();UP();PP();Ov=C(require("fast-glob")),Nv=C(nt());QE();Pr();bv=C(W());Zr();de();GP();yv=C(Q()),g7=C(YP());F_();_v();Tv();({readFile:A7}=Rs.promises),wT=DT.get(LT.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),UT=new Map;a(wv,"loadComponentDirectories");O7={REST:Cp,graphqlSchema:WE,jsResource:JE,fastifyRoutes:cT,login:ZE,static:uT,operationsApi:g7,customFunctions:{},clustering:RT,authentication:yc,mqtt:IT},N7={REST:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}},Rv=[],gv=new Map;a(Gd,"loadComponent");Zc=class extends ht{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 Bv=m((lde,vv)=>{"use strict";var Vd=require("fs-extra"),MT=require("path"),xd=x(),Dv=V(),kd=A(),Pv=Q(),b7=Nr();vv.exports=y7;async function y7(){let e=I7(),t=Pv.get(kd.CONFIG_PARAMS.ROOTPATH),r=MT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+kd.PACKAGE_ROOT}},n=MT.join(t,"node_modules");await Vd.ensureDir(n);let i,o=!0,c=!1;try{i=await Vd.readJson(r)}catch(u){if(Dv.isEmptyOrZeroLength(e))return;if(u.code!==kd.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!Dv.isEmptyOrZeroLength(e)){for(let{name:u,package:l}of e){let _=await Lv(l);s.dependencies[u]=_+l}if(!o){xd.notify("Installing components"),await Mv(r,s);return}for(let{name:u,package:l}of e){let _=i.dependencies[u],d=await Lv(l);if(_===void 0||_!==d+l){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(xd.notify("Removing component",u),c=!0);c&&(xd.notify("Updating components."),await Mv(r,s))}a(y7,"installComponents");function I7(){let e=b7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(I7,"getComponentsConfig");async function Lv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":MT.extname(e)||await Vd.pathExists(e)?"file:":"github:"}a(Lv,"getPkgPrefix");async function Mv(e,t){xd.trace("npm installing components package.json",t),await Vd.writeFile(e,JSON.stringify(t,null," ")),await W_().installAllRootModules(Pv.get(kd.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}a(Mv,"installPackages")});var vT=m((dde,qv)=>{var{isMainThread:Hv}=require("worker_threads"),{getTables:w7}=(de(),ee(Ne)),{loadComponentDirectories:C7,loadComponent:U7}=(Uv(),ee(Cv)),{resetResources:D7}=(bc(),ee(RD)),L7=Bv(),M7=Nr(),{dirname:P7}=require("path"),{getConnection:v7}=it(),B7=Q(),H7=A(),PT=new Map;async function q7(e=!1){!Hv&&B7.get(H7.CONFIG_PARAMS.CLUSTERING_ENABLED)&&v7(),Hv&&await L7();let t=D7();w7(),t.isWorker=e,await U7(P7(M7.getConfigFilePath()),t,"hdb",!0,PT),await C7(PT,t);let r=[];for(let[s]of PT)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(q7,"loadRootComponents");qv.exports.loadRootComponents=q7});var nt=m((hde,vn)=>{"use strict";var{Worker:F7,MessageChannel:G7,parentPort:gs,isMainThread:GT,threadId:x7,workerData:jc}=require("worker_threads"),{PACKAGE_ROOT:k7}=A(),{join:xv,isAbsolute:V7,extname:Yd}=require("path"),{server:$7}=(Pr(),ee(da)),{watch:Y7,readdir:K7}=require("fs/promises"),{totalmem:Fv}=require("os"),xT=A(),wi=x(),fde=A(),{randomBytes:W7}=require("crypto"),Q7=1024*1024,Pn=[],Mn=[],z7=50,kv=1e4,J7="restart",Vv="request_thread_info",$v="resource_report",Yv="thread_info",Kv="added-port",X7="ack",BT;vn.exports={startWorker:HT,restartWorkers:kT,shutdownWorkers:tee,workers:Pn,setMonitorListener:uee,onMessageFromWorkers:ree,onMessageByType:see,broadcast:nee,broadcastWithAcknowledgement:oee,setChildListenerByType:eee,getWorkerIndex:Qv,getTicketKeys:zv,setMainIsWorker:Z7,restartNumber:jc?.restartNumber||1};var Wv;function Qv(){return jc?jc.workerIndex:Wv?0:void 0}a(Qv,"getWorkerIndex");function Z7(e){Wv=e}a(Z7,"setMainIsWorker");var $d;function zv(){return $d||($d=GT?W7(48):jc.ticketKeys,$d)}a(zv,"getTicketKeys");Object.defineProperty($7,"workerIndex",{get(){return Qv()}});var Jv={[Vv](e,t){aee(t)},[$v](e,t){cee(t,e)}};function HT(e,t={}){let r=process.constrainedMemory?.()||Fv();r=Math.min(r,Fv());let s=Math.max(Math.floor(r/Q7/(1+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>7,16),64),i=[];for(let c of Mn){let{port1:u,port2:l}=new G7;c.postMessage({type:Kv,port:u},[u]),i.push(l)}Yd(e)||(e+=".js");let o=new F7(V7(e)?e:xv(k7,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:i,workerIndex:t.workerIndex,name:t.name,restartNumber:vn.exports.restartNumber,ticketKeys:zv()},transferList:i},t));return Wd(o,!0),o.unexpectedRestarts=t.unexpectedRestarts||0,o.startCopy=()=>{HT(e,t)},o.on("error",c=>{console.error("Worker error:",c),wi.error("Worker error:",c)}),o.on("exit",c=>{Pn.splice(Pn.indexOf(o),1),!o.wasShutdown&&t.autoRestart!==!1&&(o.unexpectedRestarts<z7?(t.unexpectedRestarts=o.unexpectedRestarts+1,HT(e,t)):wi.error(`Thread has been restarted ${o.restarts} times and will not be restarted`))}),o.on("message",c=>{Jv[c.type]?.(c,o)}),Pn.push(o),_ee(),t.onStarted&&t.onStarted(o),o.name=t.name,o}a(HT,"startWorker");var j7=[xT.THREAD_TYPES.HTTP];async function kT(e=null,t=2,r=!0){if(GT){if(r){let{loadRootComponents:n}=vT();await n()}vn.exports.restartNumber++,t<1&&(t=t*Pn.length);let s=[];for(let n of Pn.slice(0)){if(e&&n.name!==e||n.wasShutdown)continue;n.postMessage({restartNumber:vn.exports.restartNumber,type:xT.ITC_EVENT_TYPES.SHUTDOWN}),n.wasShutdown=!0,n.emit("shutdown",{});let i=j7.indexOf(n.name)>-1,o=new Promise(c=>{let u=setTimeout(()=>n.terminate(),kv*2).unref();n.on("exit",()=>{clearTimeout(u),s.splice(s.indexOf(o)),!i&&r&&n.startCopy(),c()})});s.push(o),i&&r&&(n.startCopy(),s.length>=t&&await Promise.race(s))}await Promise.all(s)}else gs.postMessage({type:J7,workerType:e})}a(kT,"restartWorkers");function eee(e,t){Jv[e]=t}a(eee,"setChildListenerByType");function tee(e){return kT(e,1/0,!1)}a(tee,"shutdownWorkers");var Xv=[];function ree(e){Xv.push(e)}a(ree,"onMessageFromWorkers");var qT=new Map;function see(e,t){let r=qT.get(e);r||qT.set(e,r=[]),r.push(t)}a(see,"onMessageByType");function nee(e){for(let t of Mn)try{t.postMessage(e)}catch(r){wi.error("Unable to send message to worker",r)}}a(nee,"broadcast");var Kd=new Map,iee=1;function oee(e){return new Promise(t=>{let r=0;for(let s of Mn)try{let n=iee++,i=a(()=>{Kd.delete(n),--r===0&&t(),s!==gs&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,Kd.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of Kd)o.port===s&&o()})),s.postMessage(e),r++}catch(n){wi.error("Unable to send message to worker",n)}r===0&&t()})}a(oee,"broadcastWithAcknowledgement");function aee(e){e.postMessage({type:Yv,workers:Zv()})}a(aee,"sendThreadInfo");function Zv(){let e=Date.now();return Pn.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(Zv,"getChildWorkerInfo");function cee(e,t){e.resources=t,e.resources.updated=Date.now()}a(cee,"recordResourceReport");var FT;function uee(e){FT=e}a(uee,"setMonitorListener");var lee=1e3,Gv=!1;function _ee(){Gv||(Gv=!0,setInterval(()=>{for(let e of Pn){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}FT&&FT()},lee).unref())}a(_ee,"startMonitoring");var dee=1e3;if(gs){Wd(gs);for(let e of jc.addPorts)Wd(e);setInterval(()=>{let e=process.memoryUsage();gs.postMessage({type:$v,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},dee).unref(),BT=a(()=>new Promise((e,t)=>{gs.on("message",r),gs.postMessage({type:Vv});function r(s){s.type===Yv&&(gs.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else BT=Zv;vn.exports.getThreadInfo=BT;function Wd(e,t){Mn.push(e),e.on("message",r=>{if(r.type===Kv)Wd(r.port);else if(r.type===X7){let s=Kd.get(r.id);s&&s()}else{for(let n of Xv)n(r,e);let s=qT.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){wi.error(i)}}}).on("close",()=>{Mn.splice(Mn.indexOf(e),1)}).on("exit",()=>{Mn.splice(Mn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(Wd,"addPort");if(GT){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await K7(s,{withFileTypes:!0}))i.isDirectory()&&r(xv(s,i.name));for await(let{filename:i}of Y7(s,{persistent:!1}))(Yd(i)===".ts"||Yd(i)===".js"||Yd(i)===".graphql")&&(t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await kT(),wi.info("Reloaded HarperDB components")},100))},"watch_dir");vn.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else gs.on("message",async e=>{let{type:t}=e;t===xT.ITC_EVENT_TYPES.SHUTDOWN&&(vn.exports.restartNumber=e.restartNumber,gs.unref(),setTimeout(()=>{wi.warn("Thread did not voluntarily terminate",x7),process.exit(0)},kv).unref())})});function WT(e){let t=e.auditStore=e.openDB(sB.AUDIT_STORE_NAME,fee);t.rootStore=e;let r=[];return t.addDeleteRemovalCallback=function(s,n){return r[s]=n,{remove(){delete r[s]}}},(0,iB.getWorkerIndex)()===0&&e.on("aftercommit",()=>{$T||($T=setTimeout(()=>{if($T=null,t.rootStore.status!=="closed")for(let{key:s,value:n}of t.getRange({start:[0,0],end:[Date.now()-jv,0]})){if((n[0]&15)===KT){let i=s[1];r[i]?.(s[2])}t.remove(s)}},jv/10).unref())}),t}function Jd(e,t,r){let s=cB[r.type],n=3;if(t?t.length>80?(s|=Qd,n=(0,nn.writeKey)(t,As,e?14:6),VT.setUint16(2,n)):(n=(0,nn.writeKey)(t,As,e?11:3),As[1]=n):As[1]=0,e){s|=aB;let i=s&Qd?6:3;VT.setFloat64(i,e),t||(n=i+8)}return As[0]=s,s&Qd?VT.setUint16(4,0):As[2]=0,r.value?Buffer.concat([As.slice(0,n),r.value]):As.subarray(0,n)}function Bn(e,t){let r=e[0],s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)),n=r&Qd,i=n?6:3,o;r&aB&&(o=s.getFloat64(i),i+=8);let c;n?c=s.getUint16(2):c=e[1];let u=r&YT?t.decoder.decode(e.subarray(c||i)):void 0;return{type:cB[r&7],value:u,lastVersion:o,get user(){return c?(0,nn.readKey)(e,i,c):void 0}}}var nn,zd,sB,nB,iB,oB,As,VT,Eee,fee,jv,$T,YT,eB,KT,tB,rB,Qd,aB,cB,eu=Se(()=>{nn=require("ordered-binary"),zd=C(Q()),sB=C(xe()),nB=C(A()),iB=C(nt()),oB=C(V());(0,zd.initSync)();As=Buffer.alloc(1024),VT=new DataView(As.buffer,As.byteOffset,1024),Eee={writeKey(e,t,r){if(Array.isArray(e)){let s=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength));return s.setFloat64(r,e[0]),s.setUint32(r+8,e[1]),(0,nn.writeKey)(e[2],t,r+12)}else return(0,nn.writeKey)(e,t,r)},readKey(e,t,r){if(e[t]>40){let s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength));return[s.getFloat64(t),s.getUint32(t+8),(0,nn.readKey)(e,t+12,r)]}else return(0,nn.readKey)(e,t,r)}},fee={encoding:"binary",keyEncoder:Eee},jv=(0,oB.convertToMS)((0,zd.get)(nB.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,$T=null;a(WT,"openAuditStore");YT=16,eB=1,KT=2,tB=3,rB=4,Qd=128,aB=64,cB={put:eB|YT,[eB]:"put",delete:KT,[KT]:"delete",message:tB|YT,[tB]:"message",invalidate:rB,[rB]:"invalidate"};a(Jd,"createAuditEntry");a(Bn,"readAuditEntry")});var QT,Ci,hee,tu,Xd,uB=Se(()=>{QT=C(vt());eu();Ci=Symbol("completion"),hee=100,tu=class{static{a(this,"DatabaseTransaction")}writes=[];hasWrittenTime;username;lmdbDb;auditStore;readTxn;constructor(t,r,s){this.lmdbDb=t,this.username=r?.username,this.auditStore=s}getReadTxn(){return this.readTxn||(this.readTxn=this.lmdbDb.useReadTransaction())}resetReadSnapshot(){this.readTxn&&(this.readTxn.done(),this.readTxn=null)}addWrite(t){this.writes.push(t)}validate(){for(let t of this.writes||[])t.validate?.()}commit(t=(0,QT.getNextMonotonicTime)(),r=!0,s=0){this.resetReadSnapshot();let n,i=[],o=0,c;this.hasWrittenTime=!1;let u=a(_=>{let d=_.commit(t,s);if(d&&(d[Ci]&&(i||(i=[]),i.push(d[Ci])),c=_.store,this.auditStore)){d.user=this.username,d.lastVersion=_.lastVersion,d.newTxnTime&&!this.hasWrittenTime&&(t=d.newTxnTime),this.hasWrittenTime=!0;let E=[t,_.store.tableId,_.key];_.invalidated&&(E.invalidated=!0),this.auditStore.put(E,Jd(_.lastVersion,this.username,d))}},"doWrite"),l=a(()=>{let _=this.writes[o++];if(_)if(_.key){let d=_.store.getEntry(_.key),E=s===0&&_.lastVersion!==void 0?_.lastVersion:_.lastVersion=d?.version??null,f=_.store.ifVersion(_.key,E,l);n=n||f}else l();else for(let d of this.writes)u(d)},"nextCondition");return this.writes.length<hee>>s?l():(s=1,n=this.writes[0].store.transaction(()=>{for(let _ of this.writes)u(_);return!0})),n?.then(_=>_?(c&&i.push(c.flushed),Promise.all(i).then(()=>(this.writes=[],{txnTime:t}))):this.commit(t,r,s+1))}abort(){this.resetReadSnapshot(),this.writes=[]}},Xd=class extends tu{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit(this.timestamp)}get timestamp(){return this._timestamp||(this._timestamp=(0,QT.getNextMonotonicTime)())}getReadTxn(){}}});function EB(e,t,r,s,n){let i=e.primaryStore.env.path,o=e.primaryStore.tableId;Go||((0,Ui.onMessageByType)(_B,d=>{let E=d.auditIds;JT(d.path,E,d.txnId)}),(0,Ui.onMessageByType)(dB,d=>{(0,Os.trace)("confirming to proceed with txn",d.txnId)}),Go=Object.create(null));let c=Go[i]||(Go[i]=[]);c.auditStore=e.auditStore;let u=c[o];u||(u=c[o]=new Map,u.envs=c,u.tableId=o,u.store=e.primaryStore),t=go(t);let l=new zT(r);l.startTime=s,n&&(l.includeDescendants=n);let _=u.get(t);return _?_.push(l):(u.set(t,_=[l]),_.tables=u,_.key=t),l.subscriptions=_,l}function JT(e,t,r,s){if(!Go)return;let n=Go[e];if(n){if(Fo&&Fo+1!==r){(0,Os.trace)("Waiting to ensure latest txn id",Fo,"proceeds",r,s);let i=(async()=>{for(let[o,c]of Zd)o<r&&((0,Os.trace)("Txn",r,"waiting for txn",o),await c);if(Fo+1!==r){await(0,Ui.broadcastWithAcknowledgement)({type:dB,txnId:r});for(let[o,c]of Zd)o<r&&((0,Os.trace)("Txn",r,"waiting for txn",o),await c)}Zd.delete(r),(0,Os.trace)("Proceeding with txn id",r),Fo=r-1,JT(e,t,r,s)})();return Zd.set(r,i),i}(0,Os.trace)("Notifying with txn id",r,s),Fo=r;try{n.auditStore.resetReadTxn()}catch(i){throw i.message+=" in "+e,i}e:for(let i of t){let[o,c,u]=i,l=n[c];if(!l)continue;(0,lB.writeKey)(i,See,0);let _=i[3];_&&(i.length=3);let d,E=go(u),f;do{let h=l.get(E);if(h){for(let p of h)if(!(f&&!p.includeDescendants)){if(p.startTime>=o){(0,Os.info)("omitting",u,p.startTime,o);continue}try{if(p.crossThreads===!1&&!s)continue;if(d===void 0){let R=n.auditStore.get(i);if(!R||(d=Bn(R,l.store),d.type!=="message"&&l.store.getEntry(i[2])?.version!==i[0])||_&&d.type!=="invalidate")continue e}p.listener(u,d,o)}catch(R){console.error(R),(0,Os.info)(R)}}}if(E==null)break;let T=E.lastIndexOf?.("/",E.length-2);T>-1?E=E.slice(0,T+1):E=null,f=!0}while(!0)}}}function fB(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",({next:i,last:o,txnId:c})=>{let u,l=[];if(t)do{if(i.flag&mee)continue;let _;i.meta&&i.meta.store===t&&(_=i.meta.key)&&(typeof _[2]=="symbol"&&(_[2]=null),_.invalidated&&(_[3]=!0),l.push(_))}while(i!=o&&(i=i.next));l.length!==0&&((0,Ui.broadcast)({type:_B,path:n,auditIds:l,txnId:c,start:u}),JT(n,l,c,!0))})}}var Os,Ui,lB,_B,dB,mee,Go,See,zT,Fo,Zd,hB=Se(()=>{Os=C(x()),Ui=C(nt()),lB=require("ordered-binary");ua();bc();eu();_B="transaction",dB="transaction-await",mee=67108864,See=Buffer.alloc(4096);a(EB,"addSubscription");zT=class extends Xr{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"}}},Zd=new Map;a(JT,"notifyFromTransactionData");a(fB,"listenToCommits")});var Yp={};Ye(Yp,{coerceType:()=>jd,makeTable:()=>tE,setServerUtilities:()=>Aee});function tE(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:l,dbisDB:_}=e,{expirationMS:d,audit:E,trackDeletes:f}=e,{attributes:h}=e;h||(h=[]),fB(i,u);let T=0,p,R,O,k={},$,U,b,P;for(let Z of h)(Z.assignCreatedTime||Z.name==="__createdtime__")&&($=Z),(Z.assignUpdatedTime||Z.name==="__updatedtime__")&&(U=Z),Z.expiresAt&&(b=Z),Z.isPrimaryKey&&(k=Z);let z;E&&mR();class q extends ht{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=h;static expirationTimer;static createdTimeProperty=$;static updatedTimeProperty=U;static dbisDB=_;static schemaDefined=l;static sourcedFrom(S,N){if(N&&(this.sourceOptions=N,N.expiration&&this.setTTLExpiration(N.expiration)),this.Source)if(this.Source.mergeSource)this.Source=this.Source.mergeSource(S,this.sourceOptions);else if(S.mergeSource)this.Source=S.mergeSource(this.Source,this.sourceOptions);else throw new Error("Can not assign multiple sources to a table with no source providing a (static) mergeSource method");else this.Source=S;return R=S&&S.get&&(!S.get.reliesOnPrototype||S.prototype.get),(async()=>{let D=!1,y=a(async w=>{let v=w.value,F=w.table?Pe[c][w.table]:q;if(c===zr.SYSTEM_SCHEMA_NAME&&(w.table===zr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||w.table===zr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),w.id===void 0&&(w.id=v[F.primaryKey],w.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(w));let L=await F.getResource(w.id,w,ru);switch(w.type){case"put":return L._writeUpdate(v,ru);case"delete":return L._writeDelete(ru);case"publish":return L._writePublish(v,ru);case"invalidate":return L.invalidate(ru);default:Mi.error("Unknown operation",w.type,w.id)}},"writeUpdate");try{let w=S.subscribe&&(!S.subscribe.reliesOnPrototype||S.prototype.subscribe);w&&f==null&&(f=!0);let v=S.subscribeOnThisThread?S.subscribeOnThisThread((0,Li.getWorkerIndex)()):(0,Li.getWorkerIndex)()===0,F=w&&v&&await S.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(F)for await(let L of F)try{if(!(L.type==="transaction"?L.writes[0]:L)){console.error("Bad subscription event");continue}let X=Ke(L,()=>{if(L.type==="transaction"){let J=[];for(let Y of L.writes){Y[Ae]=L;try{J.push(y(Y))}catch(j){throw j.message+=" writing "+JSON.stringify(Y)+" of event "+JSON.stringify(L),j}}return Promise.all(J)}else if(L.type==="define_schema"){let J=this.attributes.slice(0),Y;for(let j of L.attributes)J.find(De=>De.name===j.name)||(J.push(j),Y=!0);Y&&(rt({table:n,database:c,attributes:J,origin:"cluster"}),iu.signalSchemaChange(new ou.SchemaEventMsg(process.pid,zr.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return y(L)});L.onCommit&&(X?.then&&D&&iu.signalUserChange(new ou.UserEventMsg(process.pid)),X?.then?X.then(L.onCommit):L.onCommit())}catch(G){console.error("error in subscription handler",G)}}catch(w){console.error(w)}})(),this}static getResource(S,N,D){let y=super.getResource(S,N,D);if(S!=null)try{if(y.hasOwnProperty(ce))return y;let w=y._txnForRequest();if(typeof S=="object"&&S&&!Array.isArray(S))throw new Error(`Invalid id ${JSON.stringify(S)}`);let v,F,G={transaction:w?.getReadTxn()},X;return Eu(S,N,G,y,D?.allowInvalidated,(J,Y)=>{Y?F(Y):(y[ce]=J?.value,y[Zt]=J?.version,X=!0,v?.(y))}),X?y:new Promise((J,Y)=>{v=J,F=Y})}catch(w){throw w.message.includes("Unable to serialize object")&&(w.message+=": "+JSON.stringify(S)),w}return y}static setTTLExpiration(S){(0,Li.getWorkerIndex)()===0&&(d=S*1e3,this.expirationTimer&&clearInterval(this.expirationTimer),this.expirationTimer=setInterval(()=>{if(this.primaryStore.rootStore.status!=="open")return clearInterval(this.expirationTimer);for(let{key:N,value:D,version:y}of this.primaryStore.getRange({start:!1,versions:!0}))y<Date.now()-d&&y>0&&D?.__invalidated__==null&&q.evict(N,D,y)},d).unref())}static enableAuditing(){E=!0,mR(),q.audit=!0}static coerceId(S){return S===""?null:jd(S,k)}static async dropTable(){if(delete Pe[c][n],c===o){for(let S in r)_.remove(q.tableName+"/"+S),r[S].drop();_.remove(q.tableName+"/"),i.drop(),await _.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));iu.signalSchemaChange(new ou.SchemaEventMsg(process.pid,zr.OPERATIONS_ENUM.DROP_TABLE,c,n))}static Source;static get(S,N){return S&&typeof S=="object"&&!Array.isArray(S)&&S.url===""?{recordCount:this.getRecordCount(),records:"./",name:n,database:c,attributes:h}:super.get(S,N)}get(S){if(typeof S=="string")return this.getProperty(S);if(this[Ds])return this.search(S);if(S?.property)return this.getProperty(S.property);if(this.doesExist()||this[Ae]?.hasOwnProperty("returnNonexistent")&&this[Ae].returnNonexistent)return this}static allowRead(S,N){if(!S)return!1;let D=S.role.permission;if(D.super_user)return!0;if(D[n]?.read){let y=D[n].attribute_permissions;if(y){N||(N={});let w=N.select;if(w){let v=XT(y,"read");N.select=w.filter(F=>v[F])}else N.select=y.filter(v=>v.read).map(v=>v.attribute_name);return N}else return!0}}allowUpdate(S,N,D){if(!S)return!1;let y=S.role.permission;if(y.super_user)return!0;if(y[n]?.update){let w=y[n].attribute_permissions;if(w){let v=XT(w,"update");for(let F in N)if(!v[F])return!1;if(D)for(let F of w){let L=F.attribute_name;!F.update&&!(L in N)&&(N[L]=this.getProperty(L))}}else return!0}}allowCreate(S,N){return this.allowUpdate(S,{})}static allowCreate(S,N){if(!S)return!1;let D=S.role.permission;if(D.super_user)return!0;if(D[n]?.insert){let y=D[n].attribute_permissions;if(y){let w=XT(y,"insert");for(let v in N)if(!w[v])return!1}else return!0}}static allowDelete(S){if(!S)return!1;let N=S.role.permission;if(N.super_user||N[n]?.delete)return!0}update(S,N){if(!this._txnForRequest())throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;let y;if(typeof S=="object"&&S){if(N)for(let w in this[ce])S[w]===void 0&&(S[w]=void 0);y=this[ft],y&&(S=Object.assign(y,S)),this[ft]=y=S}return!this[ce]&&t&&!(y||(y=this[ft]))?.[t]&&(y||(y=this[ft]=Object.create(null)),y[t]=this[ae]),this._writeUpdate(this),this}invalidate(S){this._txnForRequest().addWrite({key:this[ae],store:i,invalidated:!0,lastVersion:this[Zt],nodeName:this[Ae]?.nodeName,commit:(D,y)=>{if(y)return;let w={__invalidated__:D};for(let G in r)w[G]=this.getProperty(G);let v=q.Source,F,L=this[ae];return S?.isNotification||v?.shouldReceiveInvalidations&&(F=v.invalidate(L,this)),i.put(this[ae],w,D),{type:E&&"invalidate",[Ci]:F}}})}static evict(S,N,D){let y=this.Source;if(y?.get&&(!y.get.reliesOnPrototype||y.prototype.get)){let w;if(!N){let v=i.getEntry(S);if(!v)return;N=v.value,D=v.version}if(N)for(let v in r)w||(w={__invalidated__:0}),w[v]=N[v];return w?i.put(S,w,D,D):i.remove(S,D)}else return i.remove(S,D)}lock(){throw new Error("Not yet implemented")}static operation(S,N){return S.table||=n,S.schema||=c,NB.operation(S,N)}async put(S){this.update(S,!0)}_writeUpdate(S,N){let D=this._txnForRequest();if(this[ae]===void 0)throw new Error("Can not save record without an id");let y=this[ce],w,v,F=this[ae];y||(this[ce]={}),D.addWrite({key:F,store:i,lastVersion:this[Zt],nodeName:this[Ae]?.nodeName,validate:()=>{this.validate(S)},commit:(L,G)=>{let X;if(G){if(w)return;let Y=i.getEntry(F);y=Y?.value;let j=this[Ae];j&&Y?.version>(j.lastModified||0)&&(j.lastModified=Y.version)}if(!v){if(v=!0,N?.isNotification)S=_a(S);else{if(S[pB]&&(w=!wu(S),w))return;t&&S[t]!==F&&(S[t]=F),U&&(S[U.name]=U.type==="Date"?new Date(L):U.type==="String"?new Date(L).toISOString():L),$&&(y?S[$.name]=y[$.name]:S[$.name]=$.type==="Date"?new Date(L):$.type==="String"?new Date(L).toISOString():L),S=_a(S);let Y=q.Source;Y?.put&&(!Y.put.reliesOnPrototype||Y.prototype.put)&&(X=Y.put(F,S,this))}if(S[ce])throw new Error("Can not assign a record with a record property");this[ce]=S}if(Mi.trace("Checking timestamp for put",F,this[Zt]>L,this[Zt],L),this[Zt]>L)return E&&{type:"put",value:i.encoder.encode(S)};let J=i.encoder.encode(S);return i.put(this[ae],(0,xo.asBinary)(J),L),je(this[ae],y,S),y===null&&!G&&xn(-1),{type:E&&"put",value:J,[Ci]:X}}})}async delete(S){return typeof S=="string"?this.deleteProperty(S):this[ce]?this._writeDelete(S):!1}_writeDelete(S){let N=this._txnForRequest(),D,y=this[ae],w;return N.addWrite({key:y,store:i,lastVersion:this[Zt],nodeName:this[Ae]?.nodeName,commit:(v,F)=>{let L=this[ce];if(F){let G=i.getEntry(y);L=G?.value;let X=this[Ae];X&&G?.version>(X.lastModified||0)&&(X.lastModified=G.version)}if(!D&&(D=!0,!S?.isNotification)){let G=q.Source;G?.delete&&(!G.delete.reliesOnPrototype||G.prototype.delete)&&(w=G.delete(y,this))}if(!(this[Zt]>v))return je(this[ae],L),Mi.trace("Write delete entry",E||f,v),E||f?(i.put(this[ae],null,v),E||hR(),F||xn(1)):i.remove(this[ae]),{type:E&&"delete",[Ci]:w}}}),!0}search(S){let N=this._txnForRequest();if(!S)throw new Error("No query provided");let D=S.reverse===!0,y=S.conditions;y?y.length===void 0&&(y=Array.from(y)):y=Array.isArray(S)?S:S[Symbol.iterator]?Array.from(S):[],this[ae]&&(y=[{attribute:null,comparator:"prefix",value:this[ae]}].concat(y));for(let Y of y){let j=Y[0]??Y.attribute,De=j==null?k:h.find(an=>an.name==j);if(De)De.type&&(Y[1]===void 0?Y.value=w(Y.value,De):Y[1]=w(Y[1],De));else if(j!=null)throw(0,Di.handleHDBError)(new Error,`${j} is not a defined attribute`,404)}function w(Y,j){return Array.isArray(Y)?Y.map(De=>jd(De,j)):jd(Y,j)}a(w,"coerceTypedValues"),y.length>1&&(y=(0,AB.sortBy)(y,Y=>{if(Y.estimated_count===void 0){let j=Y.comparator||Y.search_type;if(j===su.SEARCH_TYPES.EQUALS){let De=Y[0]??Y.attribute;if(De==null||De===t)Y.estimated_count=1;else{let an=r[De];Y.estimated_count=an?an.getValuesCount(Y[1]??Y.value):1/0}}else j===su.SEARCH_TYPES.CONTAINS||j===su.SEARCH_TYPES.ENDS_WITH||j==="ne"?Y.estimated_count=1/0:j===su.SEARCH_TYPES.STARTS_WITH||j==="prefix"?Y.estimated_count=Tee:Y.estimated_count=pee}return Y.estimated_count}));let v=N.getReadTxn();v.use();let F=S.select,L=y[0],G;if(!L)G=i.getRange(D?{end:!1,reverse:!0,transaction:v,lazy:F?.length<4}:{start:!1,transaction:v,lazy:F?.length<4}).map(({value:Y})=>Y?new Promise(j=>setImmediate(()=>j(Y))):xo.SKIP);else{let Y=GE(L,v,D,q,S.allowFullScan);if(!S.operator||S.operator.toLowerCase()==="and"){let j=y.slice(1).map(xE);G=J(Y,j)}else{for(let De=1;De<y.length;De++){let an=y[De],SE=GE(an,v,D,q,S.allowFullScan);Y=Y.concat(SE)}let j=new Set;Y=Y.filter(De=>j.has(De)?!1:(j.add(De),!0)),G=J(Y)}}(S.offset||S.limit!==void 0)&&(G=G.slice(S.offset,S.limit!==void 0?(S.offset||0)+S.limit:void 0)),G.onDone=()=>{v.done()};let X=this[Ae];function J(Y,j){let De=j?.length,an={transaction:v,lazy:De>0||F?.length<4,alwaysPrefetch:!0};return Y.map(SE=>new Promise(pE=>Eu(SE,X,an,null,!1,ZB=>{let TE=ZB?.value;if(!TE)return pE(xo.SKIP);for(let RE=0;RE<De;RE++)if(!j[RE](TE))return pE(xo.SKIP);pE(TE)})))}return a(J,"idsToRecords"),G}async subscribe(S){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||rt({table:n,database:c,schemaDefined:l,attributes:h,audit:!0});let N=EB(q,this[ae]??null,function(v,F,L){try{this.send({id:v,timestamp:L,...F})}catch(G){console.error(G)}},S.startTime,this[Ds]),D=this[ae],y=S.previousCount;y>1e3&&(y=1e3);let w=S.startTime;if(this[Ds]){if(w){if(y)throw new Di.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:v,value:F}of u.getRange({start:[w,Number.MAX_SAFE_INTEGER]})){let[L,G,X]=v;if(v.length>3&&(X=v.slice(2)),G!==s)continue;let J=Bn(F,i);(D==null||gB(D,X))&&N.send({id:X,timestamp:L,...J}),N.startTime=L}}else if(y){let v=[];for(let{key:F,value:L}of u.getRange({start:"z",end:!1,reverse:!0}))try{let[G,X,J]=F;if(F.length>3&&(J=F.slice(2)),X!==s)continue;if(D==null||gB(D,J)){let Y=Bn(L,i);if(v.push({id:J,timestamp:G,...Y}),--y<=0)break}}catch(G){Mi.error("Error getting history entry",F,G)}for(let F=v.length;F>0;)N.send(v[--F]);v[0]&&(N.startTime=v[0].timestamp)}else if(!S.omitCurrent)for(let{key:v,value:F,version:L}of i.getRange({start:D??!1,end:D==null?void 0:[D,OB.MAXIMUM_KEY],versions:!0}))F&&N.send({id:v,timestamp:L,value:F})}else{y&&!w&&(w=0);let v=this[Zt];if(w<v){let F=[],L=v;do{let G=[L,s,D],X=u.get(G);if(X){S.omitCurrent=!0;let J=Bn(X,i);F.push({id:D,timestamp:L,...J}),L=J.lastVersion}else break;y&&y--}while(L>w&&y!==0);for(let G=F.length;G>0;)N.send(F[--G]);N.startTime=v}!S.omitCurrent&&this.doesExist()&&N.send({id:D,timestamp:this[Zt],value:this})}return S.listener&&N.on("data",S.listener),N}doesExist(){return!!this[ce]}async publish(S,N){this._writePublish(S,N)}_writePublish(S,N){let D=this._txnForRequest(),y=this[ae]||null,w,v;D.addWrite({store:i,key:y,lastVersion:this[Zt],nodeName:this[Ae]?.nodeName,validate:()=>{this.validate(S)},commit:(F,L)=>{if(this.validate(S),!v&&(v=!0,!N?.isNotification)){let J=q.Source;J?.publish&&(!J.publish.reliesOnPrototype||J.prototype.publish)&&(w=J.publish(y,S,this))}let G=L>0?i.get(y):this[ce];G===void 0&&!L&&(E||f)&&(E||hR(),xn(1));let X={type:"message",value:i.encoder.encode(S),[Ci]:w};return!D.hasWrittenTime&&this[Zt]>F&&(F=X.newTxnTime=this[Zt]+.001),i.put(y,G??null,F),X}})}_txnForRequest(){let S=this[Ae],N=S?.transaction;if(N){let D;return(D=N?.find(y=>y.lmdbDb?.path===i.path))||N.push(D=new tu(i,S.user,u)),D}else return new Xd(i,S.user,u)}validate(S){let N;for(let D=0,y=h.length;D<y;D++){let w=h[D];if(w.type){let v=S[w.name];if(v!=null)switch(w.type){case"Int":case"Float":(typeof v!="number"||w.type==="Int"&&v!==Math.floor(v))&&(N||(N=[])).push(`Property ${w.name} must be an ${w.type==="Int"?"integer":"number"}`);break;case"ID":typeof v=="string"||v?.length>0&&v.every?.(F=>typeof F=="string")||(N||(N=[])).push(`Property ${w.name} must be a string, number, or an array (of strings and numbers)`);break;case"String":typeof v!="string"&&(N||(N=[])).push(`Property ${w.name} must be a string`)}}w.required&&S[w.name]==null&&(N||(N=[])).push(`Property ${w.name} is required`)}if(N)throw new Di.ClientError(N.join(". "))}getUpdatedTime(){return this[Zt]}wasLoadedFromSource(){return R?!!this[TB]:void 0}static async addAttributes(S){let N=h.slice(0);for(let D of S){if(!D.name)throw new Di.ClientError("Attribute name is required");if(D.name.match(/[`/]/))throw new Di.ClientError("Attribute names cannot include backticks or forward slashes");N.push(D)}return rt({table:n,database:c,schemaDefined:l,attributes:N}),q.indexingOperation}static async removeAttributes(S){let N=h.filter(D=>!S.includes(D.name));return rt({table:n,database:c,schemaDefined:l,attributes:N}),q.indexingOperation}static getRecordCount(){let S=0;for(let{key:N,value:D}of i.getRange({end:!1}))S++,N[0]?.description==="deletions"&&(S+=D||0);return i.getStats().entryCount-S}static updatedAttributes(){Uu(this,this)}static async deleteHistory(S=0){let N;for(let{key:D,value:y}of u.getRange({start:[0,0],end:[S,0]})){await new Promise(L=>setImmediate(L));let[w,v,F]=D;D.length>3&&(F=D.slice(2)),v===s&&(N=i.remove(F))}await N}static async*getHistory(S=0,N=1/0){for(let{key:D,value:y}of u.getRange({start:[S,0],end:[N,0]})){await new Promise(G=>setImmediate(G));let[w,v,F]=D;if(D.length>3&&(F=D.slice(2)),v!==s)continue;let L=Bn(y,i);L.id=F,L.timestamp=w,yield L}}static async getHistoryOfRecord(S){let N=[],D=i.getEntry(S);if(!D)return N;let y=D.version,w=0;do{await new Promise(L=>setImmediate(L));let v=[y,s,S],F=u.get(v);if(F){let L=Bn(F,i);L.timestamp=y,N.push(L),y=L.lastVersion}else break}while(w<1e3);return N.reverse()}static cleanup(){z?.remove()}}q.updatedAttributes();let Oe=q.prototype;return Oe[pB]=!0,d&&q.setTTLExpiration(d/1e3),b&&XB(),q;function je(Z,S,N){let D;for(let y in r){let w=r[y],v=w.isIndexing,F=N?.[y],L=S?.[y];if(F===L&&!v)continue;D=!0;let G=(0,nu.getIndexedValues)(L);if(G){mB&&w.prefetch(G.map(X=>({key:X,value:Z})),RB);for(let X=0,J=G.length;X<J;X++)w.remove(G[X],Z)}if(G=(0,nu.getIndexedValues)(F),G){mB&&w.prefetch(G.map(X=>({key:X,value:Z})),RB);for(let X=0,J=G.length;X<J;X++)w.put(G[X],Z)}}return D}a(je,"updateIndices");function Eu(Z,S,N,D,y,w){let v=a(()=>{let F=N.transaction;if(F?.isDone)throw new Error("Invalid read transaction");let L;F&&!F.hasRunLoadRecord&&(L=!0,F.hasRunLoadRecord=!0);let G;try{G=i.getEntry(Z,N)}catch(j){throw j.message+=". The read txn is "+JSON.stringify(F)+" first loadRecord: "+L,console.error(j),console.error("reader list",i.readerList()),console.error("reader check",i.readerCheck()),console.error("reader list",i.readerList()),j}let X,J,Y;if(G?(S&&G?.version>(S.lastModified||0)&&(S.lastModified=G.version),J=G.version,X=G.value,(J<0||!X||typeof X.__invalidated__=="number"||d&&J<Date.now()-d)&&(Y=!0)):Y=!0,R&&no(Y,"cache-hit",n),Y&&!y&&(D&&(D[TB]=!0),R))return Qo(Z,X,J,S).then(j=>{if(j?.value?.[ce])throw new Error("Can not assign a record with a record property");S&&j?.version>(S.lastModified||0)&&(S.lastModified=j.version),w(j)},j=>{w(null,j)});if(G?.value?.[ce])throw new Error("Can not assign a record with a record property");w(G)},"whenPrefetched");if(!N.alwaysPrefetch&&(Z==null||i.cache?.get(Z)))return v();i.prefetch([Z],v)}a(Eu,"loadRecord");function Bi(){P=new Set,(0,Li.onMessageByType)("transaction",Z),i.on("aftercommit",Z);function Z(){for(let S of P)S()}a(Z,"onCommit")}a(Bi,"setupCommitListeners");async function Qo(Z,S=null,N,D){if(N<0){let L;return P||Bi(),await new Promise(G=>{let X,J=a(()=>{if(L=i.getEntry(Z),!L||L.version>0){if(clearTimeout(X),P.delete(J),typeof L?.value?.__invalidated__=="number")return G(Qo(Z,L.value,L.version,D));G(L)}},"listener");P.add(J),X=setTimeout(()=>{P.delete(J),G(Qo(Z,L?.value,void 0,D))},1e4).unref()})}let y=S?.__invalidated__,w=-(N||1);i.put(Z,S,w,N);let v={transaction:D?.transaction,replacingRecord:S,replacingVersion:N},F=D?.responseHeaders;F&&(v.responseHeaders=F);try{let L=performance.now(),G=await q.Source.get(Z,v),X=performance.now()-L;ls(X,"cache-resolution",n),F&&F.append("Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`);let J=v.lastModified||N;(!J||d&&J<Date.now()-d)&&(J=(0,nu.getNextMonotonicTime)());let j=je(Z,S,G)&&N||y>0;return G?(t&&(G[t]=Z),typeof G.toJSON=="function"&&(G=G.toJSON()),i.put(Z,G,J,w)):i.remove(Z,w),j&&E&&u.put([J,s,Z],Jd(y,null,G?{type:"put",value:i.encoder.encode(G)}:{type:"delete"})),{version:J,value:G}}catch(L){throw i.put(Z,S,N,w),L}}a(Qo,"getFromSource");function xn(Z){T||(T=i.get([SB,ZT.threadId])||0),T+=Z,O||(O=setTimeout(()=>{O=null,i.rootStore.status==="open"&&i.put([SB,ZT.threadId],T)},50))}a(xn,"recordDeletion");function hR(){p||(p=setTimeout(()=>{if(p=null,i.rootStore.status==="open"){for(let{key:Z,value:S}of i.getRange({start:!0}))if(S===null){let N=i.getEntry(Z);N?.value===null&&i.remove(Z,N.version),xn(-1)}}},q.getRecordCount()*100+gee).unref())}a(hR,"enqueueDeletionCleanup");function mR(){z=u?.addDeleteRemovalCallback(s,Z=>{let S=i.getEntry(Z);S?.value===null&&i.remove(Z,S.version),xn(-1)})}a(mR,"addDeleteRemoval");function XB(){(0,Li.getWorkerIndex)()===0&&setInterval(async()=>{try{let Z=b.name,S=r[Z];if(!S)throw new Error(`expiresAt attribute ${b} must be indexed`);for(let{value:N}of S.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let D=i.getEntry(N);D?.value?.[Z]<Date.now()&&q.evict(N,D.value,D.version),await new Promise(y=>setImmediate(y))}}catch(Z){Mi.error("Error in evicting old records",Z)}},Ree).unref()}a(XB,"runRecordExpirationEviction")}function XT(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 RB(){}function Aee(e){NB=e}function jd(e,t){let r=t?.type;return e===null?e:r==="Int"?parseInt(e):r==="Float"?parseFloat(e):r==="Date"?(typeof e!="number"&&!Oee.test(e)&&(e+="Z"),new Date(e)):r?e:(0,eE.autoCast)(e)}function gB(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}var zr,xo,nu,AB,ZT,su,au,Di,iu,ou,Mi,OB,Li,eE,NB,pee,Tee,Ree,mB,SB,Zt,pB,qde,TB,ru,gee,Oee,Sd=Se(()=>{zr=C(A()),xo=require("lmdb"),nu=C(vt()),AB=require("lodash"),ZT=require("worker_threads");Zr();uB();su=C(xe()),au=C(Q());hB();Di=C(W()),iu=C(Gs()),ou=C(Fr());de();Pu();Mi=C(x());Lu();$n();OB=require("ordered-binary"),Li=C(nt());eu();eE=C(V());ci();pee=1e8,Tee=1e7,Ree=6e4;au.initSync();mB=au.get(zr.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),SB=Symbol.for("deletions"),Zt=Symbol.for("version"),pB=Symbol.for("incremental-update"),qde=Symbol("source-resource"),TB=Symbol("load-from-source"),ru={isNotification:!0,allowInvalidated:!0},gee=(0,eE.convertToMS)(au.get(zr.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(tE,"makeTable");a(XT,"attributesAsObject");a(RB,"noop");a(Aee,"setServerUtilities");Oee=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(jd,"coerceType");a(gB,"isDescendantId")});var Ne={};Ye(Ne,{database:()=>Va,databases:()=>Pe,dropDatabase:()=>em,dropTableMeta:()=>Cee,getDatabases:()=>xr,getTables:()=>Nee,onUpdatedTable:()=>gT,readMetaDb:()=>cu,resetDatabases:()=>bee,table:()=>rt,tables:()=>sr});function Nee(){return iE||xr(),sr||{}}function xr(){if(iE)return Pe;iE=!0,Yo=new Map;let e=(0,yt.getHdbBasePath)()&&(0,Me.join)((0,yt.getHdbBasePath)(),jt.DATABASES_DIR_NAME),t=(0,yt.get)(jt.CONFIG_PARAMS.SCHEMAS)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,yt.get)(jt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,fr.existsSync)(e)?e:(0,Me.join)((0,yt.getHdbBasePath)(),jt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,fr.existsSync)(e))for(let r of(0,fr.readdirSync)(e,{withFileTypes:!0})){let s=(0,Me.basename)(r.name,".mdb");r.isFile()&&(0,Me.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&cu((0,Me.join)(e,r.name),null,s)}if((0,fr.existsSync)((0,$o.getBaseSchemaPath)())){for(let r of(0,fr.readdirSync)((0,$o.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,Me.join)((0,$o.getBaseSchemaPath)(),r.name),n=(0,Me.join)((0,$o.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,fr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,Me.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Me.join)(n,i.name);cu((0,Me.join)(s,i.name),(0,Me.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,fr.existsSync)(n))for(let o of(0,fr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,Me.extname)(o.name).toLowerCase()===".mdb"&&cu((0,Me.join)(n,o.name),(0,Me.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,Me.join)(c.path,(0,Me.basename)(o+".mdb"));(0,fr.existsSync)(u)&&cu(u,o,r,null,!0)}}for(let r in Pe){let s=Yo.get(r);if(s){let n=Pe[r];r.includes("delete")&&Le.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Le.trace(`delete table class ${i}`),delete n[i])}else if(delete Pe[r],r==="data"){for(let n in sr)delete sr[n];delete sr[oE]}}return Yo=null,Pe}}function bee(){iE=!1;for(let[,e]of Hn)e.needsDeletion=!0;xr();for(let[e,t]of Hn)t.needsDeletion&&!e.endsWith("system.mdb")&&(console.log("closing database",e),t.close().then(()=>console.log("closed database",e)),Hn.delete(e));return Pe}function cu(e,t,r=tR,s,n){let i=new jT.default(e,!1);e.includes("delete")&&Le.trace(`reading meta data from ${e}`);try{let o=Hn.get(e);o?o.needsDeletion=!1:(o=(0,rE.open)(i),Hn.set(e,o));let c=new Pi.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(ko.INTERNAL_DBIS_NAME,c)),l=o.auditStore;l||(s?(0,fr.existsSync)(s)&&(i.path=s,l=(0,rE.open)(i),l.isLegacy=!0):l=WT(o));let _=wB(r),d=_[oE],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[T,p]=f.toString().split("/");e.includes("delete")&&Le.trace(`read key ${f}`),p===""?p=h.name:p||(p=T,T=t,h.name||(h.name=p,h.indexed=!h.is_hash_attribute)),d?.add(T);let R=E.get(T);R||E.set(T,R={attributes:[]}),(p==null||h.is_hash_attribute)&&(R.primary=h),p!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:T,primary:p}=h;if(!p){for(let q of T)if(q.is_hash_attribute||q.isPrimaryKey){p=q;break}if(!p)throw new Error(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(T)}`)}let R=_[f],O={},k=[],$,U,b=typeof p.audit=="boolean"?p.audit:(0,yt.get)(jt.CONFIG_PARAMS.LOGGING_AUDITLOG),P=p.trackDeletes,z=p.expiration;if(R)O=R.indices,k=R.attributes,R.schemaVersion++;else{$=p.tableId,$?$>=(u.get(Vo)||0)&&u.putSync(Vo,$+1):(p.tableId=$=u.get(Vo),$||($=1),u.putSync(Vo,$+1),u.putSync(p.key,p));let q=new Pi.default(!p.is_hash_attribute,p.is_hash_attribute);Le.trace(`openDB ${p.key} from ${r}`),U=o.openDB(p.key,q),U.rootStore=o,U.tableId=$}for(let q of T){q.attribute=q.name;try{if(!q.is_hash_attribute&&(q.indexed||q.attribute&&!q.name)){if(!O[q.name]){let je=new Pi.default(!q.is_hash_attribute,q.is_hash_attribute);Le.trace(`openDB ${q.key} from ${r}`),O[q.name]=o.openDB(q.key,je)}let Oe=k.find(je=>je.name===q.name);Oe?k.splice(k.indexOf(Oe),1,q):k.push(q)}}catch(Oe){Le.error("Error trying to update attribute",q,k,O,Oe)}}if(!R){Le.trace(`creating table class ${f}`,Object.keys(_)),R=CB(_,f,tE({primaryStore:U,auditStore:l,audit:b,expirationMS:z&&z*1e3,trackDeletes:P,tableName:f,tableId:$,primaryKey:p.name,databasePath:n?r+"/"+f:r,databaseName:r,indices:O,attributes:T,schemaDefined:p.schemaDefined,dbisDB:u})),R.schemaVersion=1;for(let q of rR)q(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function wB(e){let t=Pe[e];if(t||(e==="data"?t=Pe[e]=sr:e==="system"?Object.defineProperty(Pe,"system",{value:t=Object.create(null),configurable:!0}):t=Pe[e]=Object.create(null)),Yo&&!Yo.has(e)){let r=new Set;t[oE]=r,Yo.set(e,r)}return t}function CB(e,t,r){return e[t]=r,r}function Va({database:e,table:t}){e||(e=tR),xr();let r=wB(e),s=(0,Me.join)((0,yt.getHdbBasePath)(),jt.DATABASES_DIR_NAME),n=t&&(0,yt.get)(jt.CONFIG_PARAMS.SCHEMAS)?.[e]?.tables?.[t]?.path;s=n||(0,yt.get)(jt.CONFIG_PARAMS.SCHEMAS)?.[e]?.path||process.env.STORAGE_PATH||(0,yt.get)(jt.CONFIG_PARAMS.STORAGE_PATH)||((0,fr.existsSync)(s)?s:(0,Me.join)((0,yt.getHdbBasePath)(),jt.LEGACY_DATABASES_DIR_NAME));let i=(0,Me.join)(s,(n?t:e)+".mdb"),o=Hn.get(i);if(!o){let c=new jT.default(i,!1);o=(0,rE.open)(c),Hn.set(i,o)}return o}async function em(e){if(!Pe[e])throw new Error("Schema does not exist");let t=Pe[e];for(let r in t){let n=t[r].primaryStore.rootStore;Hn.delete(n.path),n.status==="open"&&(await n.close(),await bB.remove(n.path))}if(e==="data"){for(let r in sr)delete sr[r];delete sr[oE]}delete Pe[e]}function rt({table:e,database:t,expiration:r,attributes:s,audit:n,trackDeletes:i,schemaDefined:o,origin:c}){t||(t=tR);let u=Va({database:t,table:e}),l=Pe[t],_=l?.[e];if(u.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let d,E,f,h;o==null&&(o=!0);let T=new Pi.default(!1);for(let U of s)U.attribute?(U.name=U.attribute,U.indexed=!0):U.attribute=U.name,U.expiresAt&&(U.indexed=!0);let p,R;if(_){if(Le.trace(`${e} table already exists`),d=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);_.attributes.splice(0,_.attributes.length,...s)}else{let U=u.auditStore;U||(U=WT(u)),E=s.find(q=>q.isPrimaryKey)||{},d=E.name,E.is_hash_attribute=!0,E.schemaDefined=o,i&&(E.trackDeletes=!0),n=E.audit=typeof n=="boolean"?n:(0,yt.get)(jt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(E.expiration=r),c&&(E.origins?E.origins.includes(c)||E.origins.push(c):E.origins=[c]),Le.trace(`${e} table loading, opening primary store`);let b=new Pi.default(!1,!0),P=e+"/";Le.trace(`openDB ${P} from ${t}`);let z=u.openDB(P,b);z.rootStore=u,Le.trace(`openDB ${ko.INTERNAL_DBIS_NAME} from ${t}`),h=u.dbisDb=u.openDB(ko.INTERNAL_DBIS_NAME,T),z.tableId=h.get(Vo),z.tableId||(z.tableId=1),h.putSync(Vo,z.tableId+1),E.tableId=z.tableId,_=CB(l,e,tE({primaryStore:z,auditStore:U,audit:n,trackDeletes:i,expirationMS:r&&r*1e3,primaryKey:d,tableName:e,tableId:z.tableId,databasePath:t,databaseName:t,indices:{},attributes:s,schemaDefined:o,dbisDB:h})),_.schemaVersion=1,p=!0,$(),h.put(P,E)}Le.trace(`${e} table loading, getting stored attributes`),f=_.indices,h||Le.trace(`openDB ${ko.INTERNAL_DBIS_NAME} from ${t}`),h=h||(u.dbisDb=u.openDB(ko.INTERNAL_DBIS_NAME,T)),_.dbisDB=h;let O=[];for(let{key:U,value:b}of h.getRange({start:!0})){let[P,z]=U.toString().split("/");if(z===""&&(z=b.name),z){if(P!==e)continue}else z=P;if(!s.find(Oe=>Oe.name===z)?.indexed&&b.indexed&&!b.isPrimaryKey){$(),p=!0,h.remove(U);let Oe=_.indices[P];Oe&&O.push(Oe)}}Le.trace(`${e} table loading, comparing atributes`);let k=[];try{for(let U of s||[]){let b=e+"/"+(U.name||"");Object.defineProperty(U,"key",{value:b,configurable:!0});let P=h.get(b);if(U.isPrimaryKey){if(n===!0&&!_.audit){_.enableAuditing(),P||(b=e+"/",P=h.get(b));let q=Object.assign({},P,{audit:!0});p=!0,$(),h.put(b,q)}continue}P?.attribute&&!P.name&&(P.indexed=!0);let z=!P||P.type!==U.type||P.indexed!==U.indexed||JSON.stringify(P.attributes)!==JSON.stringify(U.attributes)||JSON.stringify(P.elements)!==JSON.stringify(U.elements);if(U.indexed){let q=new Pi.default(!0,!1);Le.trace(`openDB ${b} from ${t}`);let Oe=u.openDB(b,q);(z||P.indexingPID&&P.indexingPID!==process.pid||P.restartNumber<uu.workerData?.restartNumber)&&(p=!0,$(),P=h.get(b),(z||P.indexingPID&&P.indexingPID!==process.pid||P.restartNumber<uu.workerData?.restartNumber)&&(p=!0,U.lastIndexedKey=P?.lastIndexedKey||!1,U.indexingPID=process.pid,Oe.isIndexing=!0,Object.defineProperty(U,"dbi",{value:Oe}),k.push(U)),h.put(b,U)),f[U.name]=Oe}else z&&(p=!0,$(),h.put(b,U))}}finally{R&&R()}if(p&&(_.schemaVersion++,_.updatedAttributes()),Le.trace(`${e} table loading, running index`),k.length>0||O.length>0?_.indexingOperation=wee(_,k,O):p&&sE.signalSchemaChange(new nE.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=c,p)for(let U of rR)U(_,c!=="cluster");return r&&_.setTTLExpiration(+r),Le.trace(`${e} table loaded`),_;function $(){R||u.transactionSync(()=>({then(U){R=U}}))}a($,"startTxn")}async function wee(e,t,r){try{let s=e.schemaVersion;await sE.signalSchemaChange(new nE.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:l,value:_,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(_){if(u++,n=e.primaryStore.ifVersion(l,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,T=(0,yB.getIndexedValues)(_[h]);if(T)for(let p=0,R=T.length;p<R;p++)f.dbi.put(T[p],l)}}),n.then(()=>u--,E=>{u--,Le.error(E)}),uu.workerData&&uu.workerData.restartNumber!==IB.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=l,e.dbisDB.put(E.key,E);if(i)return}u>yee?await n:u>Iee&&await new Promise(E=>setImmediate(E))}for(let l of t)delete l.lastIndexedKey,delete l.indexingPID,l.dbi.isIndexing=!1,n=e.dbisDB.put(l.key,l)}await n,await sE.signalSchemaChange(new nE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Le.error("Error in indexing",s)}}function Cee({table:e,database:t}){let r=Va({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 gT(e){rR.push(e)}var yt,ko,rE,Me,fr,$o,Pi,jT,jt,bB,eR,yB,sE,nE,uu,Le,IB,tR,oE,sr,Pe,Vo,rR,iE,Hn,Yo,yee,Iee,de=Se(()=>{yt=C(Q()),ko=C(xe()),rE=require("lmdb"),Me=require("path"),fr=require("fs"),$o=C(we());Sd();Pi=C(qu()),jT=C(Gu()),jt=C(A()),bB=C(require("fs-extra")),eR=require("../../index"),yB=C(vt()),sE=C(Gs()),nE=C(Fr()),uu=require("worker_threads"),Le=C(x()),IB=C(nt());eu();tR="data",oE=Symbol("defined-tables");(0,yt.initSync)();sr=Object.create(null),Pe=Object.create(null);(0,eR._assignPackageExport)("databases",Pe);(0,eR._assignPackageExport)("tables",sr);Vo=Symbol.for("next-table-id"),rR=[],Hn=new Map;a(Nee,"getTables");a(xr,"getDatabases");a(bee,"resetDatabases");a(cu,"readMetaDb");a(wB,"ensureDB");a(CB,"setTable");a(Va,"database");a(em,"dropDatabase");a(rt,"table");yee=1e3,Iee=10;a(wee,"runIndexing");a(Cee,"dropTableMeta");a(gT,"onUpdatedTable")});var V=m((Wde,VB)=>{"use strict";var qn=require("path"),PB=require("fs-extra"),er=x(),UB=require("fs-extra"),aE=require("os"),Uee=require("net"),Dee=require("recursive-iterator"),Ge=A(),Lee=zR(),DB=require("papaparse"),cE=require("moment"),{inspect:Mee}=require("util"),LB=require("is-number"),Kde=require("lodash"),Pee=require("minimist"),vee=require("https"),Bee=require("http"),{hdb_errors:uE}=W(),Hee=/^((\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)))$/,vB=require("util").promisify(setTimeout),qee=100,Fee=5,Gee="",xee=4,MB={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};VB.exports={isEmpty:hr,isEmptyOrZeroLength:Ns,arrayHasEmptyValues:$ee,arrayHasEmptyOrZeroLengthValues:Yee,buildFolderPath:Kee,isBoolean:BB,errorizeMessage:kee,stripFileExtension:Qee,autoCast:zee,autoCastJSON:HB,autoCastJSONDeep:nR,removeDir:Jee,compareVersions:Xee,isCompatibleDataVersion:Zee,escapeRawValue:jee,unescapeValue:ete,stringifyProps:tte,timeoutPromise:ste,isClusterOperation:ite,getClusterUser:ate,checkGlobalSchemaTable:ote,getHomeDir:FB,getPropsFilePath:rte,promisifyPapaParse:cte,removeBOM:GB,createEventPromise:ute,checkProcessRunning:lte,checkSchemaTableExist:_te,checkSchemaExists:xB,checkTableExists:kB,getStartOfTomorrowInSeconds:dte,getLimitKey:Ete,isObject:Wee,isNotEmptyAndHasValue:Vee,autoCasterIsNumberCheck:qB,backtickASTSchemaItems:fte,isPortTaken:nte,createForkArgs:hte,autoCastBoolean:mte,async_set_timeout:vB,getTableHashAttribute:Ste,doesSchemaExist:pte,doesTableExist:Tte,stringifyObj:Rte,ms_to_time:gte,changeExtension:Ate,getEnvCliRootPath:iR,noBootFile:Ote,httpRequest:Nte,transformReq:bte,convertToMS:yte,PACKAGE_ROOT:Ge.PACKAGE_ROOT};function kee(e){return e instanceof Error?e:new Error(e)}a(kee,"errorizeMessage");function hr(e){return e==null}a(hr,"isEmpty");function Vee(e){return!hr(e)&&(e||e===0||e===""||BB(e))}a(Vee,"isNotEmptyAndHasValue");function Ns(e){return hr(e)||e.length===0||e.size===0}a(Ns,"isEmptyOrZeroLength");function $ee(e){if(hr(e))return!0;for(let t=0;t<e.length;t++)if(hr(e[t]))return!0;return!1}a($ee,"arrayHasEmptyValues");function Yee(e){if(Ns(e))return!0;for(let t=0;t<e.length;t++)if(Ns(e[t]))return!0;return!1}a(Yee,"arrayHasEmptyOrZeroLengthValues");function Kee(...e){try{return e.join(qn.sep)}catch{console.error(e)}}a(Kee,"buildFolderPath");function BB(e){return hr(e)?!1:e===!0||e===!1}a(BB,"isBoolean");function Wee(e){return hr(e)?!1:typeof e=="object"}a(Wee,"isObject");function Qee(e){return Ns(e)?Gee:e.slice(0,-xee)}a(Qee,"stripFileExtension");function zee(e){return hr(e)||e===""||typeof e!="string"?e:MB[e]!==void 0?MB[e]:qB(e)===!0?Number(e):Hee.test(e)?new Date(e):e}a(zee,"autoCast");function HB(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(HB,"autoCastJSON");function nR(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=nR(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=nR(r);s!==r&&(e[t]=s)}return e}else return HB(e)}a(nR,"autoCastJSONDeep");function qB(e){if(e.startsWith("0.")&&LB(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&LB(e))}a(qB,"autoCasterIsNumberCheck");async function Jee(e){if(Ns(e))throw new Error(`Directory path: ${e} does not exist`);try{await UB.emptyDir(e),await UB.remove(e)}catch(t){throw er.error(`Error removing files in ${e} -- ${t}`),t}}a(Jee,"removeDir");function Xee(e,t){if(Ns(e)){er.info("Invalid current version sent as parameter.");return}if(Ns(t)){er.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 l=0;l<u;l++)if(r=parseInt(o[l],10)-parseInt(c[l],10),r)return r;return o.length-c.length}a(Xee,"compareVersions");function Zee(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(Zee,"isCompatibleDataVersion");function jee(e){if(hr(e))return e;let t=String(e);return t==="."?Ge.UNICODE_PERIOD:t===".."?Ge.UNICODE_PERIOD+Ge.UNICODE_PERIOD:t.replace(Ge.FORWARD_SLASH_REGEX,Ge.UNICODE_FORWARD_SLASH)}a(jee,"escapeRawValue");function ete(e){if(hr(e))return e;let t=String(e);return t===Ge.UNICODE_PERIOD?".":t===Ge.UNICODE_PERIOD+Ge.UNICODE_PERIOD?"..":String(e).replace(Ge.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(ete,"unescapeValue");function tte(e,t){if(hr(e))return er.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+aE.EOL}!Ns(s)&&s[0]===";"?r+=" "+s+n+aE.EOL:Ns(s)||(r+=s+"="+n+aE.EOL)}catch{er.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(tte,"stringifyProps");function FB(){let e;try{e=aE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(FB,"getHomeDir");function rte(){let e=qn.join(FB(),Ge.HDB_HOME_DIR_NAME,Ge.BOOT_PROPS_FILE_NAME);return PB.existsSync(e)||(e=qn.join(__dirname,"../","hdb_boot_properties.file")),e}a(rte,"getPropsFilePath");function ste(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(ste,"timeoutPromise");async function nte(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=Uee.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(nte,"isPortTaken");function ite(e){try{return Ge.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){er.error(`Error checking operation against cluster ops ${t}`)}return!1}a(ite,"isClusterOperation");function ote(e,t){let r=(de(),ee(Ne)).getDatabases();if(!r[e])return uE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return uE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(ote,"checkGlobalSchemaTable");function ate(e,t){if(hr(t)){er.warn("No CLUSTERING_USER defined, clustering disabled");return}if(hr(e)||Ns(e)){er.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){er.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){er.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(ate,"getClusterUser");function cte(){DB.parsePromise=function(e,t,r){return new Promise(function(s,n){DB.parse(e,{header:!0,transformHeader:GB,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(cte,"promisifyPapaParse");function GB(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(GB,"removeBOM");function ute(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;er.info(`Got cluster status event response: ${Mee(n)}`);try{i.cancel()}catch{er.error("Error trying to cancel timeout.")}s(n)})})}a(ute,"createEventPromise");async function lte(e){let t=!0,r=0;do await vB(qee*r++),(await Lee.findPs(e)).length>0&&(t=!1);while(t&&r<Fee);if(t)throw new Error(`process ${e} was not started`)}a(lte,"checkProcessRunning");function _te(e,t){let r=xB(e);if(r)return r;let s=kB(e,t);if(s)return s}a(_te,"checkSchemaTableExist");function xB(e){let{getDatabases:t}=(de(),ee(Ne));if(!t()[e])return uE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(xB,"checkSchemaExists");function kB(e,t){let{getDatabases:r}=(de(),ee(Ne));if(!r()[e][t])return uE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(kB,"checkTableExists");function dte(){let e=cE().utc().add(1,Ge.MOMENT_DAYS_TAG).startOf(Ge.MOMENT_DAYS_TAG).unix(),t=cE().utc().unix();return e-t}a(dte,"getStartOfTomorrowInSeconds");function Ete(){return cE().utc().format("DD-MM-YYYY")}a(Ete,"getLimitKey");function fte(e){try{let t=new Dee(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){er.error("Got an error back ticking items."),er.error(t)}}a(fte,"backtickASTSchemaItems");function hte(e){return[e]}a(hte,"createForkArgs");function mte(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(mte,"autoCastBoolean");function Ste(e,t){let{getDatabases:r}=(de(),ee(Ne)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(Ste,"getTableHashAttribute");function pte(e){let{getDatabases:t}=(de(),ee(Ne));return t()[e]!==void 0}a(pte,"doesSchemaExist");function Tte(e,t){let{getDatabases:r}=(de(),ee(Ne));return r()[e]?.[t]!==void 0}a(Tte,"doesTableExist");function Rte(e){try{return JSON.stringify(e)}catch{return e}}a(Rte,"stringifyObj");function gte(e){let t=cE.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(gte,"ms_to_time");function Ate(e,t){let r=qn.basename(e,qn.extname(e));return qn.join(qn.dirname(e),r+t)}a(Ate,"changeExtension");function iR(){if(process.env[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Pee(process.argv);if(e[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ge.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(iR,"getEnvCliRootPath");var sR;function Ote(){if(sR)return sR;let e=iR();iR()&&PB.pathExistsSync(qn.join(e,Ge.HDB_CONFIG_FILE))&&(sR=!0)}a(Ote,"noBootFile");function Nte(e,t){let r;return e.protocol==="http:"?r=Bee:r=vee,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(Nte,"httpRequest");function bte(e){if(!e.schema&&!e.database){e.schema=Ge.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(bte,"transformReq");function yte(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(yte,"convertToMS")});var Q=m((zde,KB)=>{"use strict";var oR=require("fs-extra"),Jr=require("path"),$B=require("os"),Ite=require("properties-reader"),lu=x(),vi=V(),re=A(),lE=Nr(),wte="Error initializing environment manager",_E="BOOT_PROPS_FILE_PATH",YB=!1,Cte={[re.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[re.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},on={};KB.exports={BOOT_PROPS_FILE_PATH:_E,getHdbBasePath:Ute,setHdbBasePath:Dte,get:Lte,initSync:Pte,setProperty:Ee,initTestEnvironment:vte};function Ute(){return on[re.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Ute,"getHdbBasePath");function Dte(e){on[re.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Dte,"setHdbBasePath");function Lte(e){let t=lE.getConfigValue(e);return t===void 0?on[e]:t}a(Lte,"get");function Ee(e,t){Cte[e]&&(on[e]=t),lE.updateConfigObject(e,t)}a(Ee,"setProperty");function Mte(){let e;try{e=vi.getPropsFilePath(),oR.accessSync(e,oR.constants.F_OK|oR.constants.R_OK),YB=!0;let t=Ite(e);return on[re.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(re.HDB_SETTINGS_NAMES.INSTALL_USER),on[re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),on[_E]=e,!0}catch{return lu.trace(`Environment manager found no properties file at ${e}`),!1}}a(Mte,"doesPropFileExist");function Pte(e=!1){try{(YB||Mte()||vi.noBootFile())&&(lE.initConfig(e),on[re.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=lE.getConfigValue(re.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){lu.error(wte),lu.error(t),console.error(t),process.exit(1)}}a(Pte,"initSync");function vte(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=Jr.join(__dirname,"../../","unitTests");on[_E]=Jr.join(u,"hdb_boot_properties.file"),Ee(re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Jr.join(u,"settings.test")),Ee(re.HDB_SETTINGS_NAMES.INSTALL_USER,$B.userInfo()?$B.userInfo().username:void 0),Ee(re.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,Jr.join(u,"envDir","utility","keys","privateKey.pem")),Ee(re.HDB_SETTINGS_NAMES.CERT_KEY,Jr.join(u,"envDir","utility","keys","certificate.pem")),Ee(re.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,Jr.join(u,"envDir","utility","keys","privateKey.pem")),Ee(re.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,Jr.join(u,"envDir","utility","keys","certificate.pem")),Ee(re.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ee(re.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Jr.join(u,"envDir","log")),Ee(re.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ee(re.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ee(re.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ee(re.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Jr.join(u,"envDir")),Ee(re.CONFIG_PARAMS.STORAGE_PATH,Jr.join(u,"envDir")),Ee(re.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,vi.isEmpty(n)?!0:n),Ee(re.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,vi.isEmpty(n)?!0:n),Ee(re.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ee(re.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,vi.isEmpty(i)?!1:i),Ee(re.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,vi.isEmpty(i)?!1:i),Ee(re.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ee(re.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ee(re.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ee(re.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ee(re.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Jr.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ee(re.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,vi.isEmpty(c)?!1:c),o&&(Ee("CORS_ACCESSLIST",o),Ee(re.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(Ee(re.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ee(re.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(Ee(re.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ee(re.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(Ee(re.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ee(re.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${_E}. Please check your boot props and settings files`;lu.fatal(r),lu.error(t)}}a(vte,"initTestEnvironment")});var ere=m(mE=>{var{isMainThread:Bte,parentPort:du,threadId:Hte}=require("worker_threads"),{Socket:qte}=require("net"),{createServer:Fte,IncomingMessage:Gte}=require("http"),{createServer:xte}=require("https"),{readFileSync:Ko}=require("fs"),dE=x(),bs=Q(),Wo=A(),{server:hE}=(Pr(),ee(da)),{WebSocketServer:kte}=require("ws"),{createServer:Vte}=require("tls"),{getTicketKeys:$te}=nt(),{Headers:Yte}=(P_(),ee(gD));process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:Xde,CONFIG_PARAMS:Zde}=Wo;bs.initSync();var Gn={};mE.registerServer=ER;mE.httpServer=fR;mE.deliverSocket=dR;hE.http=fR;hE.request=Jte;hE.socket=Xte;hE.ws=Zte;var aR=[],cR=[],Kte,_u={},EE={},Wte=[],uR=[];Bte||vT().loadRootComponents(!0).then(()=>{du.on("message",e=>{let{port:t,fd:r,data:s}=e;if(r)dR(r,t,s);else if(e.requestId)Qte(e);else if(e.type===Wo.ITC_EVENT_TYPES.SHUTDOWN)for(let n in Gn){let i=Gn[n];i.close?.(()=>{setTimeout(()=>{i.cantCleanupProperly||dE.warn("Had to forcefully exit the thread",Hte),process.exit(0)},i.cantCleanupProperly?2500:5e3).unref()}),i.closeIdleConnections?.()}}).ref(),du.postMessage({type:Wo.ITC_EVENT_TYPES.CHILD_STARTED})});function dR(e,t,r){let s=e?.read?e:new qte({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),n=Gn[t];if(n)typeof n=="function"?n(s):n.emit("connection",s),r&&s.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=Gn[t];c?(typeof c=="function"?c(s):c.emit("connection",s),r&&s.emit("data",r)):o<5?i(o+1):(dE.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(dR,"deliverSocket");var WB=new Map;function Qte(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=WB.get(n),r){case"connection":i=dR(void 0,t),WB.set(n,i),i.write=(c,u,l)=>(du.postMessage({requestId:n,event:"data",data:c.toString("latin1")}),l&&l(),!0),i.end=(c,u,l)=>(du.postMessage({requestId:n,event:"end",data:c?.toString("latin1")}),l&&l(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),du.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(Qte,"proxyRequest");function ER(e,t){+t||(t=parseInt(bs.get(Wo.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10));let r=Gn[t];if(r){let s=r.lastServer||r;s.off("unhandled",QB),s.on("unhandled",(n,i)=>{e.cantCleanupProperly&&(r.cantCleanupProperly=!0),e.emit("request",n,i)}),r.lastServer=e}else Gn[t]=e;e.on("unhandled",QB)}a(ER,"registerServer");function zB(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=[{port:parseInt(bs.get(Wo.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10),secure:bs.get(Wo.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}]),t}a(zB,"getPorts");function fR(e,t){for(let{port:r,secure:s}of zB(t))JB(r,s,t?.isOperationsServer),typeof e=="function"?uR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):ER(e,r),EE[r]=lR(uR,r),Kte=lR(Wte,r)}a(fR,"httpServer");function JB(e,t,r){if(!_u[e]){let s={};if(t){let n=r?"operationsapi":"customfunctions",i=bs.get(n+"_tls_privatekey"),o=bs.get(n+"_tls_certificate"),c=bs.get(n+"_tls_certificateauthority");s={key:Ko(i),cert:Ko(o)+(c?`
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
`+Ko(c):""),ticketKeys:$te()}}_u[e]=(t?xte:Fte)(s,async(n,i)=>{try{let o=new fE(n);r&&(o.isOperationsServer=!0);let c=await EE[e](o);if(c.headers?.set?.("Server","HarperDB"),c.status===-1){for(let l of c.headers||[])i.setHeader(l[0],l[1]);return n.baseRequest=o,i.baseResponse=c,_u[e].emit("unhandled",n,i)}c.handlesHeaders||i.writeHead(c.status||200,c.headers&&(c.headers[Symbol.iterator]?Array.from(c.headers):c.headers));let u=c.body;u?.pipe?(u.pipe(i),u.destroy&&i.on("close",()=>{u.destroy()})):u?.then?u.then(l=>{i.end(l)},l=>{i.writeHead(l.statusCode||500),i.end(l.toString()),dE.error(l)}):i.end(u)}catch(o){i.writeHead(o.statusCode||500),i.end(o.toString()),dE.error(o)}}),ER(_u[e],e)}return _u[e]}a(JB,"getHTTPServer");function lR(e,t){let r=zte;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(lR,"makeCallbackChain");function zte(e){return e.user&&(e[Fn].user=e.user),{status:-1,body:"Not found",headers:new Yte}}a(zte,"unhandled");function Jte(e,t){fR(e,{requestOnly:!0,...t})}a(Jte,"onRequest");function Xte(e,t){if(t.securePort){let r=bs.get("customfunctions_tls_privatekey"),s=bs.get("customfunctions_tls_certificate"),n=bs.get("customfunctions_tls_certificateauthority"),i=Vte({key:Ko(r),cert:Ko(s)+(n?`
|
|
29
29
|
|
|
30
|
-
|
|
31
|
-
`)}a(
|
|
30
|
+
`+Ko(n):"")},e);Gn[t.securePort]=o=>{i.emit("connection",o)}}t.port&&(Gn[t.port]=e)}a(Xte,"onSocket");Object.defineProperty(Gte.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 Zte(e,t){for(let{port:r,secure:s}of zB(t)){cR[r]||(cR[r]=new kte({server:JB(r,s)}),cR[r].on("connection",async(i,o)=>{let c=new fE(o);c.isWebSocket=!0;let u=EE[r](c),l=c.headers["sec-websocket-protocol"]||"";for(let _=0;_<aR.length;_++){let d=aR[_];if(d.protocol){if(d.protocol===l){d.listener(i,c,u);break}}else d.listener(i,c,u)}}));let n=t?.subProtocol||"";aR.push({listener:e,protocol:n}),EE[r]=lR(uR,r)}}a(Zte,"onWebSocket");function QB(e,t){t.writeHead(404),t.end(`Not found
|
|
31
|
+
`)}a(QB,"defaultNotFound");var Fn=Symbol("node request"),fE=class{static{a(this,"Request")}[Fn];#e;constructor(t){this.method=t.method;let r=t.url;this[Fn]=t,this.url=r,this.headers=t.headers,this.headers.get=jte}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[Fn].socket.encrypted?"https":"http"}get ip(){return this[Fn].socket.remoteAddress}get body(){return this.#e||(this.#e=new _R(this[Fn]))}get host(){return this[Fn].authority||this[Fn].headers.host}get isAborted(){return!1}},_R=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}};function jte(e){return this[e.toLowerCase()]}a(jte,"get")});module.exports=ere();
|