harperdb 4.3.0-beta.1 → 4.3.0-beta.3
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 +56 -53
- package/bin/lite.js +19 -16
- package/config/yaml/defaultConfig.yaml +1 -0
- package/json/systemSchema.json +20 -0
- package/launchServiceScripts/launchInstallNATSServer.js +3 -3
- package/launchServiceScripts/launchNatsIngestService.js +19 -16
- package/launchServiceScripts/launchNatsReplyService.js +19 -16
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +19 -16
- package/npm-shrinkwrap.json +358 -357
- package/package.json +3 -3
- package/resources/search.d.ts +1 -0
- package/server/jobs/jobProcess.js +19 -16
- package/server/threads/threadServer.js +19 -16
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.67d8f5e6.js → main.f2d1cee1.js} +2 -2
- package/utility/scripts/restartHdb.js +19 -16
- /package/studio/build-local/static/js/{main.67d8f5e6.js.LICENSE.txt → main.f2d1cee1.js.LICENSE.txt} +0 -0
package/bin/lite.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
var Zx=Object.create;var za=Object.defineProperty;var eF=Object.getOwnPropertyDescriptor;var tF=Object.getOwnPropertyNames;var rF=Object.getPrototypeOf,nF=Object.prototype.hasOwnProperty;var a=(e,t)=>za(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qe=(e,t)=>{for(var r in t)za(e,r,{get:t[r],enumerable:!0})},bA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of tF(t))!nF.call(e,s)&&s!==r&&za(e,s,{get:()=>t[s],enumerable:!(n=eF(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Zx(rF(e)):{},bA(t||!e||!e.__esModule?za(r,"default",{value:e,enumerable:!0}):r,e)),ee=e=>bA(za({},"__esModule",{value:!0}),e);var M=T((Bie,xA)=>{"use strict";var Zr=require("path"),sF=require("fs"),{relative:Pie,join:vie}=Zr,{existsSync:iF}=sF;function oF(){let e=__dirname;for(;!iF(Zr.join(e,"package.json"));){let t=Zr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(oF,"getHDBPackageRoot");var Ys=oF(),NA="js",Ml=NA,aF="harperdb-config.yaml",cF="defaultConfig.yaml",uF="hdb",yA=`harperdb.${Ml}`,IA=`customFunctionsServer.${Ml}`,lF=`restartHdb.${Ml}`,eh="HarperDB",Ll="Custom Functions",Ul="Clustering Hub",Pl="Clustering Leaf",_F="Clustering Ingest Service",dF="Clustering Reply Service",fF="foreground.pid",EF="hdb.pid",hF="data",mF={HDB:eh,CLUSTERING_HUB:Ul,CLUSTERING_LEAF:Pl,CLUSTERING_INGEST_SERVICE:_F,CLUSTERING_REPLY_SERVICE:dF,CUSTOM_FUNCTIONS:Ll,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"},pF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},SF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},TF={harperdb:eh,"clustering hub":Ul,"clustering leaf":Pl,"custom functions":Ll,custom_functions:Ll,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},gF={CLUSTERING_HUB_PROC_DESCRIPTOR:Ul,CLUSTERING_LEAF_PROC_DESCRIPTOR:Pl},ZE={HDB:Zr.join(Ys,"server/harperdb"),CUSTOM_FUNCTIONS:Zr.join(Ys,"server/customFunctions"),CLUSTERING_HUB:Zr.join(Ys,"server/nats"),CLUSTERING_LEAF:Zr.join(Ys,"server/nats")},RF={HDB:Zr.join(ZE.HDB,yA),CUSTOM_FUNCTIONS:Zr.join(ZE.CUSTOM_FUNCTIONS,IA)},AF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Zr.join(Ys,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Zr.join(Ys,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Zr.join(Ys,"launchServiceScripts/launchUpdateNodes4-0-0.js")},OF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},wA="support@harperdb.io",bF="customer-success@harperdb.io",CA=1,NF=4141,DA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",yF="https://www.harperdb.io/product",IF=`For support, please submit a request at ${DA} or contact ${wA}`,LA=`For license support, please contact ${bF}`,wF="None of the specified records were found.",CF="hash attribute not found",DF=`Your current license only supports ${CA} role. ${LA}`,LF="Your current license only supports 3 connections to a node.",MF="127.0.0.1",UF=1,PF=/^\.$/,vF=/^\.\.$/,BF="U+002E",HF=/\//g,xF="U+002F",FF=/U\+002F/g,qF=/^U\+002E$/,GF=/^U\+002EU\+002E$/,kF="d",VF=999999,$F="*",YF="--max-old-space-size=",KF="system",WF="__hdb_hash",QF=".harperdb",zF=".hdb",JF="keys",XF="hdb_boot_properties.file",jF=".updateConfig.json",ZF="SIGTSTP",eq=24,tq=6e4,rq=448,nq="blob",sq="trash",iq="database",oq="schema",aq="transactions",cq=".count",uq="id",lq="PROCESS_NAME",MA={SETTINGS_PATH_KEY:"settings_path"},UA=require("lodash"),_q={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},dq={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},fq={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},Eq={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"},hq={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"},Ir="hdb_internal:",mq={CREATE_SCHEMA:Ir+"create_schema",CREATE_TABLE:Ir+"create_table",CREATE_ATTRIBUTE:Ir+"create_attribute",ADD_USER:Ir+"add_user",ALTER_USER:Ir+"alter_user",DROP_USER:Ir+"drop_user",HDB_NODES:Ir+"hdb_nodes",HDB_USERS:Ir+"hdb_users",HDB_WORKERS:Ir+"hdb_workers",CATCHUP:Ir+"catchup",SCHEMA_CATCHUP:Ir+"schema_catchup",WORKER_ROOM:Ir+"cluster_workers"},pq={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"},Sq="060493.ks",Tq=".license",gq={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},X={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},Rq={CSV:".csv",JSON:".json"},Aq={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},Oq={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Ja={};Ja[X.INSERT]=X.INSERT;Ja[X.UPDATE]=X.UPDATE;Ja[X.UPSERT]=X.UPSERT;Ja[X.DELETE]=X.DELETE;var He=Object.create(null);He[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;He[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;He[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;He[X.READ_LOG]=X.READ_LOG;He[X.ADD_NODE]=X.ADD_NODE;He[X.LIST_USERS]=X.LIST_USERS;He[X.LIST_ROLES]=X.LIST_ROLES;He[X.USER_INFO]=X.USER_INFO;He[X.SQL]=X.SQL;He[X.GET_JOB]=X.GET_JOB;He[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;He[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;He[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;He[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;He[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;He[X.REMOVE_NODE]=X.REMOVE_NODE;He[X.RESTART]=X.RESTART;He[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;He[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;He[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;He[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;He[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;He[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;He[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;He[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var bq={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},Nq={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},PA={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"},yq=UA.invert(PA),Iq={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"},C={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_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",MAXHEAPMEMORY:"maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},vA={settings_path:MA.SETTINGS_PATH_KEY,hdb_root_key:C.ROOTPATH,hdb_root:C.ROOTPATH,rootpath:C.ROOTPATH,server_port_key:C.OPERATIONSAPI_NETWORK_PORT,server_port:C.OPERATIONSAPI_NETWORK_PORT,cert_key:C.TLS_CERTIFICATE,certificate:C.TLS_CERTIFICATE,private_key_key:C.TLS_PRIVATEKEY,private_key:C.TLS_PRIVATEKEY,http_secure_enabled_key:C.OPERATIONSAPI_NETWORK_HTTPS,https_on:C.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:C.OPERATIONSAPI_NETWORK_CORS,cors_on:C.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:C.LOGGING_LEVEL,log_level:C.LOGGING_LEVEL,log_path_key:C.LOGGING_ROOT,log_path:C.LOGGING_ROOT,clustering_node_name_key:C.CLUSTERING_NODENAME,node_name:C.CLUSTERING_NODENAME,clustering_enabled_key:C.CLUSTERING_ENABLED,clustering:C.CLUSTERING_ENABLED,max_http_threads:C.THREADS,max_hdb_processes:C.THREADS,server_timeout_key:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:C.LOGGING_AUDITLOG,disable_transaction_log:C.LOGGING_AUDITLOG,operation_token_timeout_key:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:C.HTTP_PORT,custom_functions_port:C.HTTP_PORT,custom_functions_directory_key:C.COMPONENTSROOT,custom_functions_directory:C.COMPONENTSROOT,max_custom_function_processes:C.THREADS,log_to_file:C.LOGGING_FILE,log_to_stdstreams:C.LOGGING_STDSTREAMS,local_studio_on:C.LOCALSTUDIO_ENABLED,clustering_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:C.CLUSTERING_USER,clustering_enabled:C.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:C.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:C.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:C.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:C.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:C.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:C.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:C.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:C.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:C.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:C.CLUSTERING_NODENAME,clustering_tls_certificate:C.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:C.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:C.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:C.CLUSTERING_TLS_INSECURE,clustering_tls_verify:C.CLUSTERING_TLS_VERIFY,clustering_loglevel:C.CLUSTERING_LOGLEVEL,clustering_republishmessages:C.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:C.CLUSTERING_DATABASELEVEL,customfunctions_network_port:C.HTTP_PORT,customfunctions_tls_certificate:C.TLS_CERTIFICATE,customfunctions_network_cors:C.HTTP_CORS,customfunctions_network_corsaccesslist:C.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:C.HTTP_HEADERSTIMEOUT,customfunctions_network_https:C.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:C.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:C.HTTP_TIMEOUT,http_threads:C.THREADS,threads:C.THREADS,maxheapmemory:C.MAXHEAPMEMORY,http_session_affinity:C.HTTP_SESSIONAFFINITY,http_compressionthreshold:C.HTTP_COMPRESSIONTHRESHOLD,http_cors:C.HTTP_CORS,http_corsaccesslist:C.HTTP_CORSACCESSLIST,http_headerstimeout:C.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,http_timeout:C.HTTP_TIMEOUT,http_port:C.HTTP_PORT,http_secureport:C.HTTP_SECUREPORT,customfunctions_processes:C.THREADS,customfunctions_root:C.COMPONENTSROOT,localstudio_enabled:C.LOCALSTUDIO_ENABLED,logging_file:C.LOGGING_FILE,logging_level:C.LOGGING_LEVEL,logging_root:C.LOGGING_ROOT,logging_rotation_enabled:C.LOGGING_ROTATION_ENABLED,logging_rotation_compress:C.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:C.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:C.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:C.LOGGING_ROTATION_PATH,logging_stdstreams:C.LOGGING_STDSTREAMS,logging_auditlog:C.LOGGING_AUDITLOG,logging_auditretention:C.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:C.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:C.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:C.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:C.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:C.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:C.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:C.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:C.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:C.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:C.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:C.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:C.ROOTPATH,databases:C.DATABASES,storage_path:C.STORAGE_PATH,ignorescripts:C.IGNORE_SCRIPTS,mqtt_network_port:C.MQTT_NETWORK_PORT,mqtt_websocket:C.MQTT_WEBSOCKET,mqtt_network_secureport:C.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:C.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:C.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:C.MQTT_NETWORK_MTLS_USER,mqtt_requireauthentication:C.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:C.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:C.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:C.AUTHENTICATION_CACHETTL,authentication_enablesessions:C.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:C.COMPONENTSROOT,tls_certificate:C.TLS_CERTIFICATE,tls_privatekey:C.TLS_PRIVATEKEY,tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,tls_ciphers:C.TLS_CIPHERS};for(let e in C){let t=C[e];vA[t.toLowerCase()]=t}var wq={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},Cq={csv_file_load:"csv_file_load",csv_data_load:X.CSV_DATA_LOAD,csv_url_load:X.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"},Dq={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"},Lq={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Mq={VERSION_DEFAULT:"2.2.0"},Uq={DEVELOPMENT:8192,DEFAULT:512},Pq={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"},vq={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"},Bq={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},BA={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Hq=Symbol("metadata"),xq="__clustering__",Fq=Object.values(BA),qq=15984864e5,HA={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Gq=UA.invert(HA),kq={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"},Vq=111,$q=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
4
|
-
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:UG.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(HG,"findPs")});var Et=T((Kie,sO)=>{"use strict";var xG="__dbis__",FG="__txns__",qG="__environment_name__",GG="__dbi_defintion__",kG={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"},VG=["__createdtime__","__updatedtime__"],$G="\uFFFF",nO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},YG=Object.values(nO);sO.exports={AUDIT_STORE_NAME:FG,INTERNAL_DBIS_NAME:xG,DBI_DEFINITION_NAME:GG,SEARCH_TYPES:kG,TIMESTAMP_NAMES:VG,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:qG,TRANSACTIONS_DBI_NAMES_ENUM:nO,TRANSACTIONS_DBIS:YG,OVERFLOW_MARKER:$G}});var wr=T((Wie,fO)=>{"use strict";var iO=M(),oO=Et(),aO={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},cO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),uO={500:cO("There was an error processing your request."),400:"Invalid request"},KG=uO[aO.INTERNAL_SERVER_ERROR],WG={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.`},QG={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},zG={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"},JG={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 ${oO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${oO.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"},XG={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${iO.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 ${iO.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"},lO={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"},jG={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."},ZG={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`},ek={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"},tk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},rk={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`},_O={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.`},dO={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}`},nk={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."},sk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},ik={...lO,...zG,...WG,...jG,...ZG,...ek,...tk,...rk,...XG,..._O,...dO,...nk,...sk,...QG};fO.exports={CHECK_LOGS_WRAPPER:cO,HDB_ERROR_MSGS:ik,DEFAULT_ERROR_MSGS:uO,DEFAULT_ERROR_RESP:KG,HTTP_STATUS_CODES:aO,LMDB_ERRORS_ENUM:JG,AUTHENTICATION_ERROR_MSGS:lO,VALIDATION_ERROR_MSGS:_O,ITC_ERRORS:dO}});var Z=T((zie,mO)=>{"use strict";var Po=wr(),ok=Y(),ak=M(),Fl=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,EO),this.statusCode=n||Po.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Po.DEFAULT_ERROR_MSGS[n]?Po.DEFAULT_ERROR_MSGS[n]:Po.DEFAULT_ERROR_MSGS[Po.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&ok[s](i)}},fh=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},Eh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function EO(e,t,r,n=ak.LOG_LEVELS.ERROR,s=null,i=!1){if(hO(e))return e;let o=new Fl(e,t,r,n,s);return i&&delete o.stack,o}a(EO,"handleHDBError");function hO(e){return e.__proto__.constructor.name===Fl.name}a(hO,"isHDBError");mO.exports={isHDBError:hO,handleHDBError:EO,ClientError:fh,ServerError:Eh,hdb_errors:Po}});var Je=T((Xie,OO)=>{"use strict";var ac=M(),ck=J(),rr=j(),cc=require("path"),uk=require("minimist"),pO=require("fs-extra"),SO=require("lodash");rr.initSync();var{CONFIG_PARAMS:Ws,DATABASES_PARAM_CONFIG:nc,SYSTEM_SCHEMA_NAME:ql}=ac,sc,ic,oc;function TO(){if(sc!==void 0)return sc;if(rr.getHdbBasePath()!==void 0)return sc=rr.get(Ws.STORAGE_PATH)||cc.join(rr.getHdbBasePath(),ac.DATABASES_DIR_NAME),sc}a(TO,"getBaseSchemaPath");function gO(){if(ic!==void 0)return ic;if(rr.getHdbBasePath()!==void 0)return ic=AO(ql),ic}a(gO,"getSystemSchemaPath");function RO(){if(oc!==void 0)return oc;if(rr.getHdbBasePath()!==void 0)return oc=rr.get(ac.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cc.join(rr.getHdbBasePath(),ac.TRANSACTIONS_DIR_NAME),oc}a(RO,"getTransactionAuditStoreBasePath");function lk(e,t){let r=rr.get(Ws.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cc.join(RO(),e.toString())}a(lk,"getTransactionAuditStorePath");function AO(e,t){e=e.toString(),t=t&&t.toString();let r=rr.get(ac.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cc.join(TO(),e)}a(AO,"getSchemaPath");function _k(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,uk(process.argv));let n=r[Ws.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!ck.isObject(n))throw o;i=n}for(let o of i){let c=o[ql];if(!c)continue;let u=rr.get(Ws.DATABASES);u=u??{};let _=c?.tables?.[t]?.[nc.PATH];if(_)return SO.set(u,[ql,nc.TABLES,t,nc.PATH],_),rr.setProperty(Ws.DATABASES,u),_;let l=c?.[nc.PATH];if(l)return SO.set(u,[ql,nc.PATH],l),rr.setProperty(Ws.DATABASES,u),l}}let s=r[Ws.STORAGE_PATH.toUpperCase()];if(s){if(!pO.pathExistsSync(s))throw new Error(s+" does not exist");let i=cc.join(s,e);return pO.mkdirsSync(i),rr.setProperty(Ws.STORAGE_PATH,s),i}return gO()}a(_k,"initSystemSchemaPaths");function dk(){sc=void 0,ic=void 0,oc=void 0}a(dk,"resetPaths");OO.exports={getBaseSchemaPath:TO,getSystemSchemaPath:gO,getTransactionAuditStorePath:lk,getTransactionAuditStoreBasePath:RO,getSchemaPath:AO,initSystemSchemaPaths:_k,resetPaths:dk}});var Cr=T((toe,wO)=>{"use strict";var fk=wr().LMDB_ERRORS_ENUM,Zie=require("lmdb"),Ek=Et(),eoe=require("buffer").Buffer,{OVERFLOW_MARKER:bO,MAX_SEARCH_KEY_LENGTH:Gl}=Ek,NO=["number","string","symbol","boolean","bigint"];function hk(e){if(e=e?.primaryStore||e,!e)throw new Error(fk.ENV_REQUIRED)}a(hk,"validateEnv");function mk(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(mk,"stringifyData");function pk(e){return e instanceof Date?e.valueOf():e}a(pk,"convertKeyValueToWrite");function Sk(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(NO.includes(typeof e))return e.length>Gl?[e.slice(0,Gl)+bO]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(NO.includes(typeof i))i.length>Gl?r.push(i.slice(0,Gl)+bO):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(Sk,"getIndexedValues");var kl=0,yO=0;function IO(){yO=Date.now()-performance.now()}a(IO,"adjustStartTime");IO();var Tk=6e4;setInterval(IO,Tk).unref();function gk(){let e=performance.now()+yO;return e>kl?(kl=e,e):(kl+=488e-6,kl)}a(gk,"getNextMonotonicTime");wO.exports={validateEnv:hk,stringifyData:mk,convertKeyValueToWrite:pk,getNextMonotonicTime:gk,getIndexedValues:Sk}});var CO,An,hh,uc=Re(()=>{CO=require("events"),An=class extends CO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new hh;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)}},hh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var UO={};qe(UO,{HAS_EXPIRATION:()=>Oh,LAST_TIMESTAMP_PLACEHOLDER:()=>dc,LOCAL_TIMESTAMP:()=>Rk,METADATA:()=>lc,NO_TIMESTAMP:()=>ph,PENDING_LOCAL_TIME:()=>bh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Ah,RecordEncoder:()=>gh,TIMESTAMP_ASSIGN_LAST:()=>Ok,TIMESTAMP_ASSIGN_NEW:()=>LO,TIMESTAMP_ASSIGN_PREVIOUS:()=>MO,TIMESTAMP_PLACEHOLDER:()=>Vl,TIMESTAMP_RECORD_PREVIOUS:()=>Sh,fromResource:()=>Wl,getUpdateRecord:()=>Nh,handleLocalTimeForGets:()=>Ql});function Nk(){return _c[0]=_c[0]^64,Ak.getFloat64(0)}function Wl(e){Rh=!0;try{return e()}finally{Rh=!1}}function Ql(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[lc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[lc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[lc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,wi.push(new WeakRef(this))),!Rh)try{throw new Error("Read transaction used outside of resource")}catch(u){this.readStack=u.stack}o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<wi.length;u++){let _=wi[u].deref();(!_||_.isDone||_.isCommitted)&&wi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Nh(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?vo=i?.localTime?Sh|MO:ph:vo=u?i?.localTime?Sh|16384:LO|16384:ph,l>0&&(c|=Oh),Yl=c,Th=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:vo>0},S;try{f&&(h.ifVersion=S=i?.version??null);let p=e.put(n,s,h);if(u){let g=_?.user?.username;if(E&&($l=e.encoder.encode(E)),f&&i?.localTime){let A=i?.localTime,b=r.get(A);if(b){let v=Ut(b).previousLocalTime;return r.put(A,Kl(o,t,n,v,g,d,$l),{ifVersion:S}),p}}r.put(dc,Kl(o,t,n,i?.localTime?1:0,g,d,$l),{append:d!=="invalidate",instructedWrite:!0,ifVersion:S})}return p}catch(p){throw p.message+=" id: "+n+" options: "+h,p}}}var DO,mh,Vl,dc,Ah,Rk,lc,_c,Ak,ph,LO,Ok,MO,Sh,Oh,bh,bk,$l,vo,Yl,Th,gh,ooe,Rh,wi,Bo=Re(()=>{DO=require("msgpackr");Ci();mh=B(Y()),Vl=new Uint8Array([1,1,1,1,4,64,0,0]),dc=new Uint8Array([1,1,1,1,1,0,0,0]),Ah=new Uint8Array([1,1,1,1,3,64,0,0]),Rk=Symbol("local-timestamp"),lc=Symbol("metadata"),_c=new Uint8Array(8),Ak=new DataView(_c.buffer,0,8),ph=0,LO=0,Ok=1,MO=3,Sh=4,Oh=16,bh=1,vo=0,Yl=-1,Th=0,gh=class extends DO.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(vo||Yl>=0){let i=0,o=vo;o&&(i+=8,vo=0);let c=Yl,u=Th;c>=0&&(i+=2,Yl=-1,u&&(i+=8,Th=0));let _=bk=r.call(this,n,s|2048|i);$l=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(Vl[4]=o,Vl[5]=o>>8,_.set(Vl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(_c,0,c),c+=8;else for(let d=0;d<8;d++)_c[d]=t[c++];u=Nk(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Oh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[lc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(Nk,"getTimestamp");ooe=Map.prototype.get;a(Wl,"fromResource");a(Ql,"handleLocalTimeForGets");wi=[];setInterval(()=>{for(let e=0;e<wi.length;e++){let t=wi[e].deref();!t||t.isDone||t.isCommitted?wi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(mh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):mh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(Nh,"getUpdateRecord")});var YO={};qe(YO,{AUDIT_STORE_OPTIONS:()=>VO,createAuditEntry:()=>Kl,openAuditStore:()=>jl,readAuditEntry:()=>Ut,setAuditRetention:()=>Ik,transactionKeyEncoder:()=>kO});function jl(e){let t=e.auditStore=e.openDB(FO.AUDIT_STORE_NAME,VO);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=zl){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-yh})){if((_[0]&15)===Ch){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=yk){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,yh/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,Xl.getWorkerIndex)()===(0,Xl.getWorkerCount)()-1&&s(zl),t}function Ik(e,t=zl){yh=e,zl=t}function Kl(e,t,r,n,s,i,o){let c=$O[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?Ho.setFloat64(0,n):en.set(Ah),u=9),f(0),f(t),d(r),Ho.setFloat64(u,e),u+=8,s?d(s):en[u++]=0,en[n?8:0]=c;let l=en.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,xo.writeKey)(E,en,u);let S=u-h-1;S>127?S>16383?(Lh.error("Key or username was too large for audit entry",E),u=h+1,en[h]=0):(en.copyWithin(h+2,h+1,u),Ho.setUint16(h,S|32768),u++):en[h]=S}function f(E){E<128?en[u++]=E:E<16384?(Ho.setUint16(u,E|32768),u+=2):E<1056964608?(Ho.setUint32(u,E|3221225472),u+=4):(en[u]=255,Ho.setUint32(u+1,E),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new Dh(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:$O[n&7],tableId:i,get recordId(){return xO(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?xO(e,l,d):void 0},getValue(f,E,h){if(n&Ih||n&wh&&!E)return f.decoder.decode(e.subarray(t.position));if(n&wh&&h)return Mh(f.getEntry(this.recordId),h,f)}}}catch{return Lh.error("Reading audit entry error",e),{}}}function xO(e,t,r){let n=e.subarray(t,r);return(0,xo.readKey)(n,0,r-t)}var xo,Jl,FO,qO,Xl,GO,Lh,en,Ho,kO,VO,yh,yk,zl,Ih,wh,PO,Ch,vO,BO,HO,$O,Dh,Ci=Re(()=>{xo=require("ordered-binary"),Jl=B(j()),FO=B(Et()),qO=B(M()),Xl=B(tt()),GO=B(J());Bo();Lh=B(Y());Zl();(0,Jl.initSync)();en=Buffer.alloc(1024),Ho=new DataView(en.buffer,en.byteOffset,1024),kO={writeKey(e,t,r){return e===dc?(t.set(dc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,xo.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,xo.readKey)(e,t,r)}},VO={encoding:"binary",keyEncoder:kO},yh=(0,GO.convertToMS)((0,Jl.get)(qO.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,yk=1e3,zl=1e4;a(jl,"openAuditStore");a(Ik,"setAuditRetention");Ih=16,wh=32,PO=1,Ch=2,vO=3,BO=4,HO=5,$O={put:PO|Ih,[PO]:"put",delete:Ch,[Ch]:"delete",message:vO|Ih,[vO]:"message",invalidate:BO,[BO]:"invalidate",patch:HO|wh,[HO]:"patch"};a(Kl,"createAuditEntry");a(Ut,"readAuditEntry");Dh=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(xO,"readKeySafely")});var Uh={};qe(Uh,{add:()=>e_,applyReverse:()=>KO,getRecordAtTime:()=>Mh,rebuildUpdateBefore:()=>t_});function e_(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function t_(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,e_(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function KO(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=wk[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=WO}}function Mh(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Ut(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":KO(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===WO&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Ut(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var wk,WO,Zl=Re(()=>{Ci();a(e_,"add");e_.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};wk={add:e_};a(t_,"rebuildUpdateBefore");a(KO,"applyReverse");WO={};a(Mh,"getRecordAtTime")});function Dr(e){return e[Ot]||(e[Ot]=Object.create(null))}function o_(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Ae])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a string, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a string, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a number, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new tn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new tn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new tn.ClientError(`${c} must be a number, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new tn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Dr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Dr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new tn.ClientError(`${c} must be an object, attempt to assign ${l}`);Dr(this)[c]=l},"set")}_={get(){let l=this[Ot];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[be]?.[c];return f.update(E)}return f}let d=this[be]?.[c];if(d&&typeof d=="object"){let f=QO(d,o);if(f)return l||(l=this[Ot]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[Ot];return u?.[o]!==void 0?u[o]:this[be]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new tn.ClientError("Can not add a property to a sealed table schema");Dr(this)[o]=c}),i("deleteProperty",function(o){Dr(this)[o]=void 0}),i("toJSON",function(){let o=this[Ot],c;for(let _ in o){c||(c=Object.assign({},this[be]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[be])),Object.assign(c,this)),c||this[be]}),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 QO(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){this[be]=s}},o_(r,t)),new r(e)):new r_(e);case Array:let n=new s_(e.length);n[be]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=QO(o,t?.elements)),n[s]=o}return n;default:return e}}function a_(e){let t=e[Ot],r;for(let s in t){r||(r=Object.assign({},e[be]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=a_(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[be])),Object.assign(r,e)),r||e[be]}function Li(e,t=e[Ot]){let r;if(e[be]&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Li(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[be]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=Uh[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Li(s);r[n]=s}return r?Object.freeze(r):e[be]||e}function n_(e){let t=e[be];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Di]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[be]===s){if(n_(i))return!0}else return!0}}else{let r=e[Ot];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[be]===i){if(n_(s))return!0}else return!0}else return!0}}return!1}var tn,Ot,r_,Di,s_,i_,c_=Re(()=>{On();tn=B(Z());Zl();Ot=Symbol("own-data");a(Dr,"getChanges");a(o_,"assignTrackedAccessors");a(QO,"trackObject");r_=class{static{a(this,"GenericTrackedObject")}constructor(t){this[be]=t}};o_(r_,{});a(a_,"collapseData");a(Li,"deepFreeze");a(n_,"hasChanges");Di=Symbol.for("has-array-changes"),s_=class extends Array{static{a(this,"TrackedArray")}[Di];constructor(t){super(t)}splice(...t){return this[Di]=!0,super.splice(...t)}push(...t){return this[Di]=!0,super.push(...t)}pop(){return this[Di]=!0,super.pop()}unshift(...t){return this[Di]=!0,super.unshift(...t)}shift(){return this[Di]=!0,super.shift()}};s_.prototype.constructor=Array;i_=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});function Mk(){Lk=setInterval(function(){for(let e of Ph)if(e.stale){let t=e[Ae]?.url;zO.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},Dk).unref()}var vh,zO,Ck,Ph,Mi,u_,Dk,Lk,Bh=Re(()=>{vh=B(Cr()),zO=B(Y());On();Bo();Ck=100,Ph=new Set,Mi=class{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=!0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(!this.open)throw new Error("Can not start a read on a transaction that is no longer open");return this.readTxnsUsed=1,Wl(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),Ph.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),Wl(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Ph.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(!this.open&&!this.autoCommitMode)throw new Error("Can not use a transaction that is no longer open");this.writes.push(t),this.autoCommitMode&&this.commit()}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,vh.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let S=this.writes[h];if(!S)continue;let p=S[f===0?"before":"beforeIntermediate"];if(p){let g=p();E?E.push?E.push(g):E=[E,g]:E=g}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),t?.prepared?.(),this.open=!1;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<Ck>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=!1,this.writes=[]}},u_=class extends Mi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,vh.getNextMonotonicTime)())}getReadTxn(){}},Dk=3e4;a(Mk,"startMonitoringTxns");Mk()});function Xe(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new Mi;e.timestamp&&(n.timestamp=e.timestamp),n[Ae]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit(r?.resetTransaction?{prepared(){n.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var JO,Ui=Re(()=>{JO=require("../index");On();Bh();a(Xe,"transaction");(0,JO._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Ae]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function Go(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let g=o[0],A=ps(n.attributes,g);if(A.relationship){if(o.length<2)throw new ms.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let b=A.definition?.tableClass||A.elements?.definition?.tableClass,v=new Map,G=Go({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,b,s,v);if(A.relationship.to){i[o[0]]=v;let H=!!ps(b.attributes,A.relationship.to)?.elements;G=Hk(G,A,b.primaryStore,H,v)}if(A.relationship.from){let H=a(P=>Go({attribute:A.relationship.from,value:P},t,r,n,s,v),"searchEntry");A.elements?(i[o[0]]=v,G=xk(G,A,b.primaryStore,v,H)):G=G.flatMap(H)}return G}else if(o.length===1)o=o[0];else throw new ms.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(qh[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=kn.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"contains":case"ends_with":E=!0;break;default:throw new ms.ClientError(`Unknown query comparator "${u}"`)}if(r){let g=_;_=l,l=g,g=!f,f=!d,d=g}let h=o===n.primaryKey||o==null,S=h?n.primaryStore:n.indices[o];if(!S||S.isIndexing||E||c===null&&!S.indexNulls){if(!s)throw new ms.ClientError(`"${o}" is not indexed${c===null&&!S.indexNulls?" for nulls, index needs to be rebuilt to search for nulls":S?.isIndexing?" yet":""}, can not search for this attribute`,404);let g=hc(e);if(!g)throw new ms.ClientError(`Unknown search operator ${e.comparator}`);return n.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:A,value:b})=>new Promise((v,G)=>setImmediate(()=>{try{v(b&&g(b)?A:Hh.SKIP)}catch(H){G(H)}})))}let p={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let g=S.getRange(p).map(A=>A.value==null?Hh.SKIP:A);return g.hasEntries=!0,g}else return S.getRange(p).map(({value:g})=>g)}function ps(e,t){if(Array.isArray(t))if(t.length>1){let r=ps(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?ps(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function Hk(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=bn(d),o=!0);let h=s.get(E);h?h.push(f):s.set(E,h=[f]),d!==E&&(h.key=d)},"add_entry"),l=0;for await(let d of e){let f=d.value??r.get(d.key??d),E=f?.[u];if(E!=null&&!s.filters?.some(h=>!h(f))){if(n)for(let h=0;h<E.length;h++)_(E[h],d);else _(E,d);l++>100&&(await new Promise(setImmediate),l=0)}}return i=(o?s:s.keys())[Symbol.iterator](),this.next()})()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function xk(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=bn(u.value);if(!c.has(_))return c.add(_),u}if(!i)return(async()=>{let _=new Map;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>_.has(bn(f)));let l=0;for await(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(E=>!E(f)))continue}_.set(bn(d),d),l++>100&&(await new Promise(setImmediate),l=0)}return i=_.values()[Symbol.iterator](),this.next()})();do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function hc(e,t,r,n,s,i){if(e.conditions){let l=e.conditions.map(hc);return e.operator==="or"?d=>l.some(f=>f(d)):d=>l.every(f=>f(d))}let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=ps(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=hc({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},f,r,E?.[l]?.joined,c[1]===f.primaryKey,i);if(!h)return;if(E){E.filters||(E.filters=[]),E.filters.push(h);return}let S=t.propertyResolvers?.[l],p,g=a((A,b)=>{let v,G;if(S){if(S.from&&h.idFilter){if(!p)if(h.idFilter.idSet?.size===1){for(let P of h.idFilter.idSet)e={attribute:S.from,value:P};p=_(S.from,h.idFilter,!0)}else p=_(S.from,h.idFilter,!1);let H=p(A);return p.idFilter&&(g.idFilter=p.idFilter),H}G=S(A,r,b),v=G?.value}else v=A[l];return v?Array.isArray(v)?v.some(h):h(v,G):!1},"recordFilter");return g}}switch(u instanceof Date&&(u=u.getTime()),qh[o]||o){case xh.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,f=u.length;d<f;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,kn.compareKeys)(l,u[0])>=0&&(0,kn.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,kn.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,kn.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,kn.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,kn.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,kn.compareKeys)(l,u)!==0);default:throw new ms.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f){let E;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&l_(t)(e),E=e.estimated_count>>4,(isNaN(E)||E>=i)&&(f=!1));let h=0,S=3;function p(g){let A=g[l],b;if(typeof A!="object"||!A?b=d(A):Array.isArray(A)?b=A.some(d):A instanceof Date&&(b=d(A.getTime())),f&&(S++,!b&&!p.idFilter&&++h/S*(i-S)>E)){let v=Go(e,r.transaction,!1,t).map(bn),G=new Set(v);p.idFilter=H=>G.has(bn(H)),p.idFilter.idSet=G}return b}return a(p,"recordFilter"),s&&(p.idFilter=d),p}a(_,"attributeComparator")}function l_(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Qs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=qh[n]||n,n===xh.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=ps(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=l_(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"});r.estimated_count=c*Qs(e.indices[i.relationship.from]||e.primaryStore)/(Qs(o.primaryStore)||1)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Qs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=vk*Qs(e.primaryStore)+1:n==="between"?r.estimated_count=Pk*Qs(e.primaryStore)+1:r.estimated_count=Uk*Qs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=4)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function __(e){if(e)if(zs=e,Fo.lastIndex=0,Fk.test(e))try{let t=fc(new qo,"");if(nr!==zs.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${nr} in '${zs}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function fc(e,t){let r=Fo,n,s,i,o,c,u=decodeURIComponent;for(;n=r.exec(zs);){nr=r.lastIndex;let[,_,l]=n;if(o){if(_)throw new SyntaxError(`expected operator, but encountered '${_}'`);o=!1,c=!1}else c=!0;let d;switch(l){case"=":if(s){if(_.length<=2)i=_;else throw new SyntaxError(`invalid FIQL operator ${_}`);u=XO}else{if(u=decodeURIComponent,i="equals",!_)throw new SyntaxError("attribute must be specified before equality comparator");s=Ec(_)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Bk[l],u=Fh[i]?XO:decodeURIComponent,!_)throw new SyntaxError(`attribute must be specified before comparator ${l}`);s=Ec(_);break;case"|":e.operator="or";case"":case void 0:case"&":if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${l[0]?"'"+l[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${l?"'"+l+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let E={comparator:i,attribute:s,value:u(_)};i==="eq"&&jO(E,_),e.conditions.push(E)}s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(Ec(_)),s=void 0;break;case"(":Fo.lastIndex=nr;let f=fc(_?[]:new qo,")");switch(_){case"":e.conditions.push(f);break;case"limit":switch(f.length){case 1:e.limit=+f[0];break;case 2:e.offset=+f[0],e.limit=f[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(f[0])&&f.length===1&&!f[0].name?(e.select=f[0],e.select.asArray=!0):f.length===1?e.select=f[0]:f.length===2&&f[1]===""?e.select=f.slice(0,1):e.select=f;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=ZO(f);break;default:throw new SyntaxError(`unknown query function call ${_}`)}zs[nr]===","?r.lastIndex=++nr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!_)throw new SyntaxError("property sets must have a defined parent property name");Fo.lastIndex=nr,d=fc([],"}"),d.name=_,e.push(d),zs[nr]===","?r.lastIndex=++nr:o=!0;break;case"[":Fo.lastIndex=nr,_?(d=fc(new qo,"]"),d.name=_):d=fc(e.conditions?new qo:[],"]"),e.conditions?(e.conditions.push(d),s=null):e.push(d),zs[nr]===","?r.lastIndex=++nr:o=!0;break;case")":case"]":case"}":if(t===l[0]){if(e.conditions){if(s){let E={comparator:i||"equals",attribute:s,value:u(_)};i==="eq"&&jO(E,_),e.conditions.push(E)}else if(_)throw new SyntaxError("no attribute or comparison specified")}else(_||e.length>0&&c)&&e.push(Ec(_));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${l[0]}'`):new SyntaxError(`unexpected token '${l[0]}'`);default:throw new SyntaxError(`unexpected operator '${l}'`)}if(t!==")"&&(r=s?qk:Fo,r.lastIndex=nr),nr===zs.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Ec(e){return e.indexOf(".")>-1?e.split(".").map(Ec):decodeURIComponent(e)}function XO(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new ms.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function jO(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new ms.ClientError("wildcard can only be used at the end of a string")}function ZO(e){let t=eb(e[0]);return e.length>1&&(t.next=ZO(e.slice(1))),t}function eb(e){if(Array.isArray(e)){let t=eb(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function bn(e){return Array.isArray(e)?e.join("\0"):e}function Qs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function tb(e,t,r){return t*r/Qs(e)}var ms,xh,kn,Hh,Uk,Pk,vk,Bk,Fh,qh,Fk,Fo,qk,nr,zs,qo,d_=Re(()=>{ms=B(Z()),xh=B(Et()),kn=require("ordered-binary"),Hh=require("lmdb"),Uk=.3,Pk=.1,vk=.05,Bk={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Fh={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Go,"searchByIndex");a(ps,"findAttribute");a(Hk,"joinTo");a(xk,"joinFrom");qh={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(hc,"filterByType");a(l_,"estimateCondition");Fk=/[()[\]|!<>.]|(=\w*=)/,Fo=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,qk=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(__,"parseQuery");a(fc,"parseBlock");a(Ec,"decodeProperty");a(XO,"typedDecoding");a(jO,"wildcardDecoding");a(ZO,"toSortObject");a(eb,"toSortEntry");qo=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(bn,"flattenKey");a(Qs,"estimatedEntryCount");a(tb,"intersectionEstimate")});var Vh={};qe(Vh,{CONTEXT:()=>Ae,ID_PROPERTY:()=>Ce,IS_COLLECTION:()=>rn,RECORD_PROPERTY:()=>be,Resource:()=>Ft,snake_case:()=>kk,transformForSelect:()=>E_});function kk(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function rb(e,t){if(mc=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(mc=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new kh;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){mc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function Lr(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Ae]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[Ae]||i):l=i:(l=s,c=l[Ce]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ae]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let E=c.indexOf("?");if(E>-1){let S=this.parseQuery(c.slice(E+1));u?u=Object.assign(S,u):u=S,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return d.resetTransaction=!0,Xe(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(S=>{if(!S)throw new f_(o.user);return typeof l?.then=="function"?l.then(p=>e(E,u,o,p)):e(E,u,o,l)});if(!h)throw new f_(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Mr(e,t){let r=new ib.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function Gh(e,t,r){let n=e[be];if(n){let s=e[Ot];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function E_(e,t){let r=t?.propertyResolvers,n=t[Ae],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):Gh(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(Gh(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(Gh(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=E_(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var nb,sb,ib,Ae,Ce,rn,be,Gk,Ft,f_,mc,kh,On=Re(()=>{nb=require("crypto");uc();sb=require("../index"),ib=B(Z());c_();Ui();d_();Ae=Symbol.for("context"),Ce=Symbol.for("primary-key"),rn=Symbol("is-collection"),be=Symbol("stored-record"),Gk={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Ft=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ce]=t;let n=r?.[Ae];this[Ae]=n!==void 0?n:r||null}static get=Lr(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=E_(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",resetTransaction:!0,ensureLoaded:!0,async:!0});static put=Lr(function(t,r,n,s){if(Array.isArray(s)&&t[rn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Mr(t,"put")},{hasContent:!0,type:"update"});static patch=Lr(function(t,r,n,s){return t.patch?t.patch(s,r):Mr(t,"patch")},{hasContent:!0,type:"update"});static delete=Lr(function(t,r,n,s){return t.delete?t.delete(r):Mr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,nb.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),Xe(n,()=>{let i=new this(s,n),o=i.update?i.update(r):Mr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=Lr(function(t,r,n,s){return t.invalidate?t.invalidate(r):Mr(t,"delete")},{hasContent:!1,type:"update"});static post=Lr(function(t,r,n,s){return t[Ce]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Lr(function(t,r,n,s){return t.connect?t.connect(s,r):Mr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Lr(function(t,r,n,s){return t.subscribe?t.subscribe(r):Mr(t,"subscribe")},{type:"read"});static publish=Lr(function(t,r,n,s){return t[Ce]!=null&&t.update?.(),t.publish?t.publish(s,r):Mr(t,"publish")},{hasContent:!0,type:"create"});static search=Lr(function(t,r,n,s){let i=t.search?t.search(r):Mr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=E_(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Lr(function(t,r,n,s){return t.search?t.search(s,r):Mr(t,"search")},{hasContent:!0,type:"read"});static copy=Lr(function(t,r,n,s){return t.copy?t.copy(s,r):Mr(t,"copy")},{type:"create"});static move=Lr(function(t,r,n,s){return t.move?t.move(s,r):Mr(t,"move")},{type:"delete"});post(t){if(this[rn])return this.constructor.create(this[Ce],t,this[Ae]);Mr(this,"post")}static isCollection(t){return t?.[rn]}static coerceId(t){return t}static parseQuery(t){return __(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&Gk[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:rb(t,this),isCollection:mc}}let i=rb(t,this);return mc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Ae],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Ce]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Ce],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[rn]=!0),s}subscribe(t){return new An}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new An}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[Ce]}getContext(){return this[Ae]}};Ft.prototype[Ae]=null;(0,sb._assignPackageExport)("Resource",Ft);a(kk,"snake_case");f_=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(rb,"pathToId");kh=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Lr,"transactional");a(Mr,"missingMethod");a(Gh,"selectFromObject");a(E_,"transformForSelect")});var ob={};qe(ob,{Resources:()=>h_,keyArrayToString:()=>ko,resetResources:()=>Vk,resources:()=>Js});function Vk(){return Js=new h_}function ko(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var h_,Js,pc=Re(()=>{Ui();h_=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Xe(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(Vk,"resetResources");a(ko,"keyArrayToString")});function cb(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;Vo||((0,m_.onMessageByType)(ab,l=>{ub(l.path)}),Vo=Object.create(null));let o=Vo[s]||(Vo[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=ko(t);let u=new Yh(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function ub(e,t){if(!Vo)return;let r=Vo[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Ut(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=ko(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,$h.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let S;h.supportsTransactions&&h.txnInProgress!==o.version&&(S=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,S)}catch(S){console.error(S),(0,$h.info)(S)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function lb(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,m_.broadcast)({type:ab,path:s}),ub(s,!0)})}}var $h,m_,ab,Vo,koe,Yh,_b=Re(()=>{$h=B(Y()),m_=B(tt());uc();pc();Ci();ab="transaction",koe=Buffer.alloc(4096);a(cb,"addSubscription");Yh=class extends An{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(ub,"notifyFromTransactionData");a(lb,"listenToCommits")});var fb=T((Yoe,db)=>{"use strict";var Kh=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};db.exports=Kh});var hb=T((Woe,Eb)=>{"use strict";var Wh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Eb.exports=Wh});var p_=T((zoe,mb)=>{"use strict";var zh=j(),Jh=M(),{RecordEncoder:$k}=(Bo(),ee(UO));zh.initSync();var Yk=zh.get(Jh.CONFIG_PARAMS.STORAGE_COMPRESSION),Kk=zh.get(Jh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,Wk=Jh.UPDATES_PROPERTY,Qh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=Yk&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=Kk&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:$k},this.alwaysLazyProperty=n=>n===Wk)}};mb.exports=Qh});var T_=T((Xoe,Sb)=>{"use strict";var $o=j(),Sc=M();$o.initSync();var Qk=$o.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||$o.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||$o.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",pb=$o.get(Sc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),zk=$o.get(Sc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),S_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=Qk,this.noFSAccess=!0,pb!==void 0&&(this.overlappingSync=pb),this.noReadAhead=zk}};Sb.exports=S_;S_.MAX_DBS=1e4});var We=T((Zoe,wb)=>{"use strict";var jh=require("lmdb"),Nn=require("fs-extra"),Ur=require("path"),g_=Cr(),Rb=Y(),sr=wr().LMDB_ERRORS_ENUM,R_=hb(),Zh=p_(),Ab=T_(),Xs=Et(),Tb=M(),{table:Jk,resetDatabases:Xk}=(Oe(),ee(Ge)),gb=j(),yn=Xs.INTERNAL_DBIS_NAME,Ob=Xs.DBI_DEFINITION_NAME,jk="data.mdb",Zk="lock.mdb",Tc=".mdb",eV="-lock",Xh=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=nn(t,r),this.key_type=this.dbi[Xs.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Xs.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new jh.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function A_(e,t){if(e===void 0)throw new Error(sr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(sr.ENV_NAME_REQUIRED)}a(A_,"pathEnvNameValidation");async function em(e,t,r=!0){try{await Nn.access(e)}catch(n){throw n.code==="ENOENT"?new Error(sr.INVALID_BASE_PATH):n}try{let n=Ur.join(e,t+Tc);return await Nn.access(n,Nn.constants.R_OK|Nn.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await Nn.access(Ur.join(e,t,jk),Nn.constants.R_OK|Nn.constants.F_OK),Ur.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(sr.INVALID_ENVIRONMENT)}else throw new Error(sr.INVALID_ENVIRONMENT);throw n}}a(em,"validateEnvironmentPath");function O_(e,t){if(g_.validateEnv(e),t===void 0)throw new Error(sr.DBI_NAME_REQUIRED)}a(O_,"validateEnvDBIName");async function tV(e,t,r=!1,n=!1){A_(e,t);let s=Ur.basename(e);t=t.toString();let i=gb.get(Tb.CONFIG_PARAMS.DATABASES);i||gb.setProperty(Tb.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await em(e,t,n),bb(e,t,r)}catch(o){if(o.message===sr.INVALID_ENVIRONMENT){let c=Ur.join(e,t);await Nn.mkdirp(n?c:e);let u=new Ab(n?c:c+Tc,!1),_=jh.open(u);_.dbis=Object.create(null);let l=new Zh(!1);_.openDB(yn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=tm(e,t,r);return _[Xs.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(tV,"createEnvironment");async function rV(e,t,r,n=!0){A_(e,t),t=t.toString();let s=Ur.join(e,t);return Jk({table:t,database:Ur.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(rV,"copyEnvironment");async function bb(e,t,r=!1){A_(e,t),t=t.toString();let n=tm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await em(e,t),i=Ur.join(e,t+Tc),o=s!=i,c=new Ab(s,o),u=jh.open(c);u.dbis=Object.create(null);let _=yb(u);for(let l=0;l<_.length;l++)nn(u,_[l]);return u[Xs.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(bb,"openEnvironment");async function nV(e,t,r=!1){A_(e,t),t=t.toString();let n=Ur.join(e,t+Tc),s=await em(e,t);if(global.lmdb_map!==void 0){let i=tm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Nb(o),delete global.lmdb_map[i]}}await Nn.remove(s),await Nn.remove(s===n?s+eV:Ur.join(Ur.dirname(s),Zk))}a(nV,"deleteEnvironment");async function Nb(e){g_.validateEnv(e);let t=e[Xs.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Nb,"closeEnvironment");function tm(e,t,r=!1){let s=`${Ur.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(tm,"getCachedEnvironmentName");function sV(e){g_.validateEnv(e);let t=Object.create(null),r=nn(e,yn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==yn)try{t[n]=Object.assign(new R_,s)}catch{Rb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(sV,"listDBIDefinitions");function yb(e){g_.validateEnv(e);let t=[],r=nn(e,yn);for(let{key:n}of r.getRange({start:!1}))n!==yn&&t.push(n);return t}a(yb,"listDBIs");function iV(e,t){let n=nn(e,yn).getEntry(t),s=new R_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{Rb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(iV,"getDBIDefinition");function Ib(e,t,r,n=!r){if(O_(e,t),t=t.toString(),t===yn)throw new Error(sr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return nn(e,t)}catch(s){if(s.message===sr.DBI_DOES_NOT_EXIST){let i=new Zh(r,n===!0),o=e.openDB(t,i),c=new R_(r===!0,n);return o[Ob]=c,nn(e,yn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(Ib,"createDBI");function nn(e,t){if(O_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==yn?r=iV(e,t):r=new R_,r===void 0)throw new Error(sr.DBI_DOES_NOT_EXIST);let n;try{let s=new Zh(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(sr.DBI_DOES_NOT_EXIST):s}return n[Ob]=r,e.dbis[t]=n,n}a(nn,"openDBI");function oV(e,t){O_(e,t),t=t.toString();let r=nn(e,t),n=r.getStats();return r[Xs.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(oV,"statDBI");async function aV(e,t){try{let r=Ur.join(e,t+Tc);return(await Nn.stat(r)).size}catch{throw new Error(sr.INVALID_ENVIRONMENT)}}a(aV,"environmentDataSize");function cV(e,t){if(O_(e,t),t=t.toString(),t===yn)throw new Error(sr.CANNOT_DROP_INTERNAL_DBIS_NAME);nn(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],nn(e,yn).removeSync(t)}a(cV,"dropDBI");function uV(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{nn(e,i)}catch(o){if(o.message===sr.DBI_DOES_NOT_EXIST)Ib(e,i,i!==t,i===t),n=!0;else throw o}}n&&Xk()}a(uV,"initializeDBIs");wb.exports={openDBI:nn,openEnvironment:bb,createEnvironment:tV,listDBIs:yb,listDBIDefinitions:sV,createDBI:Ib,dropDBI:cV,statDBI:oV,deleteEnvironment:nV,initializeDBIs:uV,TransactionCursor:Xh,environmentDataSize:aV,copyEnvironment:rV,closeEnvironment:Nb}});var Lb=T((tae,Db)=>{"use strict";var rm=We(),lV=Y(),Cb=wr().LMDB_ERRORS_ENUM;Db.exports=_V;async function _V(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 rm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Cb.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await rm.closeEnvironment(global.lmdb_map[n]),await rm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Cb.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){lV.error(t)}}a(_V,"cleanLMDBMap")});var Pi=T((nae,dV)=>{dV.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var $b=T((iae,Vb)=>{"use strict";var nm=require("recursive-iterator"),fV=require("alasql"),sm=require("clone"),Mb=J(),{handleHDBError:Ub,hdb_errors:EV}=Z(),{HDB_ERROR_MSGS:Pb,HTTP_STATUS_CODES:vb}=EV,{getDatabases:hV}=(Oe(),ee(Ge)),mV=["DISTINCT_ARRAY"],Bb=Symbol("validateTables"),im=Symbol("validateTable"),sae=Symbol("getAllColumns"),Hb=Symbol("validateAllColumns"),b_=Symbol("findColumn"),xb=Symbol("validateOrderBy"),gc=Symbol("validateSegment"),om=Symbol("validateColumn"),Fb=Symbol("setColumnsForTable"),qb=Symbol("checkColumnsForAsterisk"),Gb=Symbol("validateGroupBy"),kb=Symbol("hasColumns"),am=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Bb](),this[qb](),this[Hb]()}[Bb](){if(this[kb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[im](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[im](t.table)})}}[kb](){let t=!1,r=new nm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[im](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=hV();if(!r[t.databaseid])throw Ub(new Error,Pb.SCHEMA_NOT_FOUND(t.databaseid),vb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Ub(new Error,Pb.TABLE_NOT_FOUND(t.databaseid,t.tableid),vb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=sm(s);i.table=sm(t),this.attributes.push(i)})}[b_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[qb](){let t=new nm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Fb](r.tableid)}[Fb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new fV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Hb](){this[gc](this.statement.columns,!1),this[gc](this.statement.joins,!1),this[gc](this.statement.where,!1),this[Gb](this.statement.group,!1),this[gc](this.statement.order,!0)}[gc](t,r){if(!t)return;let n=new nm(t),s=[];for(let{node:i,path:o}of n)!Mb.isEmpty(i)&&!Mb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[xb](i):s.push(this[om](i)));return s}[Gb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&mV.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=sm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[b_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[b_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[xb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[om](t)}[om](t){let r=this[b_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Vb.exports=am});var Kb=T((aae,Yb)=>{"use strict";var cm=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Yb.exports=cm});var Qb=T((uae,Wb)=>{"use strict";var um=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Wb.exports=um});var Jb=T((_ae,zb)=>{"use strict";var lm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};zb.exports=lm});var jb=T((fae,Xb)=>{"use strict";var _m=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Xb.exports=_m});var Yo=T((Sae,tN)=>{"use strict";var pV=We(),SV=Qb(),TV=Jb(),gV=jb(),Vn=Cr(),Rc=wr().LMDB_ERRORS_ENUM,RV=Et(),Ss=M(),AV=J(),OV=require("uuid"),hae=require("lmdb"),{handleHDBError:bV,hdb_errors:NV}=Z(),{OVERFLOW_MARKER:mae,MAX_SEARCH_KEY_LENGTH:pae}=RV,Zb=j();Zb.initSync();var N_=Zb.get(Ss.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),dm=Ss.TIME_STAMP_NAMES_ENUM.CREATED_TIME,vi=Ss.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function yV(e,t,r,n,s=Vn.getNextMonotonicTime()){mm(e,t,r,n),fm(e,t,r);let i=new SV,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];eN(_,!0,s);let l=IV(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Em(o,c,n,i,s)}a(yV,"insertRecords");function IV(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Ss.FUNC_VAL],n[o]=c)}let u=Vn.getIndexedValues(c),_=e.dbis[o];if(u){N_&&_.prefetch(u.map(l=>({key:l,value:s})),y_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}N_&&e.dbis[t].prefetch([s],y_),e.dbis[t].put(s,n,n[vi])})}a(IV,"insertRecord");function wV(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(wV,"removeSkippedRecords");function eN(e,t,r){let n=r>0;(n||!Number.isInteger(e[vi]))&&(e[vi]=r||(r=Vn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[dm]))&&(e[dm]=r||Vn.getNextMonotonicTime()):delete e[dm]}a(eN,"setTimestamps");function fm(e,t,r){r.indexOf(Ss.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ss.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ss.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ss.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),pV.initializeDBIs(e,t,r)}a(fm,"initializeTransaction");async function CV(e,t,r,n,s=Vn.getNextMonotonicTime()){mm(e,t,r,n),fm(e,t,r);let i=new TV,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=hm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return Em(c,u,n,i,s,o)}a(CV,"updateRecords");async function DV(e,t,r,n,s=Vn.getNextMonotonicTime()){try{mm(e,t,r,n)}catch(u){throw bV(u,u.message,NV.HTTP_STATUS_CODES.BAD_REQUEST)}fm(e,t,r);let i=new gV,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;AV.isEmpty(_[t])?(l=OV.v4(),_[t]=l):l=_[t];let d=hm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Em(o,c,n,i,s)}a(DV,"upsertRecords");async function Em(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Vn.getNextMonotonicTime(),wV(r,i),n}a(Em,"finalizeWrite");function hm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(eN(r,!l,o),Number.isInteger(r[vi])&&_[vi]>r[vi])return!1;l&&s.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let S=r[h],p=e.dbis[h];if(p===void 0)continue;let g=_[h];if(typeof S=="function"){let b=S([[_]]);Array.isArray(b)&&(S=b[0][Ss.FUNC_VAL],r[h]=S)}if(S===g)continue;let A=Vn.getIndexedValues(g);if(A){N_&&p.prefetch(A.map(b=>({key:b,value:n})),y_);for(let b=0,v=A.length;b<v;b++)p.remove(A[b],n)}if(A=Vn.getIndexedValues(S),A){N_&&p.prefetch(A.map(b=>({key:b,value:n})),y_);for(let b=0,v=A.length;b<v;b++)p.put(A[b],n)}}let E=Object.assign({},_,r);c.put(n,E,E[vi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:hm(e,t,r,n,s,i,o))}a(hm,"updateUpsertRecord");function LV(e,t,r){if(Vn.validateEnv(e),t===void 0)throw new Error(Rc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Rc.WRITE_ATTRIBUTES_REQUIRED):new Error(Rc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(LV,"validateBasic");function mm(e,t,r,n){if(LV(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Rc.RECORDS_REQUIRED):new Error(Rc.RECORDS_MUST_BE_ARRAY)}a(mm,"validateWrite");function y_(){}a(y_,"noop");tN.exports={insertRecords:yV,updateRecords:CV,upsertRecords:DV}});var Yn=T((gae,sN)=>{"use strict";var nN=J(),rN=M(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,$n=require("joi"),js={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},MV=$n.alternatives($n.string().min(1).max(js.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+js.schema_format.message}),$n.number(),$n.array()).required(),UV=$n.alternatives($n.string().min(1).max(js.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+js.schema_format.message}),$n.number()),PV=$n.alternatives($n.string().min(1).max(js.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+js.schema_format.message}),$n.number()).required();function vV(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>js.schema_length.maximum?`'${e}' maximum of 250 characters`:Ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(vV,"checkValidTable");function BV(e,t){return nN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(BV,"validateSchemaExists");function HV(e,t){let r=t.state.ancestors[0].schema;return nN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(HV,"validateTableExists");function xV(e,t){return e.toLowerCase()===rN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${rN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(xV,"validateSchemaName");sN.exports={common_validators:js,schema_regex:Ko,hdb_schema_table:MV,validateSchemaExists:BV,validateTableExists:HV,validateSchemaName:xV,checkValidTable:vV,hdb_database:UV,hdb_table:PV}});var rt=T((Aae,iN)=>{"use strict";var ir=require("validate.js");ir.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||ir.validators.type.checks[t](e)?null:` must be a '${t}' value`};ir.validators.type.checks={Object:function(e){return ir.isObject(e)&&!ir.isArray(e)},Array:ir.isArray,Integer:ir.isInteger,Number:ir.isNumber,String:ir.isString,Date:ir.isDate,Boolean:function(e){return typeof e=="boolean"}};ir.validators.hasValidFileExt=function(e,t){return ir.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};iN.exports={validateObject:FV,validateObjectAsync:qV,validateBySchema:GV};function FV(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=ir(e,t,{format:"flat"});return r?new Error(r):null}a(FV,"validateObject");async function qV(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await ir.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(qV,"validateObjectAsync");function GV(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(GV,"validateBySchema")});var I_=T((bae,oN)=>{var{common_validators:Kn}=Yn(),Oc=rt(),Ac="is required",ht={database:{presence:!1,format:Kn.schema_format,length:Kn.schema_length},schema:{presence:!1,format:Kn.schema_format,length:Kn.schema_length},table:{presence:!0,format:Kn.schema_format,length:Kn.schema_length},attribute:{presence:!0,format:Kn.schema_format,length:Kn.schema_length},hash_attribute:{presence:!0,format:Kn.schema_format,length:Kn.schema_length}};function bc(e){for(let t in e)e[t]=e[t]===null||e[t]===void 0||typeof e[t]=="object"?e[t]:e[t].toString();return e}a(bc,"makeAttributesStrings");function kV(e){return e=bc(e),ht.table.presence=!1,ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Oc.validateObject(e,ht)}a(kV,"schema_object");function VV(e){return e=bc(e),ht.table.presence={message:Ac},ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Oc.validateObject(e,ht)}a(VV,"table_object");function $V(e){return e=bc(e),ht.table.presence={message:Ac},ht.attribute.presence=!1,Oc.validateObject(e,ht)}a($V,"create_table_object");function YV(e){return e=bc(e),ht.table.presence={message:Ac},ht.attribute.presence={message:Ac},ht.hash_attribute.presence=!1,Oc.validateObject(e,ht)}a(YV,"attribute_object");function KV(e){return e=bc(e),ht.table.presence={message:Ac},ht.attribute.presence=!1,ht.hash_attribute.presence=!1,Oc.validateObject(e,ht)}a(KV,"describe_table");function WV(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(WV,"validateTableResidence");oN.exports={schema_object:kV,create_table_object:$V,table_object:VV,attribute_object:YV,describe_table:KV,validateTableResidence:WV}});var cN=T((yae,aN)=>{"use strict";var QV=require("uuid"),pm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||QV.v4(),this.schema_table=`${this.schema}.${this.table}`}};aN.exports=pm});var w_=T((wae,uN)=>{"use strict";var zV=cN(),Sm=class extends zV{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};uN.exports=Sm});var _N=T((Dae,lN)=>{"use strict";lN.exports=XV;var JV="inserted";function XV(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===JV?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(XV,"returnObject")});var C_=T((Mae,mN)=>{"use strict";var jV=M(),Tm=We(),ZV=Yo(),{getSystemSchemaPath:e$,getSchemaPath:t$}=Je(),r$=Pi(),n$=I_(),s$=w_(),i$=_N(),{handleHDBError:dN,hdb_errors:EN}=Z(),fN=J(),{HTTP_STATUS_CODES:o$}=EN,gm=r$.hdb_attribute,hN=[];for(let e=0;e<gm.attributes.length;e++)hN.push(gm.attributes[e].attribute);var a$="inserted";mN.exports=c$;async function c$(e){let t=n$.attribute_object(e);if(t)throw dN(new Error,t.message,EN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&fN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw dN(new Error,r,o$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=fN.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new s$(e.schema,e.table,e.attribute,e.id);try{let i=await Tm.openEnvironment(t$(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}`);Tm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Tm.openEnvironment(e$(),jV.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await ZV.insertRecords(o,gm.hash_attribute,hN,[s]);return i$(a$,c,{records:[s]},u)}catch(i){throw i}}a(c$,"lmdbCreateAttribute")});var Am=T((Pae,SN)=>{var{hdb_table:u$,hdb_database:pN}=Yn(),l$=rt(),Rm=require("joi"),_$={undefined:"undefined",null:"null"},d$=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||_$[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),f$=Rm.object({database:pN,schema:pN,table:u$,records:Rm.array().items(Rm.object().custom(d$)).required()});SN.exports=function(e){return l$.validateBySchema(e,f$)}});var Nc=T((Hae,gN)=>{"use strict";var Ts=J(),TN=Y(),Bae=Am(),{getDatabases:E$}=(Oe(),ee(Ge)),{ClientError:Bi}=Z();gN.exports=h$;function h$(e){if(Ts.isEmpty(e))throw new Bi("invalid update parameters defined.");if(Ts.isEmptyOrZeroLength(e.schema))throw new Bi("invalid schema specified.");if(Ts.isEmptyOrZeroLength(e.table))throw new Bi("invalid table specified.");if(!Array.isArray(e.records))throw new Bi("records must be an array");let t=E$()[e.schema]?.[e.table];if(Ts.isEmpty(t))throw new Bi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Ts.isEmptyOrZeroLength(o[r]))throw TN.error("a valid hash attribute must be provided with update record:",o),new Bi("a valid hash attribute must be provided with update record, check log for more info");if(!Ts.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw TN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Bi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Ts.isEmpty(o[r])&&o[r]!==""&&n.has(Ts.autoCast(o[r]))&&(o.skip=!0),n.add(Ts.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(h$,"insertUpdateValidate")});var yc=T((Fae,RN)=>{"use strict";var m$=M().OPERATIONS_ENUM,Om=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=m$.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};RN.exports=Om});var Dc=T((kae,AN)=>{"use strict";var Gae=yc(),D_=M(),Nm=J(),bm=Y(),p$=require("uuid"),{handleHDBError:Ic,hdb_errors:S$}=Z(),{HDB_ERROR_MSGS:wc,HTTP_STATUS_CODES:Cc}=S$;AN.exports=T$;function T$(e,t,r){for(let s=0;s<t.length;s++)g$(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];R$(i,r,e.operation)}}a(T$,"processRows");function g$(e){if(Buffer.byteLength(String(e))>D_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Ic(new Error,wc.ATTR_NAME_LENGTH_ERR(e),Cc.BAD_REQUEST,void 0,void 0,!0);if(Nm.isEmptyOrZeroLength(e)||Nm.isEmpty(e.trim()))throw Ic(new Error,wc.ATTR_NAME_NULLISH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}a(g$,"validateAttribute");function R$(e,t,r){if(!e.hasOwnProperty(t)||Nm.isEmptyOrZeroLength(e[t])){if(r===D_.OPERATIONS_ENUM.INSERT||r===D_.OPERATIONS_ENUM.UPSERT){e[t]=p$.v4();return}throw bm.error("Update transaction aborted due to record with no hash value:",e),Ic(new Error,wc.RECORD_MISSING_HASH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>D_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw bm.error(e),Ic(new Error,wc.HASH_VAL_LENGTH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw bm.error(e),Ic(new Error,wc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}a(R$,"validateHash")});var L_=T(($ae,bN)=>{"use strict";var ON=J(),A$=M(),O$=Y(),b$=C_(),N$=w_(),y$=gs(),{SchemaEventMsg:I$}=In(),w$="already exists in";bN.exports=C$;async function C$(e,t,r){if(ON.isEmptyOrZeroLength(r))return r;let n=[];ON.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await D$(e,t.schema,t.name,i)})),s}a(C$,"lmdbCheckForNewAttributes");async function D$(e,t,r,n){let s=new N$(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await L$(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(w$))O$.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(D$,"createNewAttribute");async function L$(e){let t;return t=await b$(e),y$.signalSchemaChange(new I$(process.pid,A$.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(L$,"createAttribute")});var Wo=T((Kae,NN)=>{"use strict";var ym=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};NN.exports=ym});var IN=T((Qae,yN)=>{"use strict";var M$=Wo(),U$=M().OPERATIONS_ENUM,Im=class extends M${static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(U$.INSERT,r,n,s,i),this.records=t}};yN.exports=Im});var CN=T((Jae,wN)=>{"use strict";var P$=Wo(),v$=M().OPERATIONS_ENUM,wm=class extends P${static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(v$.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};wN.exports=wm});var LN=T((jae,DN)=>{"use strict";var B$=Wo(),H$=M().OPERATIONS_ENUM,Cm=class extends B${static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(H$.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};DN.exports=Cm});var UN=T((ece,MN)=>{"use strict";var x$=Wo(),F$=M().OPERATIONS_ENUM,Dm=class extends x${static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(F$.DELETE,n,s,t,i),this.original_records=r}};MN.exports=Dm});var Lc=T((nce,HN)=>{"use strict";var rce=require("path"),PN=We(),q$=IN(),G$=CN(),k$=LN(),V$=UN(),Qo=Et(),vN=J(),{CONFIG_PARAMS:$$}=M(),BN=j();BN.initSync();var M_=M().OPERATIONS_ENUM,{getTransactionAuditStorePath:Y$}=Je();HN.exports=K$;async function K$(e,t){if(BN.get($$.LOGGING_AUDITLOG)===!1)return;let r=Y$(e.schema,e.table),n=await PN.openEnvironment(r,e.table,!0),s=W$(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){PN.initializeDBIs(n,Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Qo.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),vN.isEmpty(s.user_name)||n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(K$,"writeTransaction");function W$(e,t){let r=vN.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===M_.INSERT)return new q$(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===M_.UPDATE)return new G$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===M_.UPSERT)return new k$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===M_.DELETE)return new V$(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(W$,"createTransactionObject")});var Lm=T((oce,xN)=>{"use strict";var Q$=Nc(),ice=yc(),Mc=M(),z$=Dc(),J$=Yo().insertRecords,X$=We(),j$=Y(),Z$=L_(),{getSchemaPath:e1}=Je(),t1=Lc();xN.exports=r1;async function r1(e){try{let{schema_table:t,attributes:r}=Q$(e);z$(e,r,t.hash_attribute),e.schema!==Mc.SYSTEM_SCHEMA_NAME&&(r.includes(Mc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Mc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Mc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Mc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Z$(e.hdb_auth_header,t,r),s=e1(e.schema,e.table),i=await X$.openEnvironment(s,e.table),o=await J$(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await t1(e,o)}catch(c){j$.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(r1,"lmdbCreateRecords")});var GN=T((cce,qN)=>{"use strict";var FN=M(),n1=Lm(),s1=yc(),i1=require("fs-extra"),{getSchemaPath:o1}=Je();qN.exports=a1;async function a1(e){let t=[{name:e.schema,createddate:Date.now()}],r=new s1(FN.SYSTEM_SCHEMA_NAME,FN.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await n1(r),await i1.mkdirp(o1(e.schema))}a(a1,"lmdbCreateSchema")});var VN=T((lce,kN)=>{"use strict";var Mm=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};kN.exports=Mm});var WN=T((hce,KN)=>{"use strict";var $N=We(),Um=Cr(),Pm=wr().LMDB_ERRORS_ENUM,c1=Et(),YN=Y(),dce=J(),u1=require("lmdb"),l1=VN(),_1=M(),{OVERFLOW_MARKER:fce,MAX_SEARCH_KEY_LENGTH:Ece}=c1,d1=_1.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function f1(e,t,r,n){if(Um.validateEnv(e),t===void 0)throw new Error(Pm.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Pm.IDS_REQUIRED):new Error(Pm.IDS_MUST_BE_ITERABLE);try{let s=$N.listDBIs(e);$N.initializeDBIs(e,t,s);let i=new l1,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||n&&h[d1]>n){i.skipped.push(o);continue}let S=e.dbis[t].ifVersion(o,u1.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let p=0;p<s.length;p++){let g=s[p];if(!h.hasOwnProperty(g)||g===t)continue;let A=e.dbis[g],b=h[g];if(b!=null)try{let v=Um.getIndexedValues(b);if(v)for(let G=0,H=v.length;G<H;G++)A.remove(v[G],o)}catch{YN.warn(`cannot delete from attribute: ${g}, ${b}:${o}`)}}});c.push(S),u.push(o),i.original_records.push(h)}catch(h){YN.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=Um.getNextMonotonicTime(),i}catch(s){throw s}}a(f1,"deleteRecords");KN.exports={deleteRecords:f1}});var Uc=T((pce,zN)=>{"use strict";var zo=J(),E1=WN(),h1=We(),{getSchemaPath:m1}=Je(),p1=Lc(),S1=Y();zN.exports=T1;async function T1(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(zo.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(zo.isEmptyOrZeroLength(e.hash_values)&&!zo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];zo.isEmpty(u)||e.hash_values.push(u)}}if(zo.isEmptyOrZeroLength(e.hash_values))return QN([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(zo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=m1(e.schema,e.table),i=await h1.openEnvironment(s,e.table),o=await E1.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await p1(e,o)}catch(c){S1.error(`unable to write transaction due to ${c.message}`)}return QN(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(T1,"lmdbDeleteRecords");function QN(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(QN,"createDeleteResponse")});var Bm=T((gce,JN)=>{"use strict";var g1=M(),Tce=Cr();function vm(e,t){let r=Object.create(null);if(t.length===1&&g1.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(vm,"parseRow");function R1(e,t,r,n){let s=vm(r,e);n.push(s)}a(R1,"searchAll");function A1(e,t,r,n){let s=vm(r,e);n[t]=s}a(A1,"searchAllToMap");function O1(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(O1,"iterateDBI");function Hi(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Hi,"pushResults");function b1(e,t,r,n,s,i){t.toString().endsWith(e)&&Hi(t,r,n,s,i)}a(b1,"endsWith");function N1(e,t,r,n,s,i){t.toString().includes(e)&&Hi(t,r,n,s,i)}a(N1,"contains");function y1(e,t,r,n,s,i){t>e&&Hi(t,r,n,s,i)}a(y1,"greaterThanCompare");function I1(e,t,r,n,s,i){t>=e&&Hi(t,r,n,s,i)}a(I1,"greaterThanEqualCompare");function w1(e,t,r,n,s,i){t<e&&Hi(t,r,n,s,i)}a(w1,"lessThanCompare");function C1(e,t,r,n,s,i){t<=e&&Hi(t,r,n,s,i)}a(C1,"lessThanEqualCompare");JN.exports={parseRow:vm,searchAll:R1,searchAllToMap:A1,iterateDBI:O1,endsWith:b1,contains:N1,greaterThanCompare:y1,greaterThanEqualCompare:I1,lessThanCompare:w1,lessThanEqualCompare:C1,pushResults:Hi}});var Jo=T((Nce,ny)=>{"use strict";var Zs=We(),Ace=Y(),Pr=Cr(),U_=Et(),lt=wr().LMDB_ERRORS_ENUM,Oce=J(),D1=M(),P_=Bm(),{parseRow:L1}=P_,bce=require("lmdb"),{OVERFLOW_MARKER:XN,MAX_SEARCH_KEY_LENGTH:M1}=U_;function jN(e,t,r,n=!1,s=void 0,i=void 0){return xi(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(jN,"iterateFullIndex");function Pc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return xi(e,t,r,(l,d,f,E)=>{let A={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(A.values=!1,d.getRange(A).map(b=>({value:b}))):d.getRange(A)})}a(Pc,"iterateRangeBetween");function xi(e,t,r,n){let s=e.database||e,i=Zs.openDBI(s,r);i[U_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&Zs.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(xi,"setupTransaction");function ZN(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(XN)){if(!s)if(r)s=Zs.openDBI(e,r);else{let u=Zs.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=Zs.openDBI(e,u[_]),!s[U_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(ZN,"getOverflowCheck");function U1(e,t,r,n=!1,s=void 0,i=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return xi(e,t,t,(o,c,u)=>(v_(r),r=vc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>L1(_.value,r))))}a(U1,"searchAll");function P1(e,t,r,n=!1,s=void 0,i=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);v_(r),r=vc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of jN(e,t,t,n,s,i))o.set(c,P_.parseRow(u,r));return o}a(P1,"searchAllToMap");function v1(e,t,r=!1,n=void 0,s=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=jN(e,void 0,t,r,n,s),c=o.transaction,u=ZN(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(v1,"iterateDBI");function B1(e,t){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return Zs.statDBI(e,t).entryCount}a(B1,"countAll");function H1(e,t,r,n,s=!1,i=void 0,o=void 0){return ei(e,r,n),xi(e,t,r,(c,u,_,l)=>(n=Pr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(H1,"equals");function x1(e,t,r){return ei(e,t,r),Zs.openDBI(e,t).getValuesCount(r)}a(x1,"count");function F1(e,t,r,n,s=!1,i=void 0,o=void 0){return ei(e,r,n),xi(e,null,r,(c,u)=>{n=Pr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let f of u.getKeys({transaction:c,start:n}))if(!f.startsWith(n)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(n))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(F1,"startsWith");function q1(e,t,r,n,s=!1,i=void 0,o=void 0){return ey(e,t,r,n,s,i,o,!0)}a(q1,"endsWith");function ey(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ei(e,r,n),xi(e,null,r,(u,_,l,d)=>{let f=ZN(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(XN)?_.getValues(E,{transaction:u}).map(S=>{let p=f(E,S);if(c?p.endsWith(n):p.includes(n))return{key:p,value:S}}).filter(S=>S):(c?h.endsWith(n):h.includes(n))?_[U_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(S=>({key:E,value:S})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(ey,"contains");function G1(e,t,r,n,s=!1,i=void 0,o=void 0){ei(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Pc(e,t,r,n,u,s,i,o,!0,!1)}a(G1,"greaterThan");function k1(e,t,r,n,s=!1,i=void 0,o=void 0){ei(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Pc(e,t,r,n,u,s,i,o,!1,!1)}a(k1,"greaterThanEqual");function V1(e,t,r,n,s=!1,i=void 0,o=void 0){ei(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Pc(e,t,r,u,n,s,i,o,!1,!0)}a(V1,"lessThan");function $1(e,t,r,n,s=!1,i=void 0,o=void 0){ei(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Pc(e,t,r,u,n,s,i,o,!1,!1)}a($1,"lessThanEqual");function Y1(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Pr.validateEnv(e),r===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(lt.START_VALUE_REQUIRED);if(s===void 0)throw new Error(lt.END_VALUE_REQUIRED);if(n=Pr.convertKeyValueToWrite(n),s=Pr.convertKeyValueToWrite(s),n>s)throw new Error(lt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Pc(e,t,r,n,s,i,o,c)}a(Y1,"between");function K1(e,t,r,n){Pr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(v_(r),r=vc(s,r),n===void 0)throw new Error(lt.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=P_.parseRow(c,r)),o}a(K1,"searchByHash");function W1(e,t,r){Pr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(W1,"checkHashExists");function Q1(e,t,r,n,s=[]){return ry(e,t,r,n,s),ty(e,t,r,n,s).map(i=>i[1])}a(Q1,"batchSearchByHash");function z1(e,t,r,n,s=[]){ry(e,t,r,n,s);let i=new Map;for(let[o,c]of ty(e,t,r,n,s))i.set(o,c);return i}a(z1,"batchSearchByHashToMap");function ty(e,t,r,n,s=[]){return xi(e,t,t,(i,o,c)=>{r=vc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,P_.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(ty,"batchHashSearch");function ry(e,t,r,n,s){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(v_(r),n==null)throw new Error(lt.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(lt.IDS_MUST_BE_ITERABLE)}a(ry,"initializeBatchSearchByHash");function v_(e){if(!Array.isArray(e))throw e===void 0?new Error(lt.FETCH_ATTRIBUTES_REQUIRED):new Error(lt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(v_,"validateFetchAttributes");function ei(e,t,r){if(Pr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.SEARCH_VALUE_REQUIRED);if(r?.length>M1)throw new Error(lt.SEARCH_VALUE_TOO_LARGE)}a(ei,"validateComparisonFunctions");function vc(e,t){return t.length===1&&D1.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Zs.listDBIs(e)),t}a(vc,"setGetWholeRowAttributes");ny.exports={searchAll:U1,searchAllToMap:P1,count:x1,countAll:B1,equals:H1,startsWith:F1,endsWith:q1,contains:ey,searchByHash:K1,setGetWholeRowAttributes:vc,batchSearchByHash:Q1,batchSearchByHashToMap:z1,checkHashExists:W1,iterateDBI:v1,greaterThan:G1,greaterThanEqual:k1,lessThan:V1,lessThanEqual:$1,between:Y1}});var Xo=T((Ice,cy)=>{var sy=require("lodash"),iy=rt(),Ee=require("joi"),J1=J(),{hdb_schema_table:Bc,checkValidTable:oy,hdb_table:ay,hdb_database:B_}=Yn(),{handleHDBError:X1,hdb_errors:j1}=Z(),{getDatabases:Z1}=(Oe(),ee(Ge)),{HTTP_STATUS_CODES:eY}=j1,tY=Ee.object({database:B_,schema:B_,table:ay,search_attribute:Bc,search_value:Ee.any().required(),get_attributes:Ee.array().min(1).items(Ee.alternatives(Bc,Ee.object())).optional(),desc:Ee.bool(),limit:Ee.number().integer().min(1),offset:Ee.number().integer().min(0)}),rY=Ee.object({database:B_,schema:B_,table:ay,operator:Ee.string().valid("and","or").default("and").lowercase(),offset:Ee.number().integer().min(0),limit:Ee.number().integer().min(1),get_attributes:Ee.array().min(1).items(Ee.alternatives(Bc,Ee.object())).optional(),sort:Ee.object({attribute:Ee.alternatives(Bc,Ee.array().min(1)),descending:Ee.bool().optional()}).optional(),conditions:Ee.array().min(1).items(Ee.alternatives(Ee.object({operator:Ee.string().valid("and","or").default("and").lowercase(),conditions:Ee.array()}),Ee.object({search_attribute:Ee.alternatives(Bc,Ee.array().min(1)),search_type:Ee.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:Ee.when("search_type",{switch:[{is:"equals",then:Ee.any()},{is:"between",then:Ee.array().items(Ee.alternatives([Ee.string(),Ee.number()])).length(2)}],otherwise:Ee.alternatives(Ee.string(),Ee.number())}).required()}))).required()});cy.exports=function(e,t){let r=null;switch(t){case"value":r=iy.validateBySchema(e,tY);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(oy("database",e.schema)),i(oy("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=iy.validateBySchema(e,rY);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=J1.checkGlobalSchemaTable(e.schema,e.table);if(s)return X1(new Error,s,eY.NOT_FOUND);let o=Z1()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=sy.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!sy.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Hm=T((Cce,uy)=>{"use strict";var nY=We(),sY=Xo(),{getSchemaPath:iY}=Je();uy.exports=oY;function oY(e){let t=sY(e,"hashes");if(t)throw t;let r=iY(e.schema,e.table);return nY.openEnvironment(r,e.table)}a(oY,"initialize")});var xm=T((Lce,ly)=>{"use strict";var aY=Jo(),cY=Hm();ly.exports=uY;async function uY(e){let t=await cY(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return aY.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(uY,"lmdbGetDataByHash")});var jo=T((Uce,_y)=>{"use strict";var Fm=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};_y.exports=Fm});var fy=T((Bce,dy)=>{"use strict";var vce=jo(),lY=Jo(),_Y=Hm();dy.exports=dY;async function dY(e){let t=await _Y(e),r=global.hdb_schema[e.schema][e.table];return lY.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(dY,"lmdbSearchByHash")});var Wn=T((xce,Ey)=>{"use strict";var qm=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};Ey.exports=qm});var H_=T((qce,gy)=>{"use strict";var Wt=Jo(),fY=We(),EY=J(),he=Et(),Fi=M(),hY=Pi(),hy=wr().LMDB_ERRORS_ENUM,{getSchemaPath:mY}=Je(),Rs=Fi.SEARCH_WILDCARDS;async function pY(e,t,r){let n;e.schema===Fi.SYSTEM_SCHEMA_NAME?n=hY[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Ty(e,n.hash_attribute,r,t);return py(e,s,n.hash_attribute,r)}a(pY,"prepSearch");async function py(e,t,r,n){let s=mY(e.schema,e.table),i=await fY.openEnvironment(s,e.table),o=Sy(i,e,t,r),c=o.transaction||i;if([he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,he.SEARCH_TYPES.SEARCH_ALL,he.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(SY(e,r)===!1){let l=e.search_attribute;if(l===r)return n?my(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?my(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Wt.batchSearchByHashToMap(c,r,e.get_attributes,_):Wt.batchSearchByHash(c,r,e.get_attributes,_)}a(py,"executeSearch");function Sy(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case he.SEARCH_TYPES.EQUALS:s=Wt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.CONTAINS:s=Wt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.ENDS_WITH:case he.SEARCH_TYPES._ENDS_WITH:s=Wt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.STARTS_WITH:case he.SEARCH_TYPES._STARTS_WITH:s=Wt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Wt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Wt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.SEARCH_ALL:return Wt.searchAll(e,n,t.get_attributes,o,c,u);case he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Wt.searchAllToMap(e,n,t.get_attributes,o,c,u);case he.SEARCH_TYPES.BETWEEN:s=Wt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case he.SEARCH_TYPES.GREATER_THAN:case he.SEARCH_TYPES._GREATER_THAN:s=Wt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.GREATER_THAN_EQUAL:case he.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Wt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.LESS_THAN:case he.SEARCH_TYPES._LESS_THAN:s=Wt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.LESS_THAN_EQUAL:case he.SEARCH_TYPES._LESS_THAN_EQUAL:s=Wt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Sy,"searchByType");function my(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(my,"createMapFromIterable");function SY(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(SY,"checkToFetchMore");function Ty(e,t,r,n){if(EY.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Rs.indexOf(s)>-1)return r===!0?he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:he.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Rs[0])<0&&s.indexOf(Rs[1])<0)return c===!0?r===!0?he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:he.SEARCH_TYPES.EQUALS;if(Rs.indexOf(i)>=0&&Rs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),he.SEARCH_TYPES.CONTAINS;if(Rs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),he.SEARCH_TYPES.ENDS_WITH;if(Rs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),he.SEARCH_TYPES.STARTS_WITH;if(s.includes(Rs[0])||s.includes(Rs[1]))return he.SEARCH_TYPES.EQUALS;throw new Error(hy.UNKNOWN_SEARCH_TYPE)}else switch(n){case Fi.VALUE_SEARCH_COMPARATORS.BETWEEN:return he.SEARCH_TYPES.BETWEEN;case Fi.VALUE_SEARCH_COMPARATORS.GREATER:return he.SEARCH_TYPES.GREATER_THAN;case Fi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return he.SEARCH_TYPES.GREATER_THAN_EQUAL;case Fi.VALUE_SEARCH_COMPARATORS.LESS:return he.SEARCH_TYPES.LESS_THAN;case Fi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return he.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(hy.UNKNOWN_SEARCH_TYPE)}}a(Ty,"createSearchTypeFromSearchObject");gy.exports={executeSearch:py,createSearchTypeFromSearchObject:Ty,prepSearch:pY,searchByType:Sy}});var Ay=T((Vce,Ry)=>{"use strict";var kce=Wn(),TY=Xo(),gY=J(),RY=M(),AY=H_();Ry.exports=OY;function OY(e,t){if(!gY.isEmpty(t)&&RY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=TY(e,"value");if(n)throw n;return AY.prepSearch(e,t,!0)}a(OY,"lmdbGetDataByValue")});var Hc=T((Kce,Oy)=>{"use strict";var Yce=Wn(),bY=Xo(),NY=J(),yY=M(),IY=H_();Oy.exports=wY;async function wY(e,t){if(!NY.isEmpty(t)&&yY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=bY(e,"value");if(n)throw n;return IY.prepSearch(e,t,!1)}a(wY,"lmdbSearchByValue")});var Ny=T((zce,by)=>{"use strict";var Qce=Et(),Gm=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},km=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Vm=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};by.exports={SearchByConditionsObject:Gm,SearchCondition:km,SortAttribute:Vm}});var Dy=T((Zce,Cy)=>{"use strict";var Xce=Ny().SearchByConditionsObject,CY=Wn(),DY=Xo(),$m=Jo(),x_=Et(),{Resource:jce}=(On(),ee(Vh)),wy=H_(),LY=Bm(),MY=require("lodash"),{getSchemaPath:UY}=Je(),yy=We(),{handleHDBError:PY,hdb_errors:vY}=Z(),{HTTP_STATUS_CODES:BY}=vY,HY=1e8;Cy.exports=xY;async function xY(e){let t=DY(e,"conditions");if(t)throw PY(t,t.message,BY.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=UY(e.schema,e.table),n=await yy.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)yy.openDBI(n,_.search_attribute);let i=MY.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===x_.SEARCH_TYPES.EQUALS?_.estimated_count=$m.count(n,_.search_attribute,_.search_value):l===x_.SEARCH_TYPES.CONTAINS||l===x_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=HY}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Iy(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(wy.filterByType),d=l.length,f=$m.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>LY.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await Iy(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=$m.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(xY,"lmdbSearchByConditions");async function Iy(e,t,r,n){let s=new CY(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===x_.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,wy.searchByType(e,s,i,n).map(o=>o.value)}a(Iy,"executeConditionSearch")});var xc=T((tue,Ly)=>{"use strict";var FY=M().OPERATIONS_ENUM,Ym=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=FY.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Ly.exports=Ym});var Km=T((nue,Fy)=>{"use strict";var vy=Wn(),By=xc(),Hy=Hc(),xy=Uc(),or=M(),My=J(),Uy=We(),{getTransactionAuditStorePath:qY,getSchemaPath:GY}=Je(),Py=Y();Fy.exports=kY;async function kY(e){try{if(My.isEmpty(global.hdb_schema[e.schema])||My.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await VY(e),await $Y(e);let t=GY(e.schema,e.table);try{await Uy.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Py.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=qY(e.schema,e.table);await Uy.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Py.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(kY,"lmdbDropTable");async function VY(e){let t=new vy(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Hy(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new By(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await xy(s)}a(VY,"deleteAttributesFromSystem");async function $Y(e){let t=new vy(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Hy(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new By(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await xy(s)}catch(i){throw i}}a($Y,"dropTableFromSystem")});var Gy=T((iue,qy)=>{"use strict";var YY=require("fs-extra"),KY=Wn(),WY=jo(),QY=xc(),zY=Km(),JY=Uc(),XY=xm(),jY=Hc(),As=M(),{getSchemaPath:ZY}=Je(),{handleHDBError:eK,hdb_errors:tK}=Z(),{HDB_ERROR_MSGS:rK,HTTP_STATUS_CODES:nK}=tK;qy.exports=sK;async function sK(e){let t;try{t=await iK(e.schema);let r=new KY(As.SYSTEM_SCHEMA_NAME,As.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,As.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[As.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await jY(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await zY(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new QY(As.SYSTEM_SCHEMA_NAME,As.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await JY(s);let i=ZY(t);await YY.remove(i)}catch(r){throw r}}a(sK,"lmdbDropSchema");async function iK(e){let t=new WY(As.SYSTEM_SCHEMA_NAME,As.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[As.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await XY(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw eK(new Error,rK.SCHEMA_NOT_FOUND(e),nK.NOT_FOUND,void 0,void 0,!0);return n}a(iK,"validateDropSchema")});var Qm=T((aue,ky)=>{"use strict";var Wm=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};ky.exports=Wm});var $y=T((lue,Vy)=>{"use strict";var oK=require("fs-extra"),F_=We(),{getTransactionAuditStorePath:aK}=Je(),zm=Et(),uue=Qm();Vy.exports=cK;async function cK(e){let t;try{let r=aK(e.schema,e.table);await oK.mkdirp(r),t=await F_.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{F_.createDBI(t,zm.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),F_.createDBI(t,zm.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),F_.createDBI(t,zm.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(cK,"createTransactionsAuditEnvironment")});var Qy=T((due,Wy)=>{"use strict";var Jm=M(),Yy=We(),uK=Yo(),{getSystemSchemaPath:lK,getSchemaPath:_K}=Je(),dK=Pi(),fK=C_(),Xm=w_(),EK=Y(),hK=$y(),Zm=dK.hdb_table,Ky=[];for(let e=0;e<Zm.attributes.length;e++)Ky.push(Zm.attributes[e].attribute);Wy.exports=mK;async function mK(e,t){let r=_K(t.schema,t.table),n=new Xm(t.schema,t.table,Jm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Xm(t.schema,t.table,Jm.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Xm(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Yy.createEnvironment(r,t.table),e!==void 0){let o=await Yy.openEnvironment(lK(),Jm.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await uK.insertRecords(o,Zm.hash_attribute,Ky,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await jm(n),await jm(s),await jm(i)}await hK(t)}catch(o){throw o}}a(mK,"lmdbCreateTable");async function jm(e){try{await fK(e)}catch(t){EK.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(jm,"createAttribute")});var Jy=T((Eue,zy)=>{"use strict";var pK=Nc(),SK=Dc(),TK=L_(),Fc=M(),gK=Yo().updateRecords,RK=We(),{getSchemaPath:AK}=Je(),OK=Lc(),bK=Y();zy.exports=NK;async function NK(e){try{let{schema_table:t,attributes:r}=pK(e);SK(e,r,t.hash_attribute),e.schema!==Fc.SYSTEM_SCHEMA_NAME&&(r.includes(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await TK(e.hdb_auth_header,t,r),s=AK(e.schema,e.table),i=await RK.openEnvironment(s,e.table),o=await gK(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await OK(e,o)}catch(c){bK.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(NK,"lmdbUpdateRecords")});var jy=T((mue,Xy)=>{"use strict";var yK=M().OPERATIONS_ENUM,ep=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=yK.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Xy.exports=ep});var eI=T((Tue,Zy)=>{"use strict";var Sue=jy(),IK=Nc(),wK=Dc(),CK=L_(),qc=M(),DK=Yo().upsertRecords,LK=We(),{getSchemaPath:MK}=Je(),UK=Lc(),PK=Y(),{handleHDBError:vK,hdb_errors:BK}=Z();Zy.exports=HK;async function HK(e){let t;try{t=IK(e)}catch(u){throw vK(u,u.message,BK.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;wK(e,n,r.hash_attribute),e.schema!==qc.SYSTEM_SCHEMA_NAME&&(n.includes(qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await CK(e.hdb_auth_header,r,n),i=MK(e.schema,e.table),o=await LK.openEnvironment(i,e.table),c=await DK(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await UK(e,c)}catch(u){PK.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(HK,"lmdbUpsertRecords")});var rI=T((Rue,tI)=>{"use strict";var tp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};tI.exports=tp});var sI=T((Oue,nI)=>{"use strict";var rp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};nI.exports=rp});var aI=T((yue,oI)=>{"use strict";var np=We(),{getTransactionAuditStorePath:xK}=Je(),Nue=rI(),Gc=Et(),FK=J(),iI=sI(),qK=require("util").promisify,GK=qK(setTimeout),kK=1e4,VK=100;oI.exports=$K;async function $K(e){let t=xK(e.schema,e.table),r=await np.openEnvironment(t,e.table,!0),n=np.listDBIs(r);np.initializeDBIs(r,Gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new iI;do s=await YK(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await GK(VK);while(s.transactions_deleted>0);return i}a($K,"deleteAuditLogsBefore");async function YK(e,t){let r=new iI;try{let n=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[Gc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];FK.isEmpty(c)||(s=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>kK)break}return await s,r}catch(n){throw n}}a(YK,"deleteTransactions")});var uI=T((wue,cI)=>{"use strict";var sp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};cI.exports=sp});var _I=T((Lue,lI)=>{"use strict";var KK=Wn(),WK=xc(),Due=uI(),Qn=M(),QK=J(),ip=We(),zK=Pi(),JK=Hc(),XK=Uc(),{getSchemaPath:jK}=Je();lI.exports=ZK;async function ZK(e,t=!0){let r;e.schema===Qn.SYSTEM_SCHEMA_NAME?r=zK[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await tW(e),s=jK(e.schema,e.table),i=await ip.openEnvironment(s,e.table);return t===!0&&await eW(e,i,r.hash_attribute),ip.dropDBI(i,e.attribute),n}a(ZK,"lmdbDropAttribute");async function eW(e,t,r){let n=ip.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(eW,"removeAttributeFromAllObjects");async function tW(e){let t=new KK(Qn.SYSTEM_SCHEMA_NAME,Qn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await JK(t)).filter(o=>o[Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(QK.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[Qn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new WK(Qn.SYSTEM_SCHEMA_NAME,Qn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return XK(i)}a(tW,"dropAttributeFromSystem")});var pI=T((Pue,mI)=>{"use strict";var op=We(),Zo=Et(),Uue=Cr(),ap=M(),dI=J(),{getTransactionAuditStorePath:rW}=Je(),nW=Jo(),q_=Wo(),sW=Y();mI.exports=iW;async function iW(e){let t=rW(e.schema,e.table),r=await op.openEnvironment(t,e.table,!0),n=op.listDBIs(r);op.initializeDBIs(r,Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case ap.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return fI(r,e.search_values);case ap.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,aW(r,e.search_values,s);case ap.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return oW(r,e.search_values);default:return fI(r)}}a(iW,"readAuditLog");function fI(e,t=[0,Date.now()]){dI.isEmpty(t[0])&&(t[0]=0),dI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new q_,s))}a(fI,"searchTransactionsByTimestamp");function oW(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,hI(e,i))}return Object.fromEntries(r)}a(oW,"searchTransactionsByUsername");function aW(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=nW.equals(e,Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Zo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=hI(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);EI(u,"records",r,l,o),EI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(aW,"searchTransactionsByHashValues");function EI(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new q_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new q_(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(EI,"loopRecords");function hI(e,t){let r=[];try{let n=e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new q_,i);r.push(o)}}catch(i){sW.warn(i)}return r}catch(n){throw n}}a(hI,"batchSearchTransactions")});var TI=T((xue,SI)=>{"use strict";var{getSchemaPath:Bue}=Je(),Hue=We(),{database:cW}=(Oe(),ee(Ge));SI.exports={writeTransaction:uW};async function uW(e,t,r){return cW({database:e,table:t}).transaction(r)}a(uW,"writeTransaction")});var OI=T((que,AI)=>{"use strict";var{getSchemaPath:gI}=Je(),RI=We();AI.exports={flush:lW,resetReadTxn:_W};async function lW(e,t){return(await RI.openEnvironment(gI(e,t),t.toString())).flushed}a(lW,"flush");async function _W(e,t){try{(await RI.openEnvironment(gI(e,t),t.toString())).resetReadTxn()}catch{}}a(_W,"resetReadTxn")});var II=T((kue,yI)=>{"use strict";var{Readable:dW}=require("stream"),{getDatabases:fW}=(Oe(),ee(Ge)),{readSync:EW,openSync:hW,createReadStream:bI}=require("fs"),{open:mW}=require("lmdb"),NI=p_(),pW=T_(),{AUDIT_STORE_OPTIONS:SW}=(Ci(),ee(YO)),{INTERNAL_DBIS_NAME:TW,AUDIT_STORE_NAME:gW}=Et();yI.exports=AW;var cp=32768,RW=100;async function AW(e){let t=e.database||e.schema||"data",r=fW()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=mW({noSync:!0,maxDbs:pW.MAX_DBS}),f,E=d.openDB(TW,new NI(!1)),h=l.useReadTransaction(),S=0,p=a(async function(A,b){b.encoding="binary",b.encoder=void 0;let v=d.openDB(A,b),G=l.openDB(A,b);for(let{key:H,version:P,value:z}of G.getRange({transaction:h,versions:G.useVersions}))f=v.put(H,z,P),S++%RW===0&&(await new Promise(W=>setTimeout(W,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:b}of l.getRange({transaction:h,start:!1}))if(s.some(v=>A.startsWith?.(v+"/"))){E.put(A,b);let[,v]=A.split("/"),G=!v,H=new NI(!G,G);await p(A,H)}e.include_audit&&await p(gW,Object.assign({},SW)),await f;let g=bI(d.path);return g.headers=u(),g.on("close",()=>{h.done(),d.close()}),g}let o=r[Object.keys(r)[0]].primaryStore,c=hW(o.path);return o.transaction(()=>{let _=Buffer.alloc(cp);EW(c,_,0,cp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=bI(null,{fd:c,start:cp}),f=new dW.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(AW,"getBackup")});var DI=T(($ue,CI)=>{"use strict";var OW=Y(),{handleHDBError:bW}=Z(),NW=Kb(),yW=C_(),IW=Lm(),wW=GN(),CW=Uc(),DW=xm(),LW=fy(),MW=Ay(),UW=Hc(),PW=Dy(),vW=Gy(),BW=Qy(),HW=Jy(),xW=eI(),FW=aI(),qW=Km(),GW=_I(),kW=pI(),VW=TI(),wI=OI(),$W=II(),up=class extends NW{static{a(this,"LMDBBridge")}async searchByConditions(t){return PW(t)}async getDataByHash(t){return await DW(t)}async searchByHash(t){return await LW(t)}async getDataByValue(t,r){return await MW(t,r)}async searchByValue(t){return await UW(t)}async createSchema(t){return await wW(t)}async dropSchema(t){return await vW(t)}async createTable(t,r){return await BW(t,r)}async dropTable(t){return await qW(t)}async createAttribute(t){return await yW(t)}async createRecords(t){return await IW(t)}async updateRecords(t){return await HW(t)}async upsertRecords(t){try{return await xW(t)}catch(r){throw bW(r,null,null,OW.ERR,r)}}async deleteRecords(t){return await CW(t)}async dropAttribute(t){return await GW(t)}async deleteAuditLogsBefore(t){return await FW(t)}async readAuditLog(t){return await kW(t)}writeTransaction(t,r,n){return VW.writeTransaction(t,r,n)}flush(t,r){return wI.flush(t,r)}resetReadTxn(t,r){return wI.resetReadTxn(t,r)}getBackup(t){return $W(t)}};CI.exports=up});var FI={};qe(FI,{ResourceBridge:()=>dp});function fp({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 MI(e,t){let r=zn(e),n=fp(e,r);if(!r)throw new wn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Xe(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&a_(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function zn(e){let t=e.database||e.schema||KW,r=Cn()[t];if(!r)throw(0,wn.handleHDBError)(new Error,YW.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function UI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*PI(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var vI,G_,wn,BI,HI,Dn,lp,_p,xI,YW,KW,WW,QW,LI,dp,qI=Re(()=>{"use strict";vI=B(DI()),G_=B(Xo()),wn=B(Z());Oe();BI=B(Nc()),HI=B(Dc()),Dn=B(M()),lp=B(gs()),_p=B(In()),xI=B(J());Ui();c_();({HDB_ERROR_MSGS:YW}=wn.hdb_errors),KW="data",WW=1e4,QW=10,dp=class extends vI.default{static{a(this,"ResourceBridge")}constructor(t){super(t),LI=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,G_.default)(t,"conditions");if(r)throw(0,wn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=zn(t);if(!n)throw new wn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:fp(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new wn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}_t({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await zn(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=zn(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){zn(t).dropTable()}createSchema(t){return kc({database:t.schema,table:null}),lp.signalSchemaChange(new _p.SchemaEventMsg(process.pid,Dn.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Ep(t.schema),lp.signalSchemaChange(new _p.SchemaEventMsg(process.pid,Dn.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,LI.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,BI.default)(t);(0,HI.default)(t,n,r.primaryKey);let s,i=Cn()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Xe(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(f=>f.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=a_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=Cn()[t.schema][t.table],n={user:t.hdb_user};return Xe(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return UI(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=Cn()[t.schema][t.table];if(!r.createdTimeProperty)throw new wn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Dn.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,xI.async_set_timeout)(QW),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%WW===0&&await _();return u.length>0&&await _(),s?UI(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,G_.default)(t,"hashes");if(r)throw r;return MI(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of MI(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Dn.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,G_.default)(t,"value");if(n)throw n;let s=zn(t);if(!s)throw new wn.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===Dn.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:fp(t,s)})}async getDataByValue(t,r){let n=new Map,s=zn(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){zn({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return zn(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=zn(t),n={};switch(t.search_type){case Dn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Dn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of PI(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return PI(r,t.search_values?.[0],t.search_values?.[1])}}};a(fp,"getSelect");a(MI,"getRecords");a(zn,"getTable");a(UI,"createDeleteResponse");a(PI,"groupRecordsInHistory")});var Ln=T((Jue,GI)=>{"use strict";var{ResourceBridge:zW}=(qI(),ee(FI)),JW=j();JW.initSync();var k_;function XW(){return k_||(k_=new zW,k_)}a(XW,"getBridge");GI.exports=XW()});var YI=T((jue,$I)=>{"use strict";var kI=require("lodash"),Vc=require("mathjs"),jW=require("jsonata"),VI=J();$I.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?kI.uniqWith(e,kI.isEqual):e,searchJSON:ZW,mad:$c.bind(null,Vc.mad),mean:$c.bind(null,Vc.mean),mode:$c.bind(null,Vc.mode),prod:$c.bind(null,Vc.prod),median:$c.bind(null,Vc.median)};function $c(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a($c,"aggregateFunction");function ZW(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(VI.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),VI.isEmpty(this.__ala__.res[r])){let n=jW(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(ZW,"searchJSON")});var WI=T((ele,KI)=>{"use strict";var mt=require("moment"),hp="YYYY-MM-DDTHH:mm:ss.SSSZZ";mt.suppressDeprecationWarnings=!0;KI.exports={current_date:()=>mt().utc().format("YYYY-MM-DD"),current_time:()=>mt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return mt(e).utc().format("YYYY");case"month":return mt(e).utc().format("MM");case"day":return mt(e).utc().format("DD");case"hour":return mt(e).utc().format("HH");case"minute":return mt(e).utc().format("mm");case"second":return mt(e).utc().format("ss");case"millisecond":return mt(e).utc().format("SSS");default:break}},date:e=>mt(e).utc().format(hp),date_format:(e,t)=>mt(e).utc().format(t),date_add:(e,t,r)=>mt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>mt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=mt(e).utc(),s=mt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>mt().utc().valueOf(),get_server_time:()=>mt().format(hp),offset_utc:(e,t)=>mt(e).utc().utcOffset(t).format(hp)}});var XI=T((tle,JI)=>{"use strict";var eQ=require("@turf/area"),tQ=require("@turf/length"),rQ=require("@turf/circle"),nQ=require("@turf/difference"),sQ=require("@turf/distance"),iQ=require("@turf/boolean-contains"),oQ=require("@turf/boolean-equal"),aQ=require("@turf/boolean-disjoint"),cQ=require("@turf/helpers"),QI=M(),Se=J(),Os=Y();JI.exports={geoArea:uQ,geoLength:lQ,geoCircle:_Q,geoDifference:dQ,geoDistance:zI,geoNear:fQ,geoContains:EQ,geoEqual:hQ,geoCrosses:mQ,geoConvert:pQ};function uQ(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return eQ.default(e)}catch(t){return Os.trace(t,e),NaN}}a(uQ,"geoArea");function lQ(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return tQ.default(e,{units:t||"kilometers"})}catch(r){return Os.trace(r,e),NaN}}a(lQ,"geoLength");function _Q(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return rQ.default(e,t,{units:r||"kilometers"})}catch(n){return Os.trace(n,e,t),NaN}}a(_Q,"geoCircle");function dQ(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return nQ(e,t)}catch(r){return Os.trace(r,e,t),NaN}}a(dQ,"geoDifference");function zI(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return sQ.default(e,t,{units:r||"kilometers"})}catch(n){return Os.trace(n,e,t),NaN}}a(zI,"geoDistance");function fQ(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return zI(e,t,n)<=r}catch(s){return Os.trace(s,e,t),!1}}a(fQ,"geoNear");function EQ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return iQ.default(e,t)}catch(r){return Os.trace(r,e,t),!1}}a(EQ,"geoContains");function hQ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return oQ.default(e,t)}catch(r){return Os.trace(r,e,t),!1}}a(hQ,"geoEqual");function mQ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return!aQ.default(e,t)}catch(r){return Os.trace(r,e,t),!1}}a(mQ,"geoCrosses");function pQ(e,t,r){if(Se.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Se.isEmpty(t))throw new Error("geo_type is required");if(Se.isEmpty(QI.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(QI.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),cQ[t](e,r)}a(pQ,"geoConvert")});var V_=T((nle,jI)=>{var qi=YI(),vr=WI(),Jn=XI();jI.exports=e=>{e.aggr.mad=e.aggr.MAD=qi.mad,e.aggr.mean=e.aggr.MEAN=qi.mean,e.aggr.mode=e.aggr.MODE=qi.mode,e.aggr.prod=e.aggr.PROD=qi.prod,e.aggr.median=e.aggr.MEDIAN=qi.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=qi.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=qi.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=vr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=vr.current_time,e.fn.extract=e.fn.EXTRACT=vr.extract,e.fn.date=e.fn.DATE=vr.date,e.fn.date_format=e.fn.DATE_FORMAT=vr.date_format,e.fn.date_add=e.fn.DATE_ADD=vr.date_add,e.fn.date_sub=e.fn.DATE_SUB=vr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=vr.date_diff,e.fn.now=e.fn.NOW=vr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=vr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=vr.get_server_time,e.fn.getdate=e.fn.GETDATE=vr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=vr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=Jn.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=Jn.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=Jn.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=Jn.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=Jn.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=Jn.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=Jn.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=Jn.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=Jn.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=Jn.geoNear}});var rw=T((sle,tw)=>{"use strict";var Yc=require("lodash"),ar=require("alasql");ar.options.cache=!1;var SQ=V_(),ZI=require("clone"),$_=require("recursive-iterator"),ue=Y(),we=J(),ea=Ln(),TQ=M(),{hdb_errors:gQ}=Z(),{getDatabases:ew}=(Oe(),ee(Ge)),RQ="IS NULL",Mn="There was a problem performing this search. Please check the logs and try again.";SQ(ar);var mp=class{static{a(this,"SQLSearch")}constructor(t,r){if(we.isEmpty(t))throw ue.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(),we.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!we.isEmptyOrZeroLength(n))return ue.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw ue.error("Error thrown from checkEmptySQL in SQLSearch class method search."),ue.error(n),new Error(Mn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw ue.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),ue.error(n),new Error(Mn)}if(Object.keys(this.data).length===0)return ue.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw ue.error("Error thrown from processJoins in SQLSearch class method search."),ue.error(n),new Error(Mn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw ue.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),ue.error(n),new Error(Mn)}try{return t=await this._finalSQL(),t}catch(n){throw ue.error("Error thrown from finalSQL in SQLSearch class method search."),ue.error(n),new Error(Mn)}}_getColumns(){let t=new $_(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(ZI(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Yc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=ew()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(we.isEmpty(this.statement.where)){ue.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new $_(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!we.isEmpty(r)&&r.right)if(we.isNotEmptyAndHasValue(r.right.value)){let n=we.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new ar.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=we.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new ar.yy.LogicValue({value:i}):n instanceof ar.yy.StringValue&&we.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new ar.yy.NumValue({value:i}))});if(t){ue.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new $_(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!we.isEmpty(TQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(we.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(we.isEmptyOrZeroLength(r.left.columnid)||we.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(we.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"=":!we.isEmpty(r.right.value)||!we.isEmpty(r.left.value)?n.add(we.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(we.isEmptyOrZeroLength(this.all_table_attributes)&&we.isEmptyOrZeroLength(this.statement.from)&&we.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Yc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(we.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);we.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(we.isEmptyOrZeroLength(this.all_table_attributes)&&!we.isEmptyOrZeroLength(this.columns.columns))return t;if(we.isEmptyOrZeroLength(this.all_table_attributes)&&we.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await ar.promise(r)}catch(r){throw ue.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),ue.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(ZI(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(we.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(RQ)>-1&&this.tables.forEach(s=>{let i={columnid:ew()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Yc.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!we.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!we.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ea.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw ue.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),ue.error(l),new Error(Mn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await ea.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]):(this.data[i].__merged_data[E]=[...n[i]],this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),ue.error(l),new Error(Mn)}else if(!we.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!we.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await ea.getDataByValue(c,E.operation);if(u)for(let[S]of h)this.data[i].__merged_data[S]||(this.data[i].__merged_data[S]=[...n[i]],this._setMergedHashAttribute(i,S));else for(let[S,p]of h)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,s.attribute,p[s.attribute]):(this.data[i].__merged_data[S]=[...n[i]],this._updateMergedAttribute(i,S,s.attribute,p[s.attribute]),this._setMergedHashAttribute(i,S))}}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),ue.error(l),new Error(Mn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ea.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),ue.error(l),new Error(Mn)}}}_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 ar.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new ar.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new ar.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new ar.yy.FuncValue:new ar.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,S=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${S}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${S}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,s);f=await ar.promise(h,t),t=null}catch(E){throw ue.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),ue.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let S=f[E];o.forEach(p=>{S[p.key]!==null&&S[p.key]!==void 0&&p.keys.add(S[p.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),S=Yc.difference(h,[...E.keys].map(p=>p.toString()));for(let p=0,g=S.length;p<g;p++){let A=S[p];delete this.data[`${E.schema}_${E.table}`].__merged_data[A]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new $_(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=Yc.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw ue.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),ue.error(i),new Error(Mn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ea.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let S=s.columns[h],p=E[S]===void 0?null:E[S];this.data[n].__merged_data[f].push(p)}}}}catch(r){throw ue.error("Error thrown from getDataByHash function in SQLSearch class method getData."),ue.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();ue.trace(`Final SQL: ${s}`),n=await ar.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),ue.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw ue.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),ue.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return ue.error(gQ.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),ue.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await ea.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw ue.error("There was an error when processing this SQL operation. Check your logs"),ue.error(o),new Error(Mn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};tw.exports=mp});var sn=T((ole,nw)=>{"use strict";var AQ=$b();nw.exports={searchByConditions:bQ,searchByHash:NQ,searchByValue:yQ,search:IQ};var pp=Ln(),{transformReq:Sp}=J(),OQ=rw();async function bQ(e){return Sp(e),pp.searchByConditions(e)}a(bQ,"searchByConditions");async function NQ(e){Sp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of pp.searchByHash(e))r&&t.push(r);return t}a(NQ,"searchByHash");async function yQ(e){Sp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of pp.searchByValue(e))t.push(r);return t}a(yQ,"searchByValue");function IQ(e,t){try{let r=new AQ(e);r.validate(),new OQ(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(IQ,"search")});var bs=T((cle,aw)=>{"use strict";var Kc=require("crypto"),wQ=j(),{CONFIG_PARAMS:CQ}=M(),iw="aes-256-cbc",DQ=32,LQ=16,Tp=64,ow=32,MQ=Tp+ow,sw=new Map;aw.exports={encrypt:UQ,decrypt:PQ,createNatsTableStreamName:vQ};function UQ(e){let t=Kc.randomBytes(DQ),r=Kc.randomBytes(LQ),n=Kc.createCipheriv(iw,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(UQ,"encrypt");function PQ(e){let t=e.substr(0,Tp),r=e.substr(Tp,ow),n=e.substr(MQ,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Kc.createDecipheriv(iw,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(PQ,"decrypt");function vQ(e,t){let r=wQ.get(CQ.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=sw.get(r);return n||(n=Kc.createHash("md5").update(r).digest("hex"),sw.set(r,n)),n}a(vQ,"createNatsTableStreamName")});var Gi=T((_le,uw)=>{"use strict";var lle=sn(),Y_=Y(),cw=I_(),BQ=bs(),K_=J(),{handleHDBError:W_,hdb_errors:HQ}=Z(),{HDB_ERROR_MSGS:Q_,HTTP_STATUS_CODES:gp}=HQ,xQ=j();xQ.initSync();var{getDatabases:Rp}=(Oe(),ee(Ge));uw.exports={describeAll:FQ,describeTable:z_,describeSchema:qQ};async function FQ(e){try{let t=K_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Rp(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let f in d)try{let E;if(t||n)E=await z_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await z_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){Y_.error(E)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return Y_.error("Got an error in describeAll"),Y_.error(t),W_(new Error,Q_.DESCRIBE_ALL_ERR)}}a(FQ,"describeAll");async function z_(e,t){K_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=cw.describe_table(e);if(i)throw i;let c=Rp()[r];if(!c)throw W_(new Error,Q_.SCHEMA_NOT_FOUND(e.schema),gp.NOT_FOUND);let u=c[n];if(!u)throw W_(new Error,Q_.TABLE_NOT_FOUND(e.schema,e.table),gp.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=BQ.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){Y_.warn(`unable to stat table dbi due to ${f}`)}return d}a(z_,"descTable");async function qQ(e){K_.transformReq(e);let t=cw.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Rp()[n];if(!i)throw W_(new Error,Q_.SCHEMA_NOT_FOUND(e.schema),gp.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),K_.isEmpty(u)||u.describe){let _=await z_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(qQ,"describeSchema")});var ti=T((hle,Ew)=>{var GQ=Pi(),{callbackify:_w,promisify:kQ}=require("util"),{getDatabases:dw}=(Oe(),ee(Ge));Ew.exports={setSchemaDataToGlobal:lw,getTableSchema:VQ,getSystemSchema:$Q,setSchemaDataToGlobalAsync:kQ(lw)};var fw=Gi(),fle=_w(fw.describeAll),Ele=_w(fw.describeTable);function lw(e){global.hdb_schema=dw(),e&&e()}a(lw,"setSchemaDataToGlobal");function VQ(e,t,r){let n=dw()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(VQ,"getTableSchema");function $Q(){return GQ}a($Q,"getSystemSchema")});var on=T((ple,Sw)=>{"use strict";var X_=Am(),qt=J(),YQ=require("util"),j_=Ln(),KQ=ti(),hw=Y(),{handleHDBError:ki,hdb_errors:WQ}=Z(),{HTTP_STATUS_CODES:Vi}=WQ,QQ=YQ.promisify(KQ.getTableSchema),zQ="updated",mw="inserted",pw="upserted";Sw.exports={insert:XQ,update:jQ,upsert:ZQ,validation:JQ,flush:ez};async function JQ(e){if(qt.isEmpty(e))throw new Error("invalid update parameters defined.");if(qt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(qt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await QQ(e.schema,e.table),r=X_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&qt.isEmptyOrZeroLength(c[n]))throw hw.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(!qt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw hw.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!qt.isEmpty(c[n])&&c[n]!==""&&s.has(qt.autoCast(c[n]))&&(c.skip=!0),s.add(qt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(JQ,"validation");async function XQ(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=X_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await j_.createRecords(e);return J_(mw,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(XQ,"insertData");async function jQ(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=X_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await j_.updateRecords(e);return qt.isEmpty(n.existing_rows)?J_(zQ,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):J_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(jQ,"updateData");async function ZQ(e){if(e.operation!=="upsert")throw ki(new Error,"invalid operation, must be upsert",Vi.INTERNAL_SERVER_ERROR);let t=X_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);qt.transformReq(e);let r=qt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await j_.upsertRecords(e);return J_(pw,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(ZQ,"upsertData");function J_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===mw?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===pw?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(J_,"returnObject");function ez(e){return qt.transformReq(e),j_.flush(e.schema,e.table)}a(ez,"flush")});var Op=T((Tle,Rw)=>{var tz=rt(),Ap=require("joi"),{hdb_table:rz,hdb_database:Tw}=Yn(),gw={schema:Tw,database:Tw,table:rz},nz={date:Ap.date().iso().required()},sz={timestamp:Ap.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};Rw.exports=function(e,t){let r=t==="timestamp"?{...gw,...sz}:{...gw,...nz},n=Ap.object(r);return tz.validateBySchema(e,n)}});var bw=T((gle,Ow)=>{var iz=rt(),bp=require("joi"),{hdb_table:oz,hdb_database:Aw}=Yn(),az=bp.object({schema:Aw,database:Aw,table:oz,hash_values:bp.array().required(),ids:bp.array()});Ow.exports=function(e){return iz.validateBySchema(e,az)}});var yw=T((Rle,Nw)=>{"use strict";var Np=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},yp=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Ip=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};Nw.exports={InsertObject:Np,NoSQLSeachObject:yp,DeleteResponseObject:Ip}});var Ki=T((Ole,Lw)=>{"use strict";var ww=Op(),cz=bw(),$i=J(),Iw=require("moment"),Cw=Y(),{promisify:uz,callbackify:lz}=require("util"),Yi=M(),_z=ti(),wp=uz(_z.getTableSchema),Cp=Ln(),{DeleteResponseObject:dz}=yw(),{handleHDBError:ri,hdb_errors:fz}=Z(),{HDB_ERROR_MSGS:Z_,HTTP_STATUS_CODES:ni}=fz,Ez="records successfully deleted",hz=lz(Dw);Lw.exports={delete:hz,deleteRecord:Dw,deleteFilesBefore:mz,deleteAuditLogsBefore:pz};async function mz(e){let t=ww(e,"date");if(t)throw ri(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);if($i.transformReq(e),!Iw(e.date,Iw.ISO_8601).isValid())throw ri(new Error,Z_.INVALID_DATE,ni.BAD_REQUEST,Yi.LOG_LEVELS.ERROR,Z_.INVALID_DATE,!0);let n=$i.checkSchemaTableExist(e.schema,e.table);if(n)throw ri(new Error,n,ni.NOT_FOUND,Yi.LOG_LEVELS.ERROR,n,!0);let s=await Cp.deleteRecordsBefore(e);if(await wp(e.schema,e.table),Cw.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(mz,"deleteFilesBefore");async function pz(e){let t=ww(e,"timestamp");if(t)throw ri(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);if($i.transformReq(e),isNaN(e.timestamp))throw ri(new Error,Z_.INVALID_VALUE("Timestamp"),ni.BAD_REQUEST,Yi.LOG_LEVELS.ERROR,Z_.INVALID_VALUE("Timestamp"),!0);let r=$i.checkSchemaTableExist(e.schema,e.table);if(r)throw ri(new Error,r,ni.NOT_FOUND,Yi.LOG_LEVELS.ERROR,r,!0);let n=await Cp.deleteAuditLogsBefore(e);return await wp(e.schema,e.table),Cw.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(pz,"deleteAuditLogsBefore");async function Dw(e){e.ids&&(e.hash_values=e.ids);let t=cz(e);if(t)throw ri(t,t.message,ni.BAD_REQUEST,void 0,void 0,!0);$i.transformReq(e);let r=$i.checkSchemaTableExist(e.schema,e.table);if(r)throw ri(new Error,r,ni.NOT_FOUND,Yi.LOG_LEVELS.ERROR,r,!0);try{await wp(e.schema,e.table);let n=await Cp.deleteRecords(e);return $i.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${Ez}`),n}catch(n){if(n.message===Yi.SEARCH_NOT_FOUND_MESSAGE){let s=new dz;return s.message=Yi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(Dw,"deleteRecord")});var ed=T((Nle,Pw)=>{var Sz=require("crypto"),Mw=9;function Tz(e){let t=Rz(Mw),r=Uw(e+t);return t+r}a(Tz,"createHash");function gz(e,t){let r=e?.substr(0,Mw),n=r+Uw(t+r);return e===n}a(gz,"validateHash");function Rz(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(Rz,"generateSalt");function Uw(e){return Sz.createHash("md5").update(e).digest("hex")}a(Uw,"md5");Pw.exports={hash:Tz,validate:gz}});var Bw=T((Ile,vw)=>{var Dp=rt(),Qt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function Az(e){return Qt.password.presence=!0,Qt.username.presence=!0,Qt.role.presence=!0,Qt.active.presence=!0,Dp.validateObject(e,Qt)}a(Az,"addUserValidation");function Oz(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Dp.validateObject(e,Qt)}a(Oz,"alterUserValidation");function bz(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Dp.validateObject(e,Qt)}a(bz,"dropUserValidation");vw.exports={addUserValidation:Az,alterUserValidation:Oz,dropUserValidation:bz}});var nt=T((Dle,xw)=>{"use strict";var{platform:Cle}=require("os"),Nz="nats-server.zip",Lp="nats-server",yz=process.platform==="win32"?`${Lp}.exe`:Lp,Mp="HDB",Iz=/^[^\s.,*>]+$/,Hw="__request__",wz=a(e=>`${e}.${Hw}`,"REQUEST_SUBJECT"),Cz={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},Dz={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},Lz={HUB:"hub.pid",LEAF:"leaf.pid"},Mz={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},Uz={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Mp,deliver_subject:"__HDB__.WORKQUEUE"},Pz={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Mp,deliver_subject:"HDB.SCHEMAQUEUE"},vz={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Mp,deliver_subject:"HDB.USERQUEUE"},Bz={SUCCESS:"success",ERROR:"error"},Hz={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},xz={TXN:"txn",MSGID:"msgid"},ta={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},Fz={[ta.ERR]:1,[ta.WRN]:2,[ta.INF]:3,[ta.DBG]:4,[ta.TRC]:5},qz={debug:"-D",trace:"-DVV"};xw.exports={NATS_SERVER_ZIP:Nz,NATS_SERVER_NAME:Lp,NATS_BINARY_NAME:yz,PID_FILES:Lz,NATS_CONFIG_FILES:Dz,SERVER_SUFFIX:Mz,WORK_QUEUE_CONSUMER_NAMES:Uz,SCHEMA_QUEUE_CONSUMER_NAMES:Pz,USER_QUEUE_CONSUMER_NAMES:vz,NATS_TERM_CONSTRAINTS_RX:Iz,REQUEST_SUFFIX:Hw,UPDATE_REMOTE_RESPONSE_STATUSES:Bz,CLUSTER_STATUS_STATUSES:Hz,REQUEST_SUBJECT:wz,SUBJECT_PREFIXES:xz,MSG_HEADERS:Cz,LOG_LEVELS:ta,LOG_LEVEL_FLAGS:qz,LOG_LEVEL_HIERARCHY:Fz}});var qw=T((Mle,Fw)=>{"use strict";var Gz={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
|
|
1
|
+
var eF=Object.create;var za=Object.defineProperty;var tF=Object.getOwnPropertyDescriptor;var rF=Object.getOwnPropertyNames;var nF=Object.getPrototypeOf,sF=Object.prototype.hasOwnProperty;var a=(e,t)=>za(e,"name",{value:t,configurable:!0});var Oe=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fe=(e,t)=>{for(var r in t)za(e,r,{get:t[r],enumerable:!0})},yA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rF(t))!sF.call(e,s)&&s!==r&&za(e,s,{get:()=>t[s],enumerable:!(n=tF(t,s))||n.enumerable});return e};var x=(e,t,r)=>(r=e!=null?eF(nF(e)):{},yA(t||!e||!e.__esModule?za(r,"default",{value:e,enumerable:!0}):r,e)),te=e=>yA(za({},"__esModule",{value:!0}),e);var U=T((vie,qA)=>{"use strict";var Jr=require("path"),iF=require("fs"),{relative:Uie,join:Pie}=Jr,{existsSync:oF}=iF;function aF(){let e=__dirname;for(;!oF(Jr.join(e,"package.json"));){let t=Jr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(aF,"getHDBPackageRoot");var $s=aF(),wA="js",Cl=wA,cF="harperdb-config.yaml",uF="defaultConfig.yaml",lF="hdb",IA=`harperdb.${Cl}`,CA=`customFunctionsServer.${Cl}`,_F=`restartHdb.${Cl}`,JE="HarperDB",Il="Custom Functions",Dl="Clustering Hub",Ll="Clustering Leaf",dF="Clustering Ingest Service",fF="Clustering Reply Service",EF="foreground.pid",hF="hdb.pid",mF="data",pF={HDB:JE,CLUSTERING_HUB:Dl,CLUSTERING_LEAF:Ll,CLUSTERING_INGEST_SERVICE:dF,CLUSTERING_REPLY_SERVICE:fF,CUSTOM_FUNCTIONS:Il,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"},SF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},TF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},gF={harperdb:JE,"clustering hub":Dl,"clustering leaf":Ll,"custom functions":Il,custom_functions:Il,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},RF={CLUSTERING_HUB_PROC_DESCRIPTOR:Dl,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ll},zE={HDB:Jr.join($s,"server/harperdb"),CUSTOM_FUNCTIONS:Jr.join($s,"server/customFunctions"),CLUSTERING_HUB:Jr.join($s,"server/nats"),CLUSTERING_LEAF:Jr.join($s,"server/nats")},AF={HDB:Jr.join(zE.HDB,IA),CUSTOM_FUNCTIONS:Jr.join(zE.CUSTOM_FUNCTIONS,CA)},OF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Jr.join($s,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Jr.join($s,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Jr.join($s,"launchServiceScripts/launchUpdateNodes4-0-0.js")},bF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},DA="support@harperdb.io",NF="customer-success@harperdb.io",LA=1,yF=4141,MA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",wF="https://www.harperdb.io/product",IF=`For support, please submit a request at ${MA} or contact ${DA}`,UA=`For license support, please contact ${NF}`,CF="None of the specified records were found.",DF="hash attribute not found",LF=`Your current license only supports ${LA} role. ${UA}`,MF="Your current license only supports 3 connections to a node.",UF="127.0.0.1",PF=1,vF=/^\.$/,BF=/^\.\.$/,HF="U+002E",xF=/\//g,FF="U+002F",qF=/U\+002F/g,GF=/^U\+002E$/,kF=/^U\+002EU\+002E$/,VF="d",$F=999999,YF="*",KF="--max-old-space-size=",WF="system",QF="__hdb_hash",zF=".harperdb",JF=".hdb",XF="keys",jF="hdb_boot_properties.file",ZF=".updateConfig.json",eq="SIGTSTP",tq=24,rq=6e4,nq=448,sq="blob",iq="trash",oq="database",aq="schema",cq="transactions",uq=".count",lq="id",_q="PROCESS_NAME",PA={SETTINGS_PATH_KEY:"settings_path"},vA=require("lodash"),dq={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},fq={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},Eq={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},hq={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"},mq={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"},Or="hdb_internal:",pq={CREATE_SCHEMA:Or+"create_schema",CREATE_TABLE:Or+"create_table",CREATE_ATTRIBUTE:Or+"create_attribute",ADD_USER:Or+"add_user",ALTER_USER:Or+"alter_user",DROP_USER:Or+"drop_user",HDB_NODES:Or+"hdb_nodes",HDB_USERS:Or+"hdb_users",HDB_WORKERS:Or+"hdb_workers",CATCHUP:Or+"catchup",SCHEMA_CATCHUP:Or+"schema_catchup",WORKER_ROOM:Or+"cluster_workers"},Sq={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"},Tq="060493.ks",gq=".license",Rq={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},X={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},Aq={CSV:".csv",JSON:".json"},Oq={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},bq={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Ja={};Ja[X.INSERT]=X.INSERT;Ja[X.UPDATE]=X.UPDATE;Ja[X.UPSERT]=X.UPSERT;Ja[X.DELETE]=X.DELETE;var Be=Object.create(null);Be[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;Be[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;Be[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;Be[X.READ_LOG]=X.READ_LOG;Be[X.ADD_NODE]=X.ADD_NODE;Be[X.LIST_USERS]=X.LIST_USERS;Be[X.LIST_ROLES]=X.LIST_ROLES;Be[X.USER_INFO]=X.USER_INFO;Be[X.SQL]=X.SQL;Be[X.GET_JOB]=X.GET_JOB;Be[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;Be[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;Be[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;Be[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;Be[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;Be[X.REMOVE_NODE]=X.REMOVE_NODE;Be[X.RESTART]=X.RESTART;Be[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;Be[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;Be[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;Be[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;Be[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;Be[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;Be[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;Be[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;Be[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var Nq={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},yq={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},BA={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"},wq=vA.invert(BA),Iq={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"},C={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_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",MAXHEAPMEMORY:"maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},HA={settings_path:PA.SETTINGS_PATH_KEY,hdb_root_key:C.ROOTPATH,hdb_root:C.ROOTPATH,rootpath:C.ROOTPATH,server_port_key:C.OPERATIONSAPI_NETWORK_PORT,server_port:C.OPERATIONSAPI_NETWORK_PORT,cert_key:C.TLS_CERTIFICATE,certificate:C.TLS_CERTIFICATE,private_key_key:C.TLS_PRIVATEKEY,private_key:C.TLS_PRIVATEKEY,http_secure_enabled_key:C.OPERATIONSAPI_NETWORK_HTTPS,https_on:C.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:C.OPERATIONSAPI_NETWORK_CORS,cors_on:C.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:C.LOGGING_LEVEL,log_level:C.LOGGING_LEVEL,log_path_key:C.LOGGING_ROOT,log_path:C.LOGGING_ROOT,clustering_node_name_key:C.CLUSTERING_NODENAME,node_name:C.CLUSTERING_NODENAME,clustering_enabled_key:C.CLUSTERING_ENABLED,clustering:C.CLUSTERING_ENABLED,max_http_threads:C.THREADS,max_hdb_processes:C.THREADS,server_timeout_key:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:C.LOGGING_AUDITLOG,disable_transaction_log:C.LOGGING_AUDITLOG,operation_token_timeout_key:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:C.HTTP_PORT,custom_functions_port:C.HTTP_PORT,custom_functions_directory_key:C.COMPONENTSROOT,custom_functions_directory:C.COMPONENTSROOT,max_custom_function_processes:C.THREADS,log_to_file:C.LOGGING_FILE,log_to_stdstreams:C.LOGGING_STDSTREAMS,local_studio_on:C.LOCALSTUDIO_ENABLED,clustering_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:C.CLUSTERING_USER,clustering_enabled:C.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:C.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:C.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:C.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:C.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:C.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:C.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:C.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:C.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:C.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:C.CLUSTERING_NODENAME,clustering_tls_certificate:C.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:C.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:C.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:C.CLUSTERING_TLS_INSECURE,clustering_tls_verify:C.CLUSTERING_TLS_VERIFY,clustering_loglevel:C.CLUSTERING_LOGLEVEL,clustering_republishmessages:C.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:C.CLUSTERING_DATABASELEVEL,customfunctions_network_port:C.HTTP_PORT,customfunctions_tls_certificate:C.TLS_CERTIFICATE,customfunctions_network_cors:C.HTTP_CORS,customfunctions_network_corsaccesslist:C.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:C.HTTP_HEADERSTIMEOUT,customfunctions_network_https:C.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:C.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:C.HTTP_TIMEOUT,http_threads:C.THREADS,threads:C.THREADS,maxheapmemory:C.MAXHEAPMEMORY,http_session_affinity:C.HTTP_SESSIONAFFINITY,http_compressionthreshold:C.HTTP_COMPRESSIONTHRESHOLD,http_cors:C.HTTP_CORS,http_corsaccesslist:C.HTTP_CORSACCESSLIST,http_headerstimeout:C.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,http_timeout:C.HTTP_TIMEOUT,http_port:C.HTTP_PORT,http_secureport:C.HTTP_SECUREPORT,http_mtls:C.HTTP_MTLS,http_mtls_user:C.HTTP_MTLS_USER,http_mtls_required:C.HTTP_MTLS_REQUIRED,customfunctions_processes:C.THREADS,customfunctions_root:C.COMPONENTSROOT,localstudio_enabled:C.LOCALSTUDIO_ENABLED,logging_file:C.LOGGING_FILE,logging_level:C.LOGGING_LEVEL,logging_root:C.LOGGING_ROOT,logging_rotation_enabled:C.LOGGING_ROTATION_ENABLED,logging_rotation_compress:C.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:C.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:C.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:C.LOGGING_ROTATION_PATH,logging_stdstreams:C.LOGGING_STDSTREAMS,logging_auditlog:C.LOGGING_AUDITLOG,logging_auditretention:C.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:C.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:C.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:C.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:C.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:C.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:C.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:C.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:C.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:C.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:C.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:C.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:C.ROOTPATH,databases:C.DATABASES,storage_path:C.STORAGE_PATH,ignorescripts:C.IGNORE_SCRIPTS,mqtt_network_port:C.MQTT_NETWORK_PORT,mqtt_websocket:C.MQTT_WEBSOCKET,mqtt_network_secureport:C.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:C.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:C.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:C.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:C.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:C.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:C.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:C.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:C.AUTHENTICATION_CACHETTL,authentication_enablesessions:C.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:C.COMPONENTSROOT,tls_certificate:C.TLS_CERTIFICATE,tls_privatekey:C.TLS_PRIVATEKEY,tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,tls_ciphers:C.TLS_CIPHERS};for(let e in C){let t=C[e];HA[t.toLowerCase()]=t}var Cq={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},Dq={csv_file_load:"csv_file_load",csv_data_load:X.CSV_DATA_LOAD,csv_url_load:X.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"},Lq={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"},Mq={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Uq={VERSION_DEFAULT:"2.2.0"},Pq={DEVELOPMENT:8192,DEFAULT:512},vq={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"},Bq={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"},Hq={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},xA={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},xq=Symbol("metadata"),Fq="__clustering__",qq=Object.values(xA),Gq=15984864e5,FA={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},kq=vA.invert(FA),Vq={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"},$q=111,Yq=`\r
|
|
2
|
+
`,Kq={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Wq=["*","%"],Qq="unauthorized_access",zq="func_val",Jq={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Xq={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},jq={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"},Zq={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},eG={HTTP:"http"},tG={STOPPED:"stopped",ONLINE:"online"},rG="3.x.x",nG={SUCCESS:"success",FAILURE:"failure"},sG={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};qA.exports={LOCAL_HARPERDB_OPERATIONS:Be,HDB_SUPPORT_ADDRESS:DA,HDB_SUPPORT_URL:MA,HDB_PRICING_URL:wF,SUPPORT_HELP_MSG:IF,LICENSE_HELP_MSG:UA,HDB_PROC_NAME:IA,HDB_PROC_DESCRIPTOR:JE,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ll,CLUSTERING_HUB_PROC_DESCRIPTOR:Dl,SYSTEM_SCHEMA_NAME:WF,HASH_FOLDER_NAME:QF,HDB_HOME_DIR_NAME:zF,UPDATE_FILE_NAME:ZF,LICENSE_KEY_DIR_NAME:XF,BOOT_PROPS_FILE_NAME:jF,JOB_TYPE_ENUM:Dq,JOB_STATUS_ENUM:Rq,SYSTEM_TABLE_NAMES:hq,SYSTEM_TABLE_HASH_ATTRIBUTES:mq,OPERATIONS_ENUM:X,VALID_S3_FILE_TYPES:Aq,S3_BUCKET_AUTH_KEYS:Oq,VALID_SQL_OPS_ENUM:bq,GEO_CONVERSION_ENUM:yq,HDB_SETTINGS_NAMES:BA,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:wq,SERVICE_ACTIONS_ENUM:Nq,CLUSTER_MESSAGE_TYPE_ENUM:Lq,CLUSTER_CONNECTION_DIRECTION_ENUM:Mq,CLUSTER_EVENTS_DEFS_ENUM:vq,PERIOD_REGEX:vF,DOUBLE_PERIOD_REGEX:BF,UNICODE_PERIOD:HF,FORWARD_SLASH_REGEX:xF,UNICODE_FORWARD_SLASH:FF,ESCAPED_FORWARD_SLASH_REGEX:qF,ESCAPED_PERIOD_REGEX:GF,ESCAPED_DOUBLE_PERIOD_REGEX:kF,REG_KEY_FILE_NAME:Tq,RESTART_TIMEOUT_MS:rq,HDB_FILE_PERMISSIONS:nq,DATABASES_DIR_NAME:oq,LEGACY_DATABASES_DIR_NAME:aq,TRANSACTIONS_DIR_NAME:cq,LIMIT_COUNT_NAME:uq,ID_ATTRIBUTE_STRING:lq,INSERT_MODULE_ENUM:fq,UPGRADE_JSON_FIELD_NAMES_ENUM:Eq,RESTART_CODE:eq,RESTART_CODE_NUM:tq,CLUSTER_OPERATIONS:Ja,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:Sq,HDB_INTERNAL_SC_CHANNEL_PREFIX:Or,INTERNAL_SC_CHANNELS:pq,CLUSTERING_MESSAGE_TYPES:Vq,HDB_FILE_SUFFIX:JF,BLOB_FOLDER_NAME:sq,HDB_TRASH_DIR:iq,ORIGINATOR_SET_VALUE:$q,LICENSE_VALUES:Uq,RAM_ALLOCATION_ENUM:Pq,TIME_STAMP_NAMES_ENUM:xA,TIME_STAMP_NAMES:qq,PERMS_UPDATE_RELEASE_TIMESTAMP:Gq,SEARCH_NOT_FOUND_MESSAGE:CF,SEARCH_ATTRIBUTE_NOT_FOUND:DF,LICENSE_ROLE_DENIED_RESPONSE:LF,LICENSE_MAX_CONNS_REACHED:MF,BASIC_LICENSE_MAX_NON_CU_ROLES:LA,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:yF,VALUE_SEARCH_COMPARATORS:FA,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:kq,LICENSE_FILE_NAME:gq,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:Bq,NEW_LINE:Yq,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:PF,MOMENT_DAYS_TAG:VF,API_TURNOVER_SEC:$F,LOOPBACK:UF,CODE_EXTENSION:Cl,WILDCARD_SEARCH_VALUE:YF,NODE_ERROR_CODES:Hq,JAVASCRIPT_EXTENSION:wA,PERMS_CRUD_ENUM:Kq,UNAUTHORIZED_PERMISSION_NAME:Qq,SEARCH_WILDCARDS:Wq,FUNC_VAL:zq,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Jq,JWT_ENUM:Xq,CLUSTERING_FLAG:Fq,ITC_EVENT_TYPES:jq,CUSTOM_FUNCTION_PROC_NAME:CA,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Il,SERVICES:Zq,THREAD_TYPES:eG,MEM_SETTING_KEY:KF,HDB_RESTART_SCRIPT:_F,PROCESS_DESCRIPTORS:pF,SERVICE_SERVERS:AF,SERVICE_SERVERS_CWD:zE,PROCESS_DESCRIPTORS_VALIDATE:gF,LAUNCH_SERVICE_SCRIPTS:OF,LOG_LEVELS:TF,PROCESS_NAME_ENV_PROP:_q,LOG_NAMES:SF,PM2_PROCESS_STATUSES:tG,CONFIG_PARAM_MAP:HA,CONFIG_PARAMS:C,HDB_CONFIG_FILE:cF,HDB_DEFAULT_CONFIG_FILE:uF,ROLE_TYPES_ENUM:bF,BOOT_PROP_PARAMS:PA,INSTALL_PROMPTS:dq,HDB_ROOT_DIR_NAME:lF,CLUSTERING_PROCESSES:RF,FOREGROUND_PID_FILE:EF,PACKAGE_ROOT:$s,PRE_4_0_0_VERSION:rG,DATABASES_PARAM_CONFIG:Cq,METADATA_PROPERTY:xq,AUTH_AUDIT_STATUS:nG,AUTH_AUDIT_TYPES:sG,HDB_PID_FILE:hF,DEFAULT_DATABASE_NAME:mF,LEGACY_CONFIG_PARAMS:Iq};XE()});var XE=T((xie,kA)=>{var iG=require("fast-glob"),{statSync:jE,existsSync:ZE,readFileSync:oG,writeFileSync:aG}=require("fs"),{spawnSync:cG,spawn:uG,execFileSync:Hie}=require("child_process"),{isMainThread:lG}=require("worker_threads"),{join:Ys,relative:GA}=require("path"),{PACKAGE_ROOT:Sn}=U(),{tmpdir:_G,platform:dG}=require("os");require("source-map-support").install();var fG=["resources","server","dataLayer","components"],Xa="ts-build",eh,EG=__filename.endsWith("tsBuild.js");if(EG){if(lG){let r;try{jE(Ys(Sn,Xa)),r=!0}catch{}if(r)for(let n of iG.sync(fG.map(s=>s+"/**/*.ts"),{cwd:Sn})){let s=0,i=0;try{s=jE(Ys(Sn,n)).mtimeMs-5e3,i=jE(Ys(Sn,Xa,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),eh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),eh=!0;if(eh){let n=Ys(Sn,"node_modules/.bin/tsc");dG()==="win32"&&(n+=".cmd");let s=cG(n,{cwd:Sn});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=Ys(_G(),"harperdb-tsc.pid"),o;if(ZE(i))try{process.kill(+oG(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=uG(n,["--watch"],{cwd:Sn,detached:!0,stdio:"ignore"});aG(i,c.pid.toString()),c.unref()}}}}let e=kA.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(Sn)&&!n[0].includes("node_modules")){let i=GA(Sn,n[0]),o;i.startsWith(Xa)?o=Ys(Sn,GA(Xa,i)):o=Ys(Sn,Xa,i);let c=Ys(o,r),u=c+".js";if(ZE(u))return u;if(c.includes(".")&&ZE(c))return c}return t(r,n,s)}}});var yi={};Fe(yi,{server:()=>Xe});var VA,Xe,zt=Oe(()=>{VA=require("../index"),Xe={};(0,VA._assignPackageExport)("server",Xe)});var th=T((Fie,KA)=>{"use strict";var $A=require("minimist");KA.exports=hG;function hG(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=YA(process.env),n=YA($A(process.argv))):(r=process.env,n=$A(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(hG,"assignCMDENVVariables");function YA(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(YA,"objKeysToLowerCase")});var W=T((Gie,ch)=>{"use strict";var wi=require("fs-extra"),{workerData:mG,threadId:pG}=require("worker_threads"),_s=require("path"),zA=require("yaml"),JA=require("properties-reader"),Tt=U(),WA=th(),SG=require("os"),{PACKAGE_ROOT:nh}=U(),{_assignPackageExport:TG}=require("../index"),Za={};for(let e in console)Za[e]||(Za[e]=console[e]);var Xt={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},XA={STDOUT:"stdOut",STDERR:"stdErr"},gG=_s.join(nh,"logs"),RG=_s.join(nh,"config/yaml/",Tt.HDB_DEFAULT_CONFIG_FILE),AG=1e4,ls,qn,Jt,Ml,Ul,ec,Mo,ja;ja===void 0&&jA();ch.exports={notify:tO,fatal:rO,error:tc,warn:ah,info:Pl,debug:oh,trace:ih,setLogLevel:CG,log_level:Jt,loggerWithTag:OG,suppressLogging:bG,initLogSettings:jA,setupConsoleLogging:ZA,logCustomLevel:wG,closeLogFile:sh,getLogFilePath:()=>ec,OUTPUTS:XA,AuthAuditLog:MG};TG("logger",ch.exports);function jA(e=!1){try{if(ja===void 0||e){sh();let t=IG(),r=WA(["ROOTPATH"]);try{ja=JA(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!wi.pathExistsSync(_s.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE)))throw n}({level:Jt,config_log_path:Ul,to_file:ls,to_stream:qn}=DG(r.ROOTPATH?_s.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE):ja.get("settings_path"))),Ml=Tt.LOG_NAMES.HDB,ec=_s.join(Ul,Ml)}}catch(t){if(ja=void 0,t.code===Tt.NODE_ERROR_CODES.ENOENT){let r=WA(Object.keys(Tt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Tt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Tt.CONFIG_PARAMS.LOGGING_LEVEL){Jt=u;continue}if(c===Tt.CONFIG_PARAMS.LOGGING_STDSTREAMS){qn=u;continue}c===Tt.CONFIG_PARAMS.LOGGING_FILE&&(ls=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=LG();ls=ls===void 0?s:ls,ls=QA(ls),qn=qn===void 0?i:qn,qn=QA(qn),Jt=Jt===void 0?n:Jt,Ul=gG,Ml=Tt.LOG_NAMES.INSTALL,ec=_s.join(Ul,Ml);return}throw tc("Error initializing log settings"),tc(t),t}process.env.DEV_MODE&&(qn=!0),ZA()}a(jA,"initLogSettings");var rh=!0;function ZA(){Lo("error",tc),Lo("warn",ah),Lo("log",Pl),Lo("info",Pl),Lo("debug",oh),Lo("trace",ih)}a(ZA,"setupConsoleLogging");function Lo(e,t){console[e]=function(...r){if(rh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return Za[e](...r)}}a(Lo,"logConsole");function OG(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(tO),fatal:r(rO),error:r(tc),warn:r(ah),info:r(Pl),debug:r(oh),trace:r(ih)};function r(n){return function(...s){return n(t,...s)}}}a(OG,"loggerWithTag");function bG(e){try{rh=!1,e()}finally{rh=!0}}a(bG,"suppressLogging");var NG=mG?.name?.replace(/ /g,"-")||"main";function ds(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||NG+"/"+pG);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
3
|
+
`}a(ds,"createLogRecord");function rc(e){ls&&eO(e),qn&&process.stdout.write(e)}a(rc,"logStdOut");function vl(e){ls&&eO(e),qn&&process.stderr.write(e)}a(vl,"logStdErr");function eO(e){yG(),Mo?wi.appendFileSync(Mo,e):Za.log(e)}a(eO,"logToFile");function sh(){try{wi.closeSync(Mo)}catch{}Mo=null}a(sh,"closeLogFile");function yG(){if(!Mo){try{if(!ec)debugger;Mo=wi.openSync(ec,"a")}catch(e){Za.error(e)}setTimeout(()=>{sh()},AG).unref()}}a(yG,"openLogFile");function Pl(...e){Xt[Jt]<=Xt.info&&rc(ds("info",e))}a(Pl,"info");function ih(...e){Xt[Jt]<=Xt.trace&&rc(ds("trace",e))}a(ih,"trace");function tc(...e){Xt[Jt]<=Xt.error&&vl(ds("error",e))}a(tc,"error");function oh(...e){Xt[Jt]<=Xt.debug&&rc(ds("debug",e))}a(oh,"debug");function tO(...e){Xt[Jt]<=Xt.notify&&rc(ds("notify",e))}a(tO,"notify");function rO(...e){Xt[Jt]<=Xt.fatal&&vl(ds("fatal",e))}a(rO,"fatal");function ah(...e){Xt[Jt]<=Xt.warn&&vl(ds("warn",e))}a(ah,"warn");function wG(e,t,...r){t===XA.STDERR?vl(ds(e,r)):rc(ds(e,r))}a(wG,"logCustomLevel");function IG(){let e;try{e=SG.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=_s.join(e,Tt.HDB_HOME_DIR_NAME,Tt.BOOT_PROPS_FILE_NAME);return wi.existsSync(t)||(t=_s.join(nh,"utility/hdb_boot_properties.file")),t}a(IG,"getPropsFilePath");function CG(e){Jt=e}a(CG,"setLogLevel");function QA(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(QA,"autoCastBoolean");function DG(e){try{if(e.includes("config/settings.js")){let o=JA(e);return{level:o.get(Tt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:_s.dirname(o.get(Tt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=zA.parseDocument(wi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===Tt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(DG,"getLogConfig");function LG(){try{let e=zA.parseDocument(wi.readFileSync(RG,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(LG,"getDefaultConfig");function MG(e,t,r,n,s,i){this.username=e,this.status=t,this.type=r,this.originating_ip=n,this.request_method=s,this.path=i}a(MG,"AuthAuditLog")});var sO=T((Vie,nO)=>{"use strict";var UG=require("util"),PG=require("path"),vG=require("child_process"),BG=UG.promisify(vG.execFile),HG=1e3*1e3*10;nO.exports={findPs:xG};async function xG(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await BG("ps",["wwxo",`pid,${r}`],{maxBuffer:HG});for(let s of n.trim().split(`
|
|
4
|
+
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:PG.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(xG,"findPs")});var lt=T((Yie,oO)=>{"use strict";var FG="__dbis__",qG="__txns__",GG="__environment_name__",kG="__dbi_defintion__",VG={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"},$G=["__createdtime__","__updatedtime__"],YG="\uFFFF",iO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},KG=Object.values(iO);oO.exports={AUDIT_STORE_NAME:qG,INTERNAL_DBIS_NAME:FG,DBI_DEFINITION_NAME:kG,SEARCH_TYPES:VG,TIMESTAMP_NAMES:$G,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:GG,TRANSACTIONS_DBI_NAMES_ENUM:iO,TRANSACTIONS_DBIS:KG,OVERFLOW_MARKER:YG}});var br=T((Kie,hO)=>{"use strict";var aO=U(),cO=lt(),uO={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},lO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),_O={500:lO("There was an error processing your request."),400:"Invalid request"},WG=_O[uO.INTERNAL_SERVER_ERROR],QG={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.`},zG={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},JG={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"},XG={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 ${cO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${cO.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"},jG={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${aO.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 ${aO.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"},dO={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"},ZG={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."},ek={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`},tk={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"},rk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},nk={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`},fO={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.`},EO={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}`},sk={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."},ik={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},ok={...dO,...JG,...QG,...ZG,...ek,...tk,...rk,...nk,...jG,...fO,...EO,...sk,...ik,...zG};hO.exports={CHECK_LOGS_WRAPPER:lO,HDB_ERROR_MSGS:ok,DEFAULT_ERROR_MSGS:_O,DEFAULT_ERROR_RESP:WG,HTTP_STATUS_CODES:uO,LMDB_ERRORS_ENUM:XG,AUTHENTICATION_ERROR_MSGS:dO,VALIDATION_ERROR_MSGS:fO,ITC_ERRORS:EO}});var ee=T((Qie,SO)=>{"use strict";var Uo=br(),ak=W(),ck=U(),Bl=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,mO),this.statusCode=n||Uo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Uo.DEFAULT_ERROR_MSGS[n]?Uo.DEFAULT_ERROR_MSGS[n]:Uo.DEFAULT_ERROR_MSGS[Uo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&ak[s](i)}},uh=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}},lh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function mO(e,t,r,n=ck.LOG_LEVELS.ERROR,s=null,i=!1){if(pO(e))return e;let o=new Bl(e,t,r,n,s);return i&&delete o.stack,o}a(mO,"handleHDBError");function pO(e){return e.__proto__.constructor.name===Bl.name}a(pO,"isHDBError");SO.exports={isHDBError:pO,handleHDBError:mO,ClientError:uh,ServerError:lh,hdb_errors:Uo}});var Ye=T((Jie,NO)=>{"use strict";var ac=U(),uk=J(),jt=Z(),cc=require("path"),lk=require("minimist"),TO=require("fs-extra"),gO=require("lodash");jt.initSync();var{CONFIG_PARAMS:Ks,DATABASES_PARAM_CONFIG:nc,SYSTEM_SCHEMA_NAME:Hl}=ac,sc,ic,oc;function RO(){if(sc!==void 0)return sc;if(jt.getHdbBasePath()!==void 0)return sc=jt.get(Ks.STORAGE_PATH)||cc.join(jt.getHdbBasePath(),ac.DATABASES_DIR_NAME),sc}a(RO,"getBaseSchemaPath");function AO(){if(ic!==void 0)return ic;if(jt.getHdbBasePath()!==void 0)return ic=bO(Hl),ic}a(AO,"getSystemSchemaPath");function OO(){if(oc!==void 0)return oc;if(jt.getHdbBasePath()!==void 0)return oc=jt.get(ac.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||cc.join(jt.getHdbBasePath(),ac.TRANSACTIONS_DIR_NAME),oc}a(OO,"getTransactionAuditStoreBasePath");function _k(e,t){let r=jt.get(Ks.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||cc.join(OO(),e.toString())}a(_k,"getTransactionAuditStorePath");function bO(e,t){e=e.toString(),t=t&&t.toString();let r=jt.get(ac.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||cc.join(RO(),e)}a(bO,"getSchemaPath");function dk(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,lk(process.argv));let n=r[Ks.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!uk.isObject(n))throw o;i=n}for(let o of i){let c=o[Hl];if(!c)continue;let u=jt.get(Ks.DATABASES);u=u??{};let _=c?.tables?.[t]?.[nc.PATH];if(_)return gO.set(u,[Hl,nc.TABLES,t,nc.PATH],_),jt.setProperty(Ks.DATABASES,u),_;let l=c?.[nc.PATH];if(l)return gO.set(u,[Hl,nc.PATH],l),jt.setProperty(Ks.DATABASES,u),l}}let s=r[Ks.STORAGE_PATH.toUpperCase()];if(s){if(!TO.pathExistsSync(s))throw new Error(s+" does not exist");let i=cc.join(s,e);return TO.mkdirsSync(i),jt.setProperty(Ks.STORAGE_PATH,s),i}return AO()}a(dk,"initSystemSchemaPaths");function fk(){sc=void 0,ic=void 0,oc=void 0}a(fk,"resetPaths");NO.exports={getBaseSchemaPath:RO,getSystemSchemaPath:AO,getTransactionAuditStorePath:_k,getTransactionAuditStoreBasePath:OO,getSchemaPath:bO,initSystemSchemaPaths:dk,resetPaths:fk}});var Nr=T((eoe,DO)=>{"use strict";var Ek=br().LMDB_ERRORS_ENUM,jie=require("lmdb"),hk=lt(),Zie=require("buffer").Buffer,{OVERFLOW_MARKER:yO,MAX_SEARCH_KEY_LENGTH:xl}=hk,wO=["number","string","symbol","boolean","bigint"];function mk(e){if(e=e?.primaryStore||e,!e)throw new Error(Ek.ENV_REQUIRED)}a(mk,"validateEnv");function pk(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(pk,"stringifyData");function Sk(e){return e instanceof Date?e.valueOf():e}a(Sk,"convertKeyValueToWrite");function Tk(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(wO.includes(typeof e))return e.length>xl?[e.slice(0,xl)+yO]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(wO.includes(typeof i))i.length>xl?r.push(i.slice(0,xl)+yO):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(Tk,"getIndexedValues");var Fl=0,IO=0;function CO(){IO=Date.now()-performance.now()}a(CO,"adjustStartTime");CO();var gk=6e4;setInterval(CO,gk).unref();function Rk(){let e=performance.now()+IO;return e>Fl?(Fl=e,e):(Fl+=488e-6,Fl)}a(Rk,"getNextMonotonicTime");DO.exports={validateEnv:mk,stringifyData:pk,convertKeyValueToWrite:Sk,getNextMonotonicTime:Rk,getIndexedValues:Tk}});var LO,Tn,_h,uc=Oe(()=>{LO=require("events"),Tn=class extends LO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new _h;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)}},_h=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var vO={};Fe(vO,{HAS_EXPIRATION:()=>Th,LAST_TIMESTAMP_PLACEHOLDER:()=>dc,LOCAL_TIMESTAMP:()=>Ak,METADATA:()=>lc,NO_TIMESTAMP:()=>fh,PENDING_LOCAL_TIME:()=>gh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Sh,RecordEncoder:()=>mh,TIMESTAMP_ASSIGN_LAST:()=>bk,TIMESTAMP_ASSIGN_NEW:()=>UO,TIMESTAMP_ASSIGN_PREVIOUS:()=>PO,TIMESTAMP_PLACEHOLDER:()=>ql,TIMESTAMP_RECORD_PREVIOUS:()=>Eh,fromResource:()=>$l,getUpdateRecord:()=>Rh,handleLocalTimeForGets:()=>Yl});function yk(){return _c[0]=_c[0]^64,Ok.getFloat64(0)}function $l(e){ph=!0;try{return e()}finally{ph=!1}}function Yl(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[lc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[lc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[lc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,Ii.push(new WeakRef(this))),!ph)try{throw new Error("Read transaction used outside of resource")}catch(u){this.readStack=u.stack}o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Ii.length;u++){let _=Ii[u].deref();(!_||_.isDone||_.isCommitted)&&Ii.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Rh(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Po=i?.localTime?Eh|PO:fh:Po=u?i?.localTime?Eh|16384:UO|16384:fh,l>0&&(c|=Th),kl=c,hh=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Po>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let O=_?.user?.username;if(E&&(Gl=e.encoder.encode(E)),f&&i?.localTime){let g=i?.localTime,R=r.get(g);if(R){let B=Ct(R).previousLocalTime;return r.put(g,Vl(o,t,n,B,O,d,Gl),{ifVersion:p}),S}}r.put(dc,Vl(o,t,n,i?.localTime?1:0,O,d,Gl),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var MO,dh,ql,dc,Sh,Ak,lc,_c,Ok,fh,UO,bk,PO,Eh,Th,gh,Nk,Gl,Po,kl,hh,mh,ioe,ph,Ii,vo=Oe(()=>{MO=require("msgpackr");Ci();dh=x(W()),ql=new Uint8Array([1,1,1,1,4,64,0,0]),dc=new Uint8Array([1,1,1,1,1,0,0,0]),Sh=new Uint8Array([1,1,1,1,3,64,0,0]),Ak=Symbol("local-timestamp"),lc=Symbol("metadata"),_c=new Uint8Array(8),Ok=new DataView(_c.buffer,0,8),fh=0,UO=0,bk=1,PO=3,Eh=4,Th=16,gh=1,Po=0,kl=-1,hh=0,mh=class extends MO.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(Po||kl>=0){let i=0,o=Po;o&&(i+=8,Po=0);let c=kl,u=hh;c>=0&&(i+=2,kl=-1,u&&(i+=8,hh=0));let _=Nk=r.call(this,n,s|2048|i);Gl=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(ql[4]=o,ql[5]=o>>8,_.set(ql,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(_c,0,c),c+=8;else for(let d=0;d<8;d++)_c[d]=t[c++];u=yk(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Th&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[lc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(yk,"getTimestamp");ioe=Map.prototype.get;a($l,"fromResource");a(Yl,"handleLocalTimeForGets");Ii=[];setInterval(()=>{for(let e=0;e<Ii.length;e++){let t=Ii[e].deref();!t||t.isDone||t.isCommitted?Ii.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(dh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):dh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(Rh,"getUpdateRecord")});var WO={};Fe(WO,{AUDIT_STORE_OPTIONS:()=>YO,createAuditEntry:()=>Vl,openAuditStore:()=>zl,readAuditEntry:()=>Ct,setAuditRetention:()=>Ik,transactionKeyEncoder:()=>$O});function zl(e){let t=e.auditStore=e.openDB(GO.AUDIT_STORE_NAME,YO);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=Kl){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-Ah})){if((_[0]&15)===Nh){let l=Ct(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=wk){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,Ah/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,Ql.getWorkerIndex)()===(0,Ql.getWorkerCount)()-1&&s(Kl),t}function Ik(e,t=Kl){Ah=e,Kl=t}function Vl(e,t,r,n,s,i,o){let c=KO[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?Bo.setFloat64(0,n):Xr.set(Sh),u=9),f(0),f(t),d(r),Bo.setFloat64(u,e),u+=8,s?d(s):Xr[u++]=0,Xr[n?8:0]=c;let l=Xr.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Ho.writeKey)(E,Xr,u);let p=u-h-1;p>127?p>16383?(wh.error("Key or username was too large for audit entry",E),u=h+1,Xr[h]=0):(Xr.copyWithin(h+2,h+1,u),Bo.setUint16(h,p|32768),u++):Xr[h]=p}function f(E){E<128?Xr[u++]=E:E<16384?(Bo.setUint16(u,E|32768),u+=2):E<1056964608?(Bo.setUint32(u,E|3221225472),u+=4):(Xr[u]=255,Bo.setUint32(u+1,E),u+=5)}}function Ct(e){try{let t=e.dataView||(e.dataView=new yh(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:KO[n&7],tableId:i,get recordId(){return qO(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?qO(e,l,d):void 0},getValue(f,E,h){if(n&Oh||n&bh&&!E)return f.decoder.decode(e.subarray(t.position));if(n&bh&&h)return Ih(f.getEntry(this.recordId),h,f)}}}catch{return wh.error("Reading audit entry error",e),{}}}function qO(e,t,r){let n=e.subarray(t,r);return(0,Ho.readKey)(n,0,r-t)}var Ho,Wl,GO,kO,Ql,VO,wh,Xr,Bo,$O,YO,Ah,wk,Kl,Oh,bh,BO,Nh,HO,xO,FO,KO,yh,Ci=Oe(()=>{Ho=require("ordered-binary"),Wl=x(Z()),GO=x(lt()),kO=x(U()),Ql=x(je()),VO=x(J());vo();wh=x(W());Jl();(0,Wl.initSync)();Xr=Buffer.alloc(1024),Bo=new DataView(Xr.buffer,Xr.byteOffset,1024),$O={writeKey(e,t,r){return e===dc?(t.set(dc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Ho.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,Ho.readKey)(e,t,r)}},YO={encoding:"binary",keyEncoder:$O},Ah=(0,VO.convertToMS)((0,Wl.get)(kO.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,wk=1e3,Kl=1e4;a(zl,"openAuditStore");a(Ik,"setAuditRetention");Oh=16,bh=32,BO=1,Nh=2,HO=3,xO=4,FO=5,KO={put:BO|Oh,[BO]:"put",delete:Nh,[Nh]:"delete",message:HO|Oh,[HO]:"message",invalidate:xO,[xO]:"invalidate",patch:FO|bh,[FO]:"patch"};a(Vl,"createAuditEntry");a(Ct,"readAuditEntry");yh=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(qO,"readKeySafely")});var Ch={};Fe(Ch,{add:()=>Xl,applyReverse:()=>QO,getRecordAtTime:()=>Ih,rebuildUpdateBefore:()=>jl});function Xl(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function jl(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,Xl(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function QO(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=Ck[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=zO}}function Ih(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Ct(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":QO(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===zO&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Ct(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var Ck,zO,Jl=Oe(()=>{Ci();a(Xl,"add");Xl.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Ck={add:Xl};a(jl,"rebuildUpdateBefore");a(QO,"applyReverse");zO={};a(Ih,"getRecordAtTime")});function yr(e){return e[gt]||(e[gt]=Object.create(null))}function n_(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[be])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new jr.ClientError(`${c} must be a string, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new jr.ClientError(`${c} must be a string, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new jr.ClientError(`${c} must be a number, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new jr.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new jr.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new jr.ClientError(`${c} must be a number, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new jr.ClientError(`${c} must be a boolean, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new jr.ClientError(`${c} must be a Date, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new jr.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);yr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){yr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new jr.ClientError(`${c} must be an object, attempt to assign ${l}`);yr(this)[c]=l},"set")}_={get(){let l=this[gt];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[he]?.[c];return f.update(E)}return f}let d=this[he]?.[c];if(d&&typeof d=="object"){let f=XO(d,o);if(f)return l||(l=this[gt]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[gt];return u?.[o]!==void 0?u[o]:this[he]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new jr.ClientError("Can not add a property to a sealed table schema");yr(this)[o]=c}),i("deleteProperty",function(o){yr(this)[o]=void 0}),i("toJSON",function(){let o=this[gt],c;for(let _ in o){c||(c=Object.assign({},this[he]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[he])),Object.assign(c,this)),c||this[he]}),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 XO(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[he])throw new Error("Can not track an already tracked object, check for circular references");this[he]=s}},n_(r,t)),new r(e)):new Zl(e);case Array:let n=new t_(e.length);n[he]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=XO(o,t?.elements)),n[s]=o}return n;default:return e}}function s_(e){let t=e[gt],r;for(let s in t){r||(r=Object.assign({},e[he]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=s_(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[he])),Object.assign(r,e)),r||e[he]}function Li(e,t=e[gt]){let r;if(JO.call(e,he)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Li(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[he]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=Ch[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Li(s);r[n]=s}return r?Object.freeze(r):JO.call(e,he)?e[he]:e}function e_(e){let t=e[he];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Di]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[he]===s){if(e_(i))return!0}else return!0}}else{let r=e[gt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[he]===i){if(e_(s))return!0}else return!0}else return!0}}return!1}var jr,gt,Zl,JO,Di,t_,r_,i_=Oe(()=>{gn();jr=x(ee());Jl();gt=Symbol("own-data");a(yr,"getChanges");a(n_,"assignTrackedAccessors");a(XO,"trackObject");Zl=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[he])throw new Error("Can not track an already tracked object, check for circular references");this[he]=t}};n_(Zl,{});a(s_,"collapseData");JO=Object.prototype.hasOwnProperty;a(Li,"deepFreeze");a(e_,"hasChanges");Di=Symbol.for("has-array-changes"),t_=class extends Array{static{a(this,"TrackedArray")}[Di];constructor(t){super(t)}splice(...t){return this[Di]=!0,super.splice(...t)}push(...t){return this[Di]=!0,super.push(...t)}pop(){return this[Di]=!0,super.pop()}unshift(...t){return this[Di]=!0,super.unshift(...t)}shift(){return this[Di]=!0,super.shift()}};t_.prototype.constructor=Array;r_=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});function Uk(){Mk=setInterval(function(){for(let e of Dh)if(e.stale){let t=e[be]?.url;jO.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},Lk).unref()}var Lh,jO,Dk,Dh,Mi,o_,Lk,Mk,Mh=Oe(()=>{Lh=x(Nr()),jO=x(W());gn();vo();Dk=100,Dh=new Set,Mi=class{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=!0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(!this.open)throw new Error("Can not start a read on a transaction that is no longer open");return this.readTxnsUsed=1,$l(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),Dh.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),$l(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Dh.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(!this.open&&!this.autoCommitMode)throw new Error("Can not use a transaction that is no longer open");this.writes.push(t),this.autoCommitMode&&this.commit()}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,Lh.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let O=S();E?E.push?E.push(O):E=[E,O]:E=O}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),t?.prepared?.(),this.open=!1;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<Dk>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=!1,this.writes=[]}},o_=class extends Mi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Lh.getNextMonotonicTime)())}getReadTxn(){}},Lk=3e4;a(Uk,"startMonitoringTxns");Uk()});function Ke(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new Mi;e.timestamp&&(n.timestamp=e.timestamp),n[be]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit(r?.resetTransaction?{prepared(){n.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var ZO,Ui=Oe(()=>{ZO=require("../index");gn();Mh();a(Ke,"transaction");(0,ZO._assignPackageExport)("transaction",Ke);Ke.commit=function(e){let t=(e[be]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ke.abort=function(e){let t=(e[be]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});function vh(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],p=_(h);d=d.concat(p)}let f=new Set;return d.filter(E=>{let h=E.key??E;return f.has(h)?!1:(f.add(h),!0)})}else{let d=_(u),f=l(e.slice(1),!0,u.estimated_count);return f.length>0?o(d,f):d}function _(d){return d.conditions?vh(d.conditions,d.operator,r,n,s,i,o,c):qo(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let g=h.operator==="or",R=l(h.conditions,!g,E);return g?(B,H)=>R.some(v=>v(B,H)):(B,H)=>R.every(v=>v(B,H))}let S=(h.attribute||h[0])===r.primaryKey,O=Hh(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=kk(r.primaryStore,h.estimated_count,E)),O}).filter(Boolean)}a(l,"mapConditionsToFilters")}function qo(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let g=o[0],R=ms(n.attributes,g);if(R.relationship){if(o.length<2)throw new hs.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let B=R.definition?.tableClass||R.elements?.definition?.tableClass,H=new Map,v=qo({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,B,s,H);if(R.relationship.to){i[o[0]]=H;let M=!!ms(B.attributes,R.relationship.to)?.elements;v=xk(v,R,B.primaryStore,M,H)}if(R.relationship.from){let M=a($=>qo({attribute:R.relationship.from,value:$},t,r,n,s,H),"searchEntry");R.elements?(i[o[0]]=H,v=Fk(v,R,B.primaryStore,H,M)):v=v.flatMap(M)}return v}else if(o.length===1)o=o[0];else throw new hs.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Bh[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=Gn.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"sort":case"contains":case"ends_with":_=!0,E=!0;break;default:throw new hs.ClientError(`Unknown query comparator "${u}"`)}if(r){let g=_;_=l,l=g,g=!f,f=!d,d=g}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(!s)throw new hs.ClientError(E?`Can not use ${u} operator without combining with a condition that uses an index`:`"${o}" is not indexed${c===null&&!p.indexNulls?" for nulls, index needs to be rebuilt to search for nulls":p?.isIndexing?" yet":""}, can not search for this attribute`,404);if(S=Hh(e),!S)throw new hs.ClientError(`Unknown search operator ${e.comparator}`)}let O={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let g=p.getRange(O).map(S?({key:R,value:B})=>new Promise((H,v)=>setImmediate(()=>{try{H(B&&S(B)?R:fc.SKIP)}catch(M){v(M)}})):R=>R.value==null?fc.SKIP:R);return g.hasEntries=!0,g}else return p?p.getRange(O).map(S?({key:g,value:R})=>new Promise((B,H)=>setImmediate(()=>{try{B(S({[o]:g})?R:fc.SKIP)}catch(v){H(v)}})):({value:g})=>g):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(({key:g,value:R})=>new Promise((B,H)=>setImmediate(()=>{try{B(R&&S(R)?g:fc.SKIP)}catch(v){H(v)}})))}function ms(e,t){if(Array.isArray(t))if(t.length>1){let r=ms(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?ms(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function xk(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=Rn(d),o=!0);let h=s.get(E);h?h.push(f):s.set(E,h=[f]),d!==E&&(h.key=d)},"add_entry"),l=0;for await(let d of e){let f=d.value??r.get(d.key??d),E=f?.[u];if(E!=null&&!s.filters?.some(h=>!h(f))){if(n)for(let h=0;h<E.length;h++)_(E[h],d);else _(E,d);l++>100&&(await new Promise(setImmediate),l=0)}}return i=(o?s:s.keys())[Symbol.iterator](),this.next()})()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function Fk(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Rn(u.value);if(!c.has(_))return c.add(_),u}if(!i)return(async()=>{let _=new Map;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>_.has(Rn(f)));let l=0;for await(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(E=>!E(f)))continue}_.set(Rn(d),d),l++>100&&(await new Promise(setImmediate),l=0)}return i=_.values()[Symbol.iterator](),this.next()})();do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Hh(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=ms(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=Hh({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},f,r,E?.[l]?.joined,c[1]===f.primaryKey,i);if(!h)return;if(E){E.filters||(E.filters=[]),E.filters.push(h);return}let p=t.propertyResolvers?.[l],S,O=a((g,R)=>{let B,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let M of h.idFilter.idSet)e={attribute:p.from,value:M};S=_(p.from,h.idFilter,!0)}else S=_(p.from,h.idFilter,!1);let v=S(g);return S.idFilter&&(O.idFilter=S.idFilter),v}H=p(g,r,R),B=H?.value}else B=g[l];return B?Array.isArray(B)?B.some(h):h(B,H):!1},"recordFilter");return O}}switch(u instanceof Date&&(u=u.getTime()),Bh[o]||o){case Uh.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,f=u.length;d<f;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,Gn.compareKeys)(l,u[0])>=0&&(0,Gn.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,Gn.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,Gn.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,Gn.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,Gn.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,Gn.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new hs.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f){let E;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&c_(t)(e),E=e.estimated_count>>4,(isNaN(E)||E>=i)&&(f=!1));let h=0,p=3;function S(O){let g=O[l],R;if(typeof g!="object"||!g?R=d(g):Array.isArray(g)?R=g.some(d):g instanceof Date&&(R=d(g.getTime())),f&&(p++,!R&&!S.idFilter&&++h/p*(i-p)>E)){let B=qo(e,r.transaction.getReadTxn(),!1,t).map(Rn),H=new Set(B);S.idFilter=v=>H.has(Rn(v)),S.idFilter.idSet=H}return R}return a(S,"recordFilter"),s&&(S.idFilter=d),S}a(_,"attributeComparator")}function c_(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Es(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=Bh[n]||n,n===Uh.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=ms(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=c_(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"});r.estimated_count=c*Es(e.indices[i.relationship.from]||e.primaryStore)/(Es(o.primaryStore)||1)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Es(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=Bk*Es(e.primaryStore)+1:n==="between"?r.estimated_count=vk*Es(e.primaryStore)+1:n==="sort"?r.estimated_count=Es(e.primaryStore)+1:r.estimated_count=Pk*Es(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function u_(e){if(e)if(Ws=e,xo.lastIndex=0,qk.test(e))try{let t=Ec(new Fo,"");if(Zt!==Ws.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${Zt} in '${Ws}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function Ec(e,t){let r=xo,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(Ws);){Zt=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=eb}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=hc(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Hk[d],u=Ph[i]?eb:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=hc(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&tb(h,l),a_(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(hc(l)),s=void 0;break;case"(":xo.lastIndex=Zt;let E=Ec(l?[]:new Fo,")");switch(l){case"":a_(e,_),e.conditions.push(E);break;case"limit":switch(E.length){case 1:e.limit=+E[0];break;case 2:e.offset=+E[0],e.limit=E[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(E[0])&&E.length===1&&!E[0].name?(e.select=E[0],e.select.asArray=!0):E.length===1?e.select=E[0]:E.length===2&&E[1]===""?e.select=E.slice(0,1):e.select=E;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=rb(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}Ws[Zt]===","?r.lastIndex=++Zt:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");xo.lastIndex=Zt,f=Ec([],"}"),f.name=l,e.push(f),Ws[Zt]===","?r.lastIndex=++Zt:o=!0;break;case"[":xo.lastIndex=Zt,l?(f=Ec(new Fo,"]"),f.name=l):f=Ec(e.conditions?new Fo:[],"]"),e.conditions?(a_(e,_),e.conditions.push(f),s=null):e.push(f),Ws[Zt]===","?r.lastIndex=++Zt:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&tb(h,l),a_(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(hc(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?Gk:xo,r.lastIndex=Zt),Zt===Ws.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function a_(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function hc(e){return e.indexOf(".")>-1?e.split(".").map(hc):decodeURIComponent(e)}function eb(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new hs.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function tb(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new hs.ClientError("wildcard can only be used at the end of a string")}function rb(e){let t=nb(e[0]);return e.length>1&&(t.next=rb(e.slice(1))),t}function nb(e){if(Array.isArray(e)){let t=nb(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function Rn(e){return Array.isArray(e)?e.join("\0"):e}function Es(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function kk(e,t,r){return t*r/Es(e)}var hs,Uh,Gn,fc,Pk,vk,Bk,Hk,Ph,Bh,qk,xo,Gk,Zt,Ws,Fo,l_=Oe(()=>{hs=x(ee()),Uh=x(lt()),Gn=require("ordered-binary"),fc=require("lmdb"),Pk=.3,vk=.1,Bk=.05,Hk={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Ph={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(vh,"executeConditions");a(qo,"searchByIndex");a(ms,"findAttribute");a(xk,"joinTo");a(Fk,"joinFrom");Bh={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Hh,"filterByType");a(c_,"estimateCondition");qk=/[()[\]|!<>.]|(=\w*=)/,xo=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Gk=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(u_,"parseQuery");a(Ec,"parseBlock");a(a_,"assignOperator");a(hc,"decodeProperty");a(eb,"typedDecoding");a(tb,"wildcardDecoding");a(rb,"toSortObject");a(nb,"toSortEntry");Fo=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(Rn,"flattenKey");a(Es,"estimatedEntryCount");a(kk,"intersectionEstimate")});var qh={};Fe(qh,{CONTEXT:()=>be,ID_PROPERTY:()=>De,IS_COLLECTION:()=>Zr,RECORD_PROPERTY:()=>he,Resource:()=>vt,snake_case:()=>$k,transformForSelect:()=>d_});function $k(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function sb(e,t){if(mc=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(mc=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new Fh;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){mc=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function wr(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[be]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[be]||i):l=i:(l=s,c=l[De]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[be]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return d.resetTransaction=!0,Ke(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new __(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new __(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Ir(e,t){let r=new ab.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function xh(e,t,r){let n=e[he];if(n){let s=e[gt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function d_(e,t){let r=t?.propertyResolvers,n=t[be],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):xh(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(xh(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(xh(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=d_(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var ib,ob,ab,be,De,Zr,he,Vk,vt,__,mc,Fh,gn=Oe(()=>{ib=require("crypto");uc();ob=require("../index"),ab=x(ee());i_();Ui();l_();be=Symbol.for("context"),De=Symbol.for("primary-key"),Zr=Symbol("is-collection"),he=Symbol("stored-record"),Vk={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},vt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[De]=t;let n=r?.[be];this[be]=n!==void 0?n:r||null}static get=wr(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=d_(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",resetTransaction:!0,ensureLoaded:!0,async:!0});static put=wr(function(t,r,n,s){if(Array.isArray(s)&&t[Zr]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Ir(t,"put")},{hasContent:!0,type:"update"});static patch=wr(function(t,r,n,s){return t.patch?t.patch(s,r):Ir(t,"patch")},{hasContent:!0,type:"update"});static delete=wr(function(t,r,n,s){return t.delete?t.delete(r):Ir(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,ib.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),Ke(n,()=>{let i=new this(s,n),o=i.update?i.update(r):Ir(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=wr(function(t,r,n,s){return t.invalidate?t.invalidate(r):Ir(t,"delete")},{hasContent:!1,type:"update"});static post=wr(function(t,r,n,s){return t[De]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=wr(function(t,r,n,s){return t.connect?t.connect(s,r):Ir(t,"connect")},{hasContent:!0,type:"read"});static subscribe=wr(function(t,r,n,s){return t.subscribe?t.subscribe(r):Ir(t,"subscribe")},{type:"read"});static publish=wr(function(t,r,n,s){return t[De]!=null&&t.update?.(),t.publish?t.publish(s,r):Ir(t,"publish")},{hasContent:!0,type:"create"});static search=wr(function(t,r,n,s){let i=t.search?t.search(r):Ir(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=d_(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=wr(function(t,r,n,s){return t.search?t.search(s,r):Ir(t,"search")},{hasContent:!0,type:"read"});static copy=wr(function(t,r,n,s){return t.copy?t.copy(s,r):Ir(t,"copy")},{type:"create"});static move=wr(function(t,r,n,s){return t.move?t.move(s,r):Ir(t,"move")},{type:"delete"});post(t){if(this[Zr])return this.constructor.create(this[De],t,this[be]);Ir(this,"post")}static isCollection(t){return t?.[Zr]}static coerceId(t){return t}static parseQuery(t){return u_(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&Vk[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:sb(t,this),isCollection:mc}}let i=sb(t,this);return mc?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[be],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[De]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[De],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[Zr]=!0),s}subscribe(t){return new Tn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Tn}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[De]}getContext(){return this[be]}};vt.prototype[be]=null;(0,ob._assignPackageExport)("Resource",vt);a($k,"snake_case");__=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(sb,"pathToId");Fh=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(wr,"transactional");a(Ir,"missingMethod");a(xh,"selectFromObject");a(d_,"transformForSelect")});var cb={};Fe(cb,{Resources:()=>f_,keyArrayToString:()=>Go,resetResources:()=>Yk,resources:()=>Qs});function Yk(){return Qs=new f_}function Go(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var f_,Qs,pc=Oe(()=>{Ui();f_=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ke(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(Yk,"resetResources");a(Go,"keyArrayToString")});function lb(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;ko||((0,E_.onMessageByType)(ub,l=>{_b(l.path)}),ko=Object.create(null));let o=ko[s]||(ko[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Go(t);let u=new kh(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function _b(e,t){if(!ko)return;let r=ko[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Ct(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Go(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,Gh.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,p)}catch(p){console.error(p),(0,Gh.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function db(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,E_.broadcast)({type:ub,path:s}),_b(s,!0)})}}var Gh,E_,ub,ko,Goe,kh,fb=Oe(()=>{Gh=x(W()),E_=x(je());uc();pc();Ci();ub="transaction",Goe=Buffer.alloc(4096);a(lb,"addSubscription");kh=class extends Tn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(_b,"notifyFromTransactionData");a(db,"listenToCommits")});var hb=T(($oe,Eb)=>{"use strict";var Vh=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Eb.exports=Vh});var pb=T((Koe,mb)=>{"use strict";var $h=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};mb.exports=$h});var h_=T((Qoe,Sb)=>{"use strict";var Kh=Z(),Wh=U(),{RecordEncoder:Kk}=(vo(),te(vO));Kh.initSync();var Wk=Kh.get(Wh.CONFIG_PARAMS.STORAGE_COMPRESSION),Qk=Kh.get(Wh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,zk=Wh.UPDATES_PROPERTY,Yh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=Wk&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=Qk&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:Kk},this.alwaysLazyProperty=n=>n===zk)}};Sb.exports=Yh});var p_=T((Joe,gb)=>{"use strict";var Vo=Z(),Sc=U();Vo.initSync();var Jk=Vo.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Vo.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Vo.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Tb=Vo.get(Sc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),Xk=Vo.get(Sc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),m_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=Jk,this.noFSAccess=!0,Tb!==void 0&&(this.overlappingSync=Tb),this.noReadAhead=Xk}};gb.exports=m_;m_.MAX_DBS=1e4});var Ve=T((joe,Db)=>{"use strict";var zh=require("lmdb"),An=require("fs-extra"),Cr=require("path"),S_=Nr(),Ob=W(),er=br().LMDB_ERRORS_ENUM,T_=pb(),Jh=h_(),bb=p_(),zs=lt(),Rb=U(),{table:jk,resetDatabases:Zk}=(Ne(),te(qe)),Ab=Z(),On=zs.INTERNAL_DBIS_NAME,Nb=zs.DBI_DEFINITION_NAME,eV="data.mdb",tV="lock.mdb",Tc=".mdb",rV="-lock",Qh=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=en(t,r),this.key_type=this.dbi[zs.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[zs.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new zh.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function g_(e,t){if(e===void 0)throw new Error(er.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(er.ENV_NAME_REQUIRED)}a(g_,"pathEnvNameValidation");async function Xh(e,t,r=!0){try{await An.access(e)}catch(n){throw n.code==="ENOENT"?new Error(er.INVALID_BASE_PATH):n}try{let n=Cr.join(e,t+Tc);return await An.access(n,An.constants.R_OK|An.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await An.access(Cr.join(e,t,eV),An.constants.R_OK|An.constants.F_OK),Cr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(er.INVALID_ENVIRONMENT)}else throw new Error(er.INVALID_ENVIRONMENT);throw n}}a(Xh,"validateEnvironmentPath");function R_(e,t){if(S_.validateEnv(e),t===void 0)throw new Error(er.DBI_NAME_REQUIRED)}a(R_,"validateEnvDBIName");async function nV(e,t,r=!1,n=!1){g_(e,t);let s=Cr.basename(e);t=t.toString();let i=Ab.get(Rb.CONFIG_PARAMS.DATABASES);i||Ab.setProperty(Rb.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Xh(e,t,n),yb(e,t,r)}catch(o){if(o.message===er.INVALID_ENVIRONMENT){let c=Cr.join(e,t);await An.mkdirp(n?c:e);let u=new bb(n?c:c+Tc,!1),_=zh.open(u);_.dbis=Object.create(null);let l=new Jh(!1);_.openDB(On,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=jh(e,t,r);return _[zs.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(nV,"createEnvironment");async function sV(e,t,r,n=!0){g_(e,t),t=t.toString();let s=Cr.join(e,t);return jk({table:t,database:Cr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(sV,"copyEnvironment");async function yb(e,t,r=!1){g_(e,t),t=t.toString();let n=jh(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await Xh(e,t),i=Cr.join(e,t+Tc),o=s!=i,c=new bb(s,o),u=zh.open(c);u.dbis=Object.create(null);let _=Ib(u);for(let l=0;l<_.length;l++)en(u,_[l]);return u[zs.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(yb,"openEnvironment");async function iV(e,t,r=!1){g_(e,t),t=t.toString();let n=Cr.join(e,t+Tc),s=await Xh(e,t);if(global.lmdb_map!==void 0){let i=jh(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await wb(o),delete global.lmdb_map[i]}}await An.remove(s),await An.remove(s===n?s+rV:Cr.join(Cr.dirname(s),tV))}a(iV,"deleteEnvironment");async function wb(e){S_.validateEnv(e);let t=e[zs.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(wb,"closeEnvironment");function jh(e,t,r=!1){let s=`${Cr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(jh,"getCachedEnvironmentName");function oV(e){S_.validateEnv(e);let t=Object.create(null),r=en(e,On);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==On)try{t[n]=Object.assign(new T_,s)}catch{Ob.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(oV,"listDBIDefinitions");function Ib(e){S_.validateEnv(e);let t=[],r=en(e,On);for(let{key:n}of r.getRange({start:!1}))n!==On&&t.push(n);return t}a(Ib,"listDBIs");function aV(e,t){let n=en(e,On).getEntry(t),s=new T_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{Ob.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(aV,"getDBIDefinition");function Cb(e,t,r,n=!r){if(R_(e,t),t=t.toString(),t===On)throw new Error(er.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return en(e,t)}catch(s){if(s.message===er.DBI_DOES_NOT_EXIST){let i=new Jh(r,n===!0),o=e.openDB(t,i),c=new T_(r===!0,n);return o[Nb]=c,en(e,On).putSync(t,c),e.dbis[t]=o,o}throw s}}a(Cb,"createDBI");function en(e,t){if(R_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==On?r=aV(e,t):r=new T_,r===void 0)throw new Error(er.DBI_DOES_NOT_EXIST);let n;try{let s=new Jh(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(er.DBI_DOES_NOT_EXIST):s}return n[Nb]=r,e.dbis[t]=n,n}a(en,"openDBI");function cV(e,t){R_(e,t),t=t.toString();let r=en(e,t),n=r.getStats();return r[zs.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(cV,"statDBI");async function uV(e,t){try{let r=Cr.join(e,t+Tc);return(await An.stat(r)).size}catch{throw new Error(er.INVALID_ENVIRONMENT)}}a(uV,"environmentDataSize");function lV(e,t){if(R_(e,t),t=t.toString(),t===On)throw new Error(er.CANNOT_DROP_INTERNAL_DBIS_NAME);en(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],en(e,On).removeSync(t)}a(lV,"dropDBI");function _V(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{en(e,i)}catch(o){if(o.message===er.DBI_DOES_NOT_EXIST)Cb(e,i,i!==t,i===t),n=!0;else throw o}}n&&Zk()}a(_V,"initializeDBIs");Db.exports={openDBI:en,openEnvironment:yb,createEnvironment:nV,listDBIs:Ib,listDBIDefinitions:oV,createDBI:Cb,dropDBI:lV,statDBI:cV,deleteEnvironment:iV,initializeDBIs:_V,TransactionCursor:Qh,environmentDataSize:uV,copyEnvironment:sV,closeEnvironment:wb}});var Ub=T((eae,Mb)=>{"use strict";var Zh=Ve(),dV=W(),Lb=br().LMDB_ERRORS_ENUM;Mb.exports=fV;async function fV(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 Zh.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Lb.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await Zh.closeEnvironment(global.lmdb_map[n]),await Zh.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Lb.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){dV.error(t)}}a(fV,"cleanLMDBMap")});var Pi=T((rae,EV)=>{EV.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var Kb=T((sae,Yb)=>{"use strict";var em=require("recursive-iterator"),hV=require("alasql"),tm=require("clone"),Pb=J(),{handleHDBError:vb,hdb_errors:mV}=ee(),{HDB_ERROR_MSGS:Bb,HTTP_STATUS_CODES:Hb}=mV,{getDatabases:pV}=(Ne(),te(qe)),SV=["DISTINCT_ARRAY"],xb=Symbol("validateTables"),rm=Symbol("validateTable"),nae=Symbol("getAllColumns"),Fb=Symbol("validateAllColumns"),A_=Symbol("findColumn"),qb=Symbol("validateOrderBy"),gc=Symbol("validateSegment"),nm=Symbol("validateColumn"),Gb=Symbol("setColumnsForTable"),kb=Symbol("checkColumnsForAsterisk"),Vb=Symbol("validateGroupBy"),$b=Symbol("hasColumns"),sm=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[xb](),this[kb](),this[Fb]()}[xb](){if(this[$b]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[rm](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[rm](t.table)})}}[$b](){let t=!1,r=new em(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[rm](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=pV();if(!r[t.databaseid])throw vb(new Error,Bb.SCHEMA_NOT_FOUND(t.databaseid),Hb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw vb(new Error,Bb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Hb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=tm(s);i.table=tm(t),this.attributes.push(i)})}[A_](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)}[kb](){let t=new em(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Gb](r.tableid)}[Gb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new hV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Fb](){this[gc](this.statement.columns,!1),this[gc](this.statement.joins,!1),this[gc](this.statement.where,!1),this[Vb](this.statement.group,!1),this[gc](this.statement.order,!0)}[gc](t,r){if(!t)return;let n=new em(t),s=[];for(let{node:i,path:o}of n)!Pb.isEmpty(i)&&!Pb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[qb](i):s.push(this[nm](i)));return s}[Vb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&SV.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=tm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[A_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[A_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[qb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[nm](t)}[nm](t){let r=this[A_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Yb.exports=sm});var Qb=T((oae,Wb)=>{"use strict";var im=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")}};Wb.exports=im});var Jb=T((cae,zb)=>{"use strict";var om=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};zb.exports=om});var jb=T((lae,Xb)=>{"use strict";var am=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};Xb.exports=am});var eN=T((dae,Zb)=>{"use strict";var cm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Zb.exports=cm});var $o=T((pae,nN)=>{"use strict";var TV=Ve(),gV=Jb(),RV=jb(),AV=eN(),kn=Nr(),Rc=br().LMDB_ERRORS_ENUM,OV=lt(),ps=U(),bV=J(),NV=require("uuid"),Eae=require("lmdb"),{handleHDBError:yV,hdb_errors:wV}=ee(),{OVERFLOW_MARKER:hae,MAX_SEARCH_KEY_LENGTH:mae}=OV,tN=Z();tN.initSync();var O_=tN.get(ps.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),um=ps.TIME_STAMP_NAMES_ENUM.CREATED_TIME,vi=ps.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function IV(e,t,r,n,s=kn.getNextMonotonicTime()){fm(e,t,r,n),lm(e,t,r);let i=new gV,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];rN(_,!0,s);let l=CV(e,t,r,_),d=_[t];o.push(l),c.push(d)}return _m(o,c,n,i,s)}a(IV,"insertRecords");function CV(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][ps.FUNC_VAL],n[o]=c)}let u=kn.getIndexedValues(c),_=e.dbis[o];if(u){O_&&_.prefetch(u.map(l=>({key:l,value:s})),b_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}O_&&e.dbis[t].prefetch([s],b_),e.dbis[t].put(s,n,n[vi])})}a(CV,"insertRecord");function DV(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(DV,"removeSkippedRecords");function rN(e,t,r){let n=r>0;(n||!Number.isInteger(e[vi]))&&(e[vi]=r||(r=kn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[um]))&&(e[um]=r||kn.getNextMonotonicTime()):delete e[um]}a(rN,"setTimestamps");function lm(e,t,r){r.indexOf(ps.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(ps.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(ps.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(ps.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),TV.initializeDBIs(e,t,r)}a(lm,"initializeTransaction");async function LV(e,t,r,n,s=kn.getNextMonotonicTime()){fm(e,t,r,n),lm(e,t,r);let i=new RV,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=dm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return _m(c,u,n,i,s,o)}a(LV,"updateRecords");async function MV(e,t,r,n,s=kn.getNextMonotonicTime()){try{fm(e,t,r,n)}catch(u){throw yV(u,u.message,wV.HTTP_STATUS_CODES.BAD_REQUEST)}lm(e,t,r);let i=new AV,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;bV.isEmpty(_[t])?(l=NV.v4(),_[t]=l):l=_[t];let d=dm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return _m(o,c,n,i,s)}a(MV,"upsertRecords");async function _m(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||kn.getNextMonotonicTime(),DV(r,i),n}a(_m,"finalizeWrite");function dm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(rN(r,!l,o),Number.isInteger(r[vi])&&_[vi]>r[vi])return!1;l&&s.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let O=_[h];if(typeof p=="function"){let R=p([[_]]);Array.isArray(R)&&(p=R[0][ps.FUNC_VAL],r[h]=p)}if(p===O)continue;let g=kn.getIndexedValues(O);if(g){O_&&S.prefetch(g.map(R=>({key:R,value:n})),b_);for(let R=0,B=g.length;R<B;R++)S.remove(g[R],n)}if(g=kn.getIndexedValues(p),g){O_&&S.prefetch(g.map(R=>({key:R,value:n})),b_);for(let R=0,B=g.length;R<B;R++)S.put(g[R],n)}}let E=Object.assign({},_,r);c.put(n,E,E[vi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:dm(e,t,r,n,s,i,o))}a(dm,"updateUpsertRecord");function UV(e,t,r){if(kn.validateEnv(e),t===void 0)throw new Error(Rc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Rc.WRITE_ATTRIBUTES_REQUIRED):new Error(Rc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(UV,"validateBasic");function fm(e,t,r,n){if(UV(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Rc.RECORDS_REQUIRED):new Error(Rc.RECORDS_MUST_BE_ARRAY)}a(fm,"validateWrite");function b_(){}a(b_,"noop");nN.exports={insertRecords:IV,updateRecords:LV,upsertRecords:MV}});var $n=T((Tae,oN)=>{"use strict";var iN=J(),sN=U(),Yo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Vn=require("joi"),Js={schema_format:{pattern:Yo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},PV=Vn.alternatives(Vn.string().min(1).max(Js.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+Js.schema_format.message}),Vn.number(),Vn.array()).required(),vV=Vn.alternatives(Vn.string().min(1).max(Js.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+Js.schema_format.message}),Vn.number()),BV=Vn.alternatives(Vn.string().min(1).max(Js.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+Js.schema_format.message}),Vn.number()).required();function HV(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>Js.schema_length.maximum?`'${e}' maximum of 250 characters`:Yo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(HV,"checkValidTable");function xV(e,t){return iN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(xV,"validateSchemaExists");function FV(e,t){let r=t.state.ancestors[0].schema;return iN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(FV,"validateTableExists");function qV(e,t){return e.toLowerCase()===sN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${sN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(qV,"validateSchemaName");oN.exports={common_validators:Js,schema_regex:Yo,hdb_schema_table:PV,validateSchemaExists:xV,validateTableExists:FV,validateSchemaName:qV,checkValidTable:HV,hdb_database:vV,hdb_table:BV}});var Ze=T((Rae,aN)=>{"use strict";var tr=require("validate.js");tr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||tr.validators.type.checks[t](e)?null:` must be a '${t}' value`};tr.validators.type.checks={Object:function(e){return tr.isObject(e)&&!tr.isArray(e)},Array:tr.isArray,Integer:tr.isInteger,Number:tr.isNumber,String:tr.isString,Date:tr.isDate,Boolean:function(e){return typeof e=="boolean"}};tr.validators.hasValidFileExt=function(e,t){return tr.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};aN.exports={validateObject:GV,validateObjectAsync:kV,validateBySchema:VV};function GV(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=tr(e,t,{format:"flat"});return r?new Error(r):null}a(GV,"validateObject");async function kV(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await tr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(kV,"validateObjectAsync");function VV(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(VV,"validateBySchema")});var N_=T((Oae,cN)=>{var{common_validators:Yn}=$n(),Oc=Ze(),Ac="is required",_t={database:{presence:!1,format:Yn.schema_format,length:Yn.schema_length},schema:{presence:!1,format:Yn.schema_format,length:Yn.schema_length},table:{presence:!0,format:Yn.schema_format,length:Yn.schema_length},attribute:{presence:!0,format:Yn.schema_format,length:Yn.schema_length},hash_attribute:{presence:!0,format:Yn.schema_format,length:Yn.schema_length}};function bc(e){for(let t in e)e[t]=e[t]===null||e[t]===void 0||typeof e[t]=="object"?e[t]:e[t].toString();return e}a(bc,"makeAttributesStrings");function $V(e){return e=bc(e),_t.table.presence=!1,_t.attribute.presence=!1,_t.hash_attribute.presence=!1,Oc.validateObject(e,_t)}a($V,"schema_object");function YV(e){return e=bc(e),_t.table.presence={message:Ac},_t.attribute.presence=!1,_t.hash_attribute.presence=!1,Oc.validateObject(e,_t)}a(YV,"table_object");function KV(e){return e=bc(e),_t.table.presence={message:Ac},_t.attribute.presence=!1,Oc.validateObject(e,_t)}a(KV,"create_table_object");function WV(e){return e=bc(e),_t.table.presence={message:Ac},_t.attribute.presence={message:Ac},_t.hash_attribute.presence=!1,Oc.validateObject(e,_t)}a(WV,"attribute_object");function QV(e){return e=bc(e),_t.table.presence={message:Ac},_t.attribute.presence=!1,_t.hash_attribute.presence=!1,Oc.validateObject(e,_t)}a(QV,"describe_table");function zV(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(zV,"validateTableResidence");cN.exports={schema_object:$V,create_table_object:KV,table_object:YV,attribute_object:WV,describe_table:QV,validateTableResidence:zV}});var lN=T((Nae,uN)=>{"use strict";var JV=require("uuid"),Em=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||JV.v4(),this.schema_table=`${this.schema}.${this.table}`}};uN.exports=Em});var y_=T((wae,_N)=>{"use strict";var XV=lN(),hm=class extends XV{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};_N.exports=hm});var fN=T((Cae,dN)=>{"use strict";dN.exports=ZV;var jV="inserted";function ZV(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===jV?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(ZV,"returnObject")});var w_=T((Lae,SN)=>{"use strict";var e$=U(),mm=Ve(),t$=$o(),{getSystemSchemaPath:r$,getSchemaPath:n$}=Ye(),s$=Pi(),i$=N_(),o$=y_(),a$=fN(),{handleHDBError:EN,hdb_errors:mN}=ee(),hN=J(),{HTTP_STATUS_CODES:c$}=mN,pm=s$.hdb_attribute,pN=[];for(let e=0;e<pm.attributes.length;e++)pN.push(pm.attributes[e].attribute);var u$="inserted";SN.exports=l$;async function l$(e){let t=i$.attribute_object(e);if(t)throw EN(new Error,t.message,mN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&hN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw EN(new Error,r,c$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=hN.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new o$(e.schema,e.table,e.attribute,e.id);try{let i=await mm.openEnvironment(n$(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}`);mm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await mm.openEnvironment(r$(),e$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await t$.insertRecords(o,pm.hash_attribute,pN,[s]);return a$(u$,c,{records:[s]},u)}catch(i){throw i}}a(l$,"lmdbCreateAttribute")});var Tm=T((Uae,gN)=>{var{hdb_table:_$,hdb_database:TN}=$n(),d$=Ze(),Sm=require("joi"),f$={undefined:"undefined",null:"null"},E$=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||f$[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),h$=Sm.object({database:TN,schema:TN,table:_$,records:Sm.array().items(Sm.object().custom(E$)).required()});gN.exports=function(e){return d$.validateBySchema(e,h$)}});var Nc=T((Bae,AN)=>{"use strict";var Ss=J(),RN=W(),vae=Tm(),{getDatabases:m$}=(Ne(),te(qe)),{ClientError:Bi}=ee();AN.exports=p$;function p$(e){if(Ss.isEmpty(e))throw new Bi("invalid update parameters defined.");if(Ss.isEmptyOrZeroLength(e.schema))throw new Bi("invalid schema specified.");if(Ss.isEmptyOrZeroLength(e.table))throw new Bi("invalid table specified.");if(!Array.isArray(e.records))throw new Bi("records must be an array");let t=m$()[e.schema]?.[e.table];if(Ss.isEmpty(t))throw new Bi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Ss.isEmptyOrZeroLength(o[r]))throw RN.error("a valid hash attribute must be provided with update record:",o),new Bi("a valid hash attribute must be provided with update record, check log for more info");if(!Ss.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw RN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Bi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Ss.isEmpty(o[r])&&o[r]!==""&&n.has(Ss.autoCast(o[r]))&&(o.skip=!0),n.add(Ss.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(p$,"insertUpdateValidate")});var yc=T((xae,ON)=>{"use strict";var S$=U().OPERATIONS_ENUM,gm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=S$.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};ON.exports=gm});var Dc=T((Gae,bN)=>{"use strict";var qae=yc(),I_=U(),Am=J(),Rm=W(),T$=require("uuid"),{handleHDBError:wc,hdb_errors:g$}=ee(),{HDB_ERROR_MSGS:Ic,HTTP_STATUS_CODES:Cc}=g$;bN.exports=R$;function R$(e,t,r){for(let s=0;s<t.length;s++)A$(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];O$(i,r,e.operation)}}a(R$,"processRows");function A$(e){if(Buffer.byteLength(String(e))>I_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw wc(new Error,Ic.ATTR_NAME_LENGTH_ERR(e),Cc.BAD_REQUEST,void 0,void 0,!0);if(Am.isEmptyOrZeroLength(e)||Am.isEmpty(e.trim()))throw wc(new Error,Ic.ATTR_NAME_NULLISH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}a(A$,"validateAttribute");function O$(e,t,r){if(!e.hasOwnProperty(t)||Am.isEmptyOrZeroLength(e[t])){if(r===I_.OPERATIONS_ENUM.INSERT||r===I_.OPERATIONS_ENUM.UPSERT){e[t]=T$.v4();return}throw Rm.error("Update transaction aborted due to record with no hash value:",e),wc(new Error,Ic.RECORD_MISSING_HASH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>I_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Rm.error(e),wc(new Error,Ic.HASH_VAL_LENGTH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Rm.error(e),wc(new Error,Ic.INVALID_FORWARD_SLASH_IN_HASH_ERR,Cc.BAD_REQUEST,void 0,void 0,!0)}a(O$,"validateHash")});var C_=T((Vae,yN)=>{"use strict";var NN=J(),b$=U(),N$=W(),y$=w_(),w$=y_(),I$=Ts(),{SchemaEventMsg:C$}=bn(),D$="already exists in";yN.exports=L$;async function L$(e,t,r){if(NN.isEmptyOrZeroLength(r))return r;let n=[];NN.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await M$(e,t.schema,t.name,i)})),s}a(L$,"lmdbCheckForNewAttributes");async function M$(e,t,r,n){let s=new w$(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await U$(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(D$))N$.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(M$,"createNewAttribute");async function U$(e){let t;return t=await y$(e),I$.signalSchemaChange(new C$(process.pid,b$.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(U$,"createAttribute")});var Ko=T((Yae,wN)=>{"use strict";var Om=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};wN.exports=Om});var CN=T((Wae,IN)=>{"use strict";var P$=Ko(),v$=U().OPERATIONS_ENUM,bm=class extends P${static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(v$.INSERT,r,n,s,i),this.records=t}};IN.exports=bm});var LN=T((zae,DN)=>{"use strict";var B$=Ko(),H$=U().OPERATIONS_ENUM,Nm=class extends B${static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(H$.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};DN.exports=Nm});var UN=T((Xae,MN)=>{"use strict";var x$=Ko(),F$=U().OPERATIONS_ENUM,ym=class extends x${static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(F$.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};MN.exports=ym});var vN=T((Zae,PN)=>{"use strict";var q$=Ko(),G$=U().OPERATIONS_ENUM,wm=class extends q${static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(G$.DELETE,n,s,t,i),this.original_records=r}};PN.exports=wm});var Lc=T((rce,FN)=>{"use strict";var tce=require("path"),BN=Ve(),k$=CN(),V$=LN(),$$=UN(),Y$=vN(),Wo=lt(),HN=J(),{CONFIG_PARAMS:K$}=U(),xN=Z();xN.initSync();var D_=U().OPERATIONS_ENUM,{getTransactionAuditStorePath:W$}=Ye();FN.exports=Q$;async function Q$(e,t){if(xN.get(K$.LOGGING_AUDITLOG)===!1)return;let r=W$(e.schema,e.table),n=await BN.openEnvironment(r,e.table,!0),s=z$(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){BN.initializeDBIs(n,Wo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Wo.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Wo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Wo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),HN.isEmpty(s.user_name)||n.dbis[Wo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Wo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(Q$,"writeTransaction");function z$(e,t){let r=HN.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===D_.INSERT)return new k$(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===D_.UPDATE)return new V$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===D_.UPSERT)return new $$(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===D_.DELETE)return new Y$(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(z$,"createTransactionObject")});var Im=T((ice,qN)=>{"use strict";var J$=Nc(),sce=yc(),Mc=U(),X$=Dc(),j$=$o().insertRecords,Z$=Ve(),e1=W(),t1=C_(),{getSchemaPath:r1}=Ye(),n1=Lc();qN.exports=s1;async function s1(e){try{let{schema_table:t,attributes:r}=J$(e);X$(e,r,t.hash_attribute),e.schema!==Mc.SYSTEM_SCHEMA_NAME&&(r.includes(Mc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Mc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Mc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Mc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await t1(e.hdb_auth_header,t,r),s=r1(e.schema,e.table),i=await Z$.openEnvironment(s,e.table),o=await j$(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await n1(e,o)}catch(c){e1.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(s1,"lmdbCreateRecords")});var VN=T((ace,kN)=>{"use strict";var GN=U(),i1=Im(),o1=yc(),a1=require("fs-extra"),{getSchemaPath:c1}=Ye();kN.exports=u1;async function u1(e){let t=[{name:e.schema,createddate:Date.now()}],r=new o1(GN.SYSTEM_SCHEMA_NAME,GN.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await i1(r),await a1.mkdirp(c1(e.schema))}a(u1,"lmdbCreateSchema")});var YN=T((uce,$N)=>{"use strict";var Cm=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};$N.exports=Cm});var zN=T((Ece,QN)=>{"use strict";var KN=Ve(),Dm=Nr(),Lm=br().LMDB_ERRORS_ENUM,l1=lt(),WN=W(),_ce=J(),_1=require("lmdb"),d1=YN(),f1=U(),{OVERFLOW_MARKER:dce,MAX_SEARCH_KEY_LENGTH:fce}=l1,E1=f1.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function h1(e,t,r,n){if(Dm.validateEnv(e),t===void 0)throw new Error(Lm.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Lm.IDS_REQUIRED):new Error(Lm.IDS_MUST_BE_ITERABLE);try{let s=KN.listDBIs(e);KN.initializeDBIs(e,t,s);let i=new d1,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||n&&h[E1]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,_1.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let O=s[S];if(!h.hasOwnProperty(O)||O===t)continue;let g=e.dbis[O],R=h[O];if(R!=null)try{let B=Dm.getIndexedValues(R);if(B)for(let H=0,v=B.length;H<v;H++)g.remove(B[H],o)}catch{WN.warn(`cannot delete from attribute: ${O}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){WN.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=Dm.getNextMonotonicTime(),i}catch(s){throw s}}a(h1,"deleteRecords");QN.exports={deleteRecords:h1}});var Uc=T((mce,XN)=>{"use strict";var Qo=J(),m1=zN(),p1=Ve(),{getSchemaPath:S1}=Ye(),T1=Lc(),g1=W();XN.exports=R1;async function R1(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(Qo.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Qo.isEmptyOrZeroLength(e.hash_values)&&!Qo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];Qo.isEmpty(u)||e.hash_values.push(u)}}if(Qo.isEmptyOrZeroLength(e.hash_values))return JN([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Qo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=S1(e.schema,e.table),i=await p1.openEnvironment(s,e.table),o=await m1.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await T1(e,o)}catch(c){g1.error(`unable to write transaction due to ${c.message}`)}return JN(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(R1,"lmdbDeleteRecords");function JN(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(JN,"createDeleteResponse")});var Um=T((Tce,jN)=>{"use strict";var A1=U(),Sce=Nr();function Mm(e,t){let r=Object.create(null);if(t.length===1&&A1.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(Mm,"parseRow");function O1(e,t,r,n){let s=Mm(r,e);n.push(s)}a(O1,"searchAll");function b1(e,t,r,n){let s=Mm(r,e);n[t]=s}a(b1,"searchAllToMap");function N1(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(N1,"iterateDBI");function Hi(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Hi,"pushResults");function y1(e,t,r,n,s,i){t.toString().endsWith(e)&&Hi(t,r,n,s,i)}a(y1,"endsWith");function w1(e,t,r,n,s,i){t.toString().includes(e)&&Hi(t,r,n,s,i)}a(w1,"contains");function I1(e,t,r,n,s,i){t>e&&Hi(t,r,n,s,i)}a(I1,"greaterThanCompare");function C1(e,t,r,n,s,i){t>=e&&Hi(t,r,n,s,i)}a(C1,"greaterThanEqualCompare");function D1(e,t,r,n,s,i){t<e&&Hi(t,r,n,s,i)}a(D1,"lessThanCompare");function L1(e,t,r,n,s,i){t<=e&&Hi(t,r,n,s,i)}a(L1,"lessThanEqualCompare");jN.exports={parseRow:Mm,searchAll:O1,searchAllToMap:b1,iterateDBI:N1,endsWith:y1,contains:w1,greaterThanCompare:I1,greaterThanEqualCompare:C1,lessThanCompare:D1,lessThanEqualCompare:L1,pushResults:Hi}});var zo=T((bce,iy)=>{"use strict";var Xs=Ve(),Rce=W(),Dr=Nr(),L_=lt(),ot=br().LMDB_ERRORS_ENUM,Ace=J(),M1=U(),M_=Um(),{parseRow:U1}=M_,Oce=require("lmdb"),{OVERFLOW_MARKER:ZN,MAX_SEARCH_KEY_LENGTH:P1}=L_;function ey(e,t,r,n=!1,s=void 0,i=void 0){return xi(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(ey,"iterateFullIndex");function Pc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return xi(e,t,r,(l,d,f,E)=>{let g={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(g.values=!1,d.getRange(g).map(R=>({value:R}))):d.getRange(g)})}a(Pc,"iterateRangeBetween");function xi(e,t,r,n){let s=e.database||e,i=Xs.openDBI(s,r);i[L_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&Xs.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(xi,"setupTransaction");function ty(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(ZN)){if(!s)if(r)s=Xs.openDBI(e,r);else{let u=Xs.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=Xs.openDBI(e,u[_]),!s[L_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(ty,"getOverflowCheck");function v1(e,t,r,n=!1,s=void 0,i=void 0){if(Dr.validateEnv(e),t===void 0)throw new Error(ot.HASH_ATTRIBUTE_REQUIRED);return xi(e,t,t,(o,c,u)=>(U_(r),r=vc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>U1(_.value,r))))}a(v1,"searchAll");function B1(e,t,r,n=!1,s=void 0,i=void 0){if(Dr.validateEnv(e),t===void 0)throw new Error(ot.HASH_ATTRIBUTE_REQUIRED);U_(r),r=vc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of ey(e,t,t,n,s,i))o.set(c,M_.parseRow(u,r));return o}a(B1,"searchAllToMap");function H1(e,t,r=!1,n=void 0,s=void 0){if(Dr.validateEnv(e),t===void 0)throw new Error(ot.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=ey(e,void 0,t,r,n,s),c=o.transaction,u=ty(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(H1,"iterateDBI");function x1(e,t){if(Dr.validateEnv(e),t===void 0)throw new Error(ot.HASH_ATTRIBUTE_REQUIRED);return Xs.statDBI(e,t).entryCount}a(x1,"countAll");function F1(e,t,r,n,s=!1,i=void 0,o=void 0){return js(e,r,n),xi(e,t,r,(c,u,_,l)=>(n=Dr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(F1,"equals");function q1(e,t,r){return js(e,t,r),Xs.openDBI(e,t).getValuesCount(r)}a(q1,"count");function G1(e,t,r,n,s=!1,i=void 0,o=void 0){return js(e,r,n),xi(e,null,r,(c,u)=>{n=Dr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let f of u.getKeys({transaction:c,start:n}))if(!f.startsWith(n)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(n))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(G1,"startsWith");function k1(e,t,r,n,s=!1,i=void 0,o=void 0){return ry(e,t,r,n,s,i,o,!0)}a(k1,"endsWith");function ry(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return js(e,r,n),xi(e,null,r,(u,_,l,d)=>{let f=ty(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(ZN)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[L_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(p=>({key:E,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(ry,"contains");function V1(e,t,r,n,s=!1,i=void 0,o=void 0){js(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Pc(e,t,r,n,u,s,i,o,!0,!1)}a(V1,"greaterThan");function $1(e,t,r,n,s=!1,i=void 0,o=void 0){js(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Pc(e,t,r,n,u,s,i,o,!1,!1)}a($1,"greaterThanEqual");function Y1(e,t,r,n,s=!1,i=void 0,o=void 0){js(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Pc(e,t,r,u,n,s,i,o,!1,!0)}a(Y1,"lessThan");function K1(e,t,r,n,s=!1,i=void 0,o=void 0){js(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Pc(e,t,r,u,n,s,i,o,!1,!1)}a(K1,"lessThanEqual");function W1(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Dr.validateEnv(e),r===void 0)throw new Error(ot.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(ot.START_VALUE_REQUIRED);if(s===void 0)throw new Error(ot.END_VALUE_REQUIRED);if(n=Dr.convertKeyValueToWrite(n),s=Dr.convertKeyValueToWrite(s),n>s)throw new Error(ot.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Pc(e,t,r,n,s,i,o,c)}a(W1,"between");function Q1(e,t,r,n){Dr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ot.HASH_ATTRIBUTE_REQUIRED);if(U_(r),r=vc(s,r),n===void 0)throw new Error(ot.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=M_.parseRow(c,r)),o}a(Q1,"searchByHash");function z1(e,t,r){Dr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(ot.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ot.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(z1,"checkHashExists");function J1(e,t,r,n,s=[]){return sy(e,t,r,n,s),ny(e,t,r,n,s).map(i=>i[1])}a(J1,"batchSearchByHash");function X1(e,t,r,n,s=[]){sy(e,t,r,n,s);let i=new Map;for(let[o,c]of ny(e,t,r,n,s))i.set(o,c);return i}a(X1,"batchSearchByHashToMap");function ny(e,t,r,n,s=[]){return xi(e,t,t,(i,o,c)=>{r=vc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,M_.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(ny,"batchHashSearch");function sy(e,t,r,n,s){if(Dr.validateEnv(e),t===void 0)throw new Error(ot.HASH_ATTRIBUTE_REQUIRED);if(U_(r),n==null)throw new Error(ot.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(ot.IDS_MUST_BE_ITERABLE)}a(sy,"initializeBatchSearchByHash");function U_(e){if(!Array.isArray(e))throw e===void 0?new Error(ot.FETCH_ATTRIBUTES_REQUIRED):new Error(ot.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(U_,"validateFetchAttributes");function js(e,t,r){if(Dr.validateEnv(e),t===void 0)throw new Error(ot.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ot.SEARCH_VALUE_REQUIRED);if(r?.length>P1)throw new Error(ot.SEARCH_VALUE_TOO_LARGE)}a(js,"validateComparisonFunctions");function vc(e,t){return t.length===1&&M1.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Xs.listDBIs(e)),t}a(vc,"setGetWholeRowAttributes");iy.exports={searchAll:v1,searchAllToMap:B1,count:q1,countAll:x1,equals:F1,startsWith:G1,endsWith:k1,contains:ry,searchByHash:Q1,setGetWholeRowAttributes:vc,batchSearchByHash:J1,batchSearchByHashToMap:X1,checkHashExists:z1,iterateDBI:H1,greaterThan:V1,greaterThanEqual:$1,lessThan:Y1,lessThanEqual:K1,between:W1}});var Jo=T((yce,ly)=>{var oy=require("lodash"),ay=Ze(),me=require("joi"),j1=J(),{hdb_schema_table:Bc,checkValidTable:cy,hdb_table:uy,hdb_database:P_}=$n(),{handleHDBError:Z1,hdb_errors:eY}=ee(),{getDatabases:tY}=(Ne(),te(qe)),{HTTP_STATUS_CODES:rY}=eY,nY=me.object({database:P_,schema:P_,table:uy,search_attribute:Bc,search_value:me.any().required(),get_attributes:me.array().min(1).items(me.alternatives(Bc,me.object())).optional(),desc:me.bool(),limit:me.number().integer().min(1),offset:me.number().integer().min(0)}),sY=me.object({database:P_,schema:P_,table:uy,operator:me.string().valid("and","or").default("and").lowercase(),offset:me.number().integer().min(0),limit:me.number().integer().min(1),get_attributes:me.array().min(1).items(me.alternatives(Bc,me.object())).optional(),sort:me.object({attribute:me.alternatives(Bc,me.array().min(1)),descending:me.bool().optional()}).optional(),conditions:me.array().min(1).items(me.alternatives(me.object({operator:me.string().valid("and","or").default("and").lowercase(),conditions:me.array()}),me.object({search_attribute:me.alternatives(Bc,me.array().min(1)),search_type:me.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:me.when("search_type",{switch:[{is:"equals",then:me.any()},{is:"between",then:me.array().items(me.alternatives([me.string(),me.number()])).length(2)}],otherwise:me.alternatives(me.string(),me.number())}).required()}))).required()});ly.exports=function(e,t){let r=null;switch(t){case"value":r=ay.validateBySchema(e,nY);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(cy("database",e.schema)),i(cy("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=ay.validateBySchema(e,sY);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=j1.checkGlobalSchemaTable(e.schema,e.table);if(s)return Z1(new Error,s,rY.NOT_FOUND);let o=tY()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=oy.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!oy.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Pm=T((Ice,_y)=>{"use strict";var iY=Ve(),oY=Jo(),{getSchemaPath:aY}=Ye();_y.exports=cY;function cY(e){let t=oY(e,"hashes");if(t)throw t;let r=aY(e.schema,e.table);return iY.openEnvironment(r,e.table)}a(cY,"initialize")});var vm=T((Dce,dy)=>{"use strict";var uY=zo(),lY=Pm();dy.exports=_Y;async function _Y(e){let t=await lY(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return uY.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(_Y,"lmdbGetDataByHash")});var Xo=T((Mce,fy)=>{"use strict";var Bm=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};fy.exports=Bm});var hy=T((vce,Ey)=>{"use strict";var Pce=Xo(),dY=zo(),fY=Pm();Ey.exports=EY;async function EY(e){let t=await fY(e),r=global.hdb_schema[e.schema][e.table];return dY.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(EY,"lmdbSearchByHash")});var Kn=T((Hce,my)=>{"use strict";var Hm=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};my.exports=Hm});var v_=T((Fce,Ay)=>{"use strict";var Vt=zo(),hY=Ve(),mY=J(),pe=lt(),Fi=U(),pY=Pi(),py=br().LMDB_ERRORS_ENUM,{getSchemaPath:SY}=Ye(),gs=Fi.SEARCH_WILDCARDS;async function TY(e,t,r){let n;e.schema===Fi.SYSTEM_SCHEMA_NAME?n=pY[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Ry(e,n.hash_attribute,r,t);return Ty(e,s,n.hash_attribute,r)}a(TY,"prepSearch");async function Ty(e,t,r,n){let s=SY(e.schema,e.table),i=await hY.openEnvironment(s,e.table),o=gy(i,e,t,r),c=o.transaction||i;if([pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,pe.SEARCH_TYPES.SEARCH_ALL,pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(gY(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Sy(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?Sy(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Vt.batchSearchByHashToMap(c,r,e.get_attributes,_):Vt.batchSearchByHash(c,r,e.get_attributes,_)}a(Ty,"executeSearch");function gy(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case pe.SEARCH_TYPES.EQUALS:s=Vt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.CONTAINS:s=Vt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.ENDS_WITH:case pe.SEARCH_TYPES._ENDS_WITH:s=Vt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.STARTS_WITH:case pe.SEARCH_TYPES._STARTS_WITH:s=Vt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Vt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Vt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case pe.SEARCH_TYPES.SEARCH_ALL:return Vt.searchAll(e,n,t.get_attributes,o,c,u);case pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Vt.searchAllToMap(e,n,t.get_attributes,o,c,u);case pe.SEARCH_TYPES.BETWEEN:s=Vt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case pe.SEARCH_TYPES.GREATER_THAN:case pe.SEARCH_TYPES._GREATER_THAN:s=Vt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.GREATER_THAN_EQUAL:case pe.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Vt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.LESS_THAN:case pe.SEARCH_TYPES._LESS_THAN:s=Vt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.LESS_THAN_EQUAL:case pe.SEARCH_TYPES._LESS_THAN_EQUAL:s=Vt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(gy,"searchByType");function Sy(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Sy,"createMapFromIterable");function gY(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(gY,"checkToFetchMore");function Ry(e,t,r,n){if(mY.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),gs.indexOf(s)>-1)return r===!0?pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:pe.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(gs[0])<0&&s.indexOf(gs[1])<0)return c===!0?r===!0?pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:pe.SEARCH_TYPES.EQUALS;if(gs.indexOf(i)>=0&&gs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),pe.SEARCH_TYPES.CONTAINS;if(gs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),pe.SEARCH_TYPES.ENDS_WITH;if(gs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),pe.SEARCH_TYPES.STARTS_WITH;if(s.includes(gs[0])||s.includes(gs[1]))return pe.SEARCH_TYPES.EQUALS;throw new Error(py.UNKNOWN_SEARCH_TYPE)}else switch(n){case Fi.VALUE_SEARCH_COMPARATORS.BETWEEN:return pe.SEARCH_TYPES.BETWEEN;case Fi.VALUE_SEARCH_COMPARATORS.GREATER:return pe.SEARCH_TYPES.GREATER_THAN;case Fi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return pe.SEARCH_TYPES.GREATER_THAN_EQUAL;case Fi.VALUE_SEARCH_COMPARATORS.LESS:return pe.SEARCH_TYPES.LESS_THAN;case Fi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return pe.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(py.UNKNOWN_SEARCH_TYPE)}}a(Ry,"createSearchTypeFromSearchObject");Ay.exports={executeSearch:Ty,createSearchTypeFromSearchObject:Ry,prepSearch:TY,searchByType:gy}});var by=T((kce,Oy)=>{"use strict";var Gce=Kn(),RY=Jo(),AY=J(),OY=U(),bY=v_();Oy.exports=NY;function NY(e,t){if(!AY.isEmpty(t)&&OY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=RY(e,"value");if(n)throw n;return bY.prepSearch(e,t,!0)}a(NY,"lmdbGetDataByValue")});var Hc=T((Yce,Ny)=>{"use strict";var $ce=Kn(),yY=Jo(),wY=J(),IY=U(),CY=v_();Ny.exports=DY;async function DY(e,t){if(!wY.isEmpty(t)&&IY.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=yY(e,"value");if(n)throw n;return CY.prepSearch(e,t,!1)}a(DY,"lmdbSearchByValue")});var wy=T((Qce,yy)=>{"use strict";var Wce=lt(),xm=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},Fm=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},qm=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};yy.exports={SearchByConditionsObject:xm,SearchCondition:Fm,SortAttribute:qm}});var My=T((jce,Ly)=>{"use strict";var Jce=wy().SearchByConditionsObject,LY=Kn(),MY=Jo(),Gm=zo(),B_=lt(),{Resource:Xce}=(gn(),te(qh)),Dy=v_(),UY=Um(),PY=require("lodash"),{getSchemaPath:vY}=Ye(),Iy=Ve(),{handleHDBError:BY,hdb_errors:HY}=ee(),{HTTP_STATUS_CODES:xY}=HY,FY=1e8;Ly.exports=qY;async function qY(e){let t=MY(e,"conditions");if(t)throw BY(t,t.message,xY.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=vY(e.schema,e.table),n=await Iy.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Iy.openDBI(n,_.search_attribute);let i=PY.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===B_.SEARCH_TYPES.EQUALS?_.estimated_count=Gm.count(n,_.search_attribute,_.search_value):l===B_.SEARCH_TYPES.CONTAINS||l===B_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=FY}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Cy(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(Dy.filterByType),d=l.length,f=Gm.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>UY.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await Cy(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Gm.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(qY,"lmdbSearchByConditions");async function Cy(e,t,r,n){let s=new LY(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===B_.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Dy.searchByType(e,s,i,n).map(o=>o.value)}a(Cy,"executeConditionSearch")});var xc=T((eue,Uy)=>{"use strict";var GY=U().OPERATIONS_ENUM,km=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=GY.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Uy.exports=km});var Vm=T((rue,Gy)=>{"use strict";var Hy=Kn(),xy=xc(),Fy=Hc(),qy=Uc(),rr=U(),Py=J(),vy=Ve(),{getTransactionAuditStorePath:kY,getSchemaPath:VY}=Ye(),By=W();Gy.exports=$Y;async function $Y(e){try{if(Py.isEmpty(global.hdb_schema[e.schema])||Py.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await YY(e),await KY(e);let t=VY(e.schema,e.table);try{await vy.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")By.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=kY(e.schema,e.table);await vy.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")By.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a($Y,"lmdbDropTable");async function YY(e){let t=new Hy(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Fy(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new xy(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await qy(s)}a(YY,"deleteAttributesFromSystem");async function KY(e){let t=new Hy(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Fy(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new xy(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await qy(s)}catch(i){throw i}}a(KY,"dropTableFromSystem")});var Vy=T((sue,ky)=>{"use strict";var WY=require("fs-extra"),QY=Kn(),zY=Xo(),JY=xc(),XY=Vm(),jY=Uc(),ZY=vm(),eK=Hc(),Rs=U(),{getSchemaPath:tK}=Ye(),{handleHDBError:rK,hdb_errors:nK}=ee(),{HDB_ERROR_MSGS:sK,HTTP_STATUS_CODES:iK}=nK;ky.exports=oK;async function oK(e){let t;try{t=await aK(e.schema);let r=new QY(Rs.SYSTEM_SCHEMA_NAME,Rs.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await eK(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await XY(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new JY(Rs.SYSTEM_SCHEMA_NAME,Rs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await jY(s);let i=tK(t);await WY.remove(i)}catch(r){throw r}}a(oK,"lmdbDropSchema");async function aK(e){let t=new zY(Rs.SYSTEM_SCHEMA_NAME,Rs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await ZY(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw rK(new Error,sK.SCHEMA_NOT_FOUND(e),iK.NOT_FOUND,void 0,void 0,!0);return n}a(aK,"validateDropSchema")});var Ym=T((oue,$y)=>{"use strict";var $m=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};$y.exports=$m});var Ky=T((uue,Yy)=>{"use strict";var cK=require("fs-extra"),H_=Ve(),{getTransactionAuditStorePath:uK}=Ye(),Km=lt(),cue=Ym();Yy.exports=lK;async function lK(e){let t;try{let r=uK(e.schema,e.table);await cK.mkdirp(r),t=await H_.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{H_.createDBI(t,Km.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),H_.createDBI(t,Km.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),H_.createDBI(t,Km.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(lK,"createTransactionsAuditEnvironment")});var Jy=T((_ue,zy)=>{"use strict";var Wm=U(),Wy=Ve(),_K=$o(),{getSystemSchemaPath:dK,getSchemaPath:fK}=Ye(),EK=Pi(),hK=w_(),Qm=y_(),mK=W(),pK=Ky(),Jm=EK.hdb_table,Qy=[];for(let e=0;e<Jm.attributes.length;e++)Qy.push(Jm.attributes[e].attribute);zy.exports=SK;async function SK(e,t){let r=fK(t.schema,t.table),n=new Qm(t.schema,t.table,Wm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Qm(t.schema,t.table,Wm.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Qm(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Wy.createEnvironment(r,t.table),e!==void 0){let o=await Wy.openEnvironment(dK(),Wm.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await _K.insertRecords(o,Jm.hash_attribute,Qy,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await zm(n),await zm(s),await zm(i)}await pK(t)}catch(o){throw o}}a(SK,"lmdbCreateTable");async function zm(e){try{await hK(e)}catch(t){mK.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(zm,"createAttribute")});var jy=T((fue,Xy)=>{"use strict";var TK=Nc(),gK=Dc(),RK=C_(),Fc=U(),AK=$o().updateRecords,OK=Ve(),{getSchemaPath:bK}=Ye(),NK=Lc(),yK=W();Xy.exports=wK;async function wK(e){try{let{schema_table:t,attributes:r}=TK(e);gK(e,r,t.hash_attribute),e.schema!==Fc.SYSTEM_SCHEMA_NAME&&(r.includes(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Fc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await RK(e.hdb_auth_header,t,r),s=bK(e.schema,e.table),i=await OK.openEnvironment(s,e.table),o=await AK(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await NK(e,o)}catch(c){yK.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(wK,"lmdbUpdateRecords")});var ew=T((hue,Zy)=>{"use strict";var IK=U().OPERATIONS_ENUM,Xm=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=IK.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Zy.exports=Xm});var rw=T((Sue,tw)=>{"use strict";var pue=ew(),CK=Nc(),DK=Dc(),LK=C_(),qc=U(),MK=$o().upsertRecords,UK=Ve(),{getSchemaPath:PK}=Ye(),vK=Lc(),BK=W(),{handleHDBError:HK,hdb_errors:xK}=ee();tw.exports=FK;async function FK(e){let t;try{t=CK(e)}catch(u){throw HK(u,u.message,xK.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;DK(e,n,r.hash_attribute),e.schema!==qc.SYSTEM_SCHEMA_NAME&&(n.includes(qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await LK(e.hdb_auth_header,r,n),i=PK(e.schema,e.table),o=await UK.openEnvironment(i,e.table),c=await MK(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await vK(e,c)}catch(u){BK.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(FK,"lmdbUpsertRecords")});var sw=T((gue,nw)=>{"use strict";var jm=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};nw.exports=jm});var ow=T((Aue,iw)=>{"use strict";var Zm=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};iw.exports=Zm});var uw=T((Nue,cw)=>{"use strict";var ep=Ve(),{getTransactionAuditStorePath:qK}=Ye(),bue=sw(),Gc=lt(),GK=J(),aw=ow(),kK=require("util").promisify,VK=kK(setTimeout),$K=1e4,YK=100;cw.exports=KK;async function KK(e){let t=qK(e.schema,e.table),r=await ep.openEnvironment(t,e.table,!0),n=ep.listDBIs(r);ep.initializeDBIs(r,Gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new aw;do s=await WK(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await VK(YK);while(s.transactions_deleted>0);return i}a(KK,"deleteAuditLogsBefore");async function WK(e,t){let r=new aw;try{let n=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[Gc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];GK.isEmpty(c)||(s=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[Gc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>$K)break}return await s,r}catch(n){throw n}}a(WK,"deleteTransactions")});var _w=T((wue,lw)=>{"use strict";var tp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};lw.exports=tp});var fw=T((Due,dw)=>{"use strict";var QK=Kn(),zK=xc(),Cue=_w(),Wn=U(),JK=J(),rp=Ve(),XK=Pi(),jK=Hc(),ZK=Uc(),{getSchemaPath:eW}=Ye();dw.exports=tW;async function tW(e,t=!0){let r;e.schema===Wn.SYSTEM_SCHEMA_NAME?r=XK[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await nW(e),s=eW(e.schema,e.table),i=await rp.openEnvironment(s,e.table);return t===!0&&await rW(e,i,r.hash_attribute),rp.dropDBI(i,e.attribute),n}a(tW,"lmdbDropAttribute");async function rW(e,t,r){let n=rp.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(rW,"removeAttributeFromAllObjects");async function nW(e){let t=new QK(Wn.SYSTEM_SCHEMA_NAME,Wn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await jK(t)).filter(o=>o[Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(JK.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new zK(Wn.SYSTEM_SCHEMA_NAME,Wn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return ZK(i)}a(nW,"dropAttributeFromSystem")});var Tw=T((Uue,Sw)=>{"use strict";var np=Ve(),jo=lt(),Mue=Nr(),sp=U(),Ew=J(),{getTransactionAuditStorePath:sW}=Ye(),iW=zo(),x_=Ko(),oW=W();Sw.exports=aW;async function aW(e){let t=sW(e.schema,e.table),r=await np.openEnvironment(t,e.table,!0),n=np.listDBIs(r);np.initializeDBIs(r,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case sp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return hw(r,e.search_values);case sp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,uW(r,e.search_values,s);case sp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return cW(r,e.search_values);default:return hw(r)}}a(aW,"readAuditLog");function hw(e,t=[0,Date.now()]){Ew.isEmpty(t[0])&&(t[0]=0),Ew.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new x_,s))}a(hw,"searchTransactionsByTimestamp");function cW(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,pw(e,i))}return Object.fromEntries(r)}a(cW,"searchTransactionsByUsername");function uW(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=iW.equals(e,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=pw(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);mw(u,"records",r,l,o),mw(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(uW,"searchTransactionsByHashValues");function mw(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new x_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new x_(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(mw,"loopRecords");function pw(e,t){let r=[];try{let n=e.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new x_,i);r.push(o)}}catch(i){oW.warn(i)}return r}catch(n){throw n}}a(pw,"batchSearchTransactions")});var Rw=T((Hue,gw)=>{"use strict";var{getSchemaPath:vue}=Ye(),Bue=Ve(),{database:lW}=(Ne(),te(qe));gw.exports={writeTransaction:_W};async function _W(e,t,r){return lW({database:e,table:t}).transaction(r)}a(_W,"writeTransaction")});var Nw=T((Fue,bw)=>{"use strict";var{getSchemaPath:Aw}=Ye(),Ow=Ve();bw.exports={flush:dW,resetReadTxn:fW};async function dW(e,t){return(await Ow.openEnvironment(Aw(e,t),t.toString())).flushed}a(dW,"flush");async function fW(e,t){try{(await Ow.openEnvironment(Aw(e,t),t.toString())).resetReadTxn()}catch{}}a(fW,"resetReadTxn")});var Cw=T((Gue,Iw)=>{"use strict";var{Readable:EW}=require("stream"),{getDatabases:hW}=(Ne(),te(qe)),{readSync:mW,openSync:pW,createReadStream:yw}=require("fs"),{open:SW}=require("lmdb"),ww=h_(),TW=p_(),{AUDIT_STORE_OPTIONS:gW}=(Ci(),te(WO)),{INTERNAL_DBIS_NAME:RW,AUDIT_STORE_NAME:AW}=lt();Iw.exports=bW;var ip=32768,OW=100;async function bW(e){let t=e.database||e.schema||"data",r=hW()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=SW({noSync:!0,maxDbs:TW.MAX_DBS}),f,E=d.openDB(RW,new ww(!1)),h=l.useReadTransaction(),p=0,S=a(async function(g,R){R.encoding="binary",R.encoder=void 0;let B=d.openDB(g,R),H=l.openDB(g,R);for(let{key:v,version:M,value:$}of H.getRange({transaction:h,versions:H.useVersions}))f=B.put(v,$,M),p++%OW===0&&(await new Promise(K=>setTimeout(K,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:g,value:R}of l.getRange({transaction:h,start:!1}))if(s.some(B=>g.startsWith?.(B+"/"))){E.put(g,R);let[,B]=g.split("/"),H=!B,v=new ww(!H,H);await S(g,v)}e.include_audit&&await S(AW,Object.assign({},gW)),await f;let O=yw(d.path);return O.headers=u(),O.on("close",()=>{h.done(),d.close()}),O}let o=r[Object.keys(r)[0]].primaryStore,c=pW(o.path);return o.transaction(()=>{let _=Buffer.alloc(ip);mW(c,_,0,ip),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=yw(null,{fd:c,start:ip}),f=new EW.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(bW,"getBackup")});var Mw=T((Vue,Lw)=>{"use strict";var NW=W(),{handleHDBError:yW}=ee(),wW=Qb(),IW=w_(),CW=Im(),DW=VN(),LW=Uc(),MW=vm(),UW=hy(),PW=by(),vW=Hc(),BW=My(),HW=Vy(),xW=Jy(),FW=jy(),qW=rw(),GW=uw(),kW=Vm(),VW=fw(),$W=Tw(),YW=Rw(),Dw=Nw(),KW=Cw(),op=class extends wW{static{a(this,"LMDBBridge")}async searchByConditions(t){return BW(t)}async getDataByHash(t){return await MW(t)}async searchByHash(t){return await UW(t)}async getDataByValue(t,r){return await PW(t,r)}async searchByValue(t){return await vW(t)}async createSchema(t){return await DW(t)}async dropSchema(t){return await HW(t)}async createTable(t,r){return await xW(t,r)}async dropTable(t){return await kW(t)}async createAttribute(t){return await IW(t)}async createRecords(t){return await CW(t)}async updateRecords(t){return await FW(t)}async upsertRecords(t){try{return await qW(t)}catch(r){throw yW(r,null,null,NW.ERR,r)}}async deleteRecords(t){return await LW(t)}async dropAttribute(t){return await VW(t)}async deleteAuditLogsBefore(t){return await GW(t)}async readAuditLog(t){return await $W(t)}writeTransaction(t,r,n){return YW.writeTransaction(t,r,n)}flush(t,r){return Dw.flush(t,r)}resetReadTxn(t,r){return Dw.resetReadTxn(t,r)}getBackup(t){return KW(t)}};Lw.exports=op});var Gw={};Fe(Gw,{ResourceBridge:()=>up});function lp({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 Pw(e,t){let r=Qn(e),n=lp(e,r);if(!r)throw new Nn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Ke(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&s_(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function Qn(e){let t=e.database||e.schema||QW,r=yn()[t];if(!r)throw(0,Nn.handleHDBError)(new Error,WW.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function vw(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*Bw(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var Hw,F_,Nn,xw,Fw,wn,ap,cp,qw,WW,QW,zW,JW,Uw,up,kw=Oe(()=>{"use strict";Hw=x(Mw()),F_=x(Jo()),Nn=x(ee());Ne();xw=x(Nc()),Fw=x(Dc()),wn=x(U()),ap=x(Ts()),cp=x(bn()),qw=x(J());Ui();i_();({HDB_ERROR_MSGS:WW}=Nn.hdb_errors),QW="data",zW=1e4,JW=10,up=class extends Hw.default{static{a(this,"ResourceBridge")}constructor(t){super(t),Uw=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,F_.default)(t,"conditions");if(r)throw(0,Nn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=Qn(t);if(!n)throw new Nn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:lp(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Nn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}at({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await Qn(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Qn(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Qn(t).dropTable()}createSchema(t){return kc({database:t.schema,table:null}),ap.signalSchemaChange(new cp.SchemaEventMsg(process.pid,wn.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await _p(t.schema),ap.signalSchemaChange(new cp.SchemaEventMsg(process.pid,wn.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,Uw.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,xw.default)(t);(0,Fw.default)(t,n,r.primaryKey);let s,i=yn()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Ke(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(f=>f.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=s_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=yn()[t.schema][t.table],n={user:t.hdb_user};return Ke(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return vw(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=yn()[t.schema][t.table];if(!r.createdTimeProperty)throw new Nn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:wn.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,qw.async_set_timeout)(JW),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%zW===0&&await _();return u.length>0&&await _(),s?vw(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,F_.default)(t,"hashes");if(r)throw r;return Pw(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of Pw(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&wn.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,F_.default)(t,"value");if(n)throw n;let s=Qn(t);if(!s)throw new Nn.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===wn.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:lp(t,s)})}async getDataByValue(t,r){let n=new Map,s=Qn(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){Qn({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Qn(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Qn(t),n={};switch(t.search_type){case wn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case wn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of Bw(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return Bw(r,t.search_values?.[0],t.search_values?.[1])}}};a(lp,"getSelect");a(Pw,"getRecords");a(Qn,"getTable");a(vw,"createDeleteResponse");a(Bw,"groupRecordsInHistory")});var In=T((zue,Vw)=>{"use strict";var{ResourceBridge:XW}=(kw(),te(Gw)),jW=Z();jW.initSync();var q_;function ZW(){return q_||(q_=new XW,q_)}a(ZW,"getBridge");Vw.exports=ZW()});var Ww=T((Xue,Kw)=>{"use strict";var $w=require("lodash"),Vc=require("mathjs"),eQ=require("jsonata"),Yw=J();Kw.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?$w.uniqWith(e,$w.isEqual):e,searchJSON:tQ,mad:$c.bind(null,Vc.mad),mean:$c.bind(null,Vc.mean),mode:$c.bind(null,Vc.mode),prod:$c.bind(null,Vc.prod),median:$c.bind(null,Vc.median)};function $c(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a($c,"aggregateFunction");function tQ(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(Yw.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),Yw.isEmpty(this.__ala__.res[r])){let n=eQ(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(tQ,"searchJSON")});var zw=T((Zue,Qw)=>{"use strict";var dt=require("moment"),dp="YYYY-MM-DDTHH:mm:ss.SSSZZ";dt.suppressDeprecationWarnings=!0;Qw.exports={current_date:()=>dt().utc().format("YYYY-MM-DD"),current_time:()=>dt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return dt(e).utc().format("YYYY");case"month":return dt(e).utc().format("MM");case"day":return dt(e).utc().format("DD");case"hour":return dt(e).utc().format("HH");case"minute":return dt(e).utc().format("mm");case"second":return dt(e).utc().format("ss");case"millisecond":return dt(e).utc().format("SSS");default:break}},date:e=>dt(e).utc().format(dp),date_format:(e,t)=>dt(e).utc().format(t),date_add:(e,t,r)=>dt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>dt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=dt(e).utc(),s=dt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>dt().utc().valueOf(),get_server_time:()=>dt().format(dp),offset_utc:(e,t)=>dt(e).utc().utcOffset(t).format(dp)}});var Zw=T((ele,jw)=>{"use strict";var rQ=require("@turf/area"),nQ=require("@turf/length"),sQ=require("@turf/circle"),iQ=require("@turf/difference"),oQ=require("@turf/distance"),aQ=require("@turf/boolean-contains"),cQ=require("@turf/boolean-equal"),uQ=require("@turf/boolean-disjoint"),lQ=require("@turf/helpers"),Jw=U(),ge=J(),As=W();jw.exports={geoArea:_Q,geoLength:dQ,geoCircle:fQ,geoDifference:EQ,geoDistance:Xw,geoNear:hQ,geoContains:mQ,geoEqual:pQ,geoCrosses:SQ,geoConvert:TQ};function _Q(e){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return rQ.default(e)}catch(t){return As.trace(t,e),NaN}}a(_Q,"geoArea");function dQ(e,t){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return nQ.default(e,{units:t||"kilometers"})}catch(r){return As.trace(r,e),NaN}}a(dQ,"geoLength");function fQ(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return sQ.default(e,t,{units:r||"kilometers"})}catch(n){return As.trace(n,e,t),NaN}}a(fQ,"geoCircle");function EQ(e,t){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return iQ(e,t)}catch(r){return As.trace(r,e,t),NaN}}a(EQ,"geoDifference");function Xw(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return oQ.default(e,t,{units:r||"kilometers"})}catch(n){return As.trace(n,e,t),NaN}}a(Xw,"geoDistance");function hQ(e,t,r,n){if(ge.isEmpty(e)||ge.isEmpty(t))return!1;if(ge.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return Xw(e,t,n)<=r}catch(s){return As.trace(s,e,t),!1}}a(hQ,"geoNear");function mQ(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return aQ.default(e,t)}catch(r){return As.trace(r,e,t),!1}}a(mQ,"geoContains");function pQ(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return cQ.default(e,t)}catch(r){return As.trace(r,e,t),!1}}a(pQ,"geoEqual");function SQ(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return!uQ.default(e,t)}catch(r){return As.trace(r,e,t),!1}}a(SQ,"geoCrosses");function TQ(e,t,r){if(ge.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(ge.isEmpty(t))throw new Error("geo_type is required");if(ge.isEmpty(Jw.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(Jw.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=ge.autoCastJSON(e)),lQ[t](e,r)}a(TQ,"geoConvert")});var G_=T((rle,eI)=>{var qi=Ww(),Lr=zw(),zn=Zw();eI.exports=e=>{e.aggr.mad=e.aggr.MAD=qi.mad,e.aggr.mean=e.aggr.MEAN=qi.mean,e.aggr.mode=e.aggr.MODE=qi.mode,e.aggr.prod=e.aggr.PROD=qi.prod,e.aggr.median=e.aggr.MEDIAN=qi.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=qi.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=qi.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Lr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Lr.current_time,e.fn.extract=e.fn.EXTRACT=Lr.extract,e.fn.date=e.fn.DATE=Lr.date,e.fn.date_format=e.fn.DATE_FORMAT=Lr.date_format,e.fn.date_add=e.fn.DATE_ADD=Lr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Lr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Lr.date_diff,e.fn.now=e.fn.NOW=Lr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Lr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Lr.get_server_time,e.fn.getdate=e.fn.GETDATE=Lr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Lr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=zn.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=zn.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=zn.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=zn.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=zn.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=zn.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=zn.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=zn.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=zn.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=zn.geoNear}});var sI=T((nle,nI)=>{"use strict";var Yc=require("lodash"),nr=require("alasql");nr.options.cache=!1;var gQ=G_(),tI=require("clone"),k_=require("recursive-iterator"),Ee=W(),Ce=J(),Zo=In(),RQ=U(),{hdb_errors:AQ}=ee(),{getDatabases:rI}=(Ne(),te(qe)),OQ="IS NULL",Cn="There was a problem performing this search. Please check the logs and try again.";gQ(nr);var fp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw Ee.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),Ce.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(n))return Ee.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw Ee.error("Error thrown from checkEmptySQL in SQLSearch class method search."),Ee.error(n),new Error(Cn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw Ee.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),Ee.error(n),new Error(Cn)}if(Object.keys(this.data).length===0)return Ee.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw Ee.error("Error thrown from processJoins in SQLSearch class method search."),Ee.error(n),new Error(Cn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw Ee.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),Ee.error(n),new Error(Cn)}try{return t=await this._finalSQL(),t}catch(n){throw Ee.error("Error thrown from finalSQL in SQLSearch class method search."),Ee.error(n),new Error(Cn)}}_getColumns(){let t=new k_(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(tI(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Yc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=rI()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ce.isEmpty(this.statement.where)){Ee.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new k_(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ce.isEmpty(r)&&r.right)if(Ce.isNotEmptyAndHasValue(r.right.value)){let n=Ce.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new nr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Ce.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new nr.yy.LogicValue({value:i}):n instanceof nr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new nr.yy.NumValue({value:i}))});if(t){Ee.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new k_(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ce.isEmpty(RQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ce.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ce.isEmptyOrZeroLength(r.left.columnid)||Ce.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(Ce.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!Ce.isEmpty(r.right.value)||!Ce.isEmpty(r.left.value)?n.add(Ce.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Yc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(Ce.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Ce.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&!Ce.isEmptyOrZeroLength(this.columns.columns))return t;if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await nr.promise(r)}catch(r){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),Ee.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(tI(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(Ce.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(OQ)>-1&&this.tables.forEach(s=>{let i={columnid:rI()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Yc.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!Ce.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await Zo.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw Ee.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),Ee.error(l),new Error(Cn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await Zo.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]):(this.data[i].__merged_data[E]=[...n[i]],this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),Ee.error(l),new Error(Cn)}else if(!Ce.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await Zo.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),Ee.error(l),new Error(Cn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await Zo.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),Ee.error(l),new Error(Cn)}}}_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 nr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new nr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new nr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new nr.yy.FuncValue:new nr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,s);f=await nr.promise(h,t),t=null}catch(E){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),Ee.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let p=f[E];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),p=Yc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,O=p.length;S<O;S++){let g=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[g]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new k_(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=Yc.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw Ee.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),Ee.error(i),new Error(Cn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await Zo.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=s.columns[h],S=E[p]===void 0?null:E[p];this.data[n].__merged_data[f].push(S)}}}}catch(r){throw Ee.error("Error thrown from getDataByHash function in SQLSearch class method getData."),Ee.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();Ee.trace(`Final SQL: ${s}`),n=await nr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),Ee.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),Ee.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return Ee.error(AQ.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),Ee.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await Zo.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw Ee.error("There was an error when processing this SQL operation. Check your logs"),Ee.error(o),new Error(Cn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};nI.exports=fp});var tn=T((ile,iI)=>{"use strict";var bQ=Kb();iI.exports={searchByConditions:yQ,searchByHash:wQ,searchByValue:IQ,search:CQ};var Ep=In(),{transformReq:hp}=J(),NQ=sI();async function yQ(e){return hp(e),Ep.searchByConditions(e)}a(yQ,"searchByConditions");async function wQ(e){hp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Ep.searchByHash(e))r&&t.push(r);return t}a(wQ,"searchByHash");async function IQ(e){hp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Ep.searchByValue(e))t.push(r);return t}a(IQ,"searchByValue");function CQ(e,t){try{let r=new bQ(e);r.validate(),new NQ(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(CQ,"search")});var Os=T((ale,uI)=>{"use strict";var Kc=require("crypto"),DQ=Z(),{CONFIG_PARAMS:LQ}=U(),aI="aes-256-cbc",MQ=32,UQ=16,mp=64,cI=32,PQ=mp+cI,oI=new Map;uI.exports={encrypt:vQ,decrypt:BQ,createNatsTableStreamName:HQ};function vQ(e){let t=Kc.randomBytes(MQ),r=Kc.randomBytes(UQ),n=Kc.createCipheriv(aI,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(vQ,"encrypt");function BQ(e){let t=e.substr(0,mp),r=e.substr(mp,cI),n=e.substr(PQ,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Kc.createDecipheriv(aI,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(BQ,"decrypt");function HQ(e,t){let r=DQ.get(LQ.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=oI.get(r);return n||(n=Kc.createHash("md5").update(r).digest("hex"),oI.set(r,n)),n}a(HQ,"createNatsTableStreamName")});var Gi=T((lle,_I)=>{"use strict";var ule=tn(),V_=W(),lI=N_(),xQ=Os(),$_=J(),{handleHDBError:Y_,hdb_errors:FQ}=ee(),{HDB_ERROR_MSGS:K_,HTTP_STATUS_CODES:pp}=FQ,qQ=Z();qQ.initSync();var{getDatabases:Sp}=(Ne(),te(qe));_I.exports={describeAll:GQ,describeTable:W_,describeSchema:kQ};async function GQ(e){try{let t=$_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Sp(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let f in d)try{let E;if(t||n)E=await W_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await W_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){V_.error(E)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return V_.error("Got an error in describeAll"),V_.error(t),Y_(new Error,K_.DESCRIBE_ALL_ERR)}}a(GQ,"describeAll");async function W_(e,t){$_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=lI.describe_table(e);if(i)throw i;let c=Sp()[r];if(!c)throw Y_(new Error,K_.SCHEMA_NOT_FOUND(e.schema),pp.NOT_FOUND);let u=c[n];if(!u)throw Y_(new Error,K_.TABLE_NOT_FOUND(e.schema,e.table),pp.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=xQ.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){V_.warn(`unable to stat table dbi due to ${f}`)}return d}a(W_,"descTable");async function kQ(e){$_.transformReq(e);let t=lI.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Sp()[n];if(!i)throw Y_(new Error,K_.SCHEMA_NOT_FOUND(e.schema),pp.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),$_.isEmpty(u)||u.describe){let _=await W_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(kQ,"describeSchema")});var Zs=T((Ele,mI)=>{var VQ=Pi(),{callbackify:fI,promisify:$Q}=require("util"),{getDatabases:EI}=(Ne(),te(qe));mI.exports={setSchemaDataToGlobal:dI,getTableSchema:YQ,getSystemSchema:KQ,setSchemaDataToGlobalAsync:$Q(dI)};var hI=Gi(),dle=fI(hI.describeAll),fle=fI(hI.describeTable);function dI(e){global.hdb_schema=EI(),e&&e()}a(dI,"setSchemaDataToGlobal");function YQ(e,t,r){let n=EI()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(YQ,"getTableSchema");function KQ(){return VQ}a(KQ,"getSystemSchema")});var rn=T((mle,gI)=>{"use strict";var z_=Tm(),Bt=J(),WQ=require("util"),J_=In(),QQ=Zs(),pI=W(),{handleHDBError:ki,hdb_errors:zQ}=ee(),{HTTP_STATUS_CODES:Vi}=zQ,JQ=WQ.promisify(QQ.getTableSchema),XQ="updated",SI="inserted",TI="upserted";gI.exports={insert:ZQ,update:ez,upsert:tz,validation:jQ,flush:rz};async function jQ(e){if(Bt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Bt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Bt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await JQ(e.schema,e.table),r=z_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Bt.isEmptyOrZeroLength(c[n]))throw pI.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(!Bt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw pI.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Bt.isEmpty(c[n])&&c[n]!==""&&s.has(Bt.autoCast(c[n]))&&(c.skip=!0),s.add(Bt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(jQ,"validation");async function ZQ(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=z_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await J_.createRecords(e);return Q_(SI,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(ZQ,"insertData");async function ez(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=z_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await J_.updateRecords(e);return Bt.isEmpty(n.existing_rows)?Q_(XQ,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):Q_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(ez,"updateData");async function tz(e){if(e.operation!=="upsert")throw ki(new Error,"invalid operation, must be upsert",Vi.INTERNAL_SERVER_ERROR);let t=z_(e);if(t)throw ki(new Error,t.message,Vi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw ki(new Error,r,Vi.BAD_REQUEST);let n=await J_.upsertRecords(e);return Q_(TI,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(tz,"upsertData");function Q_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===SI?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===TI?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(Q_,"returnObject");function rz(e){return Bt.transformReq(e),J_.flush(e.schema,e.table)}a(rz,"flush")});var gp=T((Sle,OI)=>{var nz=Ze(),Tp=require("joi"),{hdb_table:sz,hdb_database:RI}=$n(),AI={schema:RI,database:RI,table:sz},iz={date:Tp.date().iso().required()},oz={timestamp:Tp.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};OI.exports=function(e,t){let r=t==="timestamp"?{...AI,...oz}:{...AI,...iz},n=Tp.object(r);return nz.validateBySchema(e,n)}});var yI=T((Tle,NI)=>{var az=Ze(),Rp=require("joi"),{hdb_table:cz,hdb_database:bI}=$n(),uz=Rp.object({schema:bI,database:bI,table:cz,hash_values:Rp.array().required(),ids:Rp.array()});NI.exports=function(e){return az.validateBySchema(e,uz)}});var II=T((gle,wI)=>{"use strict";var Ap=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},Op=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},bp=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};wI.exports={InsertObject:Ap,NoSQLSeachObject:Op,DeleteResponseObject:bp}});var Ki=T((Ale,UI)=>{"use strict";var DI=gp(),lz=yI(),$i=J(),CI=require("moment"),LI=W(),{promisify:_z,callbackify:dz}=require("util"),Yi=U(),fz=Zs(),Np=_z(fz.getTableSchema),yp=In(),{DeleteResponseObject:Ez}=II(),{handleHDBError:ei,hdb_errors:hz}=ee(),{HDB_ERROR_MSGS:X_,HTTP_STATUS_CODES:ti}=hz,mz="records successfully deleted",pz=dz(MI);UI.exports={delete:pz,deleteRecord:MI,deleteFilesBefore:Sz,deleteAuditLogsBefore:Tz};async function Sz(e){let t=DI(e,"date");if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);if($i.transformReq(e),!CI(e.date,CI.ISO_8601).isValid())throw ei(new Error,X_.INVALID_DATE,ti.BAD_REQUEST,Yi.LOG_LEVELS.ERROR,X_.INVALID_DATE,!0);let n=$i.checkSchemaTableExist(e.schema,e.table);if(n)throw ei(new Error,n,ti.NOT_FOUND,Yi.LOG_LEVELS.ERROR,n,!0);let s=await yp.deleteRecordsBefore(e);if(await Np(e.schema,e.table),LI.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(Sz,"deleteFilesBefore");async function Tz(e){let t=DI(e,"timestamp");if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);if($i.transformReq(e),isNaN(e.timestamp))throw ei(new Error,X_.INVALID_VALUE("Timestamp"),ti.BAD_REQUEST,Yi.LOG_LEVELS.ERROR,X_.INVALID_VALUE("Timestamp"),!0);let r=$i.checkSchemaTableExist(e.schema,e.table);if(r)throw ei(new Error,r,ti.NOT_FOUND,Yi.LOG_LEVELS.ERROR,r,!0);let n=await yp.deleteAuditLogsBefore(e);return await Np(e.schema,e.table),LI.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(Tz,"deleteAuditLogsBefore");async function MI(e){e.ids&&(e.hash_values=e.ids);let t=lz(e);if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);$i.transformReq(e);let r=$i.checkSchemaTableExist(e.schema,e.table);if(r)throw ei(new Error,r,ti.NOT_FOUND,Yi.LOG_LEVELS.ERROR,r,!0);try{await Np(e.schema,e.table);let n=await yp.deleteRecords(e);return $i.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${mz}`),n}catch(n){if(n.message===Yi.SEARCH_NOT_FOUND_MESSAGE){let s=new Ez;return s.message=Yi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(MI,"deleteRecord")});var j_=T((ble,BI)=>{var gz=require("crypto"),PI=9;function Rz(e){let t=Oz(PI),r=vI(e+t);return t+r}a(Rz,"createHash");function Az(e,t){let r=e?.substr(0,PI),n=r+vI(t+r);return e===n}a(Az,"validateHash");function Oz(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(Oz,"generateSalt");function vI(e){return gz.createHash("md5").update(e).digest("hex")}a(vI,"md5");BI.exports={hash:Rz,validate:Az}});var xI=T((yle,HI)=>{var wp=Ze(),$t={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 bz(e){return $t.password.presence=!0,$t.username.presence=!0,$t.role.presence=!0,$t.active.presence=!0,wp.validateObject(e,$t)}a(bz,"addUserValidation");function Nz(e){return $t.password.presence=!1,$t.username.presence=!0,$t.role.presence=!1,$t.active.presence=!1,wp.validateObject(e,$t)}a(Nz,"alterUserValidation");function yz(e){return $t.password.presence=!1,$t.username.presence=!0,$t.role.presence=!1,$t.active.presence=!1,wp.validateObject(e,$t)}a(yz,"dropUserValidation");HI.exports={addUserValidation:bz,alterUserValidation:Nz,dropUserValidation:yz}});var et=T((Cle,qI)=>{"use strict";var{platform:Ile}=require("os"),wz="nats-server.zip",Ip="nats-server",Iz=process.platform==="win32"?`${Ip}.exe`:Ip,Cp="HDB",Cz=/^[^\s.,*>]+$/,FI="__request__",Dz=a(e=>`${e}.${FI}`,"REQUEST_SUBJECT"),Lz={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},Mz={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},Uz={HUB:"hub.pid",LEAF:"leaf.pid"},Pz={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},vz={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Cp,deliver_subject:"__HDB__.WORKQUEUE"},Bz={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Cp,deliver_subject:"HDB.SCHEMAQUEUE"},Hz={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Cp,deliver_subject:"HDB.USERQUEUE"},xz={SUCCESS:"success",ERROR:"error"},Fz={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},qz={TXN:"txn",MSGID:"msgid"},ea={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},Gz={[ea.ERR]:1,[ea.WRN]:2,[ea.INF]:3,[ea.DBG]:4,[ea.TRC]:5},kz={debug:"-D",trace:"-DVV"};qI.exports={NATS_SERVER_ZIP:wz,NATS_SERVER_NAME:Ip,NATS_BINARY_NAME:Iz,PID_FILES:Uz,NATS_CONFIG_FILES:Mz,SERVER_SUFFIX:Pz,WORK_QUEUE_CONSUMER_NAMES:vz,SCHEMA_QUEUE_CONSUMER_NAMES:Bz,USER_QUEUE_CONSUMER_NAMES:Hz,NATS_TERM_CONSTRAINTS_RX:Cz,REQUEST_SUFFIX:FI,UPDATE_REMOTE_RESPONSE_STATUSES:xz,CLUSTER_STATUS_STATUSES:Fz,REQUEST_SUBJECT:Dz,SUBJECT_PREFIXES:qz,MSG_HEADERS:Lz,LOG_LEVELS:ea,LOG_LEVEL_FLAGS:kz,LOG_LEVEL_HIERARCHY:Gz}});var kI=T((Lle,GI)=>{"use strict";var Vz={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
|
|
5
5
|
`),cert:"-----BEGIN CERTIFICATE-----\rMIIDXDCCAkSgAwIBAgIFNTE4MzQwDQYJKoZIhvcNAQELBQAwXTEXMBUGA1UEAxMO\rSGFycGVyREIsIEluYy4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UE\rBxMGRGVudmVyMRcwFQYDVQQKEw5IYXJwZXJEQiwgSW5jLjAeFw0yMjAzMTEyMzAz\rNDlaFw0yNzAzMTAyMzAzNDlaMF0xFzAVBgNVBAMTDkhhcnBlckRCLCBJbmMuMQsw\rCQYDVQQGEwJVUzELMAkGA1UECBMCQ08xDzANBgNVBAcTBkRlbnZlcjEXMBUGA1UE\rChMOSGFycGVyREIsIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\rAQCsEUlBF8WImS78rCFXVKyntxfrW++4qZ3hGnoD2MHZAuDHyeP/5eGnaE9GQhKc\r4DwG4DGvh0wP2zIYnBfiQ3L2ZtnlDR9ZkKIQYGlVxTUn6T43krhK5nZKqDF43Yg3\rZEvO3cbJBjiKZx0eA2/toehdSsTAHHQx5gTDcggNe2tgoJHYPwi9YF/AxSBZrbgb\ryWlYgtYDmF32ytHP03GUCIdKOFuBPsHTGu4SkdEIdLIqO9oglW1YFH5qZ6NiwApW\rsP+GCuqOwDXXbdjr75iq9Tq/CDrjGFLaTPmvd2Q0qG/BtaCll0ghpG+yIHvt/iQs\rajS+LxEWAnVlGMaDdFErbDUtAgMBAAGjIzAhMA8GA1UdEwEB/wQFMAMBAf8wDgYD\rVR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4IBAQASR4YW/rPK7PNArHVe9zzM\rb0rKNX/2T9/0nybRhmE/+hdlSgliTAeebmwkUS2APckmekYt/q2ZY2NS65Fo/jjp\rG8TJrtcF4h+ylVqUp0ZXQLFtIsr7r2JZA7hJ6njW6G4DHSZ0gxtECLi4CBlTjzm5\rNmnmIDObvGRTuqmcdAZmXeObbta/He2XIzietukPAYX062pNM+G5XT5UM1eG/Vlp\rN86vjhpyI+ffKy+C60SJqxmKM3ydgN7oLscE7+2wLPN25XqN4W99OwGsp5dTdu/f\r5lPtFayXdJ55e/sNQKmGN+UGLrL05c2MWgjb8U/LFilnupUianceoeSERZmVjzKX\r-----END CERTIFICATE-----\r".replace(/\r/g,`\r
|
|
6
|
-
`)},kz="certificate.pem",Vz="privateKey.pem",$z="ca.pem";Fw.exports={CERTIFICATE_VALUES:Gz,CERTIFICATE_PEM_NAME:kz,PRIVATEKEY_PEM_NAME:Vz,CA_PEM_NAME:$z}});var Pp=T((Ple,Yw)=>{"use strict";var $w=require("fs-extra"),le=require("joi"),Yz=require("os"),{boolean:ve,string:an,number:Pt,array:Up}=le.types(),{totalmem:Gw}=require("os"),Wi=require("path"),Kz=Y(),td=J(),Ule=qw(),kw=M(),Wz=rt(),Vw="log",Qz="components",zz="Invalid logging.rotation.maxSize unit. Available units are G, M or K",Jz="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Xz="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",jz="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",Zz="rootPath config parameter is undefined",e2="clustering.enabled config parameter is undefined",Qi=Pt.min(0).required(),rd=Up.items({host:an.required(),port:Qi}).empty(null),Xn;Yw.exports={configValidator:t2,routesValidator:a2,route_constraints:rd};function t2(e){if(Xn=e.rootPath,td.isEmpty(Xn))throw Zz;let t=ve.required(),r=Pt.min(0).max(1e3).empty(null).default(o2),n=an.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Wc),s=an.optional().empty(null),i=an.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=le.string().empty(null).default(Wc),c=le.custom(n2).empty(null).default(Wc),u=e.clustering?.enabled;if(td.isEmpty(u))throw e2;let _;return u===!0?_=le.object({enabled:t,hubServer:le.object({cluster:le.object({name:le.required().empty(null),network:le.object({port:Qi,routes:rd}).required()}).required(),leafNodes:le.object({network:le.object({port:Qi}).required()}).required(),network:le.object({port:Qi}).required()}).required(),leafServer:le.object({network:le.object({port:Qi,routes:rd}).required(),streams:le.object({maxAge:Pt.min(120).allow(null).optional(),maxBytes:Pt.min(1).allow(null).optional(),maxMsgs:Pt.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:le.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:ve.optional(),databaseLevel:ve.optional(),tls:le.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:ve.required(),verify:ve.optional()}),user:an.optional().empty(null)}).required():_=le.object({enabled:t,tls:le.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:ve.required()})}).required(),le.object({authentication:le.object({authorizeLocal:ve,cacheTTL:Pt.required(),enableSessions:ve}),analytics:le.object({aggregatePeriod:Pt}),componentsRoot:n.optional(),clustering:_,localStudio:le.object({enabled:t}).required(),logging:le.object({auditAuthEvents:le.object({logFailed:ve,logSuccessful:ve}),file:ve.required(),level:le.valid("notify","fatal","error","warn","info","debug","trace"),rotation:le.object({enabled:ve.optional(),compress:ve.optional(),interval:an.custom(i2).optional().empty(null),maxSize:an.custom(s2).optional().empty(null),path:an.optional().empty(null).default(Wc)}).required(),root:n,stdStreams:ve.required(),auditLog:ve.required()}).required(),operationsApi:le.object({network:le.object({cors:ve.optional(),corsAccessList:Up.optional(),headersTimeout:Pt.min(1).optional(),keepAliveTimeout:Pt.min(1).optional(),port:Pt.optional().empty(null),domainSocket:le.optional().empty("hdb/operations-server").default(Wc),securePort:Pt.optional().empty(null),timeout:Pt.min(1).optional()}).optional(),tls:le.object({certificate:s,certificateAuthority:s,privateKey:s})}).required(),rootPath:an.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:le.object({network:le.object({port:Qi,securePort:Qi,mtls:le.alternatives([ve.optional(),le.object({user:an.optional(),certificateAuthority:s,required:ve.optional()})])}).required(),webSocket:ve.optional(),requireAuthentication:ve.optional()}),http:le.object({compressionThreshold:Pt.optional(),cors:ve.optional(),corsAccessList:Up.optional(),headersTimeout:Pt.min(1).optional(),port:Pt.min(0).optional().empty(null),securePort:Pt.min(0).optional().empty(null)}).required(),threads:r.optional(),maxHeapMemory:Pt.min(0).optional(),storage:le.object({writeAsync:ve.required(),overlappingSync:ve.optional(),caching:ve.optional(),compression:ve.optional(),noReadAhead:ve.optional(),path:c,prefetchWrites:ve.optional()}).required(),ignoreScripts:ve.optional(),tls:le.object({certificate:s.optional(),certificateAuthority:s.optional(),privateKey:s.optional(),ciphers:an.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(t2,"configValidator");function r2(e){return $w.existsSync(e)?null:`Specified path ${e} does not exist.`}a(r2,"doesPathExist");function n2(e,t){le.assert(e,an.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=r2(e);if(r)return t.message(r)}a(n2,"validatePath");function s2(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(zz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Xz):e}a(s2,"validateRotationMaxSize");function i2(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(Jz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(jz):e}a(i2,"validateRotationInterval");function o2(e,t){let r=t.state.path.join("."),n=Yz.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||Gw();return i=Math.round(Math.min(i,Gw())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Kz.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(o2,"setDefaultThreads");function Wc(e,t){let r=t.state.path.join(".");if(!td.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(td.isEmpty(Xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(Xn,Qz);case"logging.root":return Wi.join(Xn,Vw);case"clustering.leafServer.streams.path":return Wi.join(Xn,"clustering","leaf");case"storage.path":let n=Wi.join(Xn,kw.LEGACY_DATABASES_DIR_NAME);return $w.existsSync(n)?n:Wi.join(Xn,kw.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(Xn,Vw);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(Xn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Wc,"setDefaultRoot");function a2(e){let t=le.object({routes:rd});return Wz.validateBySchema({routes:e},t)}a(a2,"routesValidator")});var xr=T((Hle,eC)=>{"use strict";var Hr=M(),vt=J(),bt=Y(),{configValidator:c2,routesValidator:Kw}=Pp(),cr=require("fs-extra"),u2=require("yaml"),Un=require("path"),l2=require("is-number"),Qw=require("properties-reader"),_2=require("lodash"),{handleHDBError:d2}=Z(),{HTTP_STATUS_CODES:f2,HDB_ERROR_MSGS:nd}=wr(),Ble=require("minimist"),{server:E2}=(Zt(),ee(yi)),{DATABASES_PARAM_CONFIG:Qc,CONFIG_PARAMS:Br,CONFIG_PARAM_MAP:Pn}=Hr,h2="Unable to get config value because config is uninitialized",m2="Config successfully initialized",p2="Error backing up config file",S2="Empty parameter sent to getConfigValue",zw=Un.join(Hr.PACKAGE_ROOT,"config","yaml",Hr.HDB_DEFAULT_CONFIG_FILE),T2="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ww={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"},sd,Nt,id;eC.exports={createConfigFile:g2,getDefaultConfig:R2,getConfigValue:Xw,initConfig:Bp,flattenConfig:ra,updateConfigValue:jw,updateConfigObject:O2,getConfiguration:y2,setConfiguration:I2,readConfigFile:xp,getClusteringRoutes:w2,initOldConfig:Zw,getConfigFromFile:C2,getConfigFilePath:zi,addConfig:D2,deleteConfigFromFile:L2,getConfigObj:M2};function g2(e){let t=si(zw);sd=ra(t.toJSON());let r;for(let o in e){let c=Pn[o.toLowerCase()];if(c===Br.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=vp(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){bt.error(l)}}}r&&Jw(t,r),Hp(t);let n=t.toJSON();Nt=ra(n);let s=t.getIn(["rootPath"]),i=Un.join(s,Hr.HDB_CONFIG_FILE);cr.createFileSync(i),cr.writeFileSync(i,String(t)),bt.trace(`Config file written to ${i}`)}a(g2,"createConfigFile");function Jw(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!vt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Qc.TABLES))for(let i in n[s][Qc.TABLES])for(let o in n[s][Qc.TABLES][i]){let c=n[s][Qc.TABLES][i][o],u=[Br.DATABASES,s,Qc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Br.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){bt.error("Error parsing schemas CLI/env config arguments",n)}}a(Jw,"setSchemasConfig");function R2(e){if(sd===void 0){let r=si(zw);sd=ra(r.toJSON())}let t=Pn[e.toLowerCase()];if(t!==void 0)return sd[t.toLowerCase()]}a(R2,"getDefaultConfig");function Xw(e){if(e==null){bt.error(S2);return}if(Nt===void 0){bt.trace(h2);return}let t=Pn[e.toLowerCase()];if(t!==void 0)return Nt[t.toLowerCase()]}a(Xw,"getConfigValue");function zi(e=vt.getPropsFilePath()){let t=vt.getEnvCliRootPath();return t?Un.join(t,Hr.HDB_CONFIG_FILE):Qw(e).get(Hr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function Bp(e=!1){if(Nt===void 0||e){let t;if(!vt.noBootFile()){t=vt.getPropsFilePath();try{cr.accessSync(t,cr.constants.F_OK|cr.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=zi(t),n;if(r.includes("config/settings.js"))try{Zw(r);return}catch(i){if(i.code!==Hr.NODE_ERROR_CODES.ENOENT)throw i}try{n=si(r)}catch(i){if(i.code===Hr.NODE_ERROR_CODES.ENOENT){bt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}A2(n,r),Hp(n);let s=n.toJSON();if(E2.config=s,Nt=ra(s),Nt.logging_rotation_rotate)for(let i in Ww)Nt[i]&&bt.error(`Config ${Ww[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(m2)}}a(Bp,"initConfig");function A2(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Un.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Un.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Un.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),n&&(bt.trace("Updating config file with missing config params"),cr.writeFileSync(t,String(e)))}a(A2,"checkForUpdatedConfig");function Hp(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=c2(t);if(r.error)throw nd.CONFIG_VALIDATION(r.error.message);e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(Hp,"validateConfig");function O2(e,t){Nt===void 0&&(Nt={});let r=Pn[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Nt[r.toLowerCase()]=t}a(O2,"updateConfigObject");function jw(e,t,r=void 0,n=!1,s=!1,i=!1){Nt===void 0&&Bp();let o=Xw(Pn.hdb_root),c=Un.join(o,Hr.HDB_CONFIG_FILE),u=si(c),_;if(r===void 0&&e.toLowerCase()===Br.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Pn[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=vp(f,t);u.setIn([...E],h)}else for(let f in r){let E=Pn[f.toLowerCase()];if(E===Br.HTTP_SECUREPORT&&r[f]===Nt[Br.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Br.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===Nt[Br.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Br.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),S=Hr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];S&&S.startsWith("customFunctions")&&u.hasIn(S.split("_"))&&(E=S,h=S.split("_"));let p=vp(E,r[f]);E==="rootPath"&&p?.endsWith("/")&&(p=p.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],p)}catch(g){bt.error(g)}}}_&&Jw(u,_),Hp(u);let l=u.getIn(["rootPath"]),d=Un.join(l,Hr.HDB_CONFIG_FILE);n===!0&&b2(c,l),cr.writeFileSync(d,String(u)),s&&(Nt=ra(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(jw,"updateConfigValue");function b2(e,t){try{let r=Un.join(t,"backup",`${Hr.HDB_CONFIG_FILE}.bak`);cr.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(p2),bt.error(r)}}a(b2,"backupConfigFile");var N2=["databases"];function ra(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),id=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i))if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!N2.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Br[u.toUpperCase()]&&Pn[u]&&(s[Pn[u].toLowerCase()]=o[c]),s[u]=o[c]}}else s[i.toLowerCase()]=n[i];return s}a(r,"squashObj")}a(ra,"flattenConfig");function vp(e,t){if(e===Br.CLUSTERING_NODENAME||e===Br.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(l2(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||vt.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return vt.autoCast(t)}a(vp,"castConfigValue");function y2(){let e=vt.getPropsFilePath(),t=zi(e);return si(t).toJSON()}a(y2,"getConfiguration");async function I2(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return jw(void 0,void 0,s,!0),T2}catch(i){throw typeof i=="string"||i instanceof String?d2(i,i,f2.BAD_REQUEST,void 0,void 0,!0):i}}a(I2,"setConfiguration");function xp(){let e=vt.getPropsFilePath();try{cr.accessSync(e,cr.constants.F_OK|cr.constants.R_OK)}catch(n){if(!vt.noBootFile())throw bt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return si(t).toJSON()}a(xp,"readConfigFile");function si(e){return u2.parseDocument(cr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(si,"parseYamlDoc");function w2(){let e=xp(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=vt.isEmptyOrZeroLength(t)?[]:t;let r=Kw(t);if(r)throw nd.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=vt.isEmptyOrZeroLength(n)?[]:n;let s=Kw(n);if(s)throw nd.CONFIG_VALIDATION(s.message);if(!vt.isEmptyOrZeroLength(n)&&!vt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!vt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw nd.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(w2,"getClusteringRoutes");function Zw(e){let t=Qw(e);Nt={};for(let r in Pn){let n=t.get(r.toUpperCase());if(vt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Pn[r].toLowerCase();s===Br.LOGGING_ROOT?Nt[s]=Un.dirname(n):Nt[s]=n}return Nt}a(Zw,"initOldConfig");function C2(e){let t=xp();return _2.get(t,e.replaceAll("_","."))}a(C2,"getConfigFromFile");async function D2(e,t){let r=si(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await cr.writeFile(zi(),String(r))}a(D2,"addConfig");function L2(e){let t=zi(vt.getPropsFilePath()),r=si(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Un.join(n,Hr.HDB_CONFIG_FILE);cr.writeFileSync(s,String(r))}a(L2,"deleteConfigFromFile");function M2(){return id||(Bp(),id)}a(M2,"getConfigObj")});var rC=T((Fle,tC)=>{"use strict";var od=M(),ad=class{static{a(this,"BaseLicense")}constructor(t=0,r=od.RAM_ALLOCATION_ENUM.DEFAULT,n=od.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},Fp=class extends ad{static{a(this,"ExtendedLicense")}constructor(t=0,r=od.RAM_ALLOCATION_ENUM.DEFAULT,n=od.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};tC.exports={BaseLicense:ad,ExtendedLicense:Fp}});var Ji=T((Gle,cC)=>{"use strict";var sa=require("fs-extra"),sC=ed(),iC=require("crypto"),U2=require("moment"),P2=require("uuid").v4,zt=Y(),Gp=require("path"),v2=J(),ii=M(),{totalmem:nC}=require("os"),B2=rC().ExtendedLicense,na="invalid license key format",H2="061183",x2="mofi25",F2="aes-256-cbc",q2=16,G2=32,oC=j();oC.initSync();var qp;cC.exports={validateLicense:aC,generateFingerPrint:V2,licenseSearch:$p,getLicense:K2,checkMemoryLimit:W2};function kp(){return Gp.join(oC.getHdbBasePath(),ii.LICENSE_KEY_DIR_NAME,ii.LICENSE_FILE_NAME)}a(kp,"getLicenseDirPath");function k2(){let e=kp();return Gp.join(e,ii.LICENSE_FILE_NAME)}a(k2,"getLicenseFilePath");function Vp(){let e=kp();return Gp.join(e,ii.REG_KEY_FILE_NAME)}a(Vp,"getFingerPrintFilePath");async function V2(){let e=Vp();try{return await sa.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await $2();throw zt.error(`Error writing fingerprint file to ${e}`),zt.error(t),new Error("There was an error generating the fingerprint")}}a(V2,"generateFingerPrint");async function $2(){let e=P2(),t=sC.hash(e),r=Vp();try{await sa.mkdirp(kp()),await sa.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw zt.error(`Error writing fingerprint file to ${r}`),zt.error(n),new Error("There was an error generating the fingerprint")}return t}a($2,"writeFingerprint");function aC(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ii.RAM_ALLOCATION_ENUM.DEFAULT,version:ii.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return zt.error("empty license key passed to validate."),r;let n=Vp(),s=!1;try{s=sa.statSync(n)}catch(i){zt.error(i)}if(s){let i;try{i=sa.readFileSync(n,"utf8")}catch{zt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(x2),c=o[1];c=Buffer.concat([Buffer.from(c)],q2);let u=Buffer.concat([Buffer.from(i)],G2),_=iC.createDecipheriv(F2,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=Y2(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(na),zt.error(na),new Error(na)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(na),zt.error(na),new Error(na)}else r.exp_date=l;r.exp_date<U2().valueOf()&&(r.valid_date=!1),sC.validate(o[1],`${H2}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||zt.error("Invalid licence"),r}a(aC,"validateLicense");function Y2(e,t){try{let r=iC.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{zt.warn("Check old license failed")}}a(Y2,"checkOldLicense");function $p(){let e=new B2,t=[];try{t=sa.readFileSync(k2(),"utf-8").split(ii.NEW_LINE)}catch(r){r.code==="ENOENT"?zt.info("no license file found"):zt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(v2.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=aC(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){zt.error("There was an error parsing the license string."),zt.error(s),e.ram_allocation=ii.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return qp=e,e}a($p,"licenseSearch");async function K2(){return qp||await $p(),qp}a(K2,"getLicense");function W2(){let e=$p().ram_allocation,t=process.constrainedMemory?.()||nC();if(t=Math.round(Math.min(t,nC())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(W2,"checkMemoryLimit")});var cn=T((Kle,bC)=>{"use strict";var dC="username is required",fC="nothing to update, must supply active, role or password to update",EC="password cannot be an empty string",hC="If role is specified, it cannot be empty.",mC="active must be true or false";bC.exports={addUser:rJ,alterUser:nJ,dropUser:iJ,getSuperUser:uJ,userInfo:oJ,listUsers:ud,listUsersExternal:aJ,setUsersToGlobal:oa,findAndValidateUser:AC,getClusterUser:lJ,USERNAME_REQUIRED:dC,ALTERUSER_NOTHING_TO_UPDATE:fC,EMPTY_PASSWORD:EC,EMPTY_ROLE:hC,ACTIVE_BOOLEAN:mC};var pC=on(),Q2=Ki(),Wp=ed(),SC=Bw(),TC=sn(),Qp=gs(),Fr=J(),gC=require("validate.js"),ge=Y(),{promisify:z2}=require("util"),zp=bs(),uC=M(),lC=nt(),J2=xr(),Vle=j(),$le=Ji(),X2=Pi(),{table:Yle}=(Oe(),ee(Ge)),{handleHDBError:jn,hdb_errors:j2}=Z(),{HTTP_STATUS_CODES:Zn,AUTHENTICATION_ERROR_MSGS:Yp,HDB_ERROR_MSGS:ia}=j2,{UserEventMsg:Jp}=In(),Kp=require("lodash"),{server:Xp}=(Zt(),ee(yi)),Z2=Y();Xp.getUser=(e,t)=>AC(e,t,t!=null);var RC={username:!0,active:!0,role:!0,password:!0},_C=new Map,cd=TC.searchByValue,eJ=TC.searchByHash,tJ=z2(Q2.delete);async function rJ(e){let t=gC.cleanAttributes(e,RC),r=SC.addUserValidation(t);if(r)throw jn(new Error,r.message,Zn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await cd(n),s=s&&Array.from(s)}catch(u){throw ge.error("There was an error searching for a role in add user"),ge.error(u),u}if(!s||s.length<1)throw jn(new Error,ia.ROLE_NAME_NOT_FOUND(t.role),Zn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw jn(new Error,ia.DUP_ROLES_FOUND(t.role),Zn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=zp.encrypt(t.password)),t.password=Wp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await pC.insert(i)}catch(u){throw ge.error("There was an error searching for a user."),ge.error(u),u}ge.debug(o);try{await oa()}catch(u){throw ge.error("Got an error setting users to global"),ge.error(u),u}if(o.skipped_hashes.length===1)throw jn(new Error,ia.USER_ALREADY_EXISTS(t.username),Zn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],Qp.signalUserChange(new Jp(process.pid)),`${c.username} successfully added`}a(rJ,"addUser");async function nJ(e){let t=gC.cleanAttributes(e,RC);if(Fr.isEmptyOrZeroLength(t.username))throw new Error(dC);if(Fr.isEmptyOrZeroLength(t.password)&&Fr.isEmptyOrZeroLength(t.role)&&Fr.isEmptyOrZeroLength(t.active))throw new Error(fC);if(!Fr.isEmpty(t.password)&&Fr.isEmptyOrZeroLength(t.password.trim()))throw new Error(EC);if(!Fr.isEmpty(t.active)&&!Fr.isBoolean(t.active))throw new Error(mC);let r=sJ(t.username);if(!Fr.isEmpty(t.password)&&!Fr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=zp.encrypt(t.password)),t.password=Wp.hash(t.password)),t.role==="")throw new Error(hC);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 cd(i)||[])}catch(c){throw ge.error("Got an error searching for a role."),ge.error(c),c}if(!o||o.length===0){let c=ia.ALTER_USER_ROLE_NOT_FOUND(t.role);throw ge.error(c),jn(new Error,c,Zn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=ia.ALTER_USER_DUP_ROLES(t.role);throw ge.error(c),jn(new Error,c,Zn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await pC.update(n)}catch(i){throw ge.error("Error during update."),ge.error(i),i}try{await oa()}catch(i){throw ge.error("Got an error setting users to global"),ge.error(i),i}return Qp.signalUserChange(new Jp(process.pid)),s}a(nJ,"alterUser");function sJ(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(sJ,"isClusterUser");async function iJ(e){try{let t=SC.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Fr.isEmpty(global.hdb_users.get(e.username)))throw jn(new Error,ia.USER_NOT_EXIST(e.username),Zn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await tJ(r)}catch(s){throw ge.error("Got an error deleting a user."),ge.error(s),s}ge.debug(n);try{await oa()}catch(s){throw ge.error("Got an error setting users to global."),ge.error(s),s}return Qp.signalUserChange(new Jp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(iJ,"dropUser");async function oJ(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Kp.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await eJ(r)}catch(s){throw ge.error("Got an error searching for a role."),ge.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw ge.error(r),r}return t}a(oJ,"userInfo");async function aJ(){let e;try{e=await ud()}catch(t){throw ge.error("Got an error listing users."),ge.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(aJ,"listUsersExternal");async function ud(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await cd(e)}catch(o){throw ge.error("Got an error searching for roles."),ge.error(o),o}let r={};for(let o of t)r[o.id]=Kp.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await cd(n)}catch(o){throw ge.error("Got an error searching for users."),ge.error(o),o}let i=new Map;for(let o of s)o=Kp.cloneDeep(o),o.role=r[o.role],cJ(o.role),i.set(o.username,o);return i}catch(e){throw ge.error("got an error listing users"),ge.error(e),Fr.errorizeMessage(e)}return null}a(ud,"listUsers");function cJ(e){try{if(!e){ge.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(X2)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){ge.error("Got an error trying to set system permissions."),ge.error(t)}}a(cJ,"appendSystemTablesToRole");async function oa(){try{let e=await ud();global.hdb_users=e}catch(e){throw ge.error(e),e}}a(oa,"setUsersToGlobal");async function AC(e,t,r=!0){global.hdb_users||await oa();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw jn(new Error,Yp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw jn(new Error,Yp.USER_INACTIVE,Zn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(_C.get(t)===n.password)return s;if(Wp.validate(n.password,t))_C.set(t,n.password);else throw jn(new Error,Yp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(AC,"findAndValidateUser");async function uJ(){global.hdb_users||await oa();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(uJ,"getSuperUser");async function lJ(){let e=await ud(),t=J2.getConfigFromFile(uC.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Fr.isEmpty(r)&&r?.role?.role===uC.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=zp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+lC.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+lC.SERVER_SUFFIX.ADMIN,r}a(lJ,"getClusterUser");var OC=[];Xp.invalidateUser=function(e){for(let t of OC)try{t(e)}catch(r){Z2.error("Error invalidating user",r)}};Xp.onInvalidatedUser=function(e){OC.push(e)}});var Jc=T((Jle,wC)=>{"use strict";var Xi=Y(),qr=M(),_J=Lb(),Qle=ti(),zle=Gi(),dJ=cn(),{validateEvent:NC}=In(),zc=Ln(),fJ=require("process"),{resetDatabases:EJ}=(Oe(),ee(Ge)),hJ={[qr.ITC_EVENT_TYPES.SCHEMA]:mJ,[qr.ITC_EVENT_TYPES.USER]:IC};async function mJ(e){let t=NC(e);if(t){Xi.error(t);return}Xi.trace("ITC schemaHandler received schema event:",e),await _J(e.message),await pJ(e.message)}a(mJ,"schemaHandler");async function pJ(e){try{zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=EJ();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Xi.error(t)}}a(pJ,"syncSchemaMetadata");var yC=[];async function IC(e){try{try{zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),zc.resetReadTxn(qr.SYSTEM_SCHEMA_NAME,qr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Xi.warn(r)}let t=NC(e);if(t){Xi.error(t);return}Xi.trace(`ITC userHandler ${qr.HDB_ITC_CLIENT_PREFIX}${fJ.pid} received user event:`,e),await dJ.setUsersToGlobal();for(let r of yC)r()}catch(t){Xi.error(t)}}a(IC,"userHandler");IC.addListener=function(e){yC.push(e)};wC.exports=hJ});var In=T((r_e,DC)=>{"use strict";var jle=Y(),jp=J(),SJ=M(),{ITC_ERRORS:Xc}=wr(),{parentPort:Zle,threadId:TJ,isMainThread:gJ,workerData:e_e}=require("worker_threads"),{onMessageFromWorkers:RJ,broadcast:t_e,broadcastWithAcknowledgement:AJ}=tt();DC.exports={sendItcEvent:OJ,validateEvent:CC,SchemaEventMsg:bJ,UserEventMsg:NJ};var ld;RJ(async(e,t)=>{ld=ld||Jc(),CC(e),ld[e.type]&&await ld[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function OJ(e){return!gJ&&e.message&&(e.message.originator=TJ),AJ(e)}a(OJ,"sendItcEvent");function CC(e){if(typeof e!="object")return Xc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||jp.isEmpty(e.type))return Xc.MISSING_TYPE;if(!e.hasOwnProperty("message")||jp.isEmpty(e.message))return Xc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||jp.isEmpty(e.message.originator))return Xc.MISSING_ORIGIN;if(SJ.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Xc.INVALID_EVENT(e.type)}a(CC,"validateEvent");function bJ(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(bJ,"SchemaEventMsg");function NJ(e){this.originator=e}a(NJ,"UserEventMsg")});var gs=T((i_e,PC)=>{"use strict";var LC=M(),s_e=J(),_d=Y(),MC=fb(),aa,{sendItcEvent:UC}=In();function yJ(e){try{_d.trace("signalSchemaChange called with message:",e),aa=aa||Jc();let t=new MC(LC.ITC_EVENT_TYPES.SCHEMA,e);return aa.schema(t),UC(t)}catch(t){_d.error(t)}}a(yJ,"signalSchemaChange");function IJ(e){try{_d.trace("signalUserChange called with message:",e),aa=aa||Jc();let t=new MC(LC.ITC_EVENT_TYPES.USER,e);return aa.user(t),UC(t)}catch(t){_d.error(t)}}a(IJ,"signalUserChange");PC.exports={signalSchemaChange:yJ,signalUserChange:IJ}});var tu={};qe(tu,{addAnalyticsListener:()=>eu,recordAction:()=>Gr,recordActionBinary:()=>un,setAnalyticsEnabled:()=>wJ});function wJ(e){$C=e}function Gr(e,t,r,n,s){if(!$C)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Ed.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},Ed.set(i,o)}dd||CJ()}function un(e,t,r,n,s){Gr(!!e,t,r,n,s)}function eu(e){WC.push(e)}function CJ(){dd=performance.now(),setTimeout(async()=>{let e=performance.now()-dd;dd=0;let t=[],r={time:Date.now(),period:e,threadId:ji.threadId,metrics:t};for(let[s,i]of Ed){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of QC){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let S=_[_.length-1];typeof S=="number"?_[_.length-1]={value:S,count:1+h}:S.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await zC()}let n=process.memoryUsage();t.push({metric:"memory",threadId:ji.threadId,byThread:!0,...n});for(let s of WC)s(t);Ed=new Map,ji.parentPort?ji.parentPort.postMessage({type:KC,report:r}):jC({report:r})},YC).unref()}async function DJ(e,t=6e4){let r=tS(),n=JC(),s;for(let h of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){s=h.value.time;break}if(Date.now()-t<s)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:S}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:p,threadId:g}=S;for(let A of p||[]){let{path:b,method:v,type:G,metric:H,count:P,total:z,distribution:W,threads:Q,...se}=A;P||(P=1);let pe=H+(b?"-"+b:"");v!==void 0&&(pe+="-"+v),G!==void 0&&(pe+="-"+G);let oe=o.get(pe);if(oe){if(oe.threads){let ce=oe.threads[g];if(ce)oe=ce;else{oe.threads[g]=Object.assign({},se);continue}}oe.count||(oe.count=1);let Fe=oe.count;for(let ce in se){let Lt=se[ce];typeof Lt=="number"&&(oe[ce]=(oe[ce]*Fe+Lt*P)/(Fe+P))}oe.count+=P,z>=0&&(oe.total+=z,oe.ratio=oe.total/oe.count)}else oe=Object.assign({period:t},A),delete oe.distribution,o.set(pe,oe),oe.byThread&&(oe.threads=[],oe.threads[g]=Object.assign({},se),u.push(oe));if(W){W=W.map(ce=>typeof ce=="number"?{value:ce,count:1}:ce);let Fe=c.get(pe);Fe?Fe.push(...W):c.set(pe,W)}}await zC()}for(let h of u){let{path:S,method:p,type:g,metric:A,count:b,total:v,distribution:G,threads:H,...P}=h;H=H.filter(z=>z);for(let z in P){if(typeof h[z]!="number")continue;let W=0;for(let Q of H){let se=Q[z];typeof se=="number"&&(W+=se)}h[z]=W}h.count=H.length,delete h.threads,delete h.byThread}for(let[h,S]of c){let p=o.get(h);S.sort((ce,Lt)=>ce.value>Lt.value?1:-1);let g=p.count-1,A=[],b=0,v=0,G;for(let ce of QC){let Lt=g*ce;for(;b<Lt;)G=S[v++],b+=G.count,v===1&&b--;let Il=S[v>1?v-2:0];G||(G=S[0]),A.push(G.value-(G.value-Il.value)*(b-Lt)/G.count)}let[H,P,z,W,Q,se,pe,oe,Fe]=A;Object.assign(p,{p1:H,p10:P,p25:z,median:W,p75:Q,p90:se,p95:pe,p99:oe,p999:Fe})}let l;for(let[h,S]of o)S.id=(0,fd.getNextMonotonicTime)(),S.time=_,n.primaryStore.put(S.id,S,{append:!0}).then(p=>{p||n.primaryStore.put(S.id,S)}),l=!0;let d=Date.now(),{idle:f,active:E}=performance.eventLoopUtilization();if(l||E*10>f){let h=(0,fd.getNextMonotonicTime)(),S={id:h,metric:"main-thread-utilization",idle:f-vC,active:E-BC,time:d,...process.memoryUsage()};n.primaryStore.put(h,S,{append:!0}).then(p=>{p||n.primaryStore.put(h,S)})}vC=f,BC=E}async function HC(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function tS(){return xC||(xC=_t({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function JC(){return FC||(FC=_t({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function UJ(){XC=!0;let e=(0,Zc.get)(eS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await DJ(YC,e),await HC(tS(),LJ),await HC(JC(),MJ)},Math.min(e/2,2147483647)).unref()}function jC(e,t){let r=e.report;r.threadId=t?.threadId||ji.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(qC+=n.mean*n.count);r.totalBytesProcessed=qC,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(GC.get(t))}),GC.set(t,t.performance.eventLoopUtilization())),r.id=(0,fd.getNextMonotonicTime)(),tS().primaryStore.put(r.id,r),XC||UJ(),PJ&&(ZC=BJ(r))}async function BJ(e){if(await ZC,!oi){let r=(0,jc.dirname)((0,VC.getLogFilePath)());try{oi=await(0,Zp.open)((0,jc.join)(r,"analytics.log"),"r+")}catch{oi=await(0,Zp.open)((0,jc.join)(r,"analytics.log"),"w+")}}let t=(await oi.stat()).size;if(t>vJ){let r=Buffer.alloc(t);await oi.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await oi.write(r,{position:0}),await oi.truncate(r.length),t=r.length}await oi.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var ji,kC,VC,jc,Zp,fd,Zc,eS,Ed,$C,dd,YC,KC,WC,QC,vC,BC,zC,LJ,MJ,xC,FC,XC,qC,GC,PJ,ZC,oi,vJ,Ns=Re(()=>{ji=require("worker_threads"),kC=B(tt());Oe();VC=B(Y()),jc=require("path"),Zp=require("fs/promises"),fd=B(Cr()),Zc=B(j()),eS=B(M());Zt();(0,Zc.initSync)();Ed=new Map,$C=(0,Zc.get)(eS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(wJ,"setAnalyticsEnabled");a(Gr,"recordAction");ut.recordAnalytics=Gr;a(un,"recordActionBinary");dd=0,YC=1e3,KC="analytics-report",WC=[];a(eu,"addAnalyticsListener");QC=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(CJ,"sendAnalytics");a(DJ,"aggregation");vC=0,BC=0,zC=a(()=>new Promise(setImmediate),"rest");a(HC,"cleanup");LJ=36e5,MJ=31536e6;a(tS,"getRawAnalyticsTable");a(JC,"getAnalyticsTable");(0,kC.setChildListenerByType)(KC,jC);a(UJ,"startScheduledTasks");qC=0,GC=new Map,PJ=!1;a(jC,"recordAnalytics");vJ=1e6;a(BJ,"logAnalytics")});var iS={};qe(iS,{coerceType:()=>hd,makeTable:()=>Sd,setServerUtilities:()=>YJ,updateResource:()=>md});function Sd(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:S}=e;S||(S=[]),lb(i,u);let p=Nh(i,n,u),g=0,A,b,v={},G=Promise.resolve(),H,P,z;for(let $ of S)($.assignCreatedTime||$.name==="__createdtime__")&&(H=$),($.assignUpdatedTime||$.name==="__updatedtime__")&&(P=$),$.expiresAt&&(z=$),$.isPrimaryKey&&(v=$);let W,Q=[],se=[],pe=1,oe=2,Fe={},ce={},Lt=864e5,Il,wl,Vs,gA=!1,QE,Qx=i.getRange({start:!1,end:!1}).constructor,zx=10,Jx=6;E&&OA();class ze extends Ft{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=H;static updatedTimeProperty=P;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,R){R&&(this.sourceOptions=R,(R.expiration||R.eviction||R.scanInterval)&&this.setTTLExpiration(R)),R?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),b=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(y=>{let I=this.sources.slice(0,-1);if(I=I.filter(U=>U[y]&&(!U[y].reliesOnPrototype||U.prototype[y])),I.length>0)if(I.length===1){let U=I[0];return(L,D,x)=>{if(L?.source!==U)return U[y](D,x,L)}}else return(U,L,D)=>{let x=[];for(let k of I){if(U?.source===k)break;x.push(k[y](L,D,U))}return Promise.all(x)}},"getApplyToIntermediateSource"),O=this.sources[this.sources.length-1],N=a(y=>{if(O[y]&&(!O[y].reliesOnPrototype||O.prototype[y]))return(I,U,L)=>{if(!I?.source)return O[y](U,L,I)}},"getApplyToCanonicalSource");return Fe={put:N("put"),patch:N("patch"),delete:N("delete"),publish:N("publish")},ce={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let y=!1,I=a(async(U,L)=>{let D=U.value,x=U.table?st[c][U.table]:ze;if(c===vn.SYSTEM_SCHEMA_NAME&&(U.table===vn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===vn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(y=!0),U.id===void 0&&(U.id=D[x.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let k=await x.getResource(U.id,L,ca);switch(U.type){case"put":return k._writeUpdate(D,!0,ca);case"patch":return k._writeUpdate(D,!1,ca);case"delete":return k._writeDelete(ca);case"publish":return k._writePublish(D,ca);case"invalidate":return k.invalidate(ca);default:Ze.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&h==null&&(h=!0);let L=m.subscribeOnThisThread?m.subscribeOnThisThread((0,eo.getWorkerIndex)()):(0,eo.getWorkerIndex)()===0,D=U&&L&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let x;for await(let k of D)try{if(!(k.type==="transaction"?k.writes[0]:k)){Ze.error("Bad subscription event",k);continue}if(k.source=m,x)if(k.beginTxn)x.resolve();else{I(k,x);continue}if(k.type==="end_txn")continue;let de=Xe(k,()=>{if(k.type==="transaction"){let te=[];for(let ne of k.writes)try{te.push(I(ne,k))}catch(Be){throw Be.message+=" writing "+JSON.stringify(ne)+" of event "+JSON.stringify(k),Be}return Promise.all(te)}else if(k.type==="define_schema"){let te=this.attributes.slice(0),ne;for(let Be of k.attributes)te.find(ie=>ie.name===Be.name)||(te.push(Be),ne=!0);ne&&(_t({table:s,database:c,attributes:te,origin:"cluster"}),cu.signalSchemaChange(new uu.SchemaEventMsg(process.pid,vn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return k.beginTxn?(x=k,I(k,k),new Promise(te=>{x.resolve=te})):I(k,k)});y&&(await de,cu.signalUserChange(new uu.UserEventMsg(process.pid))),k.onCommit&&(de?.then?de.then(k.onCommit):k.onCommit())}catch(_e){Ze.error("error in subscription handler",_e)}}}catch(U){Ze.error(U)}})(),this}static getResource(m,R,w){let O=super.getResource(m,R,w);if(m!=null){Qa(m);try{if(O.hasOwnProperty(be))return O;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let N=!w?.async||i.cache?.get(m),y=br(R),I=y.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return zE(m,R,{transaction:I},N,U=>{if(U?md(O,U):O[be]=null,R.onlyIfCached&&R.noCacheStore){if(!O.doesExist())throw new ln.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let L=JE(m,U,R,O);if(L)return y?.disregardReadTxn(),O[rS]=!0,sS(L,D=>(md(O,D),O))}return O})}catch(N){throw N.message.includes("Unable to serialize object")&&(N.message+=": "+JSON.stringify(m)),N}}return O}ensureLoaded(){let m=JE(this[Ce],this[kr],this[Ae]);if(m)return this[rS]=!0,sS(m,R=>{this[kr]=R,this[be]=R.value,this[ou]=R.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,Lt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");Lt=Lt||(d+f)/4,jE()}static enableAuditing(m=!0){E=m,m&&OA(),ze.audit=m}static coerceId(m){return m===""?null:hd(m,v)}static async dropTable(){if(delete st[c][s],c===o){for(let m of S)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));cu.signalSchemaChange(new uu.SchemaEventMsg(process.pid,vn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[rn])return this.search(m);if(this[Ce]===null){if(m?.conditions)return this.search(m);let R=ze.getRecordCount();return{recordCount:R.recordCount,estimatedRecordRange:R.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Ae]?.returnNonexistent)return this}allowRead(m,R){let w=Dl(m);if(w?.read){if(w.isSuperUser)return!0;let O=w.attribute_permissions,N=R?.select;if(O?.length>0||gA&&N){if(R||(R={}),N){let y=O?.length>0&&nS(O,"read");R.select=N.map(I=>{let U=I.name||I;if(!y||y[U]){let L=Vs[U]?.definition?.tableClass;if(L){if(I.name||(I={name:I}),!L.prototype.allowRead.call(null,m,I))return!1;if(!I.select)return I.name}return I}}).filter(Boolean)}else R.select=O.filter(y=>y.read&&!Vs[y.attribute_name]).map(y=>y.attribute_name);return R}else return!0}}allowUpdate(m,R){let w=Dl(m);if(w?.update){let O=w.attribute_permissions;if(O?.length>0){let N=nS(O,"update");for(let y in R)if(!N[y])return!1;for(let y of O){let I=y.attribute_name;!y.update&&!(I in R)&&(R[I]=this.getProperty(I))}}return!0}}allowCreate(m,R){if(this[rn]){let w=Dl(m);if(w?.insert){let O=w.attribute_permissions;if(O?.length>0){let N=nS(O,"insert");for(let y in R)if(!N[y])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Dl(m)?.delete}update(m,R){if(!br(this[Ae]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let O;return typeof m=="object"&&m&&(R?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[be]={},this[Ot]=m):(O=this[Ot],O&&(m=Object.assign(O,m)),this[Ot]=O=m)),this._writeUpdate(this[Ot],R),this}addTo(m,R){if(typeof R=="number")this[ru]===tD?this.set(m,(+this.getProperty(m)||0)+R):(this[ru]||this.update(),this.set(m,new i_(R)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,R){if(typeof R=="number")return this.addTo(m,-R);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let R=this[Ae],w=this[Ce];Qa(w),br(this[Ae]).addWrite({key:w,store:i,invalidated:!0,entry:this[kr],nodeName:this[Ae]?.nodeName,before:Fe.invalidate?.bind(this,R,w),beforeIntermediate:ce.invalidate?.bind(this,R,w),commit:(N,y)=>{if(y?.version>N)return;let I=null;for(let U in r)I||(I={}),I[U]=this.getProperty(U);p(w,I,this[kr],N,nu,E,this[Ae],0,"invalidate")}})}static evict(m,R,w){let O=this.Source,N;if(!((b||E)&&(!R||(N=i.getEntry(m),!N||!R)||N.version!==w))){if(b){if(i.hasLock(m,N.version))return;let y;for(let I in r)y||(y={}),y[I]=R[I];if(y)return p(m,y,N,w,su,null,null,0,null,!0)}return i.ifVersion(w,()=>{Cl(m,R,null)}),E?p(m,null,N,w,su,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,R){return m.table||=s,m.schema||=c,aD.operation(m,R)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,R,w){let O=this[Ae],N=br(O),y=this[Ce];Qa(y);let I=this[kr];this[ru]=R?tD:kJ;let U={key:y,store:i,entry:I,nodeName:O?.nodeName,validate:L=>{m||(m=this[Ot]),R||m&&n_(m)?(this.validate(m,!R),O?.source||(P&&(m[P.name]=P.type==="Date"?new Date(L):P.type==="String"?new Date(L).toISOString():L),R&&(t&&m[t]!==y&&(m[t]=y),H&&(I?.value?m[H.name]=I?.value[H.name]:m[H.name]=H.type==="Date"?new Date(L):H.type==="String"?new Date(L).toISOString():L),m=Li(m)))):N.removeWrite(U)},before:R?Fe.put?()=>Fe.put(O,y,m):null:Fe.patch?()=>Fe.patch(O,y,m):Fe.put?()=>Fe.put(O,y,Li(this)):null,beforeIntermediate:R?ce.put?()=>ce.put(O,y,m):null:ce.patch?()=>ce.patch(O,y,m):ce.put?()=>ce.put(O,y,Li(this)):null,commit:(L,D,x)=>{x&&(O&&D?.version>(O.lastModified||0)&&(O.lastModified=D.version),this[kr]=D,R||(this[be]=D?.value??null)),this[Ot]=m,this[ou]=L;let k=D?.value,_e=m;if(this[ru]=0,D?.version>L)if(E){let Be=D.localTime,ie=D.version;for(;_e&&(Be>L||ie>L&&Be>0);){let fe=u.get(Be),Ye=Ut(fe);if(ie=Ye.version,ie>L)if(Ye.type==="patch"){let Me=Ye.getValue(i);_e=t_(_e,Me)}else(Ye.type==="put"||Ye.type==="delete")&&(_e=null);Be=Ye.previousLocalTime}}else R?_e=null:_e=t_(_e,k);let de=Li(this,_e);this[be]=de;let te;R||(te=m),Cl(y,k,de);let ne=R?"put":"patch";p(y,de,D,L,0,E,O,O.expiresAt||(d?d+Date.now():0),ne,!1,te)}};N.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[rn]){for await(let R of this.search(m))(await ze.getResource(R[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[be]?this._writeDelete(m):!1}_writeDelete(m){let R=br(this[Ae]),w=this[Ce];Qa(w);let O=this[Ae];return R.addWrite({key:w,store:i,resource:this,nodeName:O?.nodeName,before:Fe.delete?.bind(this,O,w),beforeIntermediate:ce.delete?.bind(this,O,w),commit:(N,y,I)=>{let U=y?.value;I&&(O&&y?.version>(O.lastModified||0)&&(O.lastModified=y.version),md(this,y)),!(y?.version>N)&&(Cl(this[Ce],U),Ze.trace("Write delete entry",w,N),E||h?(p(w,null,this[kr],N,0,E,this[Ae],0,"delete"),E||jE()):i.remove(this[Ce]))}}),!0}search(m){let R=this[Ae],w=br(R);if(!m)throw new Error("No query provided");let O=m.conditions;O?O.length===void 0&&(O=O[Symbol.iterator]?Array.from(O):[O]):O=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Ce]&&(O=[{attribute:null,comparator:"prefix",value:this[Ce]}].concat(O));let N,y={};function I(re,je){let Ke;switch(je){case"and":case void 0:if(re.length<1)throw new Error('An "and" operator requires at least one condition');Ke=!0;break;case"or":if(re.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+je)}let Mt=Ke&&{},Nr;for(let Ue of re){if(Ue.conditions){Ue.conditions=I(Ue.conditions,Ue.operator);continue}let xe=Ue[0]??Ue.attribute,yr=xe==null?v:ps(S,xe);if(yr){if(Ke){let _s=bn(xe),jr=Mt[_s];jr?(jr.push(Ue),Nr=!0):Mt[_s]=[Ue]}(yr.type||Fh[Ue.comparator])&&(Ue[1]===void 0?Ue.value=L(Ue.value,yr):Ue[1]=L(Ue[1],yr))}else if(xe!=null)throw(0,ln.handleHDBError)(new Error,`${xe} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return re;if(Nr)for(let Ue in Mt){let xe=Mt[Ue],yr=xe.length;if(yr>1)for(let _s=0;_s<yr;_s++){let jr=xe[_s];if(jr.comparator==="ge"||jr.comparator==="greater_than_equal")for(let $s=0;$s<yr;$s++){let Lo=xe[$s];(Lo.comparator==="le"||Lo.comparator==="less_than_equal")&&(jr.comparator="between",jr.value=[jr.value,Lo.value],re.splice(re.indexOf(Lo),1))}if(jr.comparator==="equals"||!jr.comparator){for(let $s=0;$s<yr;$s++)if($s!==_s){let Lo=xe[$s];re.splice(re.indexOf(Lo),1)}break}}}return re}a(I,"prepareConditions");function U(re,je){if(m.enforceExecutionOrder)return re;for(let Ke of re)Ke.conditions&&(Ke.conditions=U(Ke.conditions,Ke.operator));return re.length>1&&je!=="or"?(0,oD.sortBy)(re,l_(ze)):re}a(U,"orderConditions");function L(re,je){return Array.isArray(re)?re.map(Ke=>hd(Ke,je)):hd(re,je)}a(L,"coerceTypedValues");let D=m.operator;(O.length>0||D)&&(O=I(O,D));let x=typeof m.sort=="object"&&m.sort,k;if(x&&D!=="or"){let re=x.attribute;if(N=O.find(je=>bn(je.attribute)===bn(re)),!N){if(!ps(S,re))throw(0,ln.handleHDBError)(new Error,`${Array.isArray(re)?re.join("."):re} is not a defined attribute`,404);N={attribute:re},O.push(N)}N.descending=!!x.descending}O=U(O,D),x&&(O[0]===N?x.next&&(k={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(N&&O.splice(O.indexOf(N),1),k=x));function _e(re,je){let Ke=re[0];if(je==="or"){let Mt=te(Ke);for(let Ue=1;Ue<re.length;Ue++){let xe=re[Ue],yr=te(xe);Mt=Mt.concat(yr)}let Nr=new Set;return Mt.filter(Ue=>{let xe=Ue.key??Ue;return Nr.has(xe)?!1:(Nr.add(xe),!0)})}else{let Mt=te(Ke),Nr=Ke.estimated_count,Ue=re.slice(1).map((xe,yr)=>{let _s=(xe.attribute||xe[0])===t,jr=hc(xe,ze,R,y,_s,Nr);return yr<re.length-2&&Nr&&(Nr=tb(i,xe.estimated_count,Nr)),jr}).filter(Boolean);return Ue.length>0?RA(Mt,ne,R,Ue):Mt}}a(_e,"executeConditions");let de=m.reverse===!0;function te(re){return re.conditions?_e(re.conditions,re.operator):Go(re,w,re.descending||de,ze,m.allowFullScan,y)}a(te,"executeCondition");let ne=m.select;if(O.length===0&&(O=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:O,operator:D,postOrdering:k,selectApplied:!!ne};let Be=w.useReadTxn(),ie=_e(O,D);(m.offset||m.limit!==void 0)&&(ie=ie.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0));let fe=m.ensureLoaded!==!1,Ye=ze.transformEntryForSelect(ne,R,y,fe,!0),Me=ze.transformToOrderedSelect(ie,ne,k,R,Ye);return Me.onDone=()=>{Me.onDone=null,w.doneReadTxn()},Me.selectApplied=!0,Me.getColumns=()=>{if(ne){let re=[];for(let je of ne)je==="*"?re.push(...S.map(Ke=>Ke.name)):re.push(je.name||je);return re}return S.map(re=>re.name)},Me}static transformToOrderedSelect(m,R,w,O,N){let y=new Qx;if(w){m=RA(m,R,O,null);let I;y.iterate=function(){let L,D=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),x,k=w.dbOrderedAttribute,_e,de,te=!0;function ne(ie){let fe=ie.next&&ne(ie.next),Ye=ie.descending;return(Me,re)=>{let je=XE(Me,ie.attribute,O),Ke=XE(re,ie.attribute,O),Mt=Ye?(0,to.compareKeys)(Ke,je):(0,to.compareKeys)(je,Ke);return Mt===0?fe?.(Me,re)||0:Mt}}a(ne,"createComparator");let Be=ne(w);return{async next(){let ie;if(L)if(ie=L.next(),ie.done){if(x)return y.onDone&&y.onDone(),ie}else return{value:await N(ie.value)};I=[],_e&&I.push(_e);do if(ie=await D.next(),ie.done){if(x=!0,I.length)break;return y.onDone&&y.onDone(),ie}else{let fe=ie.value;if(fe?.then&&(fe=await fe),k){let Ye=XE(fe,k,O);if(te)te=!1,de=Ye;else if(Ye!==de){de=Ye,_e=fe;break}}I.push(fe)}while(!0);return w.isGrouped,I.sort(Be),L=I[Symbol.iterator](),ie=L.next(),ie.done?(y.onDone&&y.onDone(),ie):{value:await N(ie.value)}},return(){y.onDone&&y.onDone(),D.return()},throw(){y.onDone&&y.onDone(),D.throw()}}};let U=a(L=>{if(typeof R=="object"&&Array.isArray(L.attribute))for(let D=0;D<R.length;D++){let x=R[D],k;if(x.name===L.attribute[0]){for(k=x.sort||(x.sort={});k.next;)k=k.next;k.attribute=L.attribute.slice(1),k.descending=L.descending}else x===L.attribute[0]&&(R[D]=k={name:x,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&U(L.next)},"applySortingOnSelect");U(w)}else y.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),y=y.map(N);return y}static transformEntryForSelect(m,R,w,O,N){if(m&&(m===t||m?.length===1&&m[0]===t)){let L=a(D=>D?.key??D,"transform");return m===t?L:m.asArray?D=>[L(D)]:D=>({[t]:L(D)})}let y;O&&b&&!m?.every(L=>{let D;return typeof L=="object"?D=L.name:D=L,r[D]||D===t})&&(y=!0);let I,U=a(L=>{let D;if(L){if(QE=L,D=L.value||L.deref?.(),!D&&(L.key===void 0||L.deref)){if(L=zE(L.key??L,R,{transaction:br(R).getReadTxn(),lazy:m?.length<4},!1,x=>x),L?.then)return L.then(U);D=L?.value}if(y&&(L.metadataFlags&(nu|su)||L.expiresAt&&L.expiresAt<Date.now())){let x=JE(L.key??L,L,R);if(x?.then)return x.then(U)}}if(D==null)return N?Zi.SKIP:D;if(m&&!(m[0]==="*"&&m.length===1)){let x,k=a((de,te)=>{let ne;typeof de=="object"?ne=de.name:ne=de;let Be=Vs?.[ne],ie;if(Be){let fe=w?.[ne];if(fe)if(fe.hasMappings){let Me=Be.from?D[Be.from]:bn(L.key);ie=fe.get(Me),ie||(ie=[])}else ie=fe.fromRecord?.(D);else ie=Be(D,R,L);let Ye=a(Me=>{if(Me&&typeof Me=="object"){let re=Be.definition?.tableClass||ze;I||(I={});let je=I[ne]||(I[ne]=re.transformEntryForSelect(ne===de?null:de.select||(Array.isArray(de)?de:null),R,fe,O));if(Array.isArray(Me)){let Ke=[],Mt=re.transformToOrderedSelect(Me,de.select,typeof de.sort=="object"&&de.sort,R,je)[Symbol.asyncIterator](),Nr=a(xe=>{for(;!xe.done;){if(xe?.then)return xe.then(Nr);Ke.push(xe.value),xe=Mt.next()}te(Ke,ne)},"nextValue"),Ue=Nr(Mt.next());Ue&&(x||(x=[]),x.push(Ue));return}else if(Me=je(Me),Me?.then){x||(x=[]),x.push(Me.then(Ke=>te(Ke,ne)));return}}te(Me,ne)},"handleResolvedValue");ie?.then?(x||(x=[]),x.push(ie.then(Ye))):Ye(ie);return}else ie=D[ne],ie&&typeof ie=="object"&&ne!==de&&(ie=this.transformEntryForSelect(de.select||de,R,null)({value:ie}));te(ie,ne)},"selectAttribute"),_e;if(typeof m=="string")k(m,de=>{_e=de});else if(Array.isArray(m))if(m.asArray)_e=[],m.forEach((de,te)=>{de==="*"?m[te]=D:k(de,ne=>_e[te]=ne)});else{_e={};let de=m.forceNulls;for(let te of m)if(te==="*")for(let ne in D)_e[ne]=D[ne];else k(te,(ne,Be)=>{ne===void 0&&de&&(ne=null),_e[Be]=ne})}else throw new ln.ClientError("Invalid select"+m);return x?Promise.all(x).then(()=>_e):_e}return D},"transform");return U}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||_t({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let R=!m.rawEvents,w=cb(ze,this[Ce]??null,function(I,U,L,D){try{let x=U.getValue?.(i,R);if(!x&&U.type==="patch"&&R){let k=i.getEntry(I);k?.version===U.version?x=k.value:x=U.getValue?.(i,!0,L),U.type="put"}this.send({id:I,timestamp:L,value:x,version:U.version,type:U.type,beginTxn:D})}catch(x){Ze.error(x)}},m.startTime||0,this[rn]);this[rn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.crossThreads===!1&&(w.crossThreads=!1),m.supportsTransactions&&(w.supportsTransactions=!0);let O=this[Ce],N=m.previousCount;N>1e3&&(N=1e3);let y=m.startTime;if(this[rn]){if(y){if(N)throw new ln.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:I,value:U}of u.getRange({start:y,exclusiveStart:!0})){let L=Ut(U);if(L.tableId!==n)continue;let D=L.recordId;(O==null||sD(O,D))&&w.send({id:D,timestamp:I,...L}),w.startTime=I}}else if(N){let I=[];for(let{key:U,value:L}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Ut(L);if(D.tableId!==n)continue;let x=D.recordId;if(O==null||sD(O,x)){let k=D.getValue(i,R,U);if(I.push({id:x,timestamp:U,value:k,version:D.version,type:D.type}),--N<=0)break}}catch(D){Ze.error("Error getting history entry",U,D)}for(let U=I.length;U>0;)w.send(I[--U]);I[0]&&(w.startTime=I[0].timestamp)}else if(!m.omitCurrent)for(let{key:I,value:U,version:L,localTime:D}of i.getRange({start:O??!1,end:O==null?void 0:[O,to.MAXIMUM_KEY],versions:!0}))U&&w.send({id:I,version:L,timestamp:D,value:U})}else{N&&!y&&(y=0);let I=this[kr]?.localTime;if(I===bh&&(i.cache?.delete(O),this[kr]=i.getEntry(O),Ze.trace("re-retrieved record",I,this[kr]?.localTime),I=this[kr]?.localTime),Ze.trace("Subscription from",y,"from",O,I),y<I){let U=[],L=I;do{let D=u.get(L);if(D){m.omitCurrent=!0;let x=Ut(D),k=x.getValue(i,R,L);R&&(x.type="put"),U.push({id:O,value:k,timestamp:L,...x}),L=x.previousLocalTime}else break;N&&N--}while(L>y&&N!==0);for(let D=U.length;D>0;)w.send(U[--D]);w.startTime=I}!m.omitCurrent&&this.doesExist()&&w.send({id:O,version:this[ou],timestamp:I,value:this})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[be]||this[ru])}publish(m,R){this._writePublish(m,R)}_writePublish(m,R){let w=br(this[Ae]),O=this[Ce]||null;Qa(O);let N=this[Ae];w.addWrite({key:O,store:i,entry:this[kr],nodeName:N?.nodeName,validate:()=>{this.validate(m)},before:Fe.publish?.bind(this,N,O,m),beforeIntermediate:ce.publish?.bind(this,N,O,m),commit:(y,I,U)=>{I===void 0&&h&&!E&&jE(),p(O,I?.value??null,I,I?.version||y,0,!0,N,I?.expiresAt,"message",!1,m)}})}validate(m,R){let w,O=a((N,y,I)=>{if(y.type&&N!=null)if(R&&N.__op__&&(N=N.value),y.properties){typeof N!="object"&&(w||(w=[])).push(`Property ${I} must be an object${y.type?" ("+y.type+")":""}`);let U=y.properties;for(let L=0,D=U.length;L<D;L++){let x=U[L],k=O(N[x.name],x,I+"."+x.name);k&&(N[x.name]=k)}}else switch(y.type){case"Int":(typeof N!="number"||N>>0!==N)&&(w||(w=[])).push(`Property ${I} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof N!="number"||!(Math.floor(N)===N&&Math.abs(N)<=9007199254740992))&&(w||(w=[])).push(`Property ${I} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof N!="number"&&(w||(w=[])).push(`Property ${I} must be a number`);break;case"ID":typeof N=="string"||N?.length>0&&N.every?.(U=>typeof U=="string")||(w||(w=[])).push(`Property ${I} must be a string, or an array of strings`);break;case"String":typeof N!="string"&&(w||(w=[])).push(`Property ${I} must be a string`);break;case"Boolean":typeof N!="boolean"&&(w||(w=[])).push(`Property ${I} must be a boolean`);break;case"Date":if(!(N instanceof Date)){if(typeof N=="string"||typeof N=="number")return new Date(N);(w||(w=[])).push(`Property ${I} must be a Date`)}break;case"BigInt":if(typeof N!="bigint"){if(typeof N=="string"||typeof N=="number")return BigInt(N);(w||(w=[])).push(`Property ${I} must be a bigint`)}break;case"Bytes":N instanceof Uint8Array||(w||(w=[])).push(`Property ${I} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(N)){if(y.elements)for(let U=0,L=N.length;U<L;U++){let D=N[U],x=O(D,y.elements,I+"[*]");x&&(N[U]=x)}}else(w||(w=[])).push(`Property ${I} must be a Buffer or Uint8Array`);break}y.nullable===!1&&N==null&&(w||(w=[])).push(`Property ${I} is required (and not does not allow null values)`)},"validateValue");for(let N=0,y=S.length;N<y;N++){let I=S[N];if(!I.relationship&&(!R||I.name in m)){let U=O(m[I.name],I,I.name);U&&(m[I.name]=U)}}if(w)throw new ln.ClientError(w.join(". "))}getUpdatedTime(){return this[ou]}wasLoadedFromSource(){return b?!!this[rS]:void 0}static async addAttributes(m){let R=S.slice(0);for(let w of m){if(!w.name)throw new ln.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new ln.ClientError("Attribute names cannot include backticks or forward slashes");R.push(w)}return _t({table:s,database:c,schemaDefined:_,attributes:R}),ze.indexingOperation}static async removeAttributes(m){let R=S.filter(w=>!m.includes(w.name));return _t({table:s,database:c,schemaDefined:_,attributes:R}),ze.indexingOperation}static getRecordCount(m){let R=i.getStats().entryCount,w=5e3,O=1e3,N;R>w&&!m?.exactCount&&(N=O);let y=0;for(let{value:I}of i.getRange({start:!0,lazy:!0,limit:N}))I!=null&&y++;if(N){let I=y;y=0;for(let{value:ne}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:N}))ne!=null&&y++;let U=N*2,L=(y+I)/U,D=Math.pow((y-I+1)/N/2,2)+L*(1-L)/U,x=Math.max(Math.sqrt(D)*R,1),k=Math.round(L*R),_e=Math.max(k-1.96*x,0),de=Math.min(k+1.96*x,R),te=Math.pow(10,Math.round(Math.log10(x)));return te>k&&(te=te/10),y=Math.round(k/te)*te,{recordCount:y,estimatedRange:[Math.round(_e),Math.round(de)]}}return{recordCount:y}}static updatedAttributes(){Vs=this.propertyResolvers={$id:(m,R,w)=>({value:w.key}),$updatedtime:(m,R,w)=>w.version,$record:(m,R,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let R=m.relationship;if(R)if(gA=!0,R.to)m.elements?.definition?(Vs[m.name]=m.resolve=(w,O,N)=>{let y=w[R.from?R.from:t],I=m.elements.definition.tableClass;return N?Go({attribute:R.to,value:y},br(O).getReadTxn(),!1,I).asArray:I.search([{attribute:R.to,value:y}],O).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,R.from&&(m.resolve.from=R.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(R.from){let w=m.definition||m.elements?.definition;w?(Vs[m.name]=m.resolve=(O,N,y)=>{let I=O[R.from];if(I!==void 0){if(m.elements){let U,L=I.map(D=>{let x=y?w.tableClass.primaryStore.getEntry(D,{transaction:br(N).getReadTxn()}):w.tableClass.get(D,N);return x?.then&&(U=!0),x});return R.filterMissing?U?Promise.all(L).then(D=>D.filter(iD)):L.filter(iD):U?Promise.all(L):L}return y?w.tableClass.primaryStore.getEntry(I,{transaction:br(N).getReadTxn()}):w.tableClass.get(I,N)}},m.set=(O,N)=>{if(Array.isArray(N)){let y=N.map(I=>I[Ce]||I[w.tableClass.primaryKey]);O[R.from]=y}else{let y=N[Ce]||N[w.tableClass.primaryKey];O[R.from]=y}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=R.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}o_(this,this)}static async deleteHistory(m=0){let R;for(let{key:w,value:O}of u.getRange({start:0,end:m}))await iu(),Ut(O).tableId===n&&(R=u.remove(w));await R}static async*getHistory(m=0,R=1/0){for(let{key:w,value:O}of u.getRange({start:m,end:R})){await iu();let N=Ut(O);N.tableId===n&&(yield{id:N.recordId,localTime:w,version:N.version,type:N.type,value:N.getValue(i,!0,w),user:N.user})}}static async getHistoryOfRecord(m){let R=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return R;let O=w.localTime;if(!O)throw new Error("The entry does not have a local audit time");let N=0;do{await iu();let y=u.get(O);if(y){let I=Ut(y);R.push({id:I.recordId,localTime:O,version:I.version,type:I.type,value:I.getValue(i,!0,O),user:I.user}),O=I.previousLocalTime}else break}while(N<1e3&&O);return R.reverse()}static cleanup(){W?.remove()}}ze.updatedAttributes();let Xx=ze.prototype;return Xx[GJ]=!0,d&&ze.setTTLExpiration(d/1e3),z&&jx(),ze;function Cl($,m,R){let w;for(let O in r){let N=r[O],y=N.isIndexing,I=R?.[O],U=m?.[O];if(I===U&&!y)continue;w=!0;let L=N.indexNulls,D=(0,au.getIndexedValues)(U,L);if(D){eD&&N.prefetch(D.map(x=>({key:x,value:$})),nD);for(let x=0,k=D.length;x<k;x++)N.remove(D[x],$)}if(D=(0,au.getIndexedValues)(I,L),D){eD&&N.prefetch(D.map(x=>({key:x,value:$})),nD);for(let x=0,k=D.length;x<k;x++)N.put(D[x],$)}}return w}a(Cl,"updateIndices");function Qa($){switch(typeof $){case"number":return!0;case"string":if($.length<659)return!0;if($.length>rD)throw new Error("Primary key size is too large: "+$.length);break;case"object":if($===null)return!0;break;case"bigint":if($<2n**64n&&$>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof $)}if((0,to.writeKey)($,VJ,0)>rD)throw new Error("Primary key size is too large: "+$.length);return!0}a(Qa,"checkValidId");function zE($,m,R,w,O){let N=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),R.transaction?.isDone)return O(null,$);let y=i.getEntry($,R);return y&&m&&(y?.version>(m.lastModified||0)&&(m.lastModified=y.version),y?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=y.localTime)),O(y,$)},"whenPrefetched");return w?N():pe>0?(pe--,N()):new Promise((y,I)=>{pe===0?(pe--,i.prefetch([$],()=>{U(),L()})):(Q.push($),se.push(L),Q.length>Jx&&(pe--,U()));function U(){if(Q.length>0){let D=se;i.prefetch(Q,()=>{pe===-1?U():pe++;for(let x of D)x()}),Q=[],se=[],oe>2&&oe--}else pe=oe,oe<zx&&oe++}a(U,"prefetch");function L(){try{y(N())}catch(D){I(D)}}a(L,"load")})}a(zE,"loadLocalRecord");function Dl($){if(!$?.role)return;let m=$.role.permission;if(m.super_user)return $J;let R=m[c],w,O=R?.tables;if(O)return O[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(Dl,"getTablePermissions");function JE($,m,R,w){if(b){let O;if(R.noCache?O=!0:(m?(!m.value||m.metadataFlags&(nu|su)||m.expiresAt&&m.expiresAt<Date.now())&&(O=!0):O=!0,un(!O,"cache-hit",s)),O){let N=AA($,m,R).then(y=>(y?.value?.[be]&&Ze.error("Can not assign a record with a record property"),R&&(y?.version>(R.lastModified||0)&&(R.lastModified=y.version),R.lastRefreshed=Date.now()),y));if(R?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,$)){if(N.catch(y=>Ze.warn(y)),R?.onlyIfCached&&!w.doesExist())throw new ln.ServerError("Entry is not cached",504);return}else return N}}}a(JE,"ensureLoadedFromSource");function br($){let m=$?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let R=m.next;if(!R)return m=m.next=new Mi,m.lmdbDb=i,m;m=R}while(!0)}else return new u_}a(br,"txnForContext");function XE($,m,R){if(!$)return;QE=$;let w=$.value||$.deref?.()||(QE=i.getEntry($.key))?.value;if(typeof m=="object"){let N=Vs,y=w;for(let I=0,U=m.length;I<U;I++){let L=m[I],D=N?.[L];y=D&&y?D(y,R,!0)?.value:y?.[L],N=D?.definition?.tableClass?.propertyResolvers}return y}let O=Vs[m];return O?O(w,R):w[m]}a(XE,"getAttributeValue");function RA($,m,R,w){let O=br(R).getReadTxn(),N=w?.length,y={transaction:O,lazy:N>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},I;function U(L,D){let x=L?.value;if(!x)return Zi.SKIP;for(let k=0;k<N;k++)if(!I?.includes(k)&&!w[k](x,L))return Zi.SKIP;return D!==void 0&&(L.key=D),L}if(a(U,"processEntry"),N>0||!$.hasEntries){let L=$.map(D=>{if(I=null,typeof D=="object"&&D.key!==void 0)return N>0?U(D):D;if(D==null)return Zi.SKIP;for(let x=0;x<N;x++){let _e=w[x].idFilter;if(_e){if(!_e(D))return Zi.SKIP;I||(I=[]),I.push(x)}}return zE(D,R,y,!1,U)});return Array.isArray($)&&(L=L.filter(D=>D!==Zi.SKIP)),L.hasEntries=!0,L}return $}a(RA,"transformToEntries");async function AA($,m,R){let w=m?.metadataFlags,O=m?.version,N,y;if(!i.attemptLock($,O,()=>{clearTimeout(y);let D=i.getEntry($);!D||!D.value||D.metadataFlags&(nu|su)?N(AA($,i.getEntry($),R)):N(D)}))return new Promise(D=>{N=D,y=setTimeout(()=>{i.unlock($,O)},qJ)});let I=m?.value,U={requestContext:R,replacingRecord:I,replacingVersion:O,source:null,resourceCache:R?.resourceCache},L=R?.responseHeaders;return new Promise((D,x)=>{let k;sS(Xe(U,async _e=>{let de=performance.now(),te,ne,Be;try{for(let Me of ze.sources)if(Me.get&&(!Me.get.reliesOnPrototype||Me.prototype.get)&&(U.source=Me,te=await Me.get($,U),te))break;Be=wνlet fe=U.lastModified||Be&&O;ne=Be||fe>O||!I,fe||(fe=(0,au.getNextMonotonicTime)());let Ye=performance.now()-de;if(Gr(Ye,"cache-resolution",s),L&&L.append("Server-Timing",`cache-resolve;dur=${Ye.toFixed(2)}`),_e.timestamp=fe,d&&!U.expiresAt&&(U.expiresAt=Date.now()+d),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==$&&(te[t]=$)}k=!0,D({version:fe,value:te})}catch(fe){fe.message+=` while resolving record ${$} for ${s}`,I&&((fe.code==="ECONNRESET"||fe.code==="ECONNREFUSED"||fe.code==="EAI_AGAIN")&&!R?.mustRevalidate||R?.staleIfError&&(fe.statusCode===500||fe.statusCode===502||fe.statusCode===503||fe.statusCode===504))?(D({version:O,value:I}),Ze.trace(fe.message,"(returned stale record)")):x(fe),U.transaction.abort();return}if(R?.noCacheStore){U.transaction.abort();return}br(U).addWrite({key:$,store:i,entry:m,nodeName:"source",commit:(fe,Ye)=>{if(Ye?.version!==O)return;let Me=Cl($,I,te);te?(ce.put?.(U,$,te),p($,te,Ye,fe,0,E&&ne||null,U,U.expiresAt,"put",!!Be)):(ce.delete?.(U,$),E||h?p($,null,Ye,fe,0,E&&ne||null,U,0,"delete",!!Be):i.remove($,O))}})}),()=>{i.unlock($,O)},_e=>{i.unlock($,O),k&&Ze.error("Error committing cache update",_e)})})}a(AA,"getFromSource");function jE(){if(Lt!==Il&&(Il=Lt,(0,eo.getWorkerIndex)()===(0,eo.getWorkerCount)()-1)){if(wl&&clearTimeout(wl),!Lt)return;let $=new Date;$.setMonth(0),$.setDate(1),$.setHours(0),$.setMinutes(0),$.setSeconds(0);let m=Math.ceil((Date.now()-$.getTime())/Lt)*Lt+$.getTime(),R=a(w=>{Ze.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),wl=setTimeout(()=>G=G.then(async()=>{if(R(Math.max(w+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout(wl);return}let O=50,N=new Array(O),y=0;Ze.trace(`Starting cleanup scan for ${s}`);try{let I=0;for(let{key:U,value:L,version:D,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let k;L===null&&!E&&D+FJ<Date.now()?k=i.remove(U,D):x&&x+f<Date.now()&&(k=ze.evict(U,L,D),I++),k&&(await N[y],N[y]=k.catch(_e=>{Ze.error("Cleanup error",_e)}),++y>=O&&(y=0)),await iu()}Ze.trace(`Finished cleanup scan for ${s}, evicted ${I} entries`)}catch(I){Ze.trace(`Error in cleanup scan for ${s}:`,I)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");R(m)}}a(jE,"scheduleCleanup");function OA(){W=u?.addDeleteRemovalCallback(n,$=>{let m=i.getEntry($);m?.value===null&&i.remove($,m.version)})}a(OA,"addDeleteRemoval");function jx(){(0,eo.getWorkerIndex)()===0&&setInterval(async()=>{try{let $=z.name,m=r[$];if(!m)throw new Error(`expiresAt attribute ${z} must be indexed`);for(let{value:R}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let w=i.getEntry(R);w?.value?.[$]<Date.now()&&ze.evict(R,w.value,w.version),await iu()}}catch($){Ze.error("Error in evicting old records",$)}},xJ).unref()}a(jx,"runRecordExpirationEviction")}function nS(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function nD(){}function YJ(e){aD=e}function hd(e,t){let r=t?.type;return e===null?e:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Date"?(typeof e!="number"&&!KJ.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,pd.autoCast)(e):e}function sD(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function sS(e,t,r){return e?.then?e.then(t,r):t(e)}function md(e,t){e[kr]=t,e[be]=t?.value??null,e[ou]=t?.version}function iD(e){return e!=null}var vn,Zi,au,oD,lu,ln,cu,uu,Ze,to,eo,pd,HJ,aD,xJ,FJ,eD,qJ,ou,GJ,kr,ru,tD,kJ,rS,ca,nu,su,VJ,rD,$J,w_e,KJ,iu,Td=Re(()=>{vn=B(M()),Zi=require("lmdb"),au=B(Cr()),oD=require("lodash");On();Bh();lu=B(j());_b();ln=B(Z()),cu=B(gs()),uu=B(In());Oe();d_();Ze=B(Y());c_();Ui();to=require("ordered-binary"),eo=B(tt());Ci();pd=B(J());Bo();Ns();Zl();HJ=new Uint8Array(9);HJ[8]=192;xJ=6e4,FJ=864e5;lu.initSync();eD=lu.get(vn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),qJ=1e4,ou=Symbol.for("version"),GJ=Symbol.for("incremental-update"),kr=Symbol("entry"),ru=Symbol("is-saving"),tD=1,kJ=2,rS=Symbol("loaded-from-source"),ca={isNotification:!0,ensureLoaded:!1},nu=1,su=8,VJ=Buffer.allocUnsafeSlow(8192),rD=1978,$J={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},w_e=(0,pd.convertToMS)(lu.get(vn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(Sd,"makeTable");a(nS,"attributesAsObject");a(nD,"noop");a(YJ,"setServerUtilities");KJ=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(hd,"coerceType");a(sD,"isDescendantId");iu=a(()=>new Promise(setImmediate),"rest");a(sS,"when");a(md,"updateResource");a(iD,"exists")});var Ge={};qe(Ge,{database:()=>kc,databases:()=>st,dropDatabase:()=>Ep,dropTableMeta:()=>jJ,getDatabases:()=>Cn,getTables:()=>WJ,onUpdatedTable:()=>lS,readMetaDb:()=>_u,resetDatabases:()=>QJ,table:()=>_t,tables:()=>$r});function WJ(){return bd||Cn(),$r||{}}function Cn(){if(bd)return st;bd=!0,_a=new Map;let e=(0,Jt.getHdbBasePath)()&&(0,et.join)((0,Jt.getHdbBasePath)(),Yr.DATABASES_DIR_NAME),t=(0,Jt.get)(Yr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Jt.get)(Yr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Vr.existsSync)(e)?e:(0,et.join)((0,Jt.getHdbBasePath)(),Yr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Vr.existsSync)(e))for(let r of(0,Vr.readdirSync)(e,{withFileTypes:!0})){let n=(0,et.basename)(r.name,".mdb");r.isFile()&&(0,et.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&_u((0,et.join)(e,r.name),null,n)}if((0,Vr.existsSync)((0,la.getBaseSchemaPath)())){for(let r of(0,Vr.readdirSync)((0,la.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,et.join)((0,la.getBaseSchemaPath)(),r.name),s=(0,et.join)((0,la.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Vr.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,et.extname)(i.name).toLowerCase()===".mdb"){let o=(0,et.join)(s,i.name);_u((0,et.join)(n,i.name),(0,et.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,Vr.existsSync)(s))for(let o of(0,Vr.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,et.extname)(o.name).toLowerCase()===".mdb"&&_u((0,et.join)(s,o.name),(0,et.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,et.join)(c.path,(0,et.basename)(o+".mdb"));(0,Vr.existsSync)(u)&&_u(u,o,r,null,!0)}}for(let r in st){let n=_a.get(r);if(n){let s=st[r];r.includes("delete")&&_n.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(_n.trace(`delete table class ${i}`),delete s[i])}else if(delete st[r],r==="data"){for(let s in $r)delete $r[s];delete $r[Nd]}}return _a=null,st}}function QJ(){bd=!1;for(let[,e]of ai)e.needsDeletion=!0;Cn();for(let[e,t]of ai)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),ai.delete(e));return st}function _u(e,t,r=cS,n,s){let i=new oS.default(e,!1);try{let o=ai.get(e);o?o.needsDeletion=!1:(o=(0,Rd.open)(i),ai.set(e,o));let c=new ro.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(gd.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,Vr.existsSync)(n)&&(i.path=n,_=(0,Rd.open)(i),_.isLegacy=!0):_=jl(o));let l=_D(r),d=l[Nd],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[S,p]=E.toString().split("/");p===""?p=h.name:p||(p=S,S=t,h.name||(h.name=p,h.indexed=!h.is_hash_attribute)),d?.add(S);let g=f.get(S);g||f.set(S,g={attributes:[]}),(p==null||h.is_hash_attribute)&&(g.primary=h),p!=null&&g.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:S,primary:p}=h;if(!p){for(let Q of S)if(Q.is_hash_attribute||Q.isPrimaryKey){p=Q;break}if(!p){_n.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(S)}`);continue}}let g=l[E],A={},b=[],v,G,H=typeof p.audit=="boolean"?p.audit:(0,Jt.get)(Yr.CONFIG_PARAMS.LOGGING_AUDITLOG),P=p.trackDeletes,z=p.expiration,W=p.eviction;if(g)A=g.indices,b=g.attributes,g.schemaVersion++;else{v=p.tableId,v?v>=(u.get(ua)||0)&&u.putSync(ua,v+1):(p.tableId=v=u.get(ua),v||(v=1),u.putSync(ua,v+1),u.putSync(p.key,p));let Q=new ro.default(!p.is_hash_attribute,p.is_hash_attribute);G=Ql(o.openDB(p.key,Q)),G.rootStore=o,G.tableId=v}for(let Q of S){Q.attribute=Q.name;try{if(!Q.is_hash_attribute&&(Q.indexed||Q.attribute&&!Q.name)){if(!A[Q.name]){let pe=new ro.default(!Q.is_hash_attribute,Q.is_hash_attribute);A[Q.name]=o.openDB(Q.key,pe),A[Q.name].indexNulls=Q.indexNulls}let se=b.find(pe=>pe.name===Q.name);se?b.splice(b.indexOf(se),1,Q):b.push(Q)}}catch(se){_n.error("Error trying to update attribute",Q,b,A,se)}}if(!g){g=dD(l,E,Sd({primaryStore:G,auditStore:_,audit:H,expirationMS:z&&z*1e3,evictionMS:W&&W*1e3,trackDeletes:P,tableName:E,tableId:v,primaryKey:p.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:A,attributes:S,schemaDefined:p.schemaDefined,dbisDB:u})),g.schemaVersion=1;for(let Q of uS)Q(g)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function _D(e){let t=st[e];if(t||(e==="data"?t=st[e]=$r:e==="system"?Object.defineProperty(st,"system",{value:t=Object.create(null),configurable:!0}):t=st[e]=Object.create(null)),_a&&!_a.has(e)){let r=new Set;t[Nd]=r,_a.set(e,r)}return t}function dD(e,t,r){return e[t]=r,r}function kc({database:e,table:t}){e||(e=cS),Cn();let r=_D(e),n=(0,et.join)((0,Jt.getHdbBasePath)(),Yr.DATABASES_DIR_NAME),s=(0,Jt.get)(Yr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Jt.get)(Yr.CONFIG_PARAMS.STORAGE_PATH)||((0,Vr.existsSync)(n)?n:(0,et.join)((0,Jt.getHdbBasePath)(),Yr.LEGACY_DATABASES_DIR_NAME));let o=(0,et.join)(n,(i?t:e)+".mdb"),c=ai.get(o);if(!c){let u=new oS.default(o,!1);c=(0,Rd.open)(u),ai.set(o,c)}return c}async function Ep(e){if(!st[e])throw new Error("Schema does not exist");let t=st[e];for(let r in t){let s=t[r].primaryStore.rootStore;ai.delete(s.path),s.status==="open"&&(await s.close(),await cD.remove(s.path))}if(e==="data"){for(let r in $r)delete $r[r];delete $r[Nd]}delete st[e]}function _t({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=cS);let l=kc({database:t,table:e}),d=st[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,S,p;u==null&&(u=!0);let g=new ro.default(!1);for(let P of i)P.attribute?(P.name=P.attribute,P.indexed=!0):P.attribute=P.name,P.expiresAt&&(P.indexed=!0);let A,b;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let P=l.auditStore;P||(P=jl(l)),h=i.find(se=>se.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Jt.get)(Yr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),n&&(h.eviction=n),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),_n.trace(`${e} table loading, opening primary store`);let z=new ro.default(!1,!0),W=e+"/",Q=Ql(l.openDB(W,z));Q.rootStore=l,p=l.dbisDb=l.openDB(gd.INTERNAL_DBIS_NAME,g),Q.tableId=p.get(ua),Q.tableId||(Q.tableId=1),p.putSync(ua,Q.tableId+1),h.tableId=Q.tableId,f=dD(d,e,Sd({primaryStore:Q,auditStore:P,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:E,tableName:e,tableId:Q.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:p})),f.schemaVersion=1,A=!0,H(),p.put(W,h)}S=f.indices,p=p||(l.dbisDb=l.openDB(gd.INTERNAL_DBIS_NAME,g)),f.dbisDB=p;let v=[];for(let{key:P,value:z}of p.getRange({start:!0})){let[W,Q]=P.toString().split("/");if(Q===""&&(Q=z.name),Q){if(W!==e)continue}else Q=W;if(!i.find(pe=>pe.name===Q)?.indexed&&z.indexed&&!z.isPrimaryKey){H(),A=!0,p.remove(P);let pe=f.indices[W];pe&&v.push(pe)}}let G=[];try{for(let P of i||[]){if(P.relationship)continue;let z=e+"/"+(P.name||"");Object.defineProperty(P,"key",{value:z,configurable:!0});let W=p.get(z);if(P.isPrimaryKey){if(W=W||p.get(z=e+"/")||{},o!==f.audit||(+r||void 0)!==(+W.expiration||void 0)||(+n||void 0)!==(+W.eviction||void 0)){let se=Object.assign({},W);typeof o=="boolean"&&(o&&f.enableAuditing(o),se.audit=o),r&&(se.expiration=+r),n&&(se.eviction=+n),A=!0,H(),p.put(z,se)}continue}W?.attribute&&!W.name&&(W.indexed=!0);let Q=!W||W.type!==P.type||W.indexed!==P.indexed||JSON.stringify(W.attributes)!==JSON.stringify(P.attributes)||JSON.stringify(W.elements)!==JSON.stringify(P.elements);if(P.indexed){let se=new ro.default(!0,!1),pe=l.openDB(z,se);(Q||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<du.workerData?.restartNumber)&&(A=!0,H(),W=p.get(z),(Q||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<du.workerData?.restartNumber)&&(A=!0,P.lastIndexedKey=W?.lastIndexedKey||!1,P.indexingPID=process.pid,pe.isIndexing=!0,Object.defineProperty(P,"dbi",{value:pe}),P.indexNulls===void 0&&(P.indexNulls=!0),G.push(P)),p.put(z,P)),W?.indexNulls&&P.indexNulls===void 0&&(P.indexNulls=!0),pe.indexNulls=P.indexNulls,S[P.name]=pe}else Q&&(A=!0,H(),p.put(z,P))}}finally{b&&b()}if(A&&(f.schemaVersion++,f.updatedAttributes()),_n.trace(`${e} table loading, running index`),G.length>0||v.length>0?f.indexingOperation=XJ(f,G,v):A&&Ad.signalSchemaChange(new Od.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,A)for(let P of uS)P(f,_!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),_n.trace(`${e} table loaded`),f;function H(){b||l.transactionSync(()=>({then(P){b=P}}))}a(H,"startTxn")}async function XJ(e,t,r){try{let n=e.schemaVersion;await Ad.signalSchemaChange(new Od.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,S=(0,uD.getIndexedValues)(l[h]);if(S)for(let p=0,g=S.length;p<g;p++)E.dbi.put(S[p],_)}}),s.then(()=>u--,f=>{u--,_n.error(f)}),du.workerData&&du.workerData.restartNumber!==lD.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>zJ?await s:u>JJ&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await Ad.signalSchemaChange(new Od.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){_n.error("Error in indexing",n)}}function jJ({table:e,database:t}){let r=kc({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function lS(e){uS.push(e)}var Jt,gd,Rd,et,Vr,la,ro,oS,Yr,cD,aS,uD,Ad,Od,du,_n,lD,cS,Nd,$r,st,ua,uS,bd,ai,_a,zJ,JJ,Oe=Re(()=>{Jt=B(j()),gd=B(Et()),Rd=require("lmdb"),et=require("path"),Vr=require("fs"),la=B(Je());Td();ro=B(p_()),oS=B(T_()),Yr=B(M()),cD=B(require("fs-extra")),aS=require("../index"),uD=B(Cr()),Ad=B(gs()),Od=B(In()),du=require("worker_threads"),_n=B(Y()),lD=B(tt());Ci();Bo();cS="data",Nd=Symbol("defined-tables");(0,Jt.initSync)();$r=Object.create(null),st=Object.create(null);(0,aS._assignPackageExport)("databases",st);(0,aS._assignPackageExport)("tables",$r);ua=Symbol.for("next-table-id"),uS=[],ai=new Map;a(WJ,"getTables");a(Cn,"getDatabases");a(QJ,"resetDatabases");a(_u,"readMetaDb");a(_D,"ensureDB");a(dD,"setTable");a(kc,"database");a(Ep,"dropDatabase");a(_t,"table");zJ=1e3,JJ=10;a(XJ,"runIndexing");a(jJ,"dropTableMeta");a(lS,"onUpdatedTable")});var J=T((H_e,yD)=>{"use strict";var ci=require("path"),pD=require("fs-extra"),ur=Y(),fD=require("fs-extra"),yd=require("os"),ZJ=require("net"),e4=require("recursive-iterator"),it=M(),t4=rO(),ED=require("papaparse"),Id=require("moment"),{inspect:r4}=require("util"),hD=require("is-number"),B_e=require("lodash"),n4=require("minimist"),s4=require("https"),i4=require("http"),{hdb_errors:wd}=Z(),o4=/^((\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)))$/,SD=require("util").promisify(setTimeout),a4=100,c4=5,u4="",l4=4,mD={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};yD.exports={isEmpty:Kr,isEmptyOrZeroLength:es,arrayHasEmptyValues:f4,arrayHasEmptyOrZeroLengthValues:E4,buildFolderPath:h4,isBoolean:TD,errorizeMessage:_4,stripFileExtension:p4,autoCast:S4,autoCastJSON:gD,autoCastJSONDeep:dS,removeDir:T4,compareVersions:g4,isCompatibleDataVersion:R4,escapeRawValue:A4,unescapeValue:O4,stringifyProps:b4,timeoutPromise:y4,isClusterOperation:w4,getClusterUser:D4,checkGlobalSchemaTable:C4,getHomeDir:AD,getPropsFilePath:N4,promisifyPapaParse:L4,removeBOM:OD,createEventPromise:M4,checkProcessRunning:U4,checkSchemaTableExist:P4,checkSchemaExists:bD,checkTableExists:ND,getStartOfTomorrowInSeconds:v4,getLimitKey:B4,isObject:m4,isNotEmptyAndHasValue:d4,autoCasterIsNumberCheck:RD,backtickASTSchemaItems:H4,isPortTaken:I4,createForkArgs:x4,autoCastBoolean:F4,async_set_timeout:SD,getTableHashAttribute:q4,doesSchemaExist:G4,doesTableExist:k4,stringifyObj:V4,ms_to_time:$4,changeExtension:Y4,getEnvCliRootPath:fS,noBootFile:K4,httpRequest:W4,transformReq:Q4,convertToMS:z4,PACKAGE_ROOT:it.PACKAGE_ROOT};function _4(e){return e instanceof Error?e:new Error(e)}a(_4,"errorizeMessage");function Kr(e){return e==null}a(Kr,"isEmpty");function d4(e){return!Kr(e)&&(e||e===0||e===""||TD(e))}a(d4,"isNotEmptyAndHasValue");function es(e){return Kr(e)||e.length===0||e.size===0}a(es,"isEmptyOrZeroLength");function f4(e){if(Kr(e))return!0;for(let t=0;t<e.length;t++)if(Kr(e[t]))return!0;return!1}a(f4,"arrayHasEmptyValues");function E4(e){if(es(e))return!0;for(let t=0;t<e.length;t++)if(es(e[t]))return!0;return!1}a(E4,"arrayHasEmptyOrZeroLengthValues");function h4(...e){try{return e.join(ci.sep)}catch{console.error(e)}}a(h4,"buildFolderPath");function TD(e){return Kr(e)?!1:e===!0||e===!1}a(TD,"isBoolean");function m4(e){return Kr(e)?!1:typeof e=="object"}a(m4,"isObject");function p4(e){return es(e)?u4:e.slice(0,-l4)}a(p4,"stripFileExtension");function S4(e){return Kr(e)||e===""||typeof e!="string"?e:mD[e]!==void 0?mD[e]:RD(e)===!0?Number(e):o4.test(e)?new Date(e):e}a(S4,"autoCast");function gD(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(gD,"autoCastJSON");function dS(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=dS(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=dS(r);n!==r&&(e[t]=n)}return e}else return gD(e)}a(dS,"autoCastJSONDeep");function RD(e){if(e.startsWith("0.")&&hD(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&hD(e))}a(RD,"autoCasterIsNumberCheck");async function T4(e){if(es(e))throw new Error(`Directory path: ${e} does not exist`);try{await fD.emptyDir(e),await fD.remove(e)}catch(t){throw ur.error(`Error removing files in ${e} -- ${t}`),t}}a(T4,"removeDir");function g4(e,t){if(es(e)){ur.info("Invalid current version sent as parameter.");return}if(es(t)){ur.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(g4,"compareVersions");function R4(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(R4,"isCompatibleDataVersion");function A4(e){if(Kr(e))return e;let t=String(e);return t==="."?it.UNICODE_PERIOD:t===".."?it.UNICODE_PERIOD+it.UNICODE_PERIOD:t.replace(it.FORWARD_SLASH_REGEX,it.UNICODE_FORWARD_SLASH)}a(A4,"escapeRawValue");function O4(e){if(Kr(e))return e;let t=String(e);return t===it.UNICODE_PERIOD?".":t===it.UNICODE_PERIOD+it.UNICODE_PERIOD?"..":String(e).replace(it.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(O4,"unescapeValue");function b4(e,t){if(Kr(e))return ur.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+yd.EOL}!es(n)&&n[0]===";"?r+=" "+n+s+yd.EOL:es(n)||(r+=n+"="+s+yd.EOL)}catch{ur.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(b4,"stringifyProps");function AD(){let e;try{e=yd.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(AD,"getHomeDir");function N4(){let e=ci.join(AD(),it.HDB_HOME_DIR_NAME,it.BOOT_PROPS_FILE_NAME);return pD.existsSync(e)||(e=ci.join(__dirname,"../","hdb_boot_properties.file")),e}a(N4,"getPropsFilePath");function y4(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(y4,"timeoutPromise");async function I4(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=ZJ.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(I4,"isPortTaken");function w4(e){try{return it.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){ur.error(`Error checking operation against cluster ops ${t}`)}return!1}a(w4,"isClusterOperation");function C4(e,t){let r=(Oe(),ee(Ge)).getDatabases();if(!r[e])return wd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return wd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(C4,"checkGlobalSchemaTable");function D4(e,t){if(Kr(t)){ur.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Kr(e)||es(e)){ur.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){ur.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){ur.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(D4,"getClusterUser");function L4(){ED.parsePromise=function(e,t,r){return new Promise(function(n,s){ED.parse(e,{header:!0,transformHeader:OD,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(L4,"promisifyPapaParse");function OD(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(OD,"removeBOM");function M4(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;ur.info(`Got cluster status event response: ${r4(s)}`);try{i.cancel()}catch{ur.error("Error trying to cancel timeout.")}n(s)})})}a(M4,"createEventPromise");async function U4(e){let t=!0,r=0;do await SD(a4*r++),(await t4.findPs(e)).length>0&&(t=!1);while(t&&r<c4);if(t)throw new Error(`process ${e} was not started`)}a(U4,"checkProcessRunning");function P4(e,t){let r=bD(e);if(r)return r;let n=ND(e,t);if(n)return n}a(P4,"checkSchemaTableExist");function bD(e){let{getDatabases:t}=(Oe(),ee(Ge));if(!t()[e])return wd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(bD,"checkSchemaExists");function ND(e,t){let{getDatabases:r}=(Oe(),ee(Ge));if(!r()[e][t])return wd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(ND,"checkTableExists");function v4(){let e=Id().utc().add(1,it.MOMENT_DAYS_TAG).startOf(it.MOMENT_DAYS_TAG).unix(),t=Id().utc().unix();return e-t}a(v4,"getStartOfTomorrowInSeconds");function B4(){return Id().utc().format("DD-MM-YYYY")}a(B4,"getLimitKey");function H4(e){try{let t=new e4(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){ur.error("Got an error back ticking items."),ur.error(t)}}a(H4,"backtickASTSchemaItems");function x4(e){return[e]}a(x4,"createForkArgs");function F4(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(F4,"autoCastBoolean");function q4(e,t){let{getDatabases:r}=(Oe(),ee(Ge)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(q4,"getTableHashAttribute");function G4(e){let{getDatabases:t}=(Oe(),ee(Ge));return t()[e]!==void 0}a(G4,"doesSchemaExist");function k4(e,t){let{getDatabases:r}=(Oe(),ee(Ge));return r()[e]?.[t]!==void 0}a(k4,"doesTableExist");function V4(e){try{return JSON.stringify(e)}catch{return e}}a(V4,"stringifyObj");function $4(e){let t=Id.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a($4,"ms_to_time");function Y4(e,t){let r=ci.basename(e,ci.extname(e));return ci.join(ci.dirname(e),r+t)}a(Y4,"changeExtension");function fS(){if(process.env[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=n4(process.argv);if(e[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(fS,"getEnvCliRootPath");var _S;function K4(){if(_S)return _S;let e=fS();fS()&&pD.pathExistsSync(ci.join(e,it.HDB_CONFIG_FILE))&&(_S=!0)}a(K4,"noBootFile");function W4(e,t){let r;return e.protocol==="http:"?r=i4:r=s4,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(W4,"httpRequest");function Q4(e){if(!e.schema&&!e.database){e.schema=it.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Q4,"transformReq");function z4(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(z4,"convertToMS")});var j=T((F_e,DD)=>{"use strict";var ES=require("fs-extra"),no=require("path"),ID=require("os"),J4=require("properties-reader"),Eu=Y(),fu=J(),ae=M(),Cd=xr(),X4="Error initializing environment manager",Dd="BOOT_PROPS_FILE_PATH",wD=!1,j4={[ae.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},ys={};DD.exports={BOOT_PROPS_FILE_PATH:Dd,getHdbBasePath:Z4,setHdbBasePath:e3,get:CD,initSync:r3,setProperty:De,initTestEnvironment:n3};function Z4(){return ys[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Z4,"getHdbBasePath");function e3(e){ys[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(e3,"setHdbBasePath");function CD(e){let t=Cd.getConfigValue(e);return t===void 0?ys[e]:t}a(CD,"get");function De(e,t){j4[e]&&(ys[e]=t),Cd.updateConfigObject(e,t)}a(De,"setProperty");function t3(){let e;try{e=fu.getPropsFilePath(),ES.accessSync(e,ES.constants.F_OK|ES.constants.R_OK),wD=!0;let t=J4(e);return ys[ae.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ae.HDB_SETTINGS_NAMES.INSTALL_USER),ys[ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),ys[Dd]=e,!0}catch{return Eu.trace(`Environment manager found no properties file at ${e}`),!1}}a(t3,"doesPropFileExist");function r3(e=!1){try{(wD||t3()||fu.noBootFile())&&(Cd.initConfig(e),ys[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Cd.getConfigValue(ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Eu.error(X4),Eu.error(t),console.error(t),process.exit(1)}}a(r3,"initSync");function n3(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=no.join(__dirname,"../../","unitTests");ys[Dd]=no.join(u,"hdb_boot_properties.file"),De(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,no.join(u,"settings.test")),De(ae.HDB_SETTINGS_NAMES.INSTALL_USER,ID.userInfo()?ID.userInfo().username:void 0),De(ae.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),De(ae.HDB_SETTINGS_NAMES.LOG_PATH_KEY,no.join(u,"envDir","log")),De(ae.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),De(ae.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),De(ae.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),De(ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,no.join(u,"envDir")),De(ae.CONFIG_PARAMS.STORAGE_PATH,no.join(u,"envDir")),s&&(De(ae.CONFIG_PARAMS.HTTP_SECUREPORT,CD(ae.CONFIG_PARAMS.HTTP_PORT)),De(ae.CONFIG_PARAMS.HTTP_PORT,null)),De(ae.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),De(ae.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),De(ae.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,fu.isEmpty(i)?!1:i),De(ae.CONFIG_PARAMS.HTTP_CORS,fu.isEmpty(i)?!1:i),De(ae.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),De(ae.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),De(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),De(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),De(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,no.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),De(ae.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,fu.isEmpty(c)?!1:c),o&&(De("CORS_ACCESSLIST",o),De(ae.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(De(ae.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),De(ae.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(De(ae.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),De(ae.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(De(ae.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),De(ae.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Dd}. Please check your boot props and settings files`;Eu.fatal(r),Eu.error(t)}}a(n3,"initTestEnvironment")});var mS={};qe(mS,{loadGQLSchema:()=>o3,start:()=>hS,startOnMainThread:()=>i3});function hS({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),f=new Map,E=[],h;for(let p of d.definitions)switch(p.kind){case u.OBJECT_TYPE_DEFINITION:let G=function(H){if(H.kind==="NonNullType"){let W=G(H.type);return W.nullable=!1,W}if(H.kind==="ListType")return{type:"array",elements:G(H.type)};let z={type:H.name?.value};return Object.defineProperty(z,"location",{value:H.loc.startToken}),z};a(G,"getProperty");let g=p.name.value,A=[],b={table:null,database:null,properties:A};f.set(g,b);for(let H of p.directives){if(H.name.value==="table"){for(let P of H.arguments)b[P.name.value]=P.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=g),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,E.push(b)}if(H.name.value==="sealed"&&(b.sealed=!0),H.name.value==="export"){b.export=!0;for(let P of H.arguments)P.name.value==="name"&&(b.export={name:P.value.value})}}let v=!1;for(let H of p.fields){let P=G(H.type);P.name=H.name.value,A.push(P);for(let z of H.directives)if(z.name.value==="primaryKey")v?console.warn("Can not define two attributes as a primary key"):(P.isPrimaryKey=!0,v=!0);else if(z.name.value==="indexed")P.indexed=!0;else if(z.name.value==="relationship"){let W={};for(let Q of z.arguments)W[Q.name.value]=Q.value.value;P.relationship=W}else if(z.name.value==="createdTime")P.assignCreatedTime=!0;else if(z.name.value==="updatedTime")P.assignUpdatedTime=!0;else if(z.name.value==="expiresAt")P.expiresAt=!0;else if(z.name.value==="allow"){let W=P.authorizedRoles=[];for(let Q of z.arguments)Q.name.value==="role"&&W.push(Q.value.value)}}b.type=g,g==="Query"&&(h=b)}function S(p){let g=f.get(p.type);g?(Object.defineProperty(p,"properties",{value:g.properties}),Object.defineProperty(p,"definition",{value:g})):p.type==="array"?S(p.elements):s3.includes(p.type)||(0,LD.getWorkerIndex)()===0&&console.error(`The type ${p.type} is unknown at line ${p.location.line}, column ${p.location.column}, in ${s}`)}a(S,"connectPropertyType");for(let p of f.values())for(let g of p.properties)S(g);for(let p of E)p.tableClass=e(p),p.export&&(p.export.name===""?i.set((0,Ld.dirname)(n),p.tableClass):i.set((0,Ld.dirname)(n)+"/"+(p.export.name||p.type),p.tableClass));if(h)for(let p of h.properties){let g=f.get(p.type);if(!g)throw new Error(`${p.type} was not found as a Query export`);i.set((0,Ld.dirname)(n)+"/"+p.name,g.tableClass)}}}var Ld,LD,s3,i3,o3,MD=Re(()=>{Ld=require("path");Oe();LD=B(tt()),s3=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(hS,"start");i3=hS,o3=hS({ensureTable:_t}).handleFile});async function Md(e){return a3?(hu||(hu=c3(l3)),(await(await hu).import(e)).namespace):import(e)}async function c3(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),hu=new Compartment({console,Math,Date,fetch:u3,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,PD.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:Ft,tables:$r,databases:st})}};let n=await(0,UD.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),hu}function u3(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 l3(){return{Resource:Ft,tables:$r}}var UD,PD,a3,hu,pS=Re(()=>{On();Oe();UD=require("fs/promises"),PD=require("path"),a3=!1;a(Md,"secureImport");a(c3,"getCompartment");a(u3,"secureOnlyFetch");a(l3,"getGlobalVars")});var TS={};qe(TS,{handleFile:()=>_3});async function _3(e,t,r,n){let s=new Map,i=(0,vD.pathToFileURL)(r).toString(),o=await Md(i);u(o.default)&&n.set((0,SS.dirname)(t),o.default),c(o,(0,SS.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var vD,SS,BD=Re(()=>{vD=require("url");pS();SS=require("path");a(_3,"handleFile")});var RS={};qe(RS,{start:()=>d3});function d3({resources:e}){e.set("login",gS),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var gS,HD=Re(()=>{On();a(d3,"start");gS=class extends Ft{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var $D={};qe($D,{parse:()=>OS,streamAsJSON:()=>mu,stringify:()=>so});function mu(e){return new AS({value:e})}function xD(e){return console.error(e),JSON.stringify(e.toString())}function FD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function so(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===kD)return VD(e);if(t.resolution)return t.resolution.then(()=>so(e));throw t}}function VD(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=VD(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+so(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function OS(e){return h3.test(e)?f3.parse(e):JSON.parse(e)}var qD,GD,f3,E3,kD,AS,h3,bS=Re(()=>{qD=require("stream"),GD=B(require("json-bigint-fixes")),f3=(0,GD.default)({useNativeBigInt:!0}),E3=1e4,kD={};BigInt.prototype.toJSON=function(){throw kD};a(mu,"streamAsJSON");AS=class extends qD.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),xD)}catch(s){yield xD(s)}else yield so(t)}else yield so(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);FD(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>E3?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 FD(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(xD,"handleError");a(FD,"when");a(so,"stringify");a(VD,"jsStringify");h3=/-?\d{16,}/;a(OS,"parse")});var Ud=T((j_e,YD)=>{"use strict";var m3=Ln();YD.exports={writeTransaction:p3};function p3(e,t,r){return m3.writeTransaction(e,t,r)}a(p3,"writeTransaction")});var zD=T((tde,QD)=>{"use strict";var S3=sn(),T3=ti(),KD=Y(),g3=on(),ede=Ud(),R3=require("clone"),yS=require("alasql"),A3=V_(),WD=require("util"),O3=WD.promisify(T3.getTableSchema),b3=WD.promisify(S3.search),N3=M(),NS=J();A3(yS);QD.exports={update:I3};var y3="There was a problem performing this update. Please check the logs and try again.";async function I3({statement:e,hdb_user:t}){let r=await O3(e.table.databaseid,e.table.tableid),n=w3(e.columns);NS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=R3(s),c=NS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=yS.parse(u).statements[0],l=await b3(_),d=C3(n,l);return D3(o,d,t)}a(I3,"update");function w3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=yS.compile(`SELECT ${r.expression.toString()} AS [${N3.FUNC_VAL}] FROM ?`)}),t}catch(t){throw KD.error(t),new Error(y3)}}a(w3,"createUpdateRecord");function C3(e,t){return NS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(C3,"buildUpdateRecords");async function D3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await g3.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){KD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(D3,"updateRecords")});var XD=T((ide,JD)=>{var L3=require("alasql"),M3=sn(),U3=Y(),P3=Ln(),wS=require("util"),IS=J(),v3=M(),B3=ti(),nde=Ud(),sde=on(),H3="record",x3="successfully deleted",F3=wS.callbackify(V3),q3=wS.promisify(M3.search),G3=wS.promisify(B3.getTableSchema);JD.exports={convertDelete:F3};function k3(e){return`${e.deleted_hashes.length} ${H3}${e.deleted_hashes.length===1?"":"s"} ${x3}`}a(k3,"generateReturnMessage");async function V3({statement:e,hdb_user:t}){let r=await G3(e.table.databaseid,e.table.tableid);IS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=IS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=L3.parse(o).statements[0],u={operation:v3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await q3(c);let _=await P3.deleteRecords(u);return IS.isEmptyOrZeroLength(_.message)&&(_.message=k3(_)),delete _.txn_time,_}catch(_){throw U3.error(_),_.hdb_code?_.message:_}}a(V3,"convertDelete")});var rL=T((ade,tL)=>{"use strict";var $3=Gi(),{hdb_errors:jD}=Z(),{getDatabases:ZD}=(Oe(),ee(Ge));tL.exports={checkSchemaExists:eL,checkSchemaTableExists:Y3,schema_describe:$3};async function eL(e){if(!ZD()[e])return jD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(eL,"checkSchemaExists");async function Y3(e,t){let r=await eL(e);if(r)return r;if(!ZD()[e][t])return jD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Y3,"checkSchemaTableExists")});var pu=T((ude,K3)=>{K3.exports={name:"harperdb",version:"4.3.0-beta.1",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:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.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:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.9.3-beta.3-debug",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",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:"^5.3.3","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 yt=T((Ede,AL)=>{"use strict";var Gt=j();Gt.initSync();var W3=require("fs-extra"),Q3=require("semver"),gu=require("path"),{monotonicFactory:z3}=require("ulidx"),sL=z3(),J3=require("util"),iL=require("child_process"),X3=J3.promisify(iL.exec),j3=iL.spawn,Ne=nt(),Pe=M(),MS=J(),Wr=Y(),Pd=bs(),Z3=Ud(),Su=xr(),{onMessageByType:eX}=tt(),{isMainThread:tX}=require("worker_threads"),{Encoder:rX,decode:US}=require("msgpackr"),oL=new rX,{isEmpty:co}=MS,aL=cn(),nX=48*36e11,sX=5e9;tX&&eX(Pe.ITC_EVENT_TYPES.RESTART,()=>{dn=void 0,ao=void 0});var{connect:iX,StorageType:cL,RetentionPolicy:uL,AckPolicy:vd,DeliverPolicy:Bd,DiscardPolicy:oX,NatsConnection:lde,JetStreamManager:_de,JetStreamClient:dde,StringCodec:fde,JSONCodec:aX,createInbox:PS,headers:cX,ErrorCode:nL}=require("nats"),{PACKAGE_ROOT:uX}=M(),lX=pu(),{recordAction:_X}=(Ns(),ee(tu)),lL=aX(),dX="clustering",fX=lX.engines[Ne.NATS_SERVER_NAME],EX=gu.join(uX,"dependencies"),LS=gu.join(EX,`${process.platform}-${process.arch}`,Ne.NATS_BINARY_NAME),CS,DS,Tu,io,oo;AL.exports={runCommand:_L,checkNATSServerInstalled:hX,createConnection:vS,getConnection:Hd,getJetStreamManager:Ru,getJetStream:fL,getNATSReferences:lr,getServerList:pX,createLocalStream:BS,listStreams:EL,deleteLocalStream:SX,getServerConfig:Au,listRemoteStreams:TX,viewStream:gX,viewStreamIterator:RX,publishToStream:AX,createWorkQueueStream:OX,addSourceToWorkStream:mL,request:NX,removeSourceFromWorkStream:SL,reloadNATS:HS,reloadNATSHub:yX,reloadNATSLeaf:IX,extractServerName:pL,requestErrorHandler:wX,updateWorkStream:CX,createLocalTableStream:gL,createTableStreams:DX,purgeTableStream:RL,purgeSchemaTableStreams:LX,getStreamInfo:MX,updateLocalStreams:PX,closeConnection:mX,getJsmServerName:Ou,addNatsMsgHeader:hL,updateIngestStreamConsumer:bX,clearClientCache:dL};async function _L(e,t=void 0){let{stdout:r,stderr:n}=await X3(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
6
|
+
`)},$z="certificate.pem",Yz="privateKey.pem",Kz="ca.pem";GI.exports={CERTIFICATE_VALUES:Vz,CERTIFICATE_PEM_NAME:$z,PRIVATEKEY_PEM_NAME:Yz,CA_PEM_NAME:Kz}});var Lp=T((Ule,WI)=>{"use strict";var KI=require("fs-extra"),ue=require("joi"),Wz=require("os"),{boolean:Le,string:Mr,number:Dt,array:Dp}=ue.types(),{totalmem:VI}=require("os"),Wi=require("path"),Qz=W(),Z_=J(),Mle=kI(),$I=U(),zz=Ze(),YI="log",Jz="components",Xz="Invalid logging.rotation.maxSize unit. Available units are G, M or K",jz="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Zz="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",eJ="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",tJ="rootPath config parameter is undefined",rJ="clustering.enabled config parameter is undefined",Qi=Dt.min(0).required(),ed=Dp.items({host:Mr.required(),port:Qi}).empty(null),Jn;WI.exports={configValidator:nJ,routesValidator:uJ,route_constraints:ed};function nJ(e){if(Jn=e.rootPath,Z_.isEmpty(Jn))throw tJ;let t=Le.required(),r=Dt.min(0).max(1e3).empty(null).default(cJ),n=Mr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Wc),s=Mr.optional().empty(null),i=Mr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ue.string().empty(null).default(Wc),c=ue.custom(iJ).empty(null).default(Wc),u=e.clustering?.enabled;if(Z_.isEmpty(u))throw rJ;let _;return u===!0?_=ue.object({enabled:t,hubServer:ue.object({cluster:ue.object({name:ue.required().empty(null),network:ue.object({port:Qi,routes:ed}).required()}).required(),leafNodes:ue.object({network:ue.object({port:Qi}).required()}).required(),network:ue.object({port:Qi}).required()}).required(),leafServer:ue.object({network:ue.object({port:Qi,routes:ed}).required(),streams:ue.object({maxAge:Dt.min(120).allow(null).optional(),maxBytes:Dt.min(1).allow(null).optional(),maxMsgs:Dt.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ue.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:Le.optional(),databaseLevel:Le.optional(),tls:ue.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:Le.required(),verify:Le.optional()}),user:Mr.optional().empty(null)}).required():_=ue.object({enabled:t,tls:ue.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:Le.required()})}).required(),ue.object({authentication:ue.object({authorizeLocal:Le,cacheTTL:Dt.required(),enableSessions:Le}),analytics:ue.object({aggregatePeriod:Dt}),componentsRoot:n.optional(),clustering:_,localStudio:ue.object({enabled:t}).required(),logging:ue.object({auditAuthEvents:ue.object({logFailed:Le,logSuccessful:Le}),file:Le.required(),level:ue.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ue.object({enabled:Le.optional(),compress:Le.optional(),interval:Mr.custom(aJ).optional().empty(null),maxSize:Mr.custom(oJ).optional().empty(null),path:Mr.optional().empty(null).default(Wc)}).required(),root:n,stdStreams:Le.required(),auditLog:Le.required()}).required(),operationsApi:ue.object({network:ue.object({cors:Le.optional(),corsAccessList:Dp.optional(),headersTimeout:Dt.min(1).optional(),keepAliveTimeout:Dt.min(1).optional(),port:Dt.optional().empty(null),domainSocket:ue.optional().empty("hdb/operations-server").default(Wc),securePort:Dt.optional().empty(null),timeout:Dt.min(1).optional()}).optional(),tls:ue.object({certificate:s,certificateAuthority:s,privateKey:s})}).required(),rootPath:Mr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ue.object({network:ue.object({port:Qi,securePort:Qi,mtls:ue.alternatives([Le.optional(),ue.object({user:Mr.optional(),certificateAuthority:s,required:Le.optional()})])}).required(),webSocket:Le.optional(),requireAuthentication:Le.optional()}),http:ue.object({compressionThreshold:Dt.optional(),cors:Le.optional(),corsAccessList:Dp.optional(),headersTimeout:Dt.min(1).optional(),port:Dt.min(0).optional().empty(null),securePort:Dt.min(0).optional().empty(null),mtls:ue.alternatives([Le.optional(),ue.object({user:Mr.optional(),certificateAuthority:s,required:Le.optional()})])}).required(),threads:r.optional(),maxHeapMemory:Dt.min(0).optional(),storage:ue.object({writeAsync:Le.required(),overlappingSync:Le.optional(),caching:Le.optional(),compression:Le.optional(),noReadAhead:Le.optional(),path:c,prefetchWrites:Le.optional()}).required(),ignoreScripts:Le.optional(),tls:ue.object({certificate:s.optional(),certificateAuthority:s.optional(),privateKey:s.optional(),ciphers:Mr.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(nJ,"configValidator");function sJ(e){return KI.existsSync(e)?null:`Specified path ${e} does not exist.`}a(sJ,"doesPathExist");function iJ(e,t){ue.assert(e,Mr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=sJ(e);if(r)return t.message(r)}a(iJ,"validatePath");function oJ(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(Xz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Zz):e}a(oJ,"validateRotationMaxSize");function aJ(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(jz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(eJ):e}a(aJ,"validateRotationInterval");function cJ(e,t){let r=t.state.path.join("."),n=Wz.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||VI();return i=Math.round(Math.min(i,VI())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Qz.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(cJ,"setDefaultThreads");function Wc(e,t){let r=t.state.path.join(".");if(!Z_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(Z_.isEmpty(Jn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(Jn,Jz);case"logging.root":return Wi.join(Jn,YI);case"clustering.leafServer.streams.path":return Wi.join(Jn,"clustering","leaf");case"storage.path":let n=Wi.join(Jn,$I.LEGACY_DATABASES_DIR_NAME);return KI.existsSync(n)?n:Wi.join(Jn,$I.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(Jn,YI);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(Jn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Wc,"setDefaultRoot");function uJ(e){let t=ue.object({routes:ed});return zz.validateBySchema({routes:e},t)}a(uJ,"routesValidator")});var vr=T((Ble,rC)=>{"use strict";var Pr=U(),Lt=J(),Rt=W(),{configValidator:lJ,routesValidator:QI}=Lp(),sr=require("fs-extra"),_J=require("yaml"),Dn=require("path"),dJ=require("is-number"),JI=require("properties-reader"),fJ=require("lodash"),{handleHDBError:EJ}=ee(),{HTTP_STATUS_CODES:hJ,HDB_ERROR_MSGS:td}=br(),vle=require("minimist"),{server:mJ}=(zt(),te(yi)),{DATABASES_PARAM_CONFIG:Qc,CONFIG_PARAMS:Ur,CONFIG_PARAM_MAP:Ln}=Pr,pJ="Unable to get config value because config is uninitialized",SJ="Config successfully initialized",TJ="Error backing up config file",gJ="Empty parameter sent to getConfigValue",XI=Dn.join(Pr.PACKAGE_ROOT,"config","yaml",Pr.HDB_DEFAULT_CONFIG_FILE),RJ="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",zI={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"},rd,At,nd;rC.exports={createConfigFile:AJ,getDefaultConfig:OJ,getConfigValue:ZI,initConfig:Up,flattenConfig:ta,updateConfigValue:eC,updateConfigObject:NJ,getConfiguration:IJ,setConfiguration:CJ,readConfigFile:vp,getClusteringRoutes:DJ,initOldConfig:tC,getConfigFromFile:LJ,getConfigFilePath:zi,addConfig:MJ,deleteConfigFromFile:UJ,getConfigObj:PJ};function AJ(e){let t=ri(XI);rd=ta(t.toJSON());let r;for(let o in e){let c=Ln[o.toLowerCase()];if(c===Ur.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=Mp(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){Rt.error(l)}}}r&&jI(t,r),Pp(t);let n=t.toJSON();At=ta(n);let s=t.getIn(["rootPath"]),i=Dn.join(s,Pr.HDB_CONFIG_FILE);sr.createFileSync(i),sr.writeFileSync(i,String(t)),Rt.trace(`Config file written to ${i}`)}a(AJ,"createConfigFile");function jI(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Lt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Qc.TABLES))for(let i in n[s][Qc.TABLES])for(let o in n[s][Qc.TABLES][i]){let c=n[s][Qc.TABLES][i][o],u=[Ur.DATABASES,s,Qc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Ur.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){Rt.error("Error parsing schemas CLI/env config arguments",n)}}a(jI,"setSchemasConfig");function OJ(e){if(rd===void 0){let r=ri(XI);rd=ta(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return rd[t.toLowerCase()]}a(OJ,"getDefaultConfig");function ZI(e){if(e==null){Rt.error(gJ);return}if(At===void 0){Rt.trace(pJ);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return At[t.toLowerCase()]}a(ZI,"getConfigValue");function zi(e=Lt.getPropsFilePath()){let t=Lt.getEnvCliRootPath();return t?Dn.join(t,Pr.HDB_CONFIG_FILE):JI(e).get(Pr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function Up(e=!1){if(At===void 0||e){let t;if(!Lt.noBootFile()){t=Lt.getPropsFilePath();try{sr.accessSync(t,sr.constants.F_OK|sr.constants.R_OK)}catch(i){throw Rt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=zi(t),n;if(r.includes("config/settings.js"))try{tC(r);return}catch(i){if(i.code!==Pr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ri(r)}catch(i){if(i.code===Pr.NODE_ERROR_CODES.ENOENT){Rt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw Rt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}bJ(n,r),Pp(n);let s=n.toJSON();if(mJ.config=s,At=ta(s),At.logging_rotation_rotate)for(let i in zI)At[i]&&Rt.error(`Config ${zI[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Rt.trace(SJ)}}a(Up,"initConfig");function bJ(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),n&&(Rt.trace("Updating config file with missing config params"),sr.writeFileSync(t,String(e)))}a(bJ,"checkForUpdatedConfig");function Pp(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=lJ(t);if(r.error)throw td.CONFIG_VALIDATION(r.error.message);e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(Pp,"validateConfig");function NJ(e,t){At===void 0&&(At={});let r=Ln[e.toLowerCase()];if(r===void 0){Rt.trace(`Unable to update config object because config param '${e}' does not exist`);return}At[r.toLowerCase()]=t}a(NJ,"updateConfigObject");function eC(e,t,r=void 0,n=!1,s=!1,i=!1){At===void 0&&Up();let o=ZI(Ln.hdb_root),c=Dn.join(o,Pr.HDB_CONFIG_FILE),u=ri(c),_;if(r===void 0&&e.toLowerCase()===Ur.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Ln[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Mp(f,t);u.setIn([...E],h)}else for(let f in r){let E=Ln[f.toLowerCase()];if(E===Ur.HTTP_SECUREPORT&&r[f]===At[Ur.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Ur.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===At[Ur.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Ur.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=Pr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=Mp(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(O){Rt.error(O)}}}_&&jI(u,_),Pp(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,Pr.HDB_CONFIG_FILE);n===!0&&yJ(c,l),sr.writeFileSync(d,String(u)),s&&(At=ta(u.toJSON())),Rt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(eC,"updateConfigValue");function yJ(e,t){try{let r=Dn.join(t,"backup",`${Pr.HDB_CONFIG_FILE}.bak`);sr.copySync(e,r),Rt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Rt.error(TJ),Rt.error(r)}}a(yJ,"backupConfigFile");var wJ=["databases"];function ta(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),nd=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!wJ.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Ur[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(ta,"flattenConfig");function Mp(e,t){if(e===Ur.CLUSTERING_NODENAME||e===Ur.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(dJ(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Lt.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 Lt.autoCast(t)}a(Mp,"castConfigValue");function IJ(){let e=Lt.getPropsFilePath(),t=zi(e);return ri(t).toJSON()}a(IJ,"getConfiguration");async function CJ(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return eC(void 0,void 0,s,!0),RJ}catch(i){throw typeof i=="string"||i instanceof String?EJ(i,i,hJ.BAD_REQUEST,void 0,void 0,!0):i}}a(CJ,"setConfiguration");function vp(){let e=Lt.getPropsFilePath();try{sr.accessSync(e,sr.constants.F_OK|sr.constants.R_OK)}catch(n){if(!Lt.noBootFile())throw Rt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return ri(t).toJSON()}a(vp,"readConfigFile");function ri(e){return _J.parseDocument(sr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ri,"parseYamlDoc");function DJ(){let e=vp(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Lt.isEmptyOrZeroLength(t)?[]:t;let r=QI(t);if(r)throw td.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Lt.isEmptyOrZeroLength(n)?[]:n;let s=QI(n);if(s)throw td.CONFIG_VALIDATION(s.message);if(!Lt.isEmptyOrZeroLength(n)&&!Lt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Lt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw td.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(DJ,"getClusteringRoutes");function tC(e){let t=JI(e);At={};for(let r in Ln){let n=t.get(r.toUpperCase());if(Lt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Ur.LOGGING_ROOT?At[s]=Dn.dirname(n):At[s]=n}return At}a(tC,"initOldConfig");function LJ(e){let t=vp();return fJ.get(t,e.replaceAll("_","."))}a(LJ,"getConfigFromFile");async function MJ(e,t){let r=ri(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await sr.writeFile(zi(),String(r))}a(MJ,"addConfig");function UJ(e){let t=zi(Lt.getPropsFilePath()),r=ri(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,Pr.HDB_CONFIG_FILE);sr.writeFileSync(s,String(r))}a(UJ,"deleteConfigFromFile");function PJ(){return nd||(Up(),nd)}a(PJ,"getConfigObj")});var sC=T((xle,nC)=>{"use strict";var sd=U(),id=class{static{a(this,"BaseLicense")}constructor(t=0,r=sd.RAM_ALLOCATION_ENUM.DEFAULT,n=sd.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},Bp=class extends id{static{a(this,"ExtendedLicense")}constructor(t=0,r=sd.RAM_ALLOCATION_ENUM.DEFAULT,n=sd.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};nC.exports={BaseLicense:id,ExtendedLicense:Bp}});var Ji=T((qle,lC)=>{"use strict";var na=require("fs-extra"),oC=j_(),aC=require("crypto"),vJ=require("moment"),BJ=require("uuid").v4,Yt=W(),xp=require("path"),HJ=J(),ni=U(),{totalmem:iC}=require("os"),xJ=sC().ExtendedLicense,ra="invalid license key format",FJ="061183",qJ="mofi25",GJ="aes-256-cbc",kJ=16,VJ=32,cC=Z();cC.initSync();var Hp;lC.exports={validateLicense:uC,generateFingerPrint:YJ,licenseSearch:Gp,getLicense:QJ,checkMemoryLimit:zJ};function Fp(){return xp.join(cC.getHdbBasePath(),ni.LICENSE_KEY_DIR_NAME,ni.LICENSE_FILE_NAME)}a(Fp,"getLicenseDirPath");function $J(){let e=Fp();return xp.join(e,ni.LICENSE_FILE_NAME)}a($J,"getLicenseFilePath");function qp(){let e=Fp();return xp.join(e,ni.REG_KEY_FILE_NAME)}a(qp,"getFingerPrintFilePath");async function YJ(){let e=qp();try{return await na.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await KJ();throw Yt.error(`Error writing fingerprint file to ${e}`),Yt.error(t),new Error("There was an error generating the fingerprint")}}a(YJ,"generateFingerPrint");async function KJ(){let e=BJ(),t=oC.hash(e),r=qp();try{await na.mkdirp(Fp()),await na.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Yt.error(`Error writing fingerprint file to ${r}`),Yt.error(n),new Error("There was an error generating the fingerprint")}return t}a(KJ,"writeFingerprint");function uC(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ni.RAM_ALLOCATION_ENUM.DEFAULT,version:ni.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Yt.error("empty license key passed to validate."),r;let n=qp(),s=!1;try{s=na.statSync(n)}catch(i){Yt.error(i)}if(s){let i;try{i=na.readFileSync(n,"utf8")}catch{Yt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(qJ),c=o[1];c=Buffer.concat([Buffer.from(c)],kJ);let u=Buffer.concat([Buffer.from(i)],VJ),_=aC.createDecipheriv(GJ,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=WJ(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(ra),Yt.error(ra),new Error(ra)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(ra),Yt.error(ra),new Error(ra)}else r.exp_date=l;r.exp_date<vJ().valueOf()&&(r.valid_date=!1),oC.validate(o[1],`${FJ}${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||Yt.error("Invalid licence"),r}a(uC,"validateLicense");function WJ(e,t){try{let r=aC.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Yt.warn("Check old license failed")}}a(WJ,"checkOldLicense");function Gp(){let e=new xJ,t=[];try{t=na.readFileSync($J(),"utf-8").split(ni.NEW_LINE)}catch(r){r.code==="ENOENT"?Yt.info("no license file found"):Yt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(HJ.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=uC(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){Yt.error("There was an error parsing the license string."),Yt.error(s),e.ram_allocation=ni.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Hp=e,e}a(Gp,"licenseSearch");async function QJ(){return Hp||await Gp(),Hp}a(QJ,"getLicense");function zJ(){let e=Gp().ram_allocation,t=process.constrainedMemory?.()||iC();if(t=Math.round(Math.min(t,iC())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(zJ,"checkMemoryLimit")});var nn=T((Yle,yC)=>{"use strict";var EC="username is required",hC="nothing to update, must supply active, role or password to update",mC="password cannot be an empty string",pC="If role is specified, it cannot be empty.",SC="active must be true or false";yC.exports={addUser:s2,alterUser:i2,dropUser:a2,getSuperUser:_2,userInfo:c2,listUsers:ad,listUsersExternal:u2,setUsersToGlobal:ia,findAndValidateUser:bC,getClusterUser:d2,USERNAME_REQUIRED:EC,ALTERUSER_NOTHING_TO_UPDATE:hC,EMPTY_PASSWORD:mC,EMPTY_ROLE:pC,ACTIVE_BOOLEAN:SC};var TC=rn(),JJ=Ki(),$p=j_(),gC=xI(),RC=tn(),Yp=Ts(),Br=J(),AC=require("validate.js"),Ae=W(),{promisify:XJ}=require("util"),Kp=Os(),_C=U(),dC=et(),jJ=vr(),kle=Z(),Vle=Ji(),ZJ=Pi(),{table:$le}=(Ne(),te(qe)),{handleHDBError:Xn,hdb_errors:e2}=ee(),{HTTP_STATUS_CODES:jn,AUTHENTICATION_ERROR_MSGS:kp,HDB_ERROR_MSGS:sa}=e2,{UserEventMsg:Wp}=bn(),Vp=require("lodash"),{server:Qp}=(zt(),te(yi)),t2=W();Qp.getUser=(e,t)=>bC(e,t,t!=null);var OC={username:!0,active:!0,role:!0,password:!0},fC=new Map,od=RC.searchByValue,r2=RC.searchByHash,n2=XJ(JJ.delete);async function s2(e){let t=AC.cleanAttributes(e,OC),r=gC.addUserValidation(t);if(r)throw Xn(new Error,r.message,jn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await od(n),s=s&&Array.from(s)}catch(u){throw Ae.error("There was an error searching for a role in add user"),Ae.error(u),u}if(!s||s.length<1)throw Xn(new Error,sa.ROLE_NAME_NOT_FOUND(t.role),jn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Xn(new Error,sa.DUP_ROLES_FOUND(t.role),jn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=Kp.encrypt(t.password)),t.password=$p.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await TC.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await ia()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.error(u),u}if(o.skipped_hashes.length===1)throw Xn(new Error,sa.USER_ALREADY_EXISTS(t.username),jn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],Yp.signalUserChange(new Wp(process.pid)),`${c.username} successfully added`}a(s2,"addUser");async function i2(e){let t=AC.cleanAttributes(e,OC);if(Br.isEmptyOrZeroLength(t.username))throw new Error(EC);if(Br.isEmptyOrZeroLength(t.password)&&Br.isEmptyOrZeroLength(t.role)&&Br.isEmptyOrZeroLength(t.active))throw new Error(hC);if(!Br.isEmpty(t.password)&&Br.isEmptyOrZeroLength(t.password.trim()))throw new Error(mC);if(!Br.isEmpty(t.active)&&!Br.isBoolean(t.active))throw new Error(SC);let r=o2(t.username);if(!Br.isEmpty(t.password)&&!Br.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Kp.encrypt(t.password)),t.password=$p.hash(t.password)),t.role==="")throw new Error(pC);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 od(i)||[])}catch(c){throw Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=sa.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.error(c),Xn(new Error,c,jn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=sa.ALTER_USER_DUP_ROLES(t.role);throw Ae.error(c),Xn(new Error,c,jn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await TC.update(n)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await ia()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return Yp.signalUserChange(new Wp(process.pid)),s}a(i2,"alterUser");function o2(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(o2,"isClusterUser");async function a2(e){try{let t=gC.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Br.isEmpty(global.hdb_users.get(e.username)))throw Xn(new Error,sa.USER_NOT_EXIST(e.username),jn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await n2(r)}catch(s){throw Ae.error("Got an error deleting a user."),Ae.error(s),s}Ae.debug(n);try{await ia()}catch(s){throw Ae.error("Got an error setting users to global."),Ae.error(s),s}return Yp.signalUserChange(new Wp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(a2,"dropUser");async function c2(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Vp.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await r2(r)}catch(s){throw Ae.error("Got an error searching for a role."),Ae.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ae.error(r),r}return t}a(c2,"userInfo");async function u2(){let e;try{e=await ad()}catch(t){throw Ae.error("Got an error listing users."),Ae.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(u2,"listUsersExternal");async function ad(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await od(e)}catch(o){throw Ae.error("Got an error searching for roles."),Ae.error(o),o}let r={};for(let o of t)r[o.id]=Vp.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await od(n)}catch(o){throw Ae.error("Got an error searching for users."),Ae.error(o),o}let i=new Map;for(let o of s)o=Vp.cloneDeep(o),o.role=r[o.role],l2(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),Br.errorizeMessage(e)}return null}a(ad,"listUsers");function l2(e){try{if(!e){Ae.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(ZJ)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Ae.error("Got an error trying to set system permissions."),Ae.error(t)}}a(l2,"appendSystemTablesToRole");async function ia(){try{let e=await ad();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(ia,"setUsersToGlobal");async function bC(e,t,r=!0){global.hdb_users||await ia();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Xn(new Error,kp.GENERIC_AUTH_FAIL,jn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Xn(new Error,kp.USER_INACTIVE,jn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(fC.get(t)===n.password)return s;if($p.validate(n.password,t))fC.set(t,n.password);else throw Xn(new Error,kp.GENERIC_AUTH_FAIL,jn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(bC,"findAndValidateUser");async function _2(){global.hdb_users||await ia();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(_2,"getSuperUser");async function d2(){let e=await ad(),t=jJ.getConfigFromFile(_C.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Br.isEmpty(r)&&r?.role?.role===_C.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Kp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+dC.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+dC.SERVER_SUFFIX.ADMIN,r}a(d2,"getClusterUser");var NC=[];Qp.invalidateUser=function(e){for(let t of NC)try{t(e)}catch(r){t2.error("Error invalidating user",r)}};Qp.onInvalidatedUser=function(e){NC.push(e)}});var Jc=T((zle,DC)=>{"use strict";var Xi=W(),Hr=U(),f2=Ub(),Wle=Zs(),Qle=Gi(),E2=nn(),{validateEvent:wC}=bn(),zc=In(),h2=require("process"),{resetDatabases:m2}=(Ne(),te(qe)),p2={[Hr.ITC_EVENT_TYPES.SCHEMA]:S2,[Hr.ITC_EVENT_TYPES.USER]:CC};async function S2(e){let t=wC(e);if(t){Xi.error(t);return}Xi.trace("ITC schemaHandler received schema event:",e),await f2(e.message),await T2(e.message)}a(S2,"schemaHandler");async function T2(e){try{zc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),zc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),zc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=m2();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Xi.error(t)}}a(T2,"syncSchemaMetadata");var IC=[];async function CC(e){try{try{zc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),zc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Xi.warn(r)}let t=wC(e);if(t){Xi.error(t);return}Xi.trace(`ITC userHandler ${Hr.HDB_ITC_CLIENT_PREFIX}${h2.pid} received user event:`,e),await E2.setUsersToGlobal();for(let r of IC)r()}catch(t){Xi.error(t)}}a(CC,"userHandler");CC.addListener=function(e){IC.push(e)};DC.exports=p2});var bn=T((t_e,MC)=>{"use strict";var Xle=W(),zp=J(),g2=U(),{ITC_ERRORS:Xc}=br(),{parentPort:jle,threadId:R2,isMainThread:A2,workerData:Zle}=require("worker_threads"),{onMessageFromWorkers:O2,broadcast:e_e,broadcastWithAcknowledgement:b2}=je();MC.exports={sendItcEvent:N2,validateEvent:LC,SchemaEventMsg:y2,UserEventMsg:w2};var cd;O2(async(e,t)=>{cd=cd||Jc(),LC(e),cd[e.type]&&await cd[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function N2(e){return!A2&&e.message&&(e.message.originator=R2),b2(e)}a(N2,"sendItcEvent");function LC(e){if(typeof e!="object")return Xc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||zp.isEmpty(e.type))return Xc.MISSING_TYPE;if(!e.hasOwnProperty("message")||zp.isEmpty(e.message))return Xc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||zp.isEmpty(e.message.originator))return Xc.MISSING_ORIGIN;if(g2.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Xc.INVALID_EVENT(e.type)}a(LC,"validateEvent");function y2(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(y2,"SchemaEventMsg");function w2(e){this.originator=e}a(w2,"UserEventMsg")});var Ts=T((s_e,BC)=>{"use strict";var UC=U(),n_e=J(),ud=W(),PC=hb(),oa,{sendItcEvent:vC}=bn();function I2(e){try{ud.trace("signalSchemaChange called with message:",e),oa=oa||Jc();let t=new PC(UC.ITC_EVENT_TYPES.SCHEMA,e);return oa.schema(t),vC(t)}catch(t){ud.error(t)}}a(I2,"signalSchemaChange");function C2(e){try{ud.trace("signalUserChange called with message:",e),oa=oa||Jc();let t=new PC(UC.ITC_EVENT_TYPES.USER,e);return oa.user(t),vC(t)}catch(t){ud.error(t)}}a(C2,"signalUserChange");BC.exports={signalSchemaChange:I2,signalUserChange:C2}});var tu={};Fe(tu,{addAnalyticsListener:()=>eu,recordAction:()=>xr,recordActionBinary:()=>sn,setAnalyticsEnabled:()=>D2});function D2(e){KC=e}function xr(e,t,r,n,s){if(!KC)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=dd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},dd.set(i,o)}ld||L2()}function sn(e,t,r,n,s){xr(!!e,t,r,n,s)}function eu(e){zC.push(e)}function L2(){ld=performance.now(),setTimeout(async()=>{let e=performance.now()-ld;ld=0;let t=[],r={time:Date.now(),period:e,threadId:ji.threadId,metrics:t};for(let[s,i]of dd){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of JC){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await XC()}let n=process.memoryUsage();t.push({metric:"memory",threadId:ji.threadId,byThread:!0,...n});for(let s of zC)s(t);dd=new Map,ji.parentPort?ji.parentPort.postMessage({type:QC,report:r}):eD({report:r})},WC).unref()}async function M2(e,t=6e4){let r=jp(),n=jC(),s;for(let h of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){s=h.value.time;break}if(Date.now()-t<s)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:p}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:S,threadId:O}=p;for(let g of S||[]){let{path:R,method:B,type:H,metric:v,count:M,total:$,distribution:K,threads:z,...se}=g;M||(M=1);let Te=v+(R?"-"+R:"");B!==void 0&&(Te+="-"+B),H!==void 0&&(Te+="-"+H);let oe=o.get(Te);if(oe){if(oe.threads){let de=oe.threads[O];if(de)oe=de;else{oe.threads[O]=Object.assign({},se);continue}}oe.count||(oe.count=1);let xe=oe.count;for(let de in se){let It=se[de];typeof It=="number"&&(oe[de]=(oe[de]*xe+It*M)/(xe+M))}oe.count+=M,$>=0&&(oe.total+=$,oe.ratio=oe.total/oe.count)}else oe=Object.assign({period:t},g),delete oe.distribution,o.set(Te,oe),oe.byThread&&(oe.threads=[],oe.threads[O]=Object.assign({},se),u.push(oe));if(K){K=K.map(de=>typeof de=="number"?{value:de,count:1}:de);let xe=c.get(Te);xe?xe.push(...K):c.set(Te,K)}}await XC()}for(let h of u){let{path:p,method:S,type:O,metric:g,count:R,total:B,distribution:H,threads:v,...M}=h;v=v.filter($=>$);for(let $ in M){if(typeof h[$]!="number")continue;let K=0;for(let z of v){let se=z[$];typeof se=="number"&&(K+=se)}h[$]=K}h.count=v.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((de,It)=>de.value>It.value?1:-1);let O=S.count-1,g=[],R=0,B=0,H;for(let de of JC){let It=O*de;for(;R<It;)H=p[B++],R+=H.count,B===1&&R--;let bl=p[B>1?B-2:0];H||(H=p[0]),g.push(H.value-(H.value-bl.value)*(R-It)/H.count)}let[v,M,$,K,z,se,Te,oe,xe]=g;Object.assign(S,{p1:v,p10:M,p25:$,median:K,p75:z,p90:se,p95:Te,p99:oe,p999:xe})}let l;for(let[h,p]of o)p.id=(0,_d.getNextMonotonicTime)(),p.time=_,n.primaryStore.put(p.id,p,{append:!0}).then(S=>{S||n.primaryStore.put(p.id,p)}),l=!0;let d=Date.now(),{idle:f,active:E}=performance.eventLoopUtilization();if(l||E*10>f){let h=(0,_d.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-HC,active:E-xC,time:d,...process.memoryUsage()};n.primaryStore.put(h,p,{append:!0}).then(S=>{S||n.primaryStore.put(h,p)})}HC=f,xC=E}async function FC(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function jp(){return qC||(qC=at({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function jC(){return GC||(GC=at({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function v2(){ZC=!0;let e=(0,Zc.get)(Xp.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await M2(WC,e),await FC(jp(),U2),await FC(jC(),P2)},Math.min(e/2,2147483647)).unref()}function eD(e,t){let r=e.report;r.threadId=t?.threadId||ji.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(kC+=n.mean*n.count);r.totalBytesProcessed=kC,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(VC.get(t))}),VC.set(t,t.performance.eventLoopUtilization())),r.id=(0,_d.getNextMonotonicTime)(),jp().primaryStore.put(r.id,r),ZC||v2(),B2&&(tD=x2(r))}async function x2(e){if(await tD,!si){let r=(0,jc.dirname)((0,YC.getLogFilePath)());try{si=await(0,Jp.open)((0,jc.join)(r,"analytics.log"),"r+")}catch{si=await(0,Jp.open)((0,jc.join)(r,"analytics.log"),"w+")}}let t=(await si.stat()).size;if(t>H2){let r=Buffer.alloc(t);await si.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await si.write(r,{position:0}),await si.truncate(r.length),t=r.length}await si.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var ji,$C,YC,jc,Jp,_d,Zc,Xp,dd,KC,ld,WC,QC,zC,JC,HC,xC,XC,U2,P2,qC,GC,ZC,kC,VC,B2,tD,si,H2,bs=Oe(()=>{ji=require("worker_threads"),$C=x(je());Ne();YC=x(W()),jc=require("path"),Jp=require("fs/promises"),_d=x(Nr()),Zc=x(Z()),Xp=x(U());zt();(0,Zc.initSync)();dd=new Map,KC=(0,Zc.get)(Xp.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(D2,"setAnalyticsEnabled");a(xr,"recordAction");Xe.recordAnalytics=xr;a(sn,"recordActionBinary");ld=0,WC=1e3,QC="analytics-report",zC=[];a(eu,"addAnalyticsListener");JC=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(L2,"sendAnalytics");a(M2,"aggregation");HC=0,xC=0,XC=a(()=>new Promise(setImmediate),"rest");a(FC,"cleanup");U2=36e5,P2=31536e6;a(jp,"getRawAnalyticsTable");a(jC,"getAnalyticsTable");(0,$C.setChildListenerByType)(QC,eD);a(v2,"startScheduledTasks");kC=0,VC=new Map,B2=!1;a(eD,"recordAnalytics");H2=1e6;a(x2,"logAnalytics")});var rS={};Fe(rS,{coerceType:()=>fd,makeTable:()=>md,setServerUtilities:()=>W2,updateResource:()=>Ed});function md(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:p}=e;p||(p=[]),db(i,u);let S=Rh(i,n,u),O=0,g,R,B={},H=Promise.resolve(),v,M,$;for(let Y of p)(Y.assignCreatedTime||Y.name==="__createdtime__")&&(v=Y),(Y.assignUpdatedTime||Y.name==="__updatedtime__")&&(M=Y),Y.expiresAt&&($=Y),Y.isPrimaryKey&&(B=Y);let K,z=[],se=[],Te=1,oe=2,xe={},de={},It=864e5,bl,Nl,ks,AA=!1,$E,zx=i.getRange({start:!1,end:!1}).constructor,Jx=10,Xx=6;E&&NA();class We extends vt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=v;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),R=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(w=>{let y=this.sources.slice(0,-1);if(y=y.filter(P=>P[w]&&(!P[w].reliesOnPrototype||P.prototype[w])),y.length>0)if(y.length===1){let P=y[0];return(L,D,F)=>{if(L?.source!==P)return P[w](D,F,L)}}else return(P,L,D)=>{let F=[];for(let G of y){if(P?.source===G)break;F.push(G[w](L,D,P))}return Promise.all(F)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1],N=a(w=>{if(b[w]&&(!b[w].reliesOnPrototype||b.prototype[w]))return(y,P,L)=>{if(!y?.source)return b[w](P,L,y)}},"getApplyToCanonicalSource");return xe={put:N("put"),patch:N("patch"),delete:N("delete"),publish:N("publish")},de={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let w=!1,y=a(async(P,L)=>{let D=P.value,F=P.table?tt[c][P.table]:We;if(c===Mn.SYSTEM_SCHEMA_NAME&&(P.table===Mn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||P.table===Mn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(w=!0),P.id===void 0&&(P.id=D[F.primaryKey],P.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(P));P.source=m;let G=await F.getResource(P.id,L,aa);switch(P.type){case"put":return G._writeUpdate(D,!0,aa);case"patch":return G._writeUpdate(D,!1,aa);case"delete":return G._writeDelete(aa);case"publish":return G._writePublish(D,aa);case"invalidate":return G.invalidate(aa);default:ze.error("Unknown operation",P.type,P.id)}},"writeUpdate");try{let P=m.subscribe;P&&h==null&&(h=!0);let L=m.subscribeOnThisThread?m.subscribeOnThisThread((0,eo.getWorkerIndex)()):(0,eo.getWorkerIndex)()===0,D=P&&L&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let F;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){ze.error("Bad subscription event",G);continue}if(G.source=m,F)if(G.beginTxn)F.resolve();else{y(G,F);continue}if(G.type==="end_txn")continue;let ae=Ke(G,()=>{if(G.type==="transaction"){let re=[];for(let ce of G.writes)try{re.push(y(ce,G))}catch(ve){throw ve.message+=" writing "+JSON.stringify(ce)+" of event "+JSON.stringify(G),ve}return Promise.all(re)}else if(G.type==="define_schema"){let re=this.attributes.slice(0),ce;for(let ve of G.attributes)re.find(ne=>ne.name===ve.name)||(re.push(ve),ce=!0);ce&&(at({table:s,database:c,attributes:re,origin:"cluster"}),cu.signalSchemaChange(new uu.SchemaEventMsg(process.pid,Mn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(F=G,y(G,G),new Promise(re=>{F.resolve=re})):y(G,G)});w&&(await ae,cu.signalUserChange(new uu.UserEventMsg(process.pid))),G.onCommit&&(ae?.then?ae.then(G.onCommit):G.onCommit())}catch(ie){ze.error("error in subscription handler",ie)}}}catch(P){ze.error(P)}})(),this}static getResource(m,A,I){let b=super.getResource(m,A,I);if(m!=null){Qa(m);try{if(b.hasOwnProperty(he))return b;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let N=!I?.async||i.cache?.get(m),w=gr(A),y=w.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return YE(m,A,{transaction:y},N,P=>{if(P?Ed(b,P):b[he]=null,A.onlyIfCached&&A.noCacheStore){if(!b.doesExist())throw new on.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let L=KE(m,P,A,b);if(L)return w?.disregardReadTxn(),b[Zp]=!0,tS(L,D=>(Ed(b,D),b))}return b})}catch(N){throw N.message.includes("Unable to serialize object")&&(N.message+=": "+JSON.stringify(m)),N}}return b}ensureLoaded(){let m=KE(this[De],this[Fr],this[be]);if(m)return this[Zp]=!0,tS(m,A=>{this[Fr]=A,this[he]=A.value,this[ou]=A.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,It=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");It=It||(d+f)/4,QE()}static enableAuditing(m=!0){E=m,m&&NA(),We.audit=m}static coerceId(m){return m===""?null:fd(m,B)}static async dropTable(){if(delete tt[c][s],c===o){for(let m of p)l.remove(We.tableName+"/"+m.name),r[m.name]?.drop();l.remove(We.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));cu.signalSchemaChange(new uu.SchemaEventMsg(process.pid,Mn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Zr])return this.search(m);if(this[De]===null){if(m?.conditions)return this.search(m);let A=We.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[be]?.returnNonexistent)return this}allowRead(m,A){let I=wl(m);if(I?.read){if(I.isSuperUser)return!0;let b=I.attribute_permissions,N=A?.select;if(b?.length>0||AA&&N){if(A||(A={}),N){let w=b?.length>0&&eS(b,"read");A.select=N.map(y=>{let P=y.name||y;if(!w||w[P]){let L=ks[P]?.definition?.tableClass;if(L){if(y.name||(y={name:y}),!L.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else A.select=b.filter(w=>w.read&&!ks[w.attribute_name]).map(w=>w.attribute_name);return A}else return!0}}allowUpdate(m,A){let I=wl(m);if(I?.update){let b=I.attribute_permissions;if(b?.length>0){let N=eS(b,"update");for(let w in A)if(!N[w])return!1;for(let w of b){let y=w.attribute_name;!w.update&&!(y in A)&&(A[y]=this.getProperty(y))}}return!0}}allowCreate(m,A){if(this[Zr]){let I=wl(m);if(I?.insert){let b=I.attribute_permissions;if(b?.length>0){let N=eS(b,"insert");for(let w in A)if(!N[w])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return wl(m)?.delete}update(m,A){if(!gr(this[be]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let b;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[he]={},this[gt]=m):(b=this[gt],b&&(m=Object.assign(b,m)),this[gt]=b=m)),this._writeUpdate(this[gt],A),this}addTo(m,A){if(typeof A=="number")this[ru]===nD?this.set(m,(+this.getProperty(m)||0)+A):(this[ru]||this.update(),this.set(m,new r_(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let A=this[be],I=this[De];Qa(I),gr(this[be]).addWrite({key:I,store:i,invalidated:!0,entry:this[Fr],nodeName:this[be]?.nodeName,before:xe.invalidate?.bind(this,A,I),beforeIntermediate:de.invalidate?.bind(this,A,I),commit:(N,w)=>{if(w?.version>N)return;let y=null;for(let P in r)y||(y={}),y[P]=this.getProperty(P);S(I,y,this[Fr],N,nu,E,this[be],0,"invalidate")}})}static evict(m,A,I){let b=this.Source,N;if(!((R||E)&&(!A||(N=i.getEntry(m),!N||!A)||N.version!==I))){if(R){if(i.hasLock(m,N.version))return;let w;for(let y in r)w||(w={}),w[y]=A[y];if(w)return S(m,w,N,I,su,null,null,0,null,!0)}return i.ifVersion(I,()=>{yl(m,A,null)}),E?S(m,null,N,I,su,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,uD.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,I){let b=this[be],N=gr(b),w=this[De];Qa(w);let y=this[Fr];this[ru]=A?nD:$2;let P={key:w,store:i,entry:y,nodeName:b?.nodeName,validate:L=>{m||(m=this[gt]),A||m&&e_(m)?(this.validate(m,!A),b?.source||(M&&(m[M.name]=M.type==="Date"?new Date(L):M.type==="String"?new Date(L).toISOString():L),A&&(t&&m[t]!==w&&(m[t]=w),v&&(y?.value?m[v.name]=y?.value[v.name]:m[v.name]=v.type==="Date"?new Date(L):v.type==="String"?new Date(L).toISOString():L),m=Li(m)))):N.removeWrite(P)},before:A?xe.put?()=>xe.put(b,w,m):null:xe.patch?()=>xe.patch(b,w,m):xe.put?()=>xe.put(b,w,Li(this)):null,beforeIntermediate:A?de.put?()=>de.put(b,w,m):null:de.patch?()=>de.patch(b,w,m):de.put?()=>de.put(b,w,Li(this)):null,commit:(L,D,F)=>{if(F){if(b&&D?.version>(b.lastModified||0)&&(b.lastModified=D.version),this[Fr]=D,D?.value?.[he])throw new Error("Can not assign a record to a record, check for circular references");A||(this[he]=D?.value??null)}this[gt]=m,this[ou]=L;let G=D?.value,ie=m;if(this[ru]=0,D?.version>=L)if(E){let ve=D.localTime,ne=D.version;for(;ie&&(ve>L||ne>=L&&ve>0);){let fe=u.get(ve),j=Ct(fe);if(ne=j.version,ne>L){if(j.type==="patch"){let le=j.getValue(i);ie=jl(ie,le)}else if(j.type==="put"||j.type==="delete")return}else if(ne===L)return;ve=j.previousLocalTime}}else{if(A)return;ie=jl(ie,G)}let ae;if(A?ae=ie:(this[he]=G,ae=A?ie:Li(this,ie)),this[he]=ae,ae?.[he])throw new Error("Can not assign a record to a record, check for circular references");let re;A||(re=m),yl(w,G,ae);let ce=A?"put":"patch";S(w,ae,D,L,0,E,b,b.expiresAt||(d?d+Date.now():0),ce,!1,re)}};N.addWrite(P)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Zr]){for await(let A of this.search(m))(await We.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[he]?this._writeDelete(m):!1}_writeDelete(m){let A=gr(this[be]),I=this[De];Qa(I);let b=this[be];return A.addWrite({key:I,store:i,resource:this,nodeName:b?.nodeName,before:xe.delete?.bind(this,b,I),beforeIntermediate:de.delete?.bind(this,b,I),commit:(N,w,y)=>{let P=w?.value;y&&(b&&w?.version>(b.lastModified||0)&&(b.lastModified=w.version),Ed(this,w)),!(w?.version>N)&&(yl(this[De],P),ze.trace("Write delete entry",I,N),E||h?(S(I,null,this[Fr],N,0,E,this[be],0,"delete"),E||QE()):i.remove(this[De]))}}),!0}search(m){let A=this[be],I=gr(A);if(!m)throw new Error("No query provided");let b=m.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[De]&&(b=[{attribute:null,comparator:"prefix",value:this[De]}].concat(b));let N,w={};function y(j,le){let St;switch(le){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');St=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+le)}let Hn=St&&{},xn;for(let Qe of j){if(Qe.conditions){Qe.conditions=y(Qe.conditions,Qe.operator);continue}let Rr=Qe[0]??Qe.attribute,zr=Rr==null?B:ms(p,Rr);if(zr){if(St){let Ar=Rn(Rr),Fn=Hn[Ar];Fn?(Fn.push(Qe),xn=!0):Hn[Ar]=[Qe]}(zr.type||Ph[Qe.comparator])&&(Qe[1]===void 0?Qe.value=L(Qe.value,zr):Qe[1]=L(Qe[1],zr))}else if(Rr!=null)throw(0,on.handleHDBError)(new Error,`${Rr} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(xn)for(let Qe in Hn){let Rr=Hn[Qe],zr=Rr.length;if(zr>1)for(let Ar=0;Ar<zr;Ar++){let Fn=Rr[Ar];if(Fn.comparator==="ge"||Fn.comparator==="greater_than_equal")for(let Vs=0;Vs<zr;Vs++){let Do=Rr[Vs];(Do.comparator==="le"||Do.comparator==="less_than_equal")&&(Fn.comparator="between",Fn.value=[Fn.value,Do.value],j.splice(j.indexOf(Do),1))}if(Fn.comparator==="equals"||!Fn.comparator){for(let Vs=0;Vs<zr;Vs++)if(Vs!==Ar){let Do=Rr[Vs];j.splice(j.indexOf(Do),1)}break}}}return j}a(y,"prepareConditions");function P(j,le){if(m.enforceExecutionOrder)return j;for(let St of j)St.conditions&&(St.conditions=P(St.conditions,St.operator));return j.length>1&&le!=="or"?(0,cD.sortBy)(j,c_(We)):j}a(P,"orderConditions");function L(j,le){return Array.isArray(j)?j.map(St=>fd(St,le)):fd(j,le)}a(L,"coerceTypedValues");let D=m.operator;(b.length>0||D)&&(b=y(b,D));let F=typeof m.sort=="object"&&m.sort,G;if(F&&D!=="or"){let j=F.attribute;if(N=b.find(le=>Rn(le.attribute)===Rn(j)),!N){if(!ms(p,j))throw(0,on.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);N={attribute:j,comparator:"sort"},b.push(N)}N.descending=!!F.descending}b=P(b,D),F&&(b[0]===N?F.next&&(G={dbOrderedAttribute:F.attribute,attribute:F.next.attribute,descending:F.next.descending,next:F.next.next}):(N&&b.splice(b.indexOf(N),1),G=F));let ie=m.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:b,operator:D,postOrdering:G,selectApplied:!!ie};let ae=I.useReadTxn(),re=vh(b,D,We,ae,m,A,(j,le)=>OA(j,ie,A,le),w),ce=m.ensureLoaded!==!1;G||(re=fe(re));let ve=We.transformEntryForSelect(ie,A,w,ce,!0),ne=We.transformToOrderedSelect(re,ie,G,A,ve);function fe(j){return m.offset||m.limit!==void 0?j.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):j}return a(fe,"applyOffset"),G&&(ne=fe(ne)),ne.onDone=()=>{ne.onDone=null,I.doneReadTxn()},ne.selectApplied=!0,ne.getColumns=()=>{if(ie){let j=[];for(let le of ie)le==="*"?j.push(...p.map(St=>St.name)):j.push(le.name||le);return j}return p.map(j=>j.name)},ne}static transformToOrderedSelect(m,A,I,b,N){let w=new zx;if(I){m=OA(m,A,b,null);let y;w.iterate=function(){let L,D=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),F,G=I.dbOrderedAttribute,ie,ae,re=!0;function ce(ne){let fe=ne.next&&ce(ne.next),j=ne.descending;return(le,St)=>{let Hn=WE(le,ne.attribute,b),xn=WE(St,ne.attribute,b),Qe=j?(0,to.compareKeys)(xn,Hn):(0,to.compareKeys)(Hn,xn);return Qe===0?fe?.(le,St)||0:Qe}}a(ce,"createComparator");let ve=ce(I);return{async next(){let ne;if(L)if(ne=L.next(),ne.done){if(F)return w.onDone&&w.onDone(),ne}else return{value:await N(ne.value)};y=[],ie&&y.push(ie);do if(ne=await D.next(),ne.done){if(F=!0,y.length)break;return w.onDone&&w.onDone(),ne}else{let fe=ne.value;if(fe?.then&&(fe=await fe),G){let j=WE(fe,G,b);if(re)re=!1,ae=j;else if(j!==ae){ae=j,ie=fe;break}}y.push(fe)}while(!0);return I.isGrouped,y.sort(ve),L=y[Symbol.iterator](),ne=L.next(),ne.done?(w.onDone&&w.onDone(),ne):{value:await N(ne.value)}},return(){w.onDone&&w.onDone(),D.return()},throw(){w.onDone&&w.onDone(),D.throw()}}};let P=a(L=>{if(typeof A=="object"&&Array.isArray(L.attribute))for(let D=0;D<A.length;D++){let F=A[D],G;if(F.name===L.attribute[0]){for(G=F.sort||(F.sort={});G.next;)G=G.next;G.attribute=L.attribute.slice(1),G.descending=L.descending}else F===L.attribute[0]&&(A[D]=G={name:F,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&P(L.next)},"applySortingOnSelect");P(I)}else w.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),w=w.map(N);return w}static transformEntryForSelect(m,A,I,b,N){if(m&&(m===t||m?.length===1&&m[0]===t)){let L=a(D=>D?.key??D,"transform");return m===t?L:m.asArray?D=>[L(D)]:D=>({[t]:L(D)})}let w;b&&R&&!m?.every(L=>{let D;return typeof L=="object"?D=L.name:D=L,r[D]||D===t})&&(w=!0);let y,P=a(L=>{let D;if(L!=null){if($E=L,D=L.value||L.deref?.(),!D&&(L.key===void 0||L.deref)){if(L=YE(L.key??L,A,{transaction:gr(A).getReadTxn(),lazy:m?.length<4},!1,F=>F),L?.then)return L.then(P);D=L?.value}if(w&&(L.metadataFlags&(nu|su)||L.expiresAt&&L.expiresAt<Date.now())){let F=KE(L.key??L,L,A);if(F?.then)return F.then(P)}}if(D==null)return N?Zi.SKIP:D;if(m&&!(m[0]==="*"&&m.length===1)){let F,G=a((ae,re)=>{let ce;typeof ae=="object"?ce=ae.name:ce=ae;let ve=ks?.[ce],ne;if(ve){let fe=I?.[ce];if(fe)if(fe.hasMappings){let le=ve.from?D[ve.from]:Rn(L.key);ne=fe.get(le),ne||(ne=[])}else ne=fe.fromRecord?.(D);else ne=ve(D,A,L);let j=a(le=>{if(le&&typeof le=="object"){let St=ve.definition?.tableClass||We;y||(y={});let Hn=y[ce]||(y[ce]=St.transformEntryForSelect(ce===ae?null:ae.select||(Array.isArray(ae)?ae:null),A,fe,b));if(Array.isArray(le)){let xn=[],Qe=St.transformToOrderedSelect(le,ae.select,typeof ae.sort=="object"&&ae.sort,A,Hn)[Symbol.asyncIterator](),Rr=a(Ar=>{for(;!Ar.done;){if(Ar?.then)return Ar.then(Rr);xn.push(Ar.value),Ar=Qe.next()}re(xn,ce)},"nextValue"),zr=Rr(Qe.next());zr&&(F||(F=[]),F.push(zr));return}else if(le=Hn(le),le?.then){F||(F=[]),F.push(le.then(xn=>re(xn,ce)));return}}re(le,ce)},"handleResolvedValue");ne?.then?(F||(F=[]),F.push(ne.then(j))):j(ne);return}else ne=D[ce],ne&&typeof ne=="object"&&ce!==ae&&(ne=this.transformEntryForSelect(ae.select||ae,A,null)({value:ne}));re(ne,ce)},"selectAttribute"),ie;if(typeof m=="string")G(m,ae=>{ie=ae});else if(Array.isArray(m))if(m.asArray)ie=[],m.forEach((ae,re)=>{ae==="*"?m[re]=D:G(ae,ce=>ie[re]=ce)});else{ie={};let ae=m.forceNulls;for(let re of m)if(re==="*")for(let ce in D)ie[ce]=D[ce];else G(re,(ce,ve)=>{ce===void 0&&ae&&(ce=null),ie[ve]=ce})}else throw new on.ClientError("Invalid select"+m);return F?Promise.all(F).then(()=>ie):ie}return D},"transform");return P}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||at({table:s,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let A=!m.rawEvents,I=lb(We,this[De]??null,function(y,P,L,D){try{let F=P.getValue?.(i,A);if(!F&&P.type==="patch"&&A){let G=i.getEntry(y);G?.version===P.version?F=G.value:F=P.getValue?.(i,!0,L),P.type="put"}this.send({id:y,timestamp:L,value:F,version:P.version,type:P.type,beginTxn:D})}catch(F){ze.error(F)}},m.startTime||0,this[Zr]);this[Zr]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let b=this[De],N=m.previousCount;N>1e3&&(N=1e3);let w=m.startTime;if(this[Zr]){if(w){if(N)throw new on.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:P}of u.getRange({start:w,exclusiveStart:!0})){let L=Ct(P);if(L.tableId!==n)continue;let D=L.recordId;(b==null||oD(b,D))&&I.send({id:D,timestamp:y,...L}),I.startTime=y}}else if(N){let y=[];for(let{key:P,value:L}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Ct(L);if(D.tableId!==n)continue;let F=D.recordId;if(b==null||oD(b,F)){let G=D.getValue(i,A,P);if(y.push({id:F,timestamp:P,value:G,version:D.version,type:D.type}),--N<=0)break}}catch(D){ze.error("Error getting history entry",P,D)}for(let P=y.length;P>0;)I.send(y[--P]);y[0]&&(I.startTime=y[0].timestamp)}else if(!m.omitCurrent)for(let{key:y,value:P,version:L,localTime:D}of i.getRange({start:b??!1,end:b==null?void 0:[b,to.MAXIMUM_KEY],versions:!0}))P&&I.send({id:y,version:L,timestamp:D,value:P})}else{N&&!w&&(w=0);let y=this[Fr]?.localTime;if(y===gh&&(i.cache?.delete(b),this[Fr]=i.getEntry(b),ze.trace("re-retrieved record",y,this[Fr]?.localTime),y=this[Fr]?.localTime),ze.trace("Subscription from",w,"from",b,y),w<y){let P=[],L=y;do{let D=u.get(L);if(D){m.omitCurrent=!0;let F=Ct(D),G=F.getValue(i,A,L);A&&(F.type="put"),P.push({id:b,value:G,timestamp:L,...F}),L=F.previousLocalTime}else break;N&&N--}while(L>w&&N!==0);for(let D=P.length;D>0;)I.send(P[--D]);I.startTime=y}!m.omitCurrent&&this.doesExist()&&I.send({id:b,version:this[ou],timestamp:y,value:this})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[he]||this[ru])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let I=gr(this[be]),b=this[De]||null;Qa(b);let N=this[be];I.addWrite({key:b,store:i,entry:this[Fr],nodeName:N?.nodeName,validate:()=>{this.validate(m)},before:xe.publish?.bind(this,N,b,m),beforeIntermediate:de.publish?.bind(this,N,b,m),commit:(w,y,P)=>{y===void 0&&h&&!E&&QE(),S(b,y?.value??null,y,y?.version||w,0,!0,N,y?.expiresAt,"message",!1,m)}})}validate(m,A){let I,b=a((N,w,y)=>{if(w.type&&N!=null)if(A&&N.__op__&&(N=N.value),w.properties){typeof N!="object"&&(I||(I=[])).push(`Property ${y} must be an object${w.type?" ("+w.type+")":""}`);let P=w.properties;for(let L=0,D=P.length;L<D;L++){let F=P[L],G=b(N[F.name],F,y+"."+F.name);G&&(N[F.name]=G)}}else switch(w.type){case"Int":(typeof N!="number"||N>>0!==N)&&(I||(I=[])).push(`Property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof N!="number"||!(Math.floor(N)===N&&Math.abs(N)<=9007199254740992))&&(I||(I=[])).push(`Property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof N!="number"&&(I||(I=[])).push(`Property ${y} must be a number`);break;case"ID":typeof N=="string"||N?.length>0&&N.every?.(P=>typeof P=="string")||(I||(I=[])).push(`Property ${y} must be a string, or an array of strings`);break;case"String":typeof N!="string"&&(I||(I=[])).push(`Property ${y} must be a string`);break;case"Boolean":typeof N!="boolean"&&(I||(I=[])).push(`Property ${y} must be a boolean`);break;case"Date":if(!(N instanceof Date)){if(typeof N=="string"||typeof N=="number")return new Date(N);(I||(I=[])).push(`Property ${y} must be a Date`)}break;case"BigInt":if(typeof N!="bigint"){if(typeof N=="string"||typeof N=="number")return BigInt(N);(I||(I=[])).push(`Property ${y} must be a bigint`)}break;case"Bytes":N instanceof Uint8Array||(I||(I=[])).push(`Property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(N)){if(w.elements)for(let P=0,L=N.length;P<L;P++){let D=N[P],F=b(D,w.elements,y+"[*]");F&&(N[P]=F)}}else(I||(I=[])).push(`Property ${y} must be a Buffer or Uint8Array`);break}w.nullable===!1&&N==null&&(I||(I=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let N=0,w=p.length;N<w;N++){let y=p[N];if(!y.relationship&&(!A||y.name in m)){let P=b(m[y.name],y,y.name);P&&(m[y.name]=P)}}if(I)throw new on.ClientError(I.join(". "))}getUpdatedTime(){return this[ou]}wasLoadedFromSource(){return R?!!this[Zp]:void 0}static async addAttributes(m){let A=p.slice(0);for(let I of m){if(!I.name)throw new on.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new on.ClientError("Attribute names cannot include backticks or forward slashes");A.push(I)}return at({table:s,database:c,schemaDefined:_,attributes:A}),We.indexingOperation}static async removeAttributes(m){let A=p.filter(I=>!m.includes(I.name));return at({table:s,database:c,schemaDefined:_,attributes:A}),We.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,I=5e3,b=1e3,N;A>I&&!m?.exactCount&&(N=b);let w=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:N}))y!=null&&w++;if(N){let y=w;w=0;for(let{value:ce}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:N}))ce!=null&&w++;let P=N*2,L=(w+y)/P,D=Math.pow((w-y+1)/N/2,2)+L*(1-L)/P,F=Math.max(Math.sqrt(D)*A,1),G=Math.round(L*A),ie=Math.max(G-1.96*F,0),ae=Math.min(G+1.96*F,A),re=Math.pow(10,Math.round(Math.log10(F)));return re>G&&(re=re/10),w=Math.round(G/re)*re,{recordCount:w,estimatedRange:[Math.round(ie),Math.round(ae)]}}return{recordCount:w}}static updatedAttributes(){ks=this.propertyResolvers={$id:(m,A,I)=>({value:I.key}),$updatedtime:(m,A,I)=>I.version,$record:(m,A,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),AA=!0,A.to)m.elements?.definition?(ks[m.name]=m.resolve=(I,b,N)=>{let w=I[A.from?A.from:t],y=m.elements.definition.tableClass;return N?qo({attribute:A.to,value:w},gr(b).getReadTxn(),!1,y).asArray:y.search([{attribute:A.to,value:w}],b).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(A.from){let I=m.definition||m.elements?.definition;I?(ks[m.name]=m.resolve=(b,N,w)=>{let y=b[A.from];if(y!==void 0){if(m.elements){let P,L=y.map(D=>{let F=w?I.tableClass.primaryStore.getEntry(D,{transaction:gr(N).getReadTxn()}):I.tableClass.get(D,N);return F?.then&&(P=!0),F});return A.filterMissing?P?Promise.all(L).then(D=>D.filter(aD)):L.filter(aD):P?Promise.all(L):L}return w?I.tableClass.primaryStore.getEntry(y,{transaction:gr(N).getReadTxn()}):I.tableClass.get(y,N)}},m.set=(b,N)=>{if(Array.isArray(N)){let w=N.map(y=>y[De]||y[I.tableClass.primaryKey]);b[A.from]=w}else{let w=N[De]||N[I.tableClass.primaryKey];b[A.from]=w}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}n_(this,this)}static async deleteHistory(m=0){let A;for(let{key:I,value:b}of u.getRange({start:0,end:m}))await iu(),Ct(b).tableId===n&&(A=u.remove(I));await A}static async*getHistory(m=0,A=1/0){for(let{key:I,value:b}of u.getRange({start:m,end:A})){await iu();let N=Ct(b);N.tableId===n&&(yield{id:N.recordId,localTime:I,version:N.version,type:N.type,value:N.getValue(i,!0,I),user:N.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return A;let b=I.localTime;if(!b)throw new Error("The entry does not have a local audit time");let N=0;do{await iu();let w=u.get(b);if(w){let y=Ct(w);A.push({id:y.recordId,localTime:b,version:y.version,type:y.type,value:y.getValue(i,!0,b),user:y.user}),b=y.previousLocalTime}else break}while(N<1e3&&b);return A.reverse()}static cleanup(){K?.remove()}}We.updatedAttributes();let jx=We.prototype;return jx[V2]=!0,d&&We.setTTLExpiration(d/1e3),$&&Zx(),We;function yl(Y,m,A){let I;for(let b in r){let N=r[b],w=N.isIndexing,y=A?.[b],P=m?.[b];if(y===P&&!w)continue;I=!0;let L=N.indexNulls,D=(0,au.getIndexedValues)(P,L);if(D){rD&&N.prefetch(D.map(F=>({key:F,value:Y})),iD);for(let F=0,G=D.length;F<G;F++)N.remove(D[F],Y)}if(D=(0,au.getIndexedValues)(y,L),D){rD&&N.prefetch(D.map(F=>({key:F,value:Y})),iD);for(let F=0,G=D.length;F<G;F++)N.put(D[F],Y)}}return I}a(yl,"updateIndices");function Qa(Y){switch(typeof Y){case"number":return!0;case"string":if(Y.length<659)return!0;if(Y.length>sD)throw new Error("Primary key size is too large: "+Y.length);break;case"object":if(Y===null)return!0;break;case"bigint":if(Y<2n**64n&&Y>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof Y)}if((0,to.writeKey)(Y,Y2,0)>sD)throw new Error("Primary key size is too large: "+Y.length);return!0}a(Qa,"checkValidId");function YE(Y,m,A,I,b){let N=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return b(null,Y);let w=i.getEntry(Y,A);return w&&m&&(w?.version>(m.lastModified||0)&&(m.lastModified=w.version),w?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=w.localTime)),b(w,Y)},"whenPrefetched");return I?N():Te>0?(Te--,N()):new Promise((w,y)=>{Te===0?(Te--,i.prefetch([Y],()=>{P(),L()})):(z.push(Y),se.push(L),z.length>Xx&&(Te--,P()));function P(){if(z.length>0){let D=se;i.prefetch(z,()=>{Te===-1?P():Te++;for(let F of D)F()}),z=[],se=[],oe>2&&oe--}else Te=oe,oe<Jx&&oe++}a(P,"prefetch");function L(){try{w(N())}catch(D){y(D)}}a(L,"load")})}a(YE,"loadLocalRecord");function wl(Y){if(!Y?.role)return;let m=Y.role.permission;if(m.super_user)return K2;let A=m[c],I,b=A?.tables;if(b)return b[s];if(c==="data"&&(I=m[s])&&!I.tables)return I}a(wl,"getTablePermissions");function KE(Y,m,A,I){if(R){let b;if(A.noCache?b=!0:(m?(!m.value||m.metadataFlags&(nu|su)||m.expiresAt&&m.expiresAt<Date.now())&&(b=!0):b=!0,sn(!b,"cache-hit",s)),b){let N=bA(Y,m,A).then(w=>(w?.value?.[he]&&ze.error("Can not assign a record with a record property"),A&&(w?.version>(A.lastModified||0)&&(A.lastModified=w.version),A.lastRefreshed=Date.now()),w));if(A?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,Y)){if(N.catch(w=>ze.warn(w)),A?.onlyIfCached&&!I.doesExist())throw new on.ServerError("Entry is not cached",504);return}else return N}}}a(KE,"ensureLoadedFromSource");function gr(Y){let m=Y?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new Mi,m.lmdbDb=i,m;m=A}while(!0)}else return new o_}a(gr,"txnForContext");function WE(Y,m,A){if(!Y)return;$E=Y;let I=Y.value||Y.deref?.()||($E=i.getEntry(Y.key))?.value;if(typeof m=="object"){let N=ks,w=I;for(let y=0,P=m.length;y<P;y++){let L=m[y],D=N?.[L];w=D&&w?D(w,A,!0)?.value:w?.[L],N=D?.definition?.tableClass?.propertyResolvers}return w}let b=ks[m];return b?b(I,A):I[m]}a(WE,"getAttributeValue");function OA(Y,m,A,I){let b=gr(A).getReadTxn(),N=I?.length,w={transaction:b,lazy:N>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},y;function P(L,D){let F=L?.value;if(!F)return Zi.SKIP;for(let G=0;G<N;G++)if(!y?.includes(G)&&!I[G](F,L))return Zi.SKIP;return D!==void 0&&(L.key=D),L}if(a(P,"processEntry"),N>0||!Y.hasEntries){let L=Y.map(D=>{if(y=null,typeof D=="object"&&D.key!==void 0)return N>0?P(D):D;if(D==null)return Zi.SKIP;for(let F=0;F<N;F++){let ie=I[F].idFilter;if(ie){if(!ie(D))return Zi.SKIP;y||(y=[]),y.push(F)}}return YE(D,A,w,!1,P)});return Array.isArray(Y)&&(L=L.filter(D=>D!==Zi.SKIP)),L.hasEntries=!0,L}return Y}a(OA,"transformToEntries");async function bA(Y,m,A){let I=m?.metadataFlags,b=m?.version,N,w;if(!i.attemptLock(Y,b,()=>{clearTimeout(w);let D=i.getEntry(Y);!D||!D.value||D.metadataFlags&(nu|su)?N(bA(Y,i.getEntry(Y),A)):N(D)}))return new Promise(D=>{N=D,w=setTimeout(()=>{i.unlock(Y,b)},k2)});let y=m?.value,P={requestContext:A,replacingRecord:y,replacingVersion:b,source:null,resourceCache:A?.resourceCache},L=A?.responseHeaders;return new Promise((D,F)=>{let G;tS(Ke(P,async ie=>{let ae=performance.now(),re,ce,ve;try{for(let le of We.sources)if(le.get&&(!le.get.reliesOnPrototype||le.prototype.get)&&(P.source=le,re=await le.get(Y,P),re))break;ve=Iνlet fe=P.lastModified||ve&&b;ce=ve||fe>b||!y,fe||(fe=(0,au.getNextMonotonicTime)());let j=performance.now()-ae;if(xr(j,"cache-resolution",s),L&&L.append("Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`),ie.timestamp=fe,d&&!P.expiresAt&&(P.expiresAt=Date.now()+d),re){if(typeof re!="object")throw new Error("Only objects can be cached and stored in tables");typeof re.toJSON=="function"&&(re=re.toJSON()),t&&re[t]!==Y&&(re[t]=Y)}G=!0,D({version:fe,value:re})}catch(fe){fe.message+=` while resolving record ${Y} for ${s}`,y&&((fe.code==="ECONNRESET"||fe.code==="ECONNREFUSED"||fe.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(fe.statusCode===500||fe.statusCode===502||fe.statusCode===503||fe.statusCode===504))?(D({version:b,value:y}),ze.trace(fe.message,"(returned stale record)")):F(fe),P.transaction.abort();return}if(A?.noCacheStore){P.transaction.abort();return}gr(P).addWrite({key:Y,store:i,entry:m,nodeName:"source",commit:(fe,j)=>{if(j?.version!==b)return;let le=yl(Y,y,re);re?(de.put?.(P,Y,re),S(Y,re,j,fe,0,E&&ce||null,P,P.expiresAt,"put",!!ve)):(de.delete?.(P,Y),E||h?S(Y,null,j,fe,0,E&&ce||null,P,0,"delete",!!ve):i.remove(Y,b))}})}),()=>{i.unlock(Y,b)},ie=>{i.unlock(Y,b),G&&ze.error("Error committing cache update",ie)})})}a(bA,"getFromSource");function QE(){if(It!==bl&&(bl=It,(0,eo.getWorkerIndex)()===(0,eo.getWorkerCount)()-1)){if(Nl&&clearTimeout(Nl),!It)return;let Y=new Date;Y.setMonth(0),Y.setDate(1),Y.setHours(0),Y.setMinutes(0),Y.setSeconds(0);let m=Math.ceil((Date.now()-Y.getTime())/It)*It+Y.getTime(),A=a(I=>{ze.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),Nl=setTimeout(()=>H=H.then(async()=>{if(A(Math.max(I+It,Date.now())),i.rootStore.status!=="open"){clearTimeout(Nl);return}let b=50,N=new Array(b),w=0;ze.trace(`Starting cleanup scan for ${s}`);try{let y=0;for(let{key:P,value:L,version:D,expiresAt:F}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;L===null&&!E&&D+G2<Date.now()?G=i.remove(P,D):F&&F+f<Date.now()&&(G=We.evict(P,L,D),y++),G&&(await N[w],N[w]=G.catch(ie=>{ze.error("Cleanup error",ie)}),++w>=b&&(w=0)),await iu()}ze.trace(`Finished cleanup scan for ${s}, evicted ${y} entries`)}catch(y){ze.trace(`Error in cleanup scan for ${s}:`,y)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(QE,"scheduleCleanup");function NA(){K=u?.addDeleteRemovalCallback(n,Y=>{let m=i.getEntry(Y);m?.value===null&&i.remove(Y,m.version)})}a(NA,"addDeleteRemoval");function Zx(){(0,eo.getWorkerIndex)()===0&&setInterval(async()=>{try{let Y=$.name,m=r[Y];if(!m)throw new Error(`expiresAt attribute ${$} must be indexed`);for(let{value:A}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let I=i.getEntry(A);I?.value?.[Y]<Date.now()&&We.evict(A,I.value,I.version),await iu()}}catch(Y){ze.error("Error in evicting old records",Y)}},q2).unref()}a(Zx,"runRecordExpirationEviction")}function eS(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function iD(){}function W2(e){uD=e}function fd(e,t){let r=t?.type;return e===null?e:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?(typeof e!="number"&&!Q2.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,hd.autoCast)(e):e}function oD(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function tS(e,t,r){return e?.then?e.then(t,r):t(e)}function Ed(e,t){e[Fr]=t,e[he]=t?.value??null,e[ou]=t?.version}function aD(e){return e!=null}var Mn,Zi,au,cD,lu,on,cu,uu,ze,to,eo,hd,F2,uD,q2,G2,rD,k2,ou,V2,Fr,ru,nD,$2,Zp,aa,nu,su,Y2,sD,K2,C_e,Q2,iu,pd=Oe(()=>{Mn=x(U()),Zi=require("lmdb"),au=x(Nr()),cD=require("lodash");gn();Mh();lu=x(Z());fb();on=x(ee()),cu=x(Ts()),uu=x(bn());Ne();l_();ze=x(W());i_();Ui();to=require("ordered-binary"),eo=x(je());Ci();hd=x(J());vo();bs();Jl();F2=new Uint8Array(9);F2[8]=192;q2=6e4,G2=864e5;lu.initSync();rD=lu.get(Mn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),k2=1e4,ou=Symbol.for("version"),V2=Symbol.for("incremental-update"),Fr=Symbol("entry"),ru=Symbol("is-saving"),nD=1,$2=2,Zp=Symbol("loaded-from-source"),aa={isNotification:!0,ensureLoaded:!1},nu=1,su=8,Y2=Buffer.allocUnsafeSlow(8192),sD=1978,K2={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},C_e=(0,hd.convertToMS)(lu.get(Mn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(md,"makeTable");a(eS,"attributesAsObject");a(iD,"noop");a(W2,"setServerUtilities");Q2=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(fd,"coerceType");a(oD,"isDescendantId");iu=a(()=>new Promise(setImmediate),"rest");a(tS,"when");a(Ed,"updateResource");a(aD,"exists")});var qe={};Fe(qe,{database:()=>kc,databases:()=>tt,dropDatabase:()=>_p,dropTableMeta:()=>e4,getDatabases:()=>yn,getTables:()=>z2,onUpdatedTable:()=>aS,readMetaDb:()=>_u,resetDatabases:()=>J2,table:()=>at,tables:()=>Gr});function z2(){return Ad||yn(),Gr||{}}function yn(){if(Ad)return tt;Ad=!0,la=new Map;let e=(0,Kt.getHdbBasePath)()&&(0,Je.join)((0,Kt.getHdbBasePath)(),kr.DATABASES_DIR_NAME),t=(0,Kt.get)(kr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Kt.get)(kr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,qr.existsSync)(e)?e:(0,Je.join)((0,Kt.getHdbBasePath)(),kr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,qr.existsSync)(e))for(let r of(0,qr.readdirSync)(e,{withFileTypes:!0})){let n=(0,Je.basename)(r.name,".mdb");r.isFile()&&(0,Je.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&_u((0,Je.join)(e,r.name),null,n)}if((0,qr.existsSync)((0,ua.getBaseSchemaPath)())){for(let r of(0,qr.readdirSync)((0,ua.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Je.join)((0,ua.getBaseSchemaPath)(),r.name),s=(0,Je.join)((0,ua.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,qr.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,Je.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Je.join)(s,i.name);_u((0,Je.join)(n,i.name),(0,Je.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,qr.existsSync)(s))for(let o of(0,qr.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,Je.extname)(o.name).toLowerCase()===".mdb"&&_u((0,Je.join)(s,o.name),(0,Je.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,Je.join)(c.path,(0,Je.basename)(o+".mdb"));(0,qr.existsSync)(u)&&_u(u,o,r,null,!0)}}for(let r in tt){let n=la.get(r);if(n){let s=tt[r];r.includes("delete")&&an.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(an.trace(`delete table class ${i}`),delete s[i])}else if(delete tt[r],r==="data"){for(let s in Gr)delete Gr[s];delete Gr[Od]}}return la=null,tt}}function J2(){Ad=!1;for(let[,e]of ii)e.needsDeletion=!0;yn();for(let[e,t]of ii)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),ii.delete(e));return tt}function _u(e,t,r=iS,n,s){let i=new nS.default(e,!1);try{let o=ii.get(e);o?o.needsDeletion=!1:(o=(0,Td.open)(i),ii.set(e,o));let c=new ro.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(Sd.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,qr.existsSync)(n)&&(i.path=n,_=(0,Td.open)(i),_.isLegacy=!0):_=zl(o));let l=fD(r),d=l[Od],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[p,S]=E.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let O=f.get(p);O||f.set(p,O={attributes:[]}),(S==null||h.is_hash_attribute)&&(O.primary=h),S!=null&&O.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:p,primary:S}=h;if(!S){for(let z of p)if(z.is_hash_attribute||z.isPrimaryKey){S=z;break}if(!S){an.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let O=l[E],g={},R=[],B,H,v=typeof S.audit=="boolean"?S.audit:(0,Kt.get)(kr.CONFIG_PARAMS.LOGGING_AUDITLOG),M=S.trackDeletes,$=S.expiration,K=S.eviction;if(O)g=O.indices,R=O.attributes,O.schemaVersion++;else{B=S.tableId,B?B>=(u.get(ca)||0)&&u.putSync(ca,B+1):(S.tableId=B=u.get(ca),B||(B=1),u.putSync(ca,B+1),u.putSync(S.key,S));let z=new ro.default(!S.is_hash_attribute,S.is_hash_attribute);H=Yl(o.openDB(S.key,z)),H.rootStore=o,H.tableId=B}for(let z of p){z.attribute=z.name;try{if(!z.is_hash_attribute&&(z.indexed||z.attribute&&!z.name)){if(!g[z.name]){let Te=new ro.default(!z.is_hash_attribute,z.is_hash_attribute);g[z.name]=o.openDB(z.key,Te),g[z.name].indexNulls=z.indexNulls}let se=R.find(Te=>Te.name===z.name);se?R.splice(R.indexOf(se),1,z):R.push(z)}}catch(se){an.error("Error trying to update attribute",z,R,g,se)}}if(!O){O=ED(l,E,md({primaryStore:H,auditStore:_,audit:v,expirationMS:$&&$*1e3,evictionMS:K&&K*1e3,trackDeletes:M,tableName:E,tableId:B,primaryKey:S.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:g,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),O.schemaVersion=1;for(let z of oS)z(O)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function fD(e){let t=tt[e];if(t||(e==="data"?t=tt[e]=Gr:e==="system"?Object.defineProperty(tt,"system",{value:t=Object.create(null),configurable:!0}):t=tt[e]=Object.create(null)),la&&!la.has(e)){let r=new Set;t[Od]=r,la.set(e,r)}return t}function ED(e,t,r){return e[t]=r,r}function kc({database:e,table:t}){e||(e=iS),yn();let r=fD(e),n=(0,Je.join)((0,Kt.getHdbBasePath)(),kr.DATABASES_DIR_NAME),s=(0,Kt.get)(kr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Kt.get)(kr.CONFIG_PARAMS.STORAGE_PATH)||((0,qr.existsSync)(n)?n:(0,Je.join)((0,Kt.getHdbBasePath)(),kr.LEGACY_DATABASES_DIR_NAME));let o=(0,Je.join)(n,(i?t:e)+".mdb"),c=ii.get(o);if(!c){let u=new nS.default(o,!1);c=(0,Td.open)(u),ii.set(o,c)}return c}async function _p(e){if(!tt[e])throw new Error("Schema does not exist");let t=tt[e];for(let r in t){let s=t[r].primaryStore.rootStore;ii.delete(s.path),s.status==="open"&&(await s.close(),await lD.remove(s.path))}if(e==="data"){for(let r in Gr)delete Gr[r];delete Gr[Od]}delete tt[e]}function at({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=iS);let l=kc({database:t,table:e}),d=tt[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,p,S;u==null&&(u=!0);let O=new ro.default(!1);for(let M of i)M.attribute?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let g,R;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=l.auditStore;M||(M=zl(l)),h=i.find(se=>se.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Kt.get)(kr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),n&&(h.eviction=n),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),an.trace(`${e} table loading, opening primary store`);let $=new ro.default(!1,!0),K=e+"/",z=Yl(l.openDB(K,$));z.rootStore=l,S=l.dbisDb=l.openDB(Sd.INTERNAL_DBIS_NAME,O),z.tableId=S.get(ca),z.tableId||(z.tableId=1),S.putSync(ca,z.tableId+1),h.tableId=z.tableId,f=ED(d,e,md({primaryStore:z,auditStore:M,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:E,tableName:e,tableId:z.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,g=!0,v(),S.put(K,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(Sd.INTERNAL_DBIS_NAME,O)),f.dbisDB=S;let B=[];for(let{key:M,value:$}of S.getRange({start:!0})){let[K,z]=M.toString().split("/");if(z===""&&(z=$.name),z){if(K!==e)continue}else z=K;if(!i.find(Te=>Te.name===z)?.indexed&&$.indexed&&!$.isPrimaryKey){v(),g=!0,S.remove(M);let Te=f.indices[K];Te&&B.push(Te)}}let H=[];try{for(let M of i||[]){if(M.relationship)continue;let $=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:$,configurable:!0});let K=S.get($);if(M.isPrimaryKey){if(K=K||S.get($=e+"/")||{},o!==f.audit||(+r||void 0)!==(+K.expiration||void 0)||(+n||void 0)!==(+K.eviction||void 0)){let se=Object.assign({},K);typeof o=="boolean"&&(o&&f.enableAuditing(o),se.audit=o),r&&(se.expiration=+r),n&&(se.eviction=+n),g=!0,v(),S.put($,se)}continue}K?.attribute&&!K.name&&(K.indexed=!0);let z=!K||K.type!==M.type||K.indexed!==M.indexed||JSON.stringify(K.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(K.elements)!==JSON.stringify(M.elements);if(M.indexed){let se=new ro.default(!0,!1),Te=l.openDB($,se);(z||K.indexingPID&&K.indexingPID!==process.pid||K.restartNumber<du.workerData?.restartNumber)&&(g=!0,v(),K=S.get($),(z||K.indexingPID&&K.indexingPID!==process.pid||K.restartNumber<du.workerData?.restartNumber)&&(g=!0,M.lastIndexedKey=K?.lastIndexedKey||!1,M.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(M,"dbi",{value:Te}),M.indexNulls===void 0&&(M.indexNulls=!0),H.push(M)),S.put($,M)),K?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),Te.indexNulls=M.indexNulls,p[M.name]=Te}else z&&(g=!0,v(),S.put($,M))}}finally{R&&R()}if(g&&(f.schemaVersion++,f.updatedAttributes()),an.trace(`${e} table loading, running index`),H.length>0||B.length>0?f.indexingOperation=Z2(f,H,B):g&&gd.signalSchemaChange(new Rd.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,g)for(let M of oS)M(f,_!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),an.trace(`${e} table loaded`),f;function v(){R||l.transactionSync(()=>({then(M){R=M}}))}a(v,"startTxn")}async function Z2(e,t,r){try{let n=e.schemaVersion;await gd.signalSchemaChange(new Rd.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,_D.getIndexedValues)(l[h]);if(p)for(let S=0,O=p.length;S<O;S++)E.dbi.put(p[S],_)}}),s.then(()=>u--,f=>{u--,an.error(f)}),du.workerData&&du.workerData.restartNumber!==dD.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>X2?await s:u>j2&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await gd.signalSchemaChange(new Rd.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){an.error("Error in indexing",n)}}function e4({table:e,database:t}){let r=kc({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function aS(e){oS.push(e)}var Kt,Sd,Td,Je,qr,ua,ro,nS,kr,lD,sS,_D,gd,Rd,du,an,dD,iS,Od,Gr,tt,ca,oS,Ad,ii,la,X2,j2,Ne=Oe(()=>{Kt=x(Z()),Sd=x(lt()),Td=require("lmdb"),Je=require("path"),qr=require("fs"),ua=x(Ye());pd();ro=x(h_()),nS=x(p_()),kr=x(U()),lD=x(require("fs-extra")),sS=require("../index"),_D=x(Nr()),gd=x(Ts()),Rd=x(bn()),du=require("worker_threads"),an=x(W()),dD=x(je());Ci();vo();iS="data",Od=Symbol("defined-tables");(0,Kt.initSync)();Gr=Object.create(null),tt=Object.create(null);(0,sS._assignPackageExport)("databases",tt);(0,sS._assignPackageExport)("tables",Gr);ca=Symbol.for("next-table-id"),oS=[],ii=new Map;a(z2,"getTables");a(yn,"getDatabases");a(J2,"resetDatabases");a(_u,"readMetaDb");a(fD,"ensureDB");a(ED,"setTable");a(kc,"database");a(_p,"dropDatabase");a(at,"table");X2=1e3,j2=10;a(Z2,"runIndexing");a(e4,"dropTableMeta");a(aS,"onUpdatedTable")});var J=T((x_e,ID)=>{"use strict";var oi=require("path"),TD=require("fs-extra"),ir=W(),hD=require("fs-extra"),bd=require("os"),t4=require("net"),r4=require("recursive-iterator"),rt=U(),n4=sO(),mD=require("papaparse"),Nd=require("moment"),{inspect:s4}=require("util"),pD=require("is-number"),H_e=require("lodash"),i4=require("minimist"),o4=require("https"),a4=require("http"),{hdb_errors:yd}=ee(),c4=/^((\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)))$/,gD=require("util").promisify(setTimeout),u4=100,l4=5,_4="",d4=4,SD={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};ID.exports={isEmpty:Vr,isEmptyOrZeroLength:Zn,arrayHasEmptyValues:h4,arrayHasEmptyOrZeroLengthValues:m4,buildFolderPath:p4,isBoolean:RD,errorizeMessage:f4,stripFileExtension:T4,autoCast:g4,autoCastJSON:AD,autoCastJSONDeep:uS,removeDir:R4,compareVersions:A4,isCompatibleDataVersion:O4,escapeRawValue:b4,unescapeValue:N4,stringifyProps:y4,timeoutPromise:I4,isClusterOperation:D4,getClusterUser:M4,checkGlobalSchemaTable:L4,getHomeDir:bD,getPropsFilePath:w4,promisifyPapaParse:U4,removeBOM:ND,createEventPromise:P4,checkProcessRunning:v4,checkSchemaTableExist:B4,checkSchemaExists:yD,checkTableExists:wD,getStartOfTomorrowInSeconds:H4,getLimitKey:x4,isObject:S4,isNotEmptyAndHasValue:E4,autoCasterIsNumberCheck:OD,backtickASTSchemaItems:F4,isPortTaken:C4,createForkArgs:q4,autoCastBoolean:G4,async_set_timeout:gD,getTableHashAttribute:k4,doesSchemaExist:V4,doesTableExist:$4,stringifyObj:Y4,ms_to_time:K4,changeExtension:W4,getEnvCliRootPath:lS,noBootFile:Q4,httpRequest:z4,transformReq:J4,convertToMS:X4,PACKAGE_ROOT:rt.PACKAGE_ROOT};function f4(e){return e instanceof Error?e:new Error(e)}a(f4,"errorizeMessage");function Vr(e){return e==null}a(Vr,"isEmpty");function E4(e){return!Vr(e)&&(e||e===0||e===""||RD(e))}a(E4,"isNotEmptyAndHasValue");function Zn(e){return Vr(e)||e.length===0||e.size===0}a(Zn,"isEmptyOrZeroLength");function h4(e){if(Vr(e))return!0;for(let t=0;t<e.length;t++)if(Vr(e[t]))return!0;return!1}a(h4,"arrayHasEmptyValues");function m4(e){if(Zn(e))return!0;for(let t=0;t<e.length;t++)if(Zn(e[t]))return!0;return!1}a(m4,"arrayHasEmptyOrZeroLengthValues");function p4(...e){try{return e.join(oi.sep)}catch{console.error(e)}}a(p4,"buildFolderPath");function RD(e){return Vr(e)?!1:e===!0||e===!1}a(RD,"isBoolean");function S4(e){return Vr(e)?!1:typeof e=="object"}a(S4,"isObject");function T4(e){return Zn(e)?_4:e.slice(0,-d4)}a(T4,"stripFileExtension");function g4(e){return Vr(e)||e===""||typeof e!="string"?e:SD[e]!==void 0?SD[e]:OD(e)===!0?Number(e):c4.test(e)?new Date(e):e}a(g4,"autoCast");function AD(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(AD,"autoCastJSON");function uS(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=uS(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=uS(r);n!==r&&(e[t]=n)}return e}else return AD(e)}a(uS,"autoCastJSONDeep");function OD(e){if(e.startsWith("0.")&&pD(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&pD(e))}a(OD,"autoCasterIsNumberCheck");async function R4(e){if(Zn(e))throw new Error(`Directory path: ${e} does not exist`);try{await hD.emptyDir(e),await hD.remove(e)}catch(t){throw ir.error(`Error removing files in ${e} -- ${t}`),t}}a(R4,"removeDir");function A4(e,t){if(Zn(e)){ir.info("Invalid current version sent as parameter.");return}if(Zn(t)){ir.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(A4,"compareVersions");function O4(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(O4,"isCompatibleDataVersion");function b4(e){if(Vr(e))return e;let t=String(e);return t==="."?rt.UNICODE_PERIOD:t===".."?rt.UNICODE_PERIOD+rt.UNICODE_PERIOD:t.replace(rt.FORWARD_SLASH_REGEX,rt.UNICODE_FORWARD_SLASH)}a(b4,"escapeRawValue");function N4(e){if(Vr(e))return e;let t=String(e);return t===rt.UNICODE_PERIOD?".":t===rt.UNICODE_PERIOD+rt.UNICODE_PERIOD?"..":String(e).replace(rt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(N4,"unescapeValue");function y4(e,t){if(Vr(e))return ir.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+bd.EOL}!Zn(n)&&n[0]===";"?r+=" "+n+s+bd.EOL:Zn(n)||(r+=n+"="+s+bd.EOL)}catch{ir.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(y4,"stringifyProps");function bD(){let e;try{e=bd.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(bD,"getHomeDir");function w4(){let e=oi.join(bD(),rt.HDB_HOME_DIR_NAME,rt.BOOT_PROPS_FILE_NAME);return TD.existsSync(e)||(e=oi.join(__dirname,"../","hdb_boot_properties.file")),e}a(w4,"getPropsFilePath");function I4(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(I4,"timeoutPromise");async function C4(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=t4.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(C4,"isPortTaken");function D4(e){try{return rt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){ir.error(`Error checking operation against cluster ops ${t}`)}return!1}a(D4,"isClusterOperation");function L4(e,t){let r=(Ne(),te(qe)).getDatabases();if(!r[e])return yd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return yd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(L4,"checkGlobalSchemaTable");function M4(e,t){if(Vr(t)){ir.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Vr(e)||Zn(e)){ir.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){ir.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){ir.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(M4,"getClusterUser");function U4(){mD.parsePromise=function(e,t,r){return new Promise(function(n,s){mD.parse(e,{header:!0,transformHeader:ND,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(U4,"promisifyPapaParse");function ND(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(ND,"removeBOM");function P4(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;ir.info(`Got cluster status event response: ${s4(s)}`);try{i.cancel()}catch{ir.error("Error trying to cancel timeout.")}n(s)})})}a(P4,"createEventPromise");async function v4(e){let t=!0,r=0;do await gD(u4*r++),(await n4.findPs(e)).length>0&&(t=!1);while(t&&r<l4);if(t)throw new Error(`process ${e} was not started`)}a(v4,"checkProcessRunning");function B4(e,t){let r=yD(e);if(r)return r;let n=wD(e,t);if(n)return n}a(B4,"checkSchemaTableExist");function yD(e){let{getDatabases:t}=(Ne(),te(qe));if(!t()[e])return yd.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(yD,"checkSchemaExists");function wD(e,t){let{getDatabases:r}=(Ne(),te(qe));if(!r()[e][t])return yd.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(wD,"checkTableExists");function H4(){let e=Nd().utc().add(1,rt.MOMENT_DAYS_TAG).startOf(rt.MOMENT_DAYS_TAG).unix(),t=Nd().utc().unix();return e-t}a(H4,"getStartOfTomorrowInSeconds");function x4(){return Nd().utc().format("DD-MM-YYYY")}a(x4,"getLimitKey");function F4(e){try{let t=new r4(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){ir.error("Got an error back ticking items."),ir.error(t)}}a(F4,"backtickASTSchemaItems");function q4(e){return[e]}a(q4,"createForkArgs");function G4(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(G4,"autoCastBoolean");function k4(e,t){let{getDatabases:r}=(Ne(),te(qe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(k4,"getTableHashAttribute");function V4(e){let{getDatabases:t}=(Ne(),te(qe));return t()[e]!==void 0}a(V4,"doesSchemaExist");function $4(e,t){let{getDatabases:r}=(Ne(),te(qe));return r()[e]?.[t]!==void 0}a($4,"doesTableExist");function Y4(e){try{return JSON.stringify(e)}catch{return e}}a(Y4,"stringifyObj");function K4(e){let t=Nd.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(K4,"ms_to_time");function W4(e,t){let r=oi.basename(e,oi.extname(e));return oi.join(oi.dirname(e),r+t)}a(W4,"changeExtension");function lS(){if(process.env[rt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[rt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=i4(process.argv);if(e[rt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[rt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(lS,"getEnvCliRootPath");var cS;function Q4(){if(cS)return cS;let e=lS();lS()&&TD.pathExistsSync(oi.join(e,rt.HDB_CONFIG_FILE))&&(cS=!0)}a(Q4,"noBootFile");function z4(e,t){let r;return e.protocol==="http:"?r=a4:r=o4,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(z4,"httpRequest");function J4(e){if(!e.schema&&!e.database){e.schema=rt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(J4,"transformReq");function X4(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(X4,"convertToMS")});var Z=T((q_e,MD)=>{"use strict";var _S=require("fs-extra"),no=require("path"),CD=require("os"),j4=require("properties-reader"),Eu=W(),fu=J(),_e=U(),wd=vr(),Z4="Error initializing environment manager",Id="BOOT_PROPS_FILE_PATH",DD=!1,e3={[_e.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ns={};MD.exports={BOOT_PROPS_FILE_PATH:Id,getHdbBasePath:t3,setHdbBasePath:r3,get:LD,initSync:s3,setProperty:Me,initTestEnvironment:i3};function t3(){return Ns[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(t3,"getHdbBasePath");function r3(e){Ns[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(r3,"setHdbBasePath");function LD(e){let t=wd.getConfigValue(e);return t===void 0?Ns[e]:t}a(LD,"get");function Me(e,t){e3[e]&&(Ns[e]=t),wd.updateConfigObject(e,t)}a(Me,"setProperty");function n3(){let e;try{e=fu.getPropsFilePath(),_S.accessSync(e,_S.constants.F_OK|_S.constants.R_OK),DD=!0;let t=j4(e);return Ns[_e.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(_e.HDB_SETTINGS_NAMES.INSTALL_USER),Ns[_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ns[Id]=e,!0}catch{return Eu.trace(`Environment manager found no properties file at ${e}`),!1}}a(n3,"doesPropFileExist");function s3(e=!1){try{(DD||n3()||fu.noBootFile())&&(wd.initConfig(e),Ns[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=wd.getConfigValue(_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Eu.error(Z4),Eu.error(t),console.error(t),process.exit(1)}}a(s3,"initSync");function i3(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=no.join(__dirname,"../../","unitTests");Ns[Id]=no.join(u,"hdb_boot_properties.file"),Me(_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,no.join(u,"settings.test")),Me(_e.HDB_SETTINGS_NAMES.INSTALL_USER,CD.userInfo()?CD.userInfo().username:void 0),Me(_e.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(_e.HDB_SETTINGS_NAMES.LOG_PATH_KEY,no.join(u,"envDir","log")),Me(_e.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(_e.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(_e.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,no.join(u,"envDir")),Me(_e.CONFIG_PARAMS.STORAGE_PATH,no.join(u,"envDir")),s&&(Me(_e.CONFIG_PARAMS.HTTP_SECUREPORT,LD(_e.CONFIG_PARAMS.HTTP_PORT)),Me(_e.CONFIG_PARAMS.HTTP_PORT,null)),Me(_e.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(_e.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(_e.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,fu.isEmpty(i)?!1:i),Me(_e.CONFIG_PARAMS.HTTP_CORS,fu.isEmpty(i)?!1:i),Me(_e.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(_e.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,no.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(_e.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,fu.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(_e.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(_e.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(_e.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(_e.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(_e.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(_e.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(_e.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Id}. Please check your boot props and settings files`;Eu.fatal(r),Eu.error(t)}}a(i3,"initTestEnvironment")});var ES={};Fe(ES,{loadGQLSchema:()=>c3,start:()=>fS,startOnMainThread:()=>a3});function fS({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(v){if(v.kind==="NonNullType"){let K=H(v.type);return K.nullable=!1,K}if(v.kind==="ListType")return{type:"array",elements:H(v.type)};let $={type:v.name?.value};return Object.defineProperty($,"location",{value:v.loc.startToken}),$};a(H,"getProperty");let O=S.name.value,g=[],R={table:null,database:null,properties:g};f.set(O,R);for(let v of S.directives){if(v.name.value==="table"){for(let M of v.arguments)R[M.name.value]=M.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=O),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,E.push(R)}if(v.name.value==="sealed"&&(R.sealed=!0),v.name.value==="export"){R.export=!0;for(let M of v.arguments)M.name.value==="name"&&(R.export={name:M.value.value})}}let B=!1;for(let v of S.fields){let M=H(v.type);M.name=v.name.value,g.push(M);for(let $ of v.directives)if($.name.value==="primaryKey")B?console.warn("Can not define two attributes as a primary key"):(M.isPrimaryKey=!0,B=!0);else if($.name.value==="indexed")M.indexed=!0;else if($.name.value==="relationship"){let K={};for(let z of $.arguments)K[z.name.value]=z.value.value;M.relationship=K}else if($.name.value==="createdTime")M.assignCreatedTime=!0;else if($.name.value==="updatedTime")M.assignUpdatedTime=!0;else if($.name.value==="expiresAt")M.expiresAt=!0;else if($.name.value==="allow"){let K=M.authorizedRoles=[];for(let z of $.arguments)z.name.value==="role"&&K.push(z.value.value)}}R.type=O,O==="Query"&&(h=R)}function p(S){let O=f.get(S.type);O?(Object.defineProperty(S,"properties",{value:O.properties}),Object.defineProperty(S,"definition",{value:O})):S.type==="array"?p(S.elements):o3.includes(S.type)||(0,UD.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of f.values())for(let O of S.properties)p(O);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,dS.dirname)(n),S.tableClass):i.set((0,dS.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var dS,UD,o3,a3,c3,PD=Oe(()=>{dS=require("path");Ne();UD=x(je()),o3=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(fS,"start");a3=fS,c3=fS({ensureTable:at}).handleFile});async function Cd(e){return u3?(hu||(hu=l3(d3)),(await(await hu).import(e)).namespace):import(e)}async function l3(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),hu=new Compartment({console,Math,Date,fetch:_3,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,BD.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:vt,tables:Gr,databases:tt})}};let n=await(0,vD.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),hu}function _3(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 d3(){return{Resource:vt,tables:Gr}}var vD,BD,u3,hu,hS=Oe(()=>{gn();Ne();vD=require("fs/promises"),BD=require("path"),u3=!1;a(Cd,"secureImport");a(l3,"getCompartment");a(_3,"secureOnlyFetch");a(d3,"getGlobalVars")});var pS={};Fe(pS,{handleFile:()=>f3});async function f3(e,t,r,n){let s=new Map,i=(0,HD.pathToFileURL)(r).toString(),o=await Cd(i);u(o.default)&&n.set((0,mS.dirname)(t),o.default),c(o,(0,mS.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var HD,mS,xD=Oe(()=>{HD=require("url");hS();mS=require("path");a(f3,"handleFile")});var TS={};Fe(TS,{start:()=>E3});function E3({resources:e}){e.set("login",SS),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var SS,FD=Oe(()=>{gn();a(E3,"start");SS=class extends vt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var KD={};Fe(KD,{parse:()=>RS,streamAsJSON:()=>mu,stringify:()=>so});function mu(e){return new gS({value:e})}function qD(e){return console.error(e),JSON.stringify(e.toString())}function GD(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function so(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===$D)return YD(e);if(t.resolution)return t.resolution.then(()=>so(e));throw t}}function YD(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=YD(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+so(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function RS(e){return p3.test(e)?h3.parse(e):JSON.parse(e)}var kD,VD,h3,m3,$D,gS,p3,AS=Oe(()=>{kD=require("stream"),VD=x(require("json-bigint-fixes")),h3=(0,VD.default)({useNativeBigInt:!0}),m3=1e4,$D={};BigInt.prototype.toJSON=function(){throw $D};a(mu,"streamAsJSON");gS=class extends kD.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),qD)}catch(s){yield qD(s)}else yield so(t)}else yield so(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);GD(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>m3?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 GD(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(qD,"handleError");a(GD,"when");a(so,"stringify");a(YD,"jsStringify");p3=/-?\d{16,}/;a(RS,"parse")});var Dd=T((Z_e,WD)=>{"use strict";var S3=In();WD.exports={writeTransaction:T3};function T3(e,t,r){return S3.writeTransaction(e,t,r)}a(T3,"writeTransaction")});var XD=T((rde,JD)=>{"use strict";var g3=tn(),R3=Zs(),QD=W(),A3=rn(),tde=Dd(),O3=require("clone"),bS=require("alasql"),b3=G_(),zD=require("util"),N3=zD.promisify(R3.getTableSchema),y3=zD.promisify(g3.search),w3=U(),OS=J();b3(bS);JD.exports={update:C3};var I3="There was a problem performing this update. Please check the logs and try again.";async function C3({statement:e,hdb_user:t}){let r=await N3(e.table.databaseid,e.table.tableid),n=D3(e.columns);OS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=O3(s),c=OS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=bS.parse(u).statements[0],l=await y3(_),d=L3(n,l);return M3(o,d,t)}a(C3,"update");function D3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=bS.compile(`SELECT ${r.expression.toString()} AS [${w3.FUNC_VAL}] FROM ?`)}),t}catch(t){throw QD.error(t),new Error(I3)}}a(D3,"createUpdateRecord");function L3(e,t){return OS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(L3,"buildUpdateRecords");async function M3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await A3.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){QD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(M3,"updateRecords")});var ZD=T((ode,jD)=>{var U3=require("alasql"),P3=tn(),v3=W(),B3=In(),yS=require("util"),NS=J(),H3=U(),x3=Zs(),sde=Dd(),ide=rn(),F3="record",q3="successfully deleted",G3=yS.callbackify(Y3),k3=yS.promisify(P3.search),V3=yS.promisify(x3.getTableSchema);jD.exports={convertDelete:G3};function $3(e){return`${e.deleted_hashes.length} ${F3}${e.deleted_hashes.length===1?"":"s"} ${q3}`}a($3,"generateReturnMessage");async function Y3({statement:e,hdb_user:t}){let r=await V3(e.table.databaseid,e.table.tableid);NS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=NS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=U3.parse(o).statements[0],u={operation:H3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await k3(c);let _=await B3.deleteRecords(u);return NS.isEmptyOrZeroLength(_.message)&&(_.message=$3(_)),delete _.txn_time,_}catch(_){throw v3.error(_),_.hdb_code?_.message:_}}a(Y3,"convertDelete")});var sL=T((cde,nL)=>{"use strict";var K3=Gi(),{hdb_errors:eL}=ee(),{getDatabases:tL}=(Ne(),te(qe));nL.exports={checkSchemaExists:rL,checkSchemaTableExists:W3,schema_describe:K3};async function rL(e){if(!tL()[e])return eL.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(rL,"checkSchemaExists");async function W3(e,t){let r=await rL(e);if(r)return r;if(!tL()[e][t])return eL.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(W3,"checkSchemaTableExists")});var pu=T((lde,Q3)=>{Q3.exports={name:"harperdb",version:"4.3.0-beta.3",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:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.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:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.10.0-beta.1",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",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:"^5.3.3","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 Ot=T((hde,bL)=>{"use strict";var Ht=Z();Ht.initSync();var z3=require("fs-extra"),J3=require("semver"),gu=require("path"),{monotonicFactory:X3}=require("ulidx"),oL=X3(),j3=require("util"),aL=require("child_process"),Z3=j3.promisify(aL.exec),eX=aL.spawn,ye=et(),Pe=U(),DS=J(),$r=W(),Ld=Os(),tX=Dd(),Su=vr(),{onMessageByType:rX}=je(),{isMainThread:nX}=require("worker_threads"),{Encoder:sX,decode:LS}=require("msgpackr"),cL=new sX,{isEmpty:co}=DS,uL=nn(),iX=48*36e11,oX=5e9;nX&&rX(Pe.ITC_EVENT_TYPES.RESTART,()=>{cn=void 0,ao=void 0});var{connect:aX,StorageType:lL,RetentionPolicy:_L,AckPolicy:Md,DeliverPolicy:Ud,DiscardPolicy:cX,NatsConnection:_de,JetStreamManager:dde,JetStreamClient:fde,StringCodec:Ede,JSONCodec:uX,createInbox:MS,headers:lX,ErrorCode:iL}=require("nats"),{PACKAGE_ROOT:_X}=U(),dX=pu(),{recordAction:fX}=(bs(),te(tu)),dL=uX(),EX="clustering",hX=dX.engines[ye.NATS_SERVER_NAME],mX=gu.join(_X,"dependencies"),CS=gu.join(mX,`${process.platform}-${process.arch}`,ye.NATS_BINARY_NAME),wS,IS,Tu,io,oo;bL.exports={runCommand:fL,checkNATSServerInstalled:pX,createConnection:US,getConnection:Pd,getJetStreamManager:Ru,getJetStream:hL,getNATSReferences:or,getServerList:TX,createLocalStream:PS,listStreams:mL,deleteLocalStream:gX,getServerConfig:Au,listRemoteStreams:RX,viewStream:AX,viewStreamIterator:OX,publishToStream:bX,createWorkQueueStream:NX,addSourceToWorkStream:SL,request:wX,removeSourceFromWorkStream:gL,reloadNATS:vS,reloadNATSHub:IX,reloadNATSLeaf:CX,extractServerName:TL,requestErrorHandler:DX,updateWorkStream:LX,createLocalTableStream:AL,createTableStreams:MX,purgeTableStream:OL,purgeSchemaTableStreams:UX,getStreamInfo:PX,updateLocalStreams:BX,closeConnection:SX,getJsmServerName:Ou,addNatsMsgHeader:pL,updateIngestStreamConsumer:yX,clearClientCache:EL};async function fL(e,t=void 0){let{stdout:r,stderr:n}=await Z3(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(_L,"runCommand");async function hX(){try{await W3.access(LS)}catch{return!1}let e=await _L(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return Q3.eq(t,fX)}a(hX,"checkNATSServerInstalled");async function vS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await aL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Wr.trace("create nats connection called");let i=await iX({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Wr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Wr.error("Error with Nats client connection, connection closed",o),dL()}),i}a(vS,"createConnection");function dL(){dn=void 0,io=void 0,oo=void 0,ao=void 0}a(dL,"clearClientCache");async function mX(){dn&&(await dn.drain(),dn=void 0,io=void 0,oo=void 0,ao=void 0)}a(mX,"closeConnection");var dn,ao;async function Hd(){return ao||(ao=vS(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),dn=await ao),dn||ao}a(Hd,"getConnection");async function Ru(){if(io)return io;co(dn)&&await Hd();let{domain:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await dn.jetstreamManager({domain:e,timeout:6e4}),io}a(Ru,"getJetStreamManager");async function fL(){if(oo)return oo;co(dn)&&await Hd();let{domain:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=dn.jetstream({domain:e,timeout:6e4}),oo}a(fL,"getJetStream");async function lr(){let e=dn||await Hd(),t=io||await Ru(),r=oo||await fL();return{connection:e,jsm:t,js:r}}a(lr,"getNATSReferences");async function pX(e){let t=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await aL.getClusterUser(),s=await vS(t,r,n),i=PS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=lL.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await MS.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(pX,"getServerList");async function BS(e,t){let{jsm:r}=await lr(),n=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:cL.File,retention:uL.Limits,subjects:t,discard:oX.Old,max_msgs:s,max_bytes:i,max_age:n})}a(BS,"createLocalStream");async function EL(){let{jsm:e}=await lr(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(EL,"listStreams");async function SX(e){let{jsm:t}=await lr();await t.streams.delete(e)}a(SX,"deleteLocalStream");async function TX(e){let{connection:t}=await lr(),r=[],n=PS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(lL.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(TX,"listRemoteStreams");async function gX(e,t=void 0,r=void 0){let{jsm:n,js:s}=await lr(),i=sL(),o={durable_name:i,ack_policy:vd.Explicit};t&&(o.deliver_policy=Bd.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=US(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Ne.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(gX,"viewStream");async function*RX(e,t=void 0,r=void 0){let{jsm:n,js:s}=await lr(),i=sL(),o={durable_name:i,ack_policy:vd.Explicit};t&&(o.deliver_policy=Bd.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=US(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(Ne.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(RX,"viewStreamIterator");async function AX(e,t,r,n){Wr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=hL(n,r);let{js:s}=await lr(),i=await Ou(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:oL.encode(n);try{Wr.trace(`publishToStream publishing to subject: ${o}`),_X(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return TL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Wr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await BS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(AX,"publishToStream");function hL(e,t){t===void 0&&(t=cX());let r=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Ne.MSG_HEADERS.ORIGIN)&&r&&t.append(Ne.MSG_HEADERS.ORIGIN,r),t}a(hL,"addNatsMsgHeader");function Au(e){e=e.toLowerCase();let t=gu.join(Gt.get(Pe.CONFIG_PARAMS.ROOTPATH),dX);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(DS)&&(DS={port:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.HUB,config_file:Ne.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:gu.join(t,Ne.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(CS)&&(CS={port:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.LEAF,config_file:Ne.NATS_CONFIG_FILES.LEAF_SERVER,domain:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.LEAF,pid_file_path:gu.join(t,Ne.PID_FILES.LEAF),hdb_nats_path:t}),CS;Wr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Au,"getServerConfig");async function OX(e){let{jsm:t}=await lr(),r=await Ou();try{await t.streams.add({name:e.stream_name,storage:cL.File,retention:uL.Limits,max_age:nX,max_bytes:sX,subjects:[`${Ne.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(n){if(n.code!=="400")throw n}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(n){if(n.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:vd.Explicit,durable_name:e.durable_name,deliver_policy:Bd.All,max_ack_pending:1e4});else throw n}}a(OX,"createWorkQueueStream");async function bX(){let{jsm:e}=await lr();(await e.consumers.info(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Wr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name),Wr.info("Adding pull consumer to ingest stream"),await e.consumers.add(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:vd.Explicit,durable_name:Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:Bd.All,max_ack_pending:1e4}))}a(bX,"updateIngestStreamConsumer");async function mL(e,t,r){let{jsm:n}=await lr(),s=await n.streams.info(t),i=pL(n.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=Pd.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(s.config.sources)||s.config.sources.length===0)s.config.sources=[];else for(let S=0,p=s.config.sources.length;S<p;S++)if(d=s.config.sources[S],f=S,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let S=`txn.${c}.${u}.${e}`;await n.streams.purge(t,{filter:S}),s.config.sources.splice(f,1),await n.streams.update(t,s.config)}let h={name:_,opt_start_time:o,filter_subject:`${Ne.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),s.config.sources.push(h),await n.streams.update(t,s.config)}a(mL,"addSourceToWorkStream");function pL(e){return e.split(".")[1]}a(pL,"extractServerName");async function SL(e,t,r){let{jsm:n}=await lr(),{schema:s,table:i}=r,o=`txn.${s}.${i}.${e}`;await n.streams.purge(t,{filter:o});let c=Pd.createNatsTableStreamName(s,i),u=await n.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await n.streams.update(t,u.config)}a(SL,"removeSourceFromWorkStream");async function NX(e,t,r=6e4,n=PS()){if(!MS.isObject(t))throw new Error("data param must be an object");let s=oL.encode(t),{connection:i}=await lr(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return US(c.data)}a(NX,"request");function HS(e){return new Promise(async(t,r)=>{let n=j3(LS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(HS,"reloadNATS");async function yX(){let{pid_file_path:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await HS(e)}a(yX,"reloadNATSHub");async function IX(){let{pid_file_path:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await HS(e)}a(IX,"reloadNATSLeaf");function wX(e,t,r){let n;switch(e.code){case nL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case nL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(wX,"requestErrorHandler");async function CX(e,t){let r=t+Ne.SERVER_SUFFIX.LEAF;await TL(async()=>{e.subscribe===!0?await mL(r,Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await SL(r,Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(CX,"updateWorkStream");function TL(e){return Z3.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(TL,"exclusiveLock");async function gL(e,t){let r=Pd.createNatsTableStreamName(e,t),n=await Ou(),s=UX(e,t,n);await BS(r,[s])}a(gL,"createLocalTableStream");async function DX(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await gL(n,s)}}a(DX,"createTableStreams");async function RL(e,t,r=!1){if(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Pd.createNatsTableStreamName(e,t),{jsm:s}=await lr();r?await s.streams.purge(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name):await s.streams.purge(n)}catch(n){if(n.message==="stream not found")Wr.warn(n);else throw n}}a(RL,"purgeTableStream");async function LX(e,t){if(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await RL(e,t[r])}a(LX,"purgeSchemaTableStreams");async function MX(e){return(await Ru()).streams.info(e)}a(MX,"getStreamInfo");function UX(e,t,r){return`${Ne.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(UX,"createSubjectName");async function Ou(){if(Tu)return Tu;if(Tu=(await Ru())?.nc?.info?.server_name,Tu===void 0)throw new Error("Unable to get jetstream manager server name");return Tu}a(Ou,"getJsmServerName");async function PX(){let e=await Ru(),t=await Ou(),r=await EL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=vX(n),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(s.name===Ne.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Ne.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Wr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else if(s.name===Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Wr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Wr.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l}await e.streams.update(s.name,s)}}}a(PX,"updateLocalStreams");function vX(e){let{config:t}=e,r=!1;if(t.name===Ne.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let n=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(vX,"updateStreamLimits")});var Gd=T((pde,yL)=>{"use strict";var da=I_(),fa=rL(),BX=Y(),HX=require("uuid").v4,mde=require("clone"),Fd=gs(),Ea=M(),xX=require("util"),ui=Ln(),{handleHDBError:_r,hdb_errors:FX}=Z(),{HDB_ERROR_MSGS:xd,HTTP_STATUS_CODES:dr}=FX,{SchemaEventMsg:qd}=In(),OL=yt(),{getDatabases:qX}=(Oe(),ee(Ge)),{transformReq:ha}=J();yL.exports={createSchema:GX,createSchemaStructure:bL,createTable:kX,createTableStructure:NL,createAttribute:WX,dropSchema:VX,dropTable:$X,dropAttribute:YX,getBackup:QX};async function GX(e){let t=await bL(e);return Fd.signalSchemaChange(new qd(process.pid,e.operation,e.schema)),t}a(GX,"createSchema");async function bL(e){let t=da.schema_object(e);if(t)throw _r(t,t.message,dr.BAD_REQUEST,void 0,void 0,!0);if(ha(e),!await fa.checkSchemaExists(e.schema))throw _r(new Error,xd.SCHEMA_EXISTS_ERR(e.schema),dr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,xd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ui.createSchema(e),`database '${e.schema}' successfully created`}a(bL,"createSchemaStructure");async function kX(e){return ha(e),e.hash_attribute=e.primary_key??e.hash_attribute,await NL(e)}a(kX,"createTable");async function NL(e){let t=da.create_table_object(e);if(t)throw _r(t,t.message,dr.BAD_REQUEST,void 0,void 0,!0);if(da.validateTableResidence(e.residence),!await fa.checkSchemaTableExists(e.schema,e.table))throw _r(new Error,xd.TABLE_EXISTS_ERR(e.schema,e.table),dr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,xd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:HX(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ui.createTable(n,e);else throw _r(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",dr.BAD_REQUEST);else await ui.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(NL,"createTableStructure");async function VX(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=da.schema_object(e),n=t??r;if(n)throw _r(n,n.message,dr.BAD_REQUEST,void 0,void 0,!0);ha(e);let s=await fa.checkSchemaExists(e.schema);if(s)throw _r(new Error,s,dr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,s,!0);let i=await fa.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ui.dropSchema(e),Fd.signalSchemaChange(new qd(process.pid,e.operation,e.schema)),await OL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(VX,"dropSchema");async function $X(e){let t=da.table_object(e);if(t)throw _r(t,t.message,dr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw _r(new Error,r,dr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);return await ui.dropTable(e),await OL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a($X,"dropTable");async function YX(e){let t=da.attribute_object(e);if(t)throw _r(t,t.message,dr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw _r(new Error,r,dr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw _r(new Error,"You cannot drop a hash attribute",dr.BAD_REQUEST,void 0,void 0,!0);if(Ea.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw _r(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,dr.BAD_REQUEST,void 0,void 0,!0);try{return await ui.dropAttribute(e),KX(e),Fd.signalSchemaChange(new qd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw BX.error(`Got an error deleting attribute ${xX.inspect(e)}.`),n}}a(YX,"dropAttribute");function KX(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(KX,"dropAttributeFromGlobal");async function WX(e){ha(e);let t=qX()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw _r(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,dr.BAD_REQUEST,void 0,void 0,!0);return await ui.createAttribute(e),Fd.signalSchemaChange(new qd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(WX,"createAttribute");function QX(e){return ui.getBackup(e)}a(QX,"getBackup")});var wL=T((Tde,IL)=>{"use strict";var{OPERATIONS_ENUM:zX}=M(),xS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=zX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};IL.exports=xS});var FS=T((Ade,UL)=>{"use strict";var JX=Ln(),Rde=wL(),kd=J(),Vd=M(),XX=j(),{handleHDBError:CL,hdb_errors:jX}=Z(),{HDB_ERROR_MSGS:DL,HTTP_STATUS_CODES:LL}=jX,ZX=Object.values(Vd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),ML="To use this operation audit log must be enabled in harperdb-config.yaml";UL.exports=ej;async function ej(e){if(kd.isEmpty(e.schema))throw new Error(DL.SCHEMA_REQUIRED_ERR);if(kd.isEmpty(e.table))throw new Error(DL.TABLE_REQUIRED_ERR);if(!XX.get(Vd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw CL(new Error,ML,LL.BAD_REQUEST,Vd.LOG_LEVELS.ERROR,ML,!0);let t=kd.checkSchemaTableExist(e.schema,e.table);if(t)throw CL(new Error,t,LL.NOT_FOUND,Vd.LOG_LEVELS.ERROR,t,!0);if(!kd.isEmpty(e.search_type)&&ZX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await JX.readAuditLog(e)}a(ej,"readAuditLog")});var vL=T((bde,PL)=>{"use strict";var{OPERATIONS_ENUM:tj}=M(),qS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=tj.GET_BACKUP,this.schema=t,this.table=r}};PL.exports=qS});var xL=T((wde,HL)=>{"use strict";var rj=Ln(),yde=vL(),GS=J(),nj=M(),Ide=j(),{handleHDBError:sj,hdb_errors:ij}=Z(),{HDB_ERROR_MSGS:BL,HTTP_STATUS_CODES:oj}=ij;HL.exports=aj;async function aj(e){if(GS.isEmpty(e.schema))throw new Error(BL.SCHEMA_REQUIRED_ERR);if(GS.isEmpty(e.table))throw new Error(BL.TABLE_REQUIRED_ERR);let t=GS.checkSchemaTableExist(e.schema,e.table);if(t)throw sj(new Error,t,oj.NOT_FOUND,nj.LOG_LEVELS.ERROR,t,!0);return await rj.getBackup(read_audit_log_object)}a(aj,"getBackup")});var $L=T((Dde,VL)=>{var li=require("validate.js"),qL=rt(),ma=M(),{handleHDBError:cj,hdb_errors:uj}=Z(),{HDB_ERROR_MSGS:dt,HTTP_STATUS_CODES:lj}=uj,kS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),_j={STRUCTURE_USER:"structure_user"},FL=Object.values(ma.ROLE_TYPES_ENUM),dj="attribute_permissions",fj="attribute_name",{PERMS_CRUD_ENUM:pa}=ma,Ej=[dj,...Object.values(pa)],GL=[pa.READ,pa.INSERT,pa.UPDATE],hj=[fj,...GL];function mj(e){let t=kS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,kL(e,t)}a(mj,"addRoleValidation");function pj(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,kL(e,t)}a(pj,"alterRoleValidation");function Sj(e){let t=kS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,qL.validateObject(e,t)}a(Sj,"dropRoleValidation");var Tj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function kL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Tj.includes(n[o])||s.push(n[o]);s.length>0&&pt(dt.INVALID_ROLE_JSON_KEYS(s),r);let i=qL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{pt(o,r)}),e.permission){let o=gj(e);o&&pt(o,r),FL.forEach(c=>{e.permission[c]&&!li.isBoolean(e.permission[c])&&pt(dt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(FL.indexOf(o)<0){if(o===_j.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||pt(dt.SCHEMA_NOT_FOUND(d),r)}continue}pt(dt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){pt(dt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){pt(dt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{Ej.includes(l)||pt(dt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(pa).forEach(l=>{li.isDefined(_[l])?li.isBoolean(_[l])||pt(dt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):pt(dt.TABLE_PERM_MISSING(l),r,o,u)}),li.isDefined(_.attribute_permissions)){if(!li.isArray(_.attribute_permissions)){pt(dt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{pt(dt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(S=>{!hj.includes(S)&&S!==pa.DELETE&&pt(dt.INVALID_ATTR_PERM_KEY(S),r,o,u)}),!li.isDefined(E.attribute_name)){pt(dt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){pt(dt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}GL.forEach(S=>{li.isDefined(E[S])?li.isBoolean(E[S])||pt(dt.ATTR_PERM_NOT_BOOLEAN(S,h),r,o,u):pt(dt.ATTR_PERM_MISSING(S,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;pt(dt.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return Rj(r)}a(kL,"customValidate");VL.exports={addRoleValidation:mj,alterRoleValidation:pj,dropRoleValidation:Sj};function gj(e){let{operation:t,permission:r}=e;if(t===ma.OPERATIONS_ENUM.ADD_ROLE||t===ma.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return dt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ma.ROLE_TYPES_ENUM.SUPER_USER:ma.ROLE_TYPES_ENUM.CLUSTER_USER;return dt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(gj,"validateNoSUPerms");function Rj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:dt.ROLE_PERMS_ERROR,...e};return cj(new Error,n,lj.BAD_REQUEST)}else return null}a(Rj,"generateRolePermResponse");function pt(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(pt,"addPermError")});var QS=T((Mde,QL)=>{"use strict";var YL=on(),KL=sn(),Aj=Ki(),$S=$L(),YS=gs(),Oj=require("uuid").v4,bj=require("util"),$d=M(),Nj=J(),KS=KL.searchByValue,yj=KL.searchByHash,Ij=bj.promisify(Aj.delete),wj=Wn(),Cj=jo(),{hdb_errors:Dj,handleHDBError:uo}=Z(),{HDB_ERROR_MSGS:WL,HTTP_STATUS_CODES:bu}=Dj,{UserEventMsg:WS}=In();QL.exports={addRole:Lj,alterRole:Mj,dropRole:Uj,listRoles:Pj};function VS(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a(VS,"scrubRoleDetails");async function Lj(e){let t=$S.addRoleValidation(e);if(t)throw t;e=VS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await KS(r)||[])}catch(i){throw uo(i)}if(n&&n.length>0)throw uo(new Error,WL.ROLE_ALREADY_EXISTS(e.role),bu.CONFLICT,void 0,void 0,!0);e.id||(e.id=Oj());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await YL.insert(s),YS.signalUserChange(new WS(process.pid)),e=VS(e),e}a(Lj,"addRole");async function Mj(e){let t=$S.alterRoleValidation(e);if(t)throw t;e=VS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await YL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",bu.BAD_REQUEST,void 0,void 0,!0);return await YS.signalUserChange(new WS(process.pid)),e}a(Mj,"alterRole");async function Uj(e){let t=$S.dropRoleValidation(e);if(t)throw uo(new Error,t,bu.BAD_REQUEST,void 0,void 0,!0);let r=new Cj($d.SYSTEM_SCHEMA_NAME,$d.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await yj(r));if(n.length===0)throw uo(new Error,WL.ROLE_NOT_FOUND,bu.NOT_FOUND,void 0,void 0,!0);let s=new wj($d.SYSTEM_SCHEMA_NAME,$d.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await KS(s)),o=!1;if(Nj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,bu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Ij(c),YS.signalUserChange(new WS(process.pid)),`${n[0].role} successfully deleted`}a(Uj,"dropRole");async function Pj(){return KS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Pj,"listRoles")});var jL=T((Pde,XL)=>{"use strict";var vj=j(),_i=require("joi"),Bj=rt(),zL=require("moment"),Hj=require("fs-extra"),zS=require("path"),xj=require("lodash"),Nu=M(),{LOG_LEVELS:lo}=M(),Fj="YYYY-MM-DD hh:mm:ss",qj=zS.resolve(__dirname,"../logs");XL.exports=function(e){return Bj.validateBySchema(e,Gj)};var Gj=_i.object({from:_i.custom(JL),until:_i.custom(JL),level:_i.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:_i.valid("asc","desc"),limit:_i.number().min(1),start:_i.number().min(0),log_name:_i.custom(kj)});function JL(e,t){if(zL(e,zL.ISO_8601).format(Fj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(JL,"validateDatetime");function kj(e,t){if(xj.invert(Nu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=vj.get(Nu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Nu.LOG_NAMES.HDB:e,i=s===Nu.LOG_NAMES.INSTALL?zS.join(qj,Nu.LOG_NAMES.INSTALL):zS.join(n,s);return Hj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(kj,"validateReadLogPath")});var XS=T((Bde,eM)=>{"use strict";var Yd=M(),Vj=Y(),$j=j(),Yj=jL(),JS=require("path"),ZL=require("fs-extra"),{once:Kj}=require("events"),{handleHDBError:Wj,hdb_errors:Qj}=Z(),{PACKAGE_ROOT:zj}=M(),Jj=JS.join(zj,"logs"),Xj=1e3,jj=200;eM.exports=Zj;async function Zj(e){let t=Yj(e);if(t)throw Wj(t,t.message,Qj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=$j.get(Yd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Yd.LOG_NAMES.HDB:e.log_name,s=n===Yd.LOG_NAMES.INSTALL?JS.join(Jj,Yd.LOG_NAMES.INSTALL):JS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?Xj:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,S=0;f==="desc"&&!u&&!l&&(S=Math.max(ZL.statSync(s).size-(h+5)*jj,0));let p=ZL.createReadStream(s,{start:S});p.on("error",H=>{Vj.error(H)});let g=0,A=[],b="",v;p.on("data",H=>{let P=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;H=b+H;let z=0,W;for(;(W=P.exec(H))&&!p.destroyed;){v&&(v.message=H.slice(z,W.index),G(v));let[Q,se,pe]=W,oe=pe.split("] ["),Fe=oe[0],ce=oe[1];oe.splice(0,2),v={timestamp:se,thread:Fe,level:ce,tags:oe,message:""},z=W.index+Q.length}b=H.slice(z)}),p.on("end",H=>{p.destroyed||v&&(v.message=b.trim(),G(v))}),p.resume();function G(H){let P,z,W;switch(!0){case(i&&c&&_):P=new Date(H.timestamp),z=new Date(u),W=new Date(l),H.level===o&&P>=z&&P<=W&&g<E?g++:H.level===o&&P>=z&&P<=W&&(di(H,f,A),g++,g===h&&p.destroy());break;case(i&&c):P=new Date(H.timestamp),z=new Date(u),H.level===o&&P>=z&&g<E?g++:H.level===o&&P>=z&&(di(H,f,A),g++,g===h&&p.destroy());break;case(i&&_):P=new Date(H.timestamp),W=new Date(l),H.level===o&&P<=W&&g<E?g++:H.level===o&&P<=W&&(di(H,f,A),g++,g===h&&p.destroy());break;case(c&&_):P=new Date(H.timestamp),z=new Date(u),W=new Date(l),P>=z&&P<=W&&g<E?g++:P>=z&&P<=W&&(di(H,f,A),g++,g===h&&p.destroy());break;case i:H.level===o&&g<E?g++:H.level===o&&(di(H,f,A),g++,g===h&&p.destroy());break;case c:P=new Date(H.timestamp),z=new Date(u),P>=z&&g<E?g++:P>=z&&g>=E&&(di(H,f,A),g++,g===h&&p.destroy());break;case _:P=new Date(H.timestamp),W=new Date(l),P<=W&&g<E?g++:P<=W&&g>=E&&(di(H,f,A),g++,g===h&&p.destroy());break;default:g<E?g++:(di(H,f,A),g++,g===h&&p.destroy())}}return a(G,"onLogMessage"),await Kj(p,"close"),A}a(Zj,"readLog");function di(e,t,r){t==="desc"?eZ(e,r):t==="asc"?tZ(e,r):r.push(e)}a(di,"pushLineToResult");function eZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(eZ,"insertDescending");function tZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(tZ,"insertAscending")});var Kd=T((Gde,sM)=>{"use strict";var jS=require("joi"),{string:yu,boolean:tM,date:rZ}=jS.types(),nZ=rt(),{validateSchemaExists:xde,validateTableExists:Fde,validateSchemaName:qde}=Yn(),sZ=M(),iZ=nt(),rM=j();rM.initSync();var oZ=yu.invalid(rM.get(sZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(iZ.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(),nM={operation:yu.valid("add_node","update_node","set_node_replication"),node_name:oZ,subscriptions:jS.array().items({table:yu.optional(),schema:yu.optional(),database:yu.optional(),subscribe:tM.required(),publish:tM.required().custom(cZ),start_time:rZ.iso()}).min(1).required()};function aZ(e){return nZ.validateBySchema(e,jS.object(nM))}a(aZ,"addUpdateNodeValidator");function cZ(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(cZ,"checkForFalsy");sM.exports={addUpdateNodeValidator:aZ,validation_schema:nM}});var oM=T((Vde,iM)=>{var uZ=rt(),lZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};iM.exports=function(e){return uZ.validateObject(e,lZ)}});var eT=T(($de,aM)=>{"use strict";var _Z=M().OPERATIONS_ENUM,ZS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=_Z.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};aM.exports=ZS});var uM=T((Kde,cM)=>{"use strict";var dZ={OPERATION:"operation",REFRESH:"refresh"},tT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},rT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};cM.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:dZ,JWTRSAKeys:rT}});var Cu=T((Qde,fM)=>{"use strict";var wu=require("jsonwebtoken"),nT=require("fs-extra"),sT=J(),fn=M(),{handleHDBError:fr,hdb_errors:fZ}=Z(),{HTTP_STATUS_CODES:Er,AUTHENTICATION_ERROR_MSGS:hr}=fZ,Iu=Y(),lM=ed(),aT=cn(),EZ=on().update,hZ=eT(),mZ=gs(),{UserEventMsg:pZ}=In(),fi=j();fi.initSync();var iT=require("path"),{JWTTokens:SZ,JWTRSAKeys:TZ,TOKEN_TYPE_ENUM:Wd}=uM(),gZ=fi.get(fn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?fi.get(fn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",RZ=fi.get(fn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?fi.get(fn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Qd="RS256",oT;fM.exports={createTokens:AZ,validateOperationToken:bZ,refreshOperationToken:OZ,validateRefreshToken:dM};async function AZ(e){if(sT.isEmpty(e)||typeof e!="object")throw fr(new Error,hr.INVALID_AUTH_OBJECT,Er.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.username))throw fr(new Error,hr.USERNAME_REQUIRED,Er.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.password))throw fr(new Error,hr.PASSWORD_REQUIRED,Er.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw fr(new Error,hr.INVALID_CREDENTIALS,Er.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Iu.error(f),fr(new Error,hr.INVALID_CREDENTIALS,Er.UNAUTHORIZED,void 0,void 0,!0)}let r=await zd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await _M(i,r.private_key,r.passphrase),c=await wu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:RZ,algorithm:Qd,subject:Wd.REFRESH}),u=lM.hash(c),_=new hZ(fn.SYSTEM_SCHEMA_NAME,fn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await EZ(_)}catch(f){Iu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw fr(new Error,hr.REFRESH_TOKEN_SAVE_FAILED,Er.INTERNAL_SERVER_ERROR);return mZ.signalUserChange(new pZ(process.pid)),new SZ(o,c)}a(AZ,"createTokens");async function _M(e,t,r){return await wu.sign(e,{key:t,passphrase:r},{expiresIn:gZ,algorithm:Qd,subject:Wd.OPERATION})}a(_M,"signOperationToken");async function zd(){if(oT===void 0)try{let e=iT.join(fi.getHdbBasePath(),fn.LICENSE_KEY_DIR_NAME,fn.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(fi.getHdbBasePath(),fn.LICENSE_KEY_DIR_NAME,fn.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(fi.getHdbBasePath(),fn.LICENSE_KEY_DIR_NAME,fn.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await nT.readFile(e)).toString(),s=(await nT.readFile(t)).toString(),i=(await nT.readFile(r)).toString();oT=new TZ(i,s,n)}catch(e){throw Iu.error(e),fr(new Error,hr.NO_ENCRYPTION_KEYS,Er.INTERNAL_SERVER_ERROR)}return oT}a(zd,"getJWTRSAKeys");async function OZ(e){if(!e)throw fr(new Error,hr.INVALID_BODY,Er.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw fr(new Error,hr.REFRESH_TOKEN_REQUIRED,Er.BAD_REQUEST,void 0,void 0,!0);await dM(e.refresh_token);let t=await zd(),r=await wu.decode(e.refresh_token);return{operation_token:await _M({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(OZ,"refreshOperationToken");async function bZ(e){try{let t=await zd(),r=await wu.verify(e,t.public_key,{algorithms:Qd,subject:Wd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Iu.warn(t),t.name&&t.name==="TokenExpiredError"?fr(new Error,hr.TOKEN_EXPIRED,Er.FORBIDDEN):fr(new Error,hr.INVALID_TOKEN,Er.UNAUTHORIZED)}}a(bZ,"validateOperationToken");async function dM(e){let t;try{let r=await zd(),n=await wu.verify(e,r.public_key,{algorithms:Qd,subject:Wd.REFRESH});t=await aT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Iu.warn(r),r.name&&r.name==="TokenExpiredError"?fr(new Error,hr.TOKEN_EXPIRED,Er.FORBIDDEN):fr(new Error,hr.INVALID_TOKEN,Er.UNAUTHORIZED)}if(!lM.validate(t.refresh_token,e))throw fr(new Error,hr.INVALID_TOKEN,Er.UNAUTHORIZED);return t}a(dM,"validateRefreshToken")});var cT=T((Xde,mM)=>{"use strict";var NZ=oM(),Sa=require("passport"),yZ=require("passport-local").Strategy,IZ=require("passport-http").BasicStrategy,wZ=require("util"),CZ=cn(),hM=wZ.callbackify(CZ.findAndValidateUser),Jde=wr(),DZ=M(),EM=Cu();Sa.use(new yZ(function(e,t,r){hM(e,t,r)}));Sa.use(new IZ(function(e,t,r){hM(e,t,r)}));Sa.serializeUser(function(e,t){t(null,e)});Sa.deserializeUser(function(e,t){t(null,e)});function LZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":Sa.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===DZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?EM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):EM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Sa.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(LZ,"authorize");function MZ(e,t){let r=NZ(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(MZ,"checkPermissions");mM.exports={authorize:LZ,checkPermissions:MZ}});var Ta=T((Zde,pM)=>{"use strict";var uT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},lT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};pM.exports={Node:uT,NodeSubscription:lT}});var TM=T((tfe,SM)=>{"use strict";var UZ=M().OPERATIONS_ENUM,_T=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=UZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};SM.exports=_T});var Du=T((nfe,gM)=>{"use strict";var dT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},fT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};gM.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var AM=T((ife,RM)=>{"use strict";var ET=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};RM.exports=ET});var NM=T((lfe,bM)=>{"use strict";var PZ=AM(),afe=Et(),OM=We(),vZ=Y(),{getSchemaPath:cfe,getTransactionAuditStorePath:ufe}=Je(),{getDatabases:BZ}=(Oe(),ee(Ge));bM.exports=HZ;async function HZ(e){let t=new PZ;try{let r=BZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await OM.environmentDataSize(schema_path,e.name),o=await OM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){vZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(HZ,"lmdbGetTableSize")});var IM=T((dfe,yM)=>{"use strict";var hT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};yM.exports=hT});var ga=T((mfe,LM)=>{"use strict";var xZ=require("fs-extra"),FZ=require("path"),Xt=require("systeminformation"),Ei=Y(),qZ=yt(),mT=nt(),Xd=M(),GZ=NM(),DM=Gi(),{getThreadInfo:wM}=tt(),yT=j();yT.initSync();var kZ=IM(),{openEnvironment:Efe}=We(),{getSchemaPath:hfe}=Je(),{database:VZ}=(Oe(),ee(Ge)),Jd;LM.exports={getHDBProcessInfo:gT,getNetworkInfo:AT,getDiskInfo:RT,getMemoryInfo:TT,getCPUInfo:ST,getTimeInfo:pT,getSystemInformation:OT,systemInformation:$Z,getTableSize:bT,getMetrics:NT};function pT(){return Xt.time()}a(pT,"getTimeInfo");async function ST(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Xt.cpu();l.cpu_speed=await Xt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:S,raw_currentload_user:p,cpus:g,...A}=await Xt.currentLoad();return A.cpus=[],g.forEach(b=>{let{raw_load:v,raw_load_idle:G,raw_load_irq:H,raw_load_nice:P,raw_load_system:z,raw_load_user:W,...Q}=b;A.cpus.push(Q)}),l.current_load=A,l}catch(e){return Ei.error(`error in getCPUInfo: ${e}`),{}}}a(ST,"getCPUInfo");async function TT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Xt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ei.error(`error in getMemoryInfo: ${e}`),{}}}a(TT,"getMemoryInfo");async function gT(){let e={core:[],clustering:[]};try{let t=await Xt.processes(),r;try{r=Number.parseInt(await xZ.readFile(FZ.join(yT.get(Xd.CONFIG_PARAMS.ROOTPATH),Xd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Xd.NODE_ERROR_CODES.ENOENT)Ei.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Ei.error(`error in getHDBProcessInfo: ${t}`),e}}a(gT,"getHDBProcessInfo");async function RT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Xt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Xt.fsStats();return e.read_write=_,e.size=await Xt.fsSize(),e}catch(t){return Ei.error(`error in getDiskInfo: ${t}`),e}}a(RT,"getDiskInfo");async function AT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Xt.networkInterfaceDefault(),e.latency=await Xt.inetChecksite("google.com"),(await Xt.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=n;e.interfaces.push(f)}),(await Xt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Ei.error(`error in getNetworkInfo: ${t}`),e}}a(AT,"getNetworkInfo");async function OT(){if(Jd!==void 0)return Jd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Xt.osInfo();e=c;let u=await Xt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Jd=e,Jd}catch(t){return Ei.error(`error in getSystemInformation: ${t}`),e}}a(OT,"getSystemInformation");async function bT(){let e=[],t=await DM.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await GZ(n));return e}a(bT,"getTableSize");async function NT(){let e=await DM.describeAll(),t={};for(let r in e){let n=t[r]={};for(let s in e[r])try{let i=VZ({database:r,table:s}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),n[s]=o}catch(i){Ei.notify(`Error getting stats for table ${s}: ${i}`)}}return t}a(NT,"getMetrics");async function CM(){if(yT.get(Xd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await qZ.getNATSReferences(),r=await t.streams.info(mT.WORK_QUEUE_CONSUMER_NAMES.stream_name),n=await e.consumers.get(mT.WORK_QUEUE_CONSUMER_NAMES.stream_name,mT.WORK_QUEUE_CONSUMER_NAMES.durable_name),s={ingest:{stream:{...r.state},consumer:{num_ack_pending:n._info.num_ack_pending,num_redelivered:n._info.num_redelivered,num_waiting:n._info.num_waiting,num_pending:n._info.num_pending}}};return r.sources&&(s.ingest.stream.sources=r.sources),s}}a(CM,"getNatsStreamInfo");async function $Z(e){let t=new kZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await OT(),t.time=pT(),t.cpu=await ST(),t.memory=await TT(),t.disk=await RT(),t.network=await AT(),t.harperdb_processes=await gT(),t.table_size=await bT(),t.metrics=await NT(),t.threads=await wM(),t.replication=await CM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await OT();break;case"time":t.time=pT();break;case"cpu":t.cpu=await ST();break;case"memory":t.memory=await TT();break;case"disk":t.disk=await RT();break;case"network":t.network=await AT();break;case"harperdb_processes":t.harperdb_processes=await gT();break;case"table_size":t.table_size=await bT();break;case"database_metrics":case"metrics":t.metrics=await NT();break;case"threads":t.threads=await wM();break;case"replication":t.replication=await CM();break;default:break}return t}a($Z,"systemInformation")});var Zd=T((Sfe,MM)=>{"use strict";MM.exports={version:YZ,printVersion:KZ};var jd=pu();function YZ(){if(jd)return jd.version}a(YZ,"version");function KZ(){jd&&console.log(`HarperDB Version ${jd.version}`)}a(KZ,"printVersion")});var Is=T((Afe,BM)=>{"use strict";var WZ=on(),IT=J(),QZ=require("util"),_o=M(),UM=j();UM.initSync();var zZ=cT(),PM=sn(),{Node:gfe,NodeSubscription:Rfe}=Ta(),JZ=jo(),XZ=TM(),{RemotePayloadObject:jZ,RemotePayloadSubscription:ZZ}=Du(),{handleHDBError:e5,hdb_errors:t5}=Z(),{HTTP_STATUS_CODES:r5,HDB_ERROR_MSGS:n5}=t5,s5=Wn(),i5=ga(),o5=Zd(),{getDatabases:a5}=(Oe(),ee(Ge)),c5=QZ.promisify(zZ.authorize),u5=PM.searchByHash,l5=PM.searchByValue;BM.exports={authHeaderToUser:_5,isEmpty:d5,getNodeRecord:f5,upsertNodeRecord:E5,buildNodePayloads:h5,checkClusteringEnabled:m5,getAllNodeRecords:p5,getSystemInfo:S5,reverseSubscription:vM};async function _5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await c5(t,null),e}a(_5,"authHeaderToUser");function d5(e){return e==null}a(d5,"isEmpty");async function f5(e){let t=new JZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return u5(t)}a(f5,"getNodeRecord");async function E5(e){let t=new XZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return WZ.upsert(t)}a(E5,"upsertNodeRecord");function vM(e){if(IT.isEmpty(e.subscribe)||IT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(vM,"reverseSubscription");function h5(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=IT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=vM(c),E=a5()[u]?.[_],h=new ZZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new jZ(r,t,s,n)}a(h5,"buildNodePayloads");function m5(){if(!UM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw e5(new Error,n5.CLUSTERING_NOT_ENABLED,r5.BAD_REQUEST,void 0,void 0,!0)}a(m5,"checkClusteringEnabled");async function p5(){let e=new s5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await l5(e))}a(p5,"getAllNodeRecords");async function S5(){let e=await i5.getSystemInformation();return{hdb_version:o5.version(),node_version:e.node_version,platform:e.platform}}a(S5,"getSystemInfo")});var wT=T((bfe,$M)=>{"use strict";var ef=yt(),HM=J(),xM=nt(),FM=M(),tf=Y(),qM=Gd(),T5=Qm(),{RemotePayloadObject:g5}=Du(),{handleHDBError:GM,hdb_errors:R5}=Z(),{HTTP_STATUS_CODES:kM}=R5,{NodeSubscription:VM}=Ta();$M.exports=A5;async function A5(e,t){let r;try{r=await ef.request(`${t}.${xM.REQUEST_SUFFIX}`,new g5(FM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),tf.trace("Response from remote describe all request:",r)}catch(o){tf.error(`addNode received error from describe all request to remote node: ${o}`);let c=ef.requestErrorHandler(o,"add_node",t);throw GM(new Error,c,kM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===xM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw GM(new Error,o,kM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===FM.SYSTEM_SCHEMA_NAME){await ef.createLocalTableStream(u,c);let h=new VM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=HM.doesSchemaExist(u),l=n[u]!==void 0,d=c?HM.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(tf.trace(`addNode creating schema: ${u}`),await qM.createSchema({operation:"create_schema",schema:u})),!d&&f){tf.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new T5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await qM.createTable(h)}await ef.createLocalTableStream(u,c);let E=new VM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(A5,"reviewSubscriptions")});var sf=T((yfe,WM)=>{"use strict";var{handleHDBError:rf,hdb_errors:O5}=Z(),{HTTP_STATUS_CODES:nf}=O5,{addUpdateNodeValidator:b5}=Kd(),Lu=Y(),KM=M(),YM=nt(),N5=J(),CT=yt(),Mu=Is(),y5=j(),I5=wT(),{Node:w5,NodeSubscription:C5}=Ta(),{broadcast:D5}=tt(),L5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",M5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",U5=y5.get(KM.CONFIG_PARAMS.CLUSTERING_NODENAME);WM.exports=P5;async function P5(e,t=!1){Lu.trace("addNode called with:",e),Mu.checkClusteringEnabled();let r=b5(e);if(r)throw rf(r,r.message,nf.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Mu.getNodeRecord(n);if(!N5.isEmptyOrZeroLength(d))throw rf(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,nf.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await I5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=L5,o;let c=Mu.buildNodePayloads(s,U5,KM.OPERATIONS_ENUM.ADD_NODE,await Mu.getSystemInfo());Lu.trace("addNode sending remote payload:",c);let u;try{u=await CT.request(`${n}.${YM.REQUEST_SUFFIX}`,c)}catch(d){Lu.error(`addNode received error from request: ${d}`);let f=CT.requestErrorHandler(d,"add_node",n);throw rf(new Error,f,nf.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===YM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${u.message}`;throw rf(new Error,d,nf.INTERNAL_SERVER_ERROR,"error",d)}Lu.trace(u);let _=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];Lu.trace("Add node updating work stream for node:",n,"subscriptions:",E),await CT.updateWorkStream(E,n),s[d].start_time===void 0&&delete s[d].start_time,_.push(new C5(E.schema,E.table,E.publish,E.subscribe))}let l=new w5(n,_,u.system_info);return await Mu.upsertNodeRecord(l),D5({type:"nats_update"}),i.length>0?o.message=M5:o.message=`Successfully added '${n}' to manifest`,o}a(P5,"addNode")});var UT=T((Cfe,JM)=>{"use strict";var{handleHDBError:DT,hdb_errors:v5}=Z(),{HTTP_STATUS_CODES:LT}=v5,{addUpdateNodeValidator:B5}=Kd(),Uu=Y(),zM=M(),QM=nt(),wfe=J(),MT=yt(),Pu=Is(),H5=j(),{cloneDeep:x5}=require("lodash"),F5=wT(),{Node:q5,NodeSubscription:G5}=Ta(),{broadcast:k5}=tt(),V5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",$5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Y5=H5.get(zM.CONFIG_PARAMS.CLUSTERING_NODENAME);JM.exports=K5;async function K5(e){Uu.trace("updateNode called with:",e),Pu.checkClusteringEnabled();let t=B5(e);if(t)throw DT(t,t.message,LT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Pu.getNodeRecord(r);s.length>0&&(n=x5(s));let{added:i,skipped:o}=await F5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=V5,c;let u=Pu.buildNodePayloads(i,Y5,zM.OPERATIONS_ENUM.UPDATE_NODE,await Pu.getSystemInfo());Uu.trace("updateNode sending remote payload:",u);let _;try{_=await MT.request(`${r}.${QM.REQUEST_SUFFIX}`,u)}catch(l){Uu.error(`updateNode received error from request: ${l}`);let d=MT.requestErrorHandler(l,"update_node",r);throw DT(new Error,d,LT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===QM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw DT(new Error,l,LT.INTERNAL_SERVER_ERROR,"error",l)}Uu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];Uu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await MT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return n||(n=[new q5(r,[],_.system_info)]),await W5(n[0],i,_.system_info),o.length>0?c.message=$5:c.message=`Successfully updated '${r}'`,c}a(K5,"updateNode");async function W5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new G5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Pu.upsertNodeRecord(n),k5({type:"nats_update"})}a(W5,"updateNodeTable")});var tU=T((Lfe,eU)=>{"use strict";var ZM=require("joi"),{string:XM}=ZM.types(),Q5=rt(),jM=M(),z5=j(),J5=nt();eU.exports=X5;function X5(e){let t=XM.invalid(z5.get(jM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(J5.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=ZM.object({operation:XM.valid(jM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Q5.validateBySchema(e,r)}a(X5,"removeNodeValidator")});var af=T((Ufe,aU)=>{"use strict";var{handleHDBError:rU,hdb_errors:j5}=Z(),{HTTP_STATUS_CODES:nU}=j5,Z5=tU(),vu=Y(),sU=Is(),e8=J(),of=M(),iU=nt(),oU=yt(),t8=j(),{RemotePayloadObject:r8}=Du(),{NodeSubscription:n8}=Ta(),s8=xc(),i8=Ki(),{broadcast:o8}=tt(),a8=t8.get(of.CONFIG_PARAMS.CLUSTERING_NODENAME);aU.exports=c8;async function c8(e){vu.trace("removeNode called with:",e),sU.checkClusteringEnabled();let t=Z5(e);if(t)throw rU(t,t.message,nU.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await sU.getNodeRecord(r);if(e8.isEmptyOrZeroLength(n))throw rU(new Error,`Node '${r}' was not found.`,nU.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new r8(of.OPERATIONS_ENUM.REMOVE_NODE,a8,[]),i,o=!1;try{i=await oU.request(`${r}.${iU.REQUEST_SUFFIX}`,s),vu.trace("Remove node reply from remote node:",r,i)}catch(u){vu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];vu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new n8(l.schema,l.table,!1,!1);await oU.updateWorkStream(d,r)}let c=new s8(of.SYSTEM_SCHEMA_NAME,of.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await i8.deleteRecord(c),o8({type:"nats_update"}),i?.status===iU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(vu.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(c8,"removeNode")});var lU=T((vfe,uU)=>{"use strict";var cU=require("joi"),{string:u8,array:l8}=cU.types(),_8=rt(),d8=Kd();uU.exports=f8;function f8(e){let t=cU.object({operation:u8.valid("configure_cluster").required(),connections:l8.items(d8.validation_schema).required()});return _8.validateBySchema(e,t)}a(f8,"configureClusterValidator")});var PT=T((Hfe,hU)=>{"use strict";var E8=M(),cf=Y(),h8=J(),m8=af(),p8=sf(),_U=Is(),S8=lU(),{handleHDBError:dU,hdb_errors:T8}=Z(),{HTTP_STATUS_CODES:fU}=T8,g8="Configure cluster complete.",R8="Failed to configure the cluster. Check the logs for more details.",A8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";hU.exports=O8;async function O8(e){cf.trace("configure cluster called with:",e),_U.checkClusteringEnabled();let t=S8(e);if(t)throw dU(t,t.message,fU.BAD_REQUEST,void 0,void 0,!0);let r=await _U.getAllNodeRecords(),n=[];for(let f=0,E=r.length;f<E;f++)n.push(EU(m8,{operation:E8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let s=await Promise.allSettled(n);cf.trace("All results from configure_cluster remove node:",s);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(EU(p8,E,E.node_name))}let c=await Promise.allSettled(i);cf.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=s.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(cf.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let S=h?.value?.result;typeof S=="string"&&S.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(h8.isEmptyOrZeroLength(u))return{message:g8,connections:_};if(l)return{message:A8,failed_nodes:u,connections:_};throw dU(new Error,R8,fU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(O8,"configureCluster");async function EU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){throw{node_name:r,error:n}}}a(EU,"functionWrapper")});var pU=T((Ffe,mU)=>{"use strict";var uf=require("joi"),b8=rt(),{validateSchemaExists:N8,validateTableExists:y8,validateSchemaName:I8}=Yn(),w8=uf.object({operation:uf.string().valid("purge_stream"),schema:uf.string().custom(N8).custom(I8).required(),table:uf.string().custom(y8).required()});function C8(e){return b8.validateBySchema(e,w8)}a(C8,"purgeStreamValidator");mU.exports=C8});var vT=T((Gfe,SU)=>{"use strict";var{handleHDBError:D8,hdb_errors:L8}=Z(),{HTTP_STATUS_CODES:M8}=L8,U8=pU(),P8=yt(),v8=Is();SU.exports=B8;async function B8(e){if(e.purge_ingest!==!0){let s=U8(e);if(s)throw D8(s,s.message,M8.BAD_REQUEST,void 0,void 0,!0)}v8.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:n}=e;return await P8.purgeTableStream(t,r,n),n?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(B8,"purgeStream")});var xT=T((Vfe,bU)=>{"use strict";var HT=Is(),H8=yt(),RU=j(),lf=M(),fo=nt(),x8=J(),BT=Y(),{RemotePayloadObject:F8}=Du(),{ErrorCode:TU}=require("nats"),gU=RU.get(lf.CONFIG_PARAMS.CLUSTERING_ENABLED),AU=RU.get(lf.CONFIG_PARAMS.CLUSTERING_NODENAME);bU.exports={clusterStatus:q8,buildNodeStatus:OU};async function q8(){let e={node_name:AU,is_enabled:gU,connections:[]};if(!gU)return e;let t=await HT.getAllNodeRecords();if(x8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(OU(t[n],e.connections));return await Promise.allSettled(r),e}a(q8,"clusterStatus");async function OU(e,t){let r=e.name,n=new F8(lf.OPERATIONS_ENUM.CLUSTER_STATUS,AU,void 0,await HT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await H8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,BT.error(`Error getting node status from ${r} `,s))}catch(u){BT.warn(`Error getting node status from ${r}`,u),u.code===TU.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===TU.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new G8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==lf.PRE_4_0_0_VERSION&&await HT.upsertNodeRecord(u)}catch(u){BT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(OU,"buildNodeStatus");function G8(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(G8,"NodeStatusObject")});var qT=T((Yfe,NU)=>{"use strict";var{handleHDBError:k8,hdb_errors:V8}=Z(),{HTTP_STATUS_CODES:$8}=V8,Y8=yt(),K8=Is(),FT=J(),_f=require("joi"),W8=rt(),Q8=2e3,z8=_f.object({timeout:_f.number().min(1),connected_nodes:_f.boolean(),routes:_f.boolean()});NU.exports=J8;async function J8(e){K8.checkClusteringEnabled();let t=W8.validateBySchema(e,z8);if(t)throw k8(t,t.message,$8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||FT.autoCastBoolean(n),o=s===void 0||FT.autoCastBoolean(s),c={nodes:[]},u=await Y8.getServerList(r??Q8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(S=>{h.connected_nodes.includes(S.name.slice(0,-4))||h.connected_nodes.push(S.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(S=>({host:S.split(":")[0],port:FT.autoCast(S.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(J8,"clusterNetwork")});var CU=T((Wfe,wU)=>{"use strict";var GT=require("joi"),yU=rt(),{route_constraints:IU}=Pp();wU.exports={setRoutesValidator:X8,deleteRoutesValidator:j8};function X8(e){let t=GT.object({server:GT.valid("hub","leaf").required(),routes:IU.required()});return yU.validateBySchema(e,t)}a(X8,"setRoutesValidator");function j8(e){let t=GT.object({routes:IU.required()});return yU.validateBySchema(e,t)}a(j8,"deleteRoutesValidator")});var VT=T((zfe,UU)=>{"use strict";var Eo=xr(),kT=J(),df=M(),DU=CU(),{handleHDBError:LU,hdb_errors:Z8}=Z(),{HTTP_STATUS_CODES:MU}=Z8,e6="cluster routes successfully set",t6="cluster routes successfully deleted";UU.exports={setRoutes:r6,getRoutes:n6,deleteRoutes:s6};function r6(e){let t=DU.setRoutesValidator(e);if(t)throw LU(t,t.message,MU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=kT.autoCast(_.port);let l=n.some(f=>f.host===_.host&&f.port===_.port),d=s.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(df.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(df.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:e6,set:o,skipped:i}}a(r6,"setRoutes");function n6(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(n6,"getRoutes");function s6(e){let t=DU.deleteRoutesValidator(e);if(t)throw LU(t,t.message,MU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=n.length;E<h;E++){let S=n[E];if(d.host===S.host&&d.port===S.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,S=s.length;h<S;h++){let p=s[h];if(d.host===p.host&&d.port===p.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=kT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(df.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=kT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(df.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:t6,deleted:i,skipped:o}}a(s6,"deleteRoutes")});var vU=T((Xfe,PU)=>{"use strict";var Bu=require("alasql"),ho=require("recursive-iterator"),Bn=Y(),i6=J(),Hu=M(),$T=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,a6(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Hu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Hu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Hu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=o6(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!Hu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Bu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function o6(e){return e.filter(t=>t[Hu.PERMS_CRUD_ENUM.READ])}a(o6,"filterReadRestrictedAttrs");function a6(e,t,r,n,s){c6(e,t,r,n,s)}a(a6,"interpretAST");function xu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(xu,"addSchemaTableToMap");function c6(e,t,r,n,s){if(!e){Bn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Bu.yy.Insert?d6(e,t,r):e instanceof Bu.yy.Select?u6(e,t,r,n,s):e instanceof Bu.yy.Update?l6(e,t,r):e instanceof Bu.yy.Delete?_6(e,t,r):Bn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(c6,"getRecordAttributesAST");function u6(e,t,r,n,s){if(!e){Bn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(i6.isEmptyOrZeroLength(i)){Bn.error("No schema specified");return}e.from.forEach(c=>{xu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),xu(c.table,t,r,n,s)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Bn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Bn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Bn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Bn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(u6,"getSelectAttributes");function l6(e,t,r){if(!e){Bn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;xu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.table.tableid,s,i.columnid,t,r)}a(l6,"getUpdateAttributes");function _6(e,t,r){if(!e){Bn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;xu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.table.tableid,s,i.columnid,t,r)}a(_6,"getDeleteAttributes");function d6(e,t,r){if(!e){Bn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;xu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&YT(e.into.tableid,s,i.columnid,t,r)}a(d6,"getInsertAttributes");function YT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(YT,"pushAttribute");PU.exports=$T});var QT=T((Zfe,FU)=>{var ff=Ji(),BU=require("chalk"),Qr=Y(),HU=require("prompt"),{promisify:f6}=require("util"),KT=M(),E6=require("fs-extra"),h6=require("path"),m6=J(),p6=Zd(),xU=j();xU.initSync();var S6=require("moment"),T6=f6(HU.get),g6=h6.join(xU.getHdbBasePath(),KT.LICENSE_KEY_DIR_NAME,KT.LICENSE_FILE_NAME,KT.LICENSE_FILE_NAME);FU.exports={getFingerprint:A6,setLicense:R6,parseLicense:WT,register:O6,getRegistrationInfo:N6};async function R6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await WT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Qr.error(r),Qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(R6,"setLicense");async function A6(){let e={};try{e=await ff.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(A6,"getFingerprint");async function WT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=ff.validateLicense(e,t);if(Qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Qr.info("writing license to disk"),await E6.writeFile(g6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(WT,"parseLicense");async function O6(){let e=await b6();return WT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(O6,"register");async function b6(){let e=await ff.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:BU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:BU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{HU.start()}catch(n){Qr.error(n)}let r;try{r=await T6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(b6,"promptForRegistration");async function N6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await ff.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(m6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=p6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=S6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(N6,"getRegistrationInfo")});var GU=T((tEe,qU)=>{"use strict";var y6=nt(),zT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+y6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};qU.exports=zT});var $U=T((nEe,VU)=>{"use strict";var kU=nt(),JT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+kU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+kU.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};VU.exports=JT});var KU=T((iEe,YU)=>{"use strict";var XT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};YU.exports=XT});var QU=T((aEe,WU)=>{"use strict";var I6=nt(),jT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+I6.SERVER_SUFFIX.ADMIN,this.password=r}};WU.exports=jT});var tg=T((uEe,XU)=>{"use strict";var Ra=require("path"),mf=require("fs-extra"),w6=GU(),C6=$U(),D6=KU(),L6=QU(),ZT=cn(),Oa=J(),mr=xr(),hf=M(),Fu=nt(),{CONFIG_PARAMS:ft}=hf,qu=Y(),Gu=j(),zU=bs(),eg=yt(),Aa="clustering",M6=1e4,JU=5;XU.exports={generateNatsConfig:P6,removeNatsConfig:v6,getHubConfigPath:U6};function U6(){let e=Gu.get(ft.ROOTPATH);return Ra.join(e,Aa,Fu.NATS_CONFIG_FILES.HUB_SERVER)}a(U6,"getHubConfigPath");async function P6(e=!1,t=void 0){Gu.initSync();let r=Gu.get(ft.ROOTPATH),n=Ra.join(r,Aa,Fu.PID_FILES.HUB),s=Ra.join(r,Aa,Fu.PID_FILES.LEAF),i=mr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ra.join(r,Aa,Fu.NATS_CONFIG_FILES.HUB_SERVER),c=Ra.join(r,Aa,Fu.NATS_CONFIG_FILES.LEAF_SERVER),u=mr.getConfigFromFile(ft.CLUSTERING_TLS_CERTIFICATE),_=mr.getConfigFromFile(ft.CLUSTERING_TLS_PRIVATEKEY),l=mr.getConfigFromFile(ft.CLUSTERING_TLS_CERT_AUTH),d=mr.getConfigFromFile(ft.CLUSTERING_TLS_INSECURE),f=mr.getConfigFromFile(ft.CLUSTERING_TLS_VERIFY),E=mr.getConfigFromFile(ft.CLUSTERING_NODENAME),h=mr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await eg.checkNATSServerInstalled()||pf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let S=await ZT.listUsers(),p=mr.getConfigFromFile(ft.CLUSTERING_USER),g=await ZT.getClusterUser();(Oa.isEmpty(g)||g.active!==!0)&&pf(`Invalid cluster user '${p}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Ef(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Ef(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Ef(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),await Ef(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],b=[];for(let[Q,se]of S.entries())se.role.role===hf.ROLE_TYPES_ENUM.CLUSTER_USER&&se.active&&(A.push(new L6(se.username,zU.decrypt(se.hash))),b.push(new D6(se.username,zU.decrypt(se.hash))));let v=[],{hub_routes:G}=mr.getClusteringRoutes();if(!Oa.isEmptyOrZeroLength(G))for(let Q of G)v.push(`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@${Q.host}:${Q.port}`);let H=new w6(mr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,mr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NAME),mr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),v,A,b);l==null&&(delete H.tls.ca_file,delete H.leafnodes.tls.ca_file),t=Oa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===hf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await mf.writeJson(o,H),qu.trace(`Hub server config written to ${o}`));let P=`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,z=`tls://${g.uri_encoded_name}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,W=new C6(mr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[P],[z],A,b,u,_,l,d);l==null&&delete W.tls.ca_file,(t===void 0||t===hf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await mf.writeJson(c,W),qu.trace(`Leaf server config written to ${c}`))}a(P6,"generateNatsConfig");async function Ef(e){let t=Gu.get(e);return Oa.isEmpty(t)&&pf(`port undefined for '${e}'`),await Oa.isPortTaken(t)&&pf(`'${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(Ef,"isPortAvailable");function pf(e){let t=`Error generating clustering config: ${e}`;qu.error(t),console.error(t),process.exit(1)}a(pf,"generateNatsConfigError");async function v6(e){let{port:t,config_file:r}=eg.getServerConfig(e),{username:n,decrypt_hash:s}=await ZT.getClusterUser(),i=0,o=2e3;for(;i<JU;){try{let _=await eg.createConnection(t,n,s,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){qu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=JU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await Oa.async_set_timeout(o*(i*2))}let c="0".repeat(M6),u=Ra.join(Gu.get(ft.ROOTPATH),Aa,r);await mf.writeFile(u,c),await mf.remove(u),qu.notify(e,"started.")}a(v6,"removeNatsConfig")});var nP=T((_Ee,rP)=>{"use strict";var zr=j(),B6=Ji(),me=M(),ku=nt(),ws=require("path"),{PACKAGE_ROOT:Tf}=M(),jU=j(),Sf=J(),ba="/dev/null",H6=ws.join(Tf,"launchServiceScripts"),ZU=ws.join(Tf,"utility/scripts"),x6=ws.join(ZU,me.HDB_RESTART_SCRIPT),eP=ws.resolve(Tf,"dependencies",`${process.platform}-${process.arch}`,ku.NATS_BINARY_NAME);function tP(){let t=B6.licenseSearch().ram_allocation||me.RAM_ALLOCATION_ENUM.DEFAULT,r=me.MEM_SETTING_KEY+t,n={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Sf.noBootFile()&&(n[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Sf.getEnvCliRootPath()),{name:me.PROCESS_DESCRIPTORS.HDB,script:me.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:Tf}}a(tP,"generateMainServerConfig");var F6=9930;function q6(){zr.initSync(!0);let e=zr.get(me.CONFIG_PARAMS.ROOTPATH),t=ws.join(e,"clustering",ku.NATS_CONFIG_FILES.HUB_SERVER),r=ws.join(zr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),n=jU.get(me.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[zr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==F6?"-"+n:""),script:eP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(q6,"generateNatsHubServerConfig");var G6=9940;function k6(){zr.initSync(!0);let e=zr.get(me.CONFIG_PARAMS.ROOTPATH),t=ws.join(e,"clustering",ku.NATS_CONFIG_FILES.LEAF_SERVER),r=ws.join(zr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),n=jU.get(me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[zr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==G6?"-"+n:""),script:eP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(k6,"generateNatsLeafServerConfig");function V6(){zr.initSync();let e=ws.join(zr.get(me.CONFIG_PARAMS.LOGGING_ROOT),me.LOG_NAMES.HDB),t={name:me.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:me.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:H6,autorestart:!1};return zr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ba,t.error_file=ba),t}a(V6,"generateClusteringUpgradeV4ServiceConfig");function $6(){let e={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.RESTART_HDB};return Sf.noBootFile()&&(e[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Sf.getEnvCliRootPath()),{...{name:me.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:ZU},script:x6}}a($6,"generateRestart");function Y6(){return{apps:[tP()]}}a(Y6,"generateAllServiceConfigs");rP.exports={generateAllServiceConfigs:Y6,generateMainServerConfig:tP,generateRestart:$6,generateNatsHubServerConfig:q6,generateNatsLeafServerConfig:k6,generateClusteringUpgradeV4ServiceConfig:V6}});var pP=T((EEe,mP)=>{"use strict";var Le=M(),K6=J(),Cs=tg(),Vu=yt(),ts=nt(),hi=nP(),gf=j(),mi=Y(),W6=Is(),{startWorker:sP,onMessageFromWorkers:Q6}=tt(),z6=ga(),fEe=require("util"),J6=require("child_process"),X6=require("fs"),{execFile:j6}=J6,ye;mP.exports={enterPM2Mode:Z6,start:pi,stop:rg,reload:oP,restart:aP,list:ng,describe:uP,connect:Ds,kill:s9,startAllServices:i9,startService:sg,getUniqueServicesList:lP,restartAllServices:o9,isServiceRegistered:_P,reloadStopStart:dP,restartHdb:cP,deleteProcess:r9,startClusteringProcesses:EP,startClusteringThreads:hP,isHdbRestartRunning:n9,isClusteringRunning:c9,stopClustering:a9,reloadClustering:u9};var $u=!1;Q6(e=>{e.type==="restart"&&gf.initSync(!0)});function Z6(){$u=!0}a(Z6,"enterPM2Mode");function Ds(){return ye||(ye=require("pm2")),new Promise((e,t)=>{ye.connect((r,n)=>{mi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ds,"connect");var pr,e9=10,iP;function pi(e,t=!1){if($u)return t9(e);let r=j6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=pr.indexOf(r);o>-1&&pr.splice(o,1),!iP&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<e9&&(X6.existsSync(Cs.getHubConfigPath())?pi(e):(await Cs.generateNatsConfig(!0),pi(e),await new Promise(c=>setTimeout(c,3e3)),await Cs.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Cs.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=gf.get(Le.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&ts.LOG_LEVEL_HIERARCHY[o]>=ts.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===ts.LOG_LEVELS.ERR||l===ts.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=ts.LOG_LEVELS[f]}if(ts.LOG_LEVEL_HIERARCHY[o]>=ts.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===ts.LOG_LEVELS.ERR||l===ts.LOG_LEVELS.WRN?mi.OUTPUTS.STDERR:mi.OUTPUTS.STDOUT;mi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),pr=[],!pr&&!t){let i=a(()=>{iP=!0,pr&&(pr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}pr.push(r)}a(pi,"start");function t9(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.start(e,(n,s)=>{n&&(ye.disconnect(),r(n)),ye.disconnect(),t(s)})})}a(t9,"startWithPM2");function rg(e){if(!$u){for(let t of pr||[])t.name===e&&(pr.splice(pr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.stop(e,async(n,s)=>{n&&(ye.disconnect(),r(n)),ye.delete(e,(i,o)=>{i&&(ye.disconnect(),r(n)),ye.disconnect(),t(o)})})})}a(rg,"stop");function oP(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.reload(e,(n,s)=>{n&&(ye.disconnect(),r(n)),ye.disconnect(),t(s)})})}a(oP,"reload");function aP(e){if(!$u)for(let t of pr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.restart(e,(n,s)=>{ye.disconnect(),t(s)})})}a(aP,"restart");function r9(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.delete(e,(n,s)=>{n&&(ye.disconnect(),r(n)),ye.disconnect(),t(s)})})}a(r9,"deleteProcess");async function cP(){await pi(hi.generateRestart())}a(cP,"restartHdb");async function n9(){let e=await ng();for(let t in e)if(e[t].name===Le.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(n9,"isHdbRestartRunning");function ng(){return new Promise(async(e,t)=>{try{await Ds()}catch(r){t(r)}ye.list((r,n)=>{r&&(ye.disconnect(),t(r)),ye.disconnect(),e(n)})})}a(ng,"list");function uP(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}ye.describe(e,(n,s)=>{n&&(ye.disconnect(),r(n)),ye.disconnect(),t(s)})})}a(uP,"describe");function s9(){if(!$u){for(let e of pr||[])e.kill();pr=[];return}return new Promise(async(e,t)=>{try{await Ds()}catch(r){t(r)}ye.killDaemon((r,n)=>{r&&(ye.disconnect(),t(r)),ye.disconnect(),e(n)})})}a(s9,"kill");async function i9(){try{await EP(),await hP(),await pi(hi.generateAllServiceConfigs())}catch(e){throw ye?.disconnect(),e}}a(i9,"startAllServices");async function sg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Le.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=hi.generateMainServerConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=hi.generateNatsIngestServiceConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=hi.generateNatsReplyServiceConfig();break;case Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=hi.generateNatsHubServerConfig(),await pi(r,t),await Cs.removeNatsConfig(e);return;case Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=hi.generateNatsLeafServerConfig(),await pi(r,t),await Cs.removeNatsConfig(e);return;case Le.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=hi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await pi(r)}catch(r){throw ye?.disconnect(),r}}a(sg,"startService");async function lP(){try{let e=await ng(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw ye?.disconnect(),e}}a(lP,"getUniqueServicesList");async function o9(e=[]){try{let t=!1,r=await lP();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Le.PROCESS_DESCRIPTORS.HDB?t=!0:await aP(o))}t&&await dP(Le.PROCESS_DESCRIPTORS.HDB)}catch(t){throw ye?.disconnect(),t}}a(o9,"restartAllServices");async function _P(e){if(pr?.find(r=>r.name===e))return!0;let t=await z6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(_P,"isServiceRegistered");async function dP(e){let t=e===Le.PROCESS_DESCRIPTORS.HDB?gf.get(Le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):gf.get(Le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await uP(e),n=K6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await rg(e),await sg(e)):e===Le.PROCESS_DESCRIPTORS.HDB?await cP():await oP(e)}a(dP,"reloadStopStart");var fP;async function EP(e=!1){for(let t in Le.CLUSTERING_PROCESSES){let r=Le.CLUSTERING_PROCESSES[t];await sg(r,e)}}a(EP,"startClusteringProcesses");async function hP(){fP=sP(Le.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Le.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Vu.createWorkQueueStream(ts.WORK_QUEUE_CONSUMER_NAMES),await Vu.updateIngestStreamConsumer(),await Vu.updateLocalStreams();let e=await W6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Le.PRE_4_0_0_VERSION){mi.info("Starting clustering upgrade 4.0.0 process"),sP(Le.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(hP,"startClusteringThreads");async function a9(){for(let e in Le.CLUSTERING_PROCESSES)if(e!==Le.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Le.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await fP.terminate();else{let t=Le.CLUSTERING_PROCESSES[e];await rg(t)}}a(a9,"stopClustering");async function c9(){for(let e in Le.CLUSTERING_PROCESSES){let t=Le.CLUSTERING_PROCESSES[e];if(await _P(t)===!1)return!1}return!0}a(c9,"isClusteringRunning");async function u9(){await Cs.generateNatsConfig(!0),await Vu.reloadNATSHub(),await Vu.reloadNATSLeaf(),await Cs.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Cs.removeNatsConfig(Le.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(u9,"reloadClustering")});var bf=T((mEe,bP)=>{"use strict";var l9=require("minimist"),{isMainThread:ag,parentPort:gP}=require("worker_threads"),ot=M(),{PROCESS_DESCRIPTORS_VALIDATE:Yu}=ot,rs=Y(),cg=J(),Rf=tg(),Na=yt(),ig=nt(),RP=xr(),ns=pP(),SP=ga(),_9=ih(),{restartWorkers:Af,onMessageByType:d9}=tt(),{handleHDBError:f9,hdb_errors:E9}=Z(),{HTTP_STATUS_CODES:h9}=E9,Of=j();Of.initSync();var Ku=`Restarting HarperDB. This may take up to ${ot.RESTART_TIMEOUT_MS/1e3} seconds.`,m9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",TP="Clustering is not enabled so cannot be restarted",p9="Invalid service",ya,En;bP.exports={restart:AP,restartService:ug};ag&&d9(ot.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?ug({service:e.workerType}):AP({operation:"restart"})});async function AP(e){En=Object.keys(e).length===0,ya=await ns.isServiceRegistered(ot.HDB_PROC_DESCRIPTOR);let t=l9(process.argv);if(t.service){await ug(t);return}if(En&&!ya){console.error(m9);return}if(En&&console.log(Ku),ya){ns.enterPM2Mode(),rs.notify(Ku);let r=_9(Object.keys(ot.CONFIG_PARAM_MAP),!0);return cg.isEmptyOrZeroLength(Object.keys(r))||RP.updateConfigValue(void 0,void 0,r,!0,!0),T9(),Ku}return ag?(rs.notify(Ku),setTimeout(()=>{Af()},50)):gP.postMessage({type:ot.ITC_EVENT_TYPES.RESTART}),Ku}a(AP,"restart");async function ug(e){let{service:t}=e;if(ot.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw f9(new Error,p9,h9.BAD_REQUEST,void 0,void 0,!0);if(ya=await ns.isServiceRegistered(ot.HDB_PROC_DESCRIPTOR),!ag)return gP.postMessage({type:ot.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Yu.clustering:if(!Of.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=TP;break}En&&console.log("Restarting clustering"),rs.notify("Restarting clustering"),await OP();break;case Yu.clustering_config:case Yu["clustering config"]:if(!Of.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=TP;break}En&&console.log("Restarting clustering_config"),rs.notify("Restarting clustering_config"),await ns.reloadClustering();break;case"custom_functions":case"custom functions":case Yu.harperdb:case Yu.http_workers:if(En&&!ya){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}En&&console.log("Restarting http_workers"),rs.notify("Restarting http_workers"),En?await ns.restart(ot.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Af("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(rs.error(r),En&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(ug,"restartService");async function S9(){await Na.publishToStream(`${ig.SUBJECT_PREFIXES.TXN}.${ig.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,ig.WORK_QUEUE_CONSUMER_NAMES.stream_name,Na.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(S9,"postDummyNatsMsg");async function T9(){await OP(),await ns.restart(ot.HDB_PROC_DESCRIPTOR),await cg.async_set_timeout(2e3),Of.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await og(),En&&(await Na.closeConnection(),process.exit(0))}a(T9,"restartPM2Mode");async function OP(){if(!RP.getConfigFromFile(ot.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await SP.getHDBProcessInfo()).clustering.length===0)rs.trace("Clustering not running, restart will start clustering services"),await Rf.generateNatsConfig(!0),await ns.startClusteringProcesses(),await ns.startClusteringThreads(),await og(),En&&await Na.closeConnection();else{await S9(),await Rf.generateNatsConfig(!0),ya?(rs.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await ns.restart(ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await ns.restart(ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await SP.getHDBProcessInfo()).clustering.forEach(s=>{rs.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await cg.async_set_timeout(3e3),await og(),await Na.updateLocalStreams(),En&&await Na.closeConnection(),rs.trace("Restart clustering restarting ingest and reply service threads");let t=Af(ot.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Af(ot.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(OP,"restartClustering");async function og(){await Rf.removeNatsConfig(ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Rf.removeNatsConfig(ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(og,"removeNatsConfig")});var vP=T((TEe,PP)=>{"use strict";var SEe=require("lodash"),Sr=M(),{handleHDBError:NP,hdb_errors:g9}=Z(),{HDB_ERROR_MSGS:R9,HTTP_STATUS_CODES:A9}=g9,lg=Y();PP.exports={getRolePermissions:b9};var mo=Object.create(null),O9=a(e=>({key:e,perms:{}}),"perms_template_obj"),CP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),DP=a((e=!1,t=!1,r=!1,n=!1)=>({[Sr.PERMS_CRUD_ENUM.READ]:e,[Sr.PERMS_CRUD_ENUM.INSERT]:t,[Sr.PERMS_CRUD_ENUM.UPDATE]:r,[Sr.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),_g=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...DP(t,r,n,s)}),"table_perms_template"),yP=a((e,t=DP())=>({attribute_name:e,describe:UP(t),[Wu]:t[Wu],[dg]:t[dg],[fg]:t[fg]}),"attr_perms_template"),IP=a((e,t=!1)=>({attribute_name:e,describe:t,[Wu]:t}),"timestamp_attr_perms_template"),{READ:Wu,INSERT:dg,UPDATE:fg}=Sr.PERMS_CRUD_ENUM,LP=Object.values(Sr.PERMS_CRUD_ENUM),MP=[Wu,dg,fg];function b9(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[Sr.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(mo[t]&&mo[t].key===n)return mo[t].perms;let s=N9(e,r);return mo[t]?mo[t].key=n:mo[t]=O9(n),mo[t].perms=s,s}catch(r){if(!e[Sr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Sr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Sr.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw lg.error(n),lg.debug(r),NP(new Error,R9.OUTDATED_PERMS_TRANSLATION_ERROR,A9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
-
${r.stack}`;throw lg.error(n),NP(new Error)}}}a(b9,"getRolePermissions");function N9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Sr.SYSTEM_SCHEMA_NAME]=n[Sr.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=y9(t[i]);return}r[i]=CP(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=I9(c,u);r[i].describe||LP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=_g()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=_g()})}),r}a(N9,"translateRolePermissions");function y9(e){let t=CP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=_g(!0,!0,!0,!0,!0)}),t}a(y9,"createStructureUserPermissions");function I9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return Sr.TIME_STAMP_NAMES.includes(d)&&(f=IP(d,l[Wu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=yP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=UP(l),s.attribute_permissions.push(l),c||w9(l,u)}else if(_!==o){let l;Sr.TIME_STAMP_NAMES.includes(_)?l=IP(_):l=yP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=wP(s),s}else return e.describe=wP(e),e}a(I9,"getTableAttrPerms");function wP(e){return LP.filter(t=>e[t]).length>0}a(wP,"getSchemaTableDescribePerm");function UP(e){return MP.filter(t=>e[t]).length>0}a(UP,"getAttributeDescribePerm");function w9(e,t){MP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(w9,"checkForHashPerms")});var BP={};qe(BP,{Headers:()=>Si});var Si,Nf=Re(()=>{Si=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];n?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var Qu={};qe(Qu,{authentication:()=>$P,bypassAuth:()=>v9,login:()=>H9,logout:()=>x9,start:()=>B9});function v9(){VP=!0}async function $P(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?M9?L9:[]:D9?C9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Si([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return yf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),yf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(yf){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let S=s.indexOf(";",h),p=s.indexOf("=",h);u=s.slice(p+1,S===-1?s.length:S),_=await xP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,S)=>{let p=new wf.AuthAuditLog(E,h,kt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);p.auth_strategy=S,u&&(p.session_id=u),r.referer&&(p.referer=r.referer),r.origin&&(p.origin=r.origin),h===kt.AUTH_AUDIT_STATUS.SUCCESS?HP.notify(p):HP.error(p)},"authAuditLog"),d;if(n){if(d=po.get(n),!d){let[E,h]=n.split(" "),S,p;try{switch(E){case"Basic":[S,p]=atob(h).split(":"),d=S||p?await ut.getUser(S,p,e):null;break;case"Bearer":try{d=await(0,If.validateOperationToken)(h)}catch(g){if(g.message==="invalid token")try{return await(0,If.validateRefreshToken)(h),c({status:-1})}catch{throw g}}break}}catch(g){return P9&&(po.get(h)||(po.set(h,h),l(S,kt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ti({error:g.message},e)})}po.set(n,d),U9&&l(d.username,kt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await ut.getUser(_.user,null,e):(VP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,qP.getSuperUser)());yf&&(e.session.update=function(E){if(!u){u=(0,GP.v4)();let S=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",S):f?.headers?.set&&f.headers.set("Set-Cookie",S)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,xP.put(E)},e.login=async function(E,h){e.user=await ut.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&Js.loginPath?(f.status=302,f.headers.set("Location",Js.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new Si);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function B9({server:e,port:t}){e.request($P,{port:t||"all"}),FP||(FP=!0,setInterval(()=>{po=new Map},hn.get(kt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),kP.user.addListener(()=>{po=new Map}))}async function H9(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function x9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var qP,If,GP,hn,kt,wf,kP,HP,C9,D9,L9,M9,xP,yf,VP,U9,P9,po,FP,Cf=Re(()=>{qP=B(cn());Zt();pc();If=B(Cu());Oe();GP=require("uuid"),hn=B(j()),kt=B(M()),wf=B(Y()),kP=B(Jc());Nf();Ia();HP=(0,wf.loggerWithTag)("auth-event");hn.initSync();C9=hn.get(kt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),D9=hn.get(kt.CONFIG_PARAMS.HTTP_CORS),L9=hn.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),M9=hn.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),xP=_t({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),yf=hn.get(kt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,VP=hn.get(kt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,U9=hn.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,P9=hn.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,po=new Map;ut.onInvalidatedUser(()=>{po=new Map});a(v9,"bypassAuth");a($P,"authentication");a(B9,"start");a(H9,"login");a(x9,"logout")});var XP=T((wEe,JP)=>{"use strict";var Ie=require("joi"),YP=require("fs-extra"),KP=require("path"),Ms=rt(),WP=j(),QP=M(),zP=Y(),{hdb_errors:F9}=Z(),{HDB_ERROR_MSGS:jt}=F9,Ls=/^[a-zA-Z0-9-_]+$/;JP.exports={getDropCustomFunctionValidator:G9,setCustomFunctionValidator:k9,addComponentValidator:K9,dropCustomFunctionProjectValidator:W9,packageComponentValidator:Q9,deployComponentValidator:z9,setComponentFileValidator:V9,getComponentFileValidator:Y9,dropComponentFileValidator:$9};function Df(e,t,r){try{let n=WP.get(QP.CONFIG_PARAMS.COMPONENTSROOT),s=KP.join(n,t);return YP.existsSync(s)?e?t:r.message(jt.PROJECT_EXISTS):e?r.message(jt.NO_PROJECT):t}catch(n){return zP.error(n),r.message(jt.VALIDATION_ERR)}}a(Df,"checkProjectExists");function zu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(zu,"checkFilePath");function q9(e,t,r,n){try{let s=WP.get(QP.CONFIG_PARAMS.COMPONENTSROOT),i=KP.join(s,e,t,r+".js");return YP.existsSync(i)?r:n.message(jt.NO_FILE)}catch(s){return zP.error(s),n.message(jt.VALIDATION_ERR)}}a(q9,"checkFileExists");function G9(e){let t=Ie.object({project:Ie.string().pattern(Ls).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(Ls).custom(q9.bind(null,e.project,e.type)).custom(zu).required().messages({"string.pattern.base":jt.BAD_FILE_NAME})});return Ms.validateBySchema(e,t)}a(G9,"getDropCustomFunctionValidator");function k9(e){let t=Ie.object({project:Ie.string().pattern(Ls).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(zu).required(),function_content:Ie.string().required()});return Ms.validateBySchema(e,t)}a(k9,"setCustomFunctionValidator");function V9(e){let t=Ie.object({project:Ie.string().pattern(Ls).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ms.validateBySchema(e,t)}a(V9,"setComponentFileValidator");function $9(e){let t=Ie.object({project:Ie.string().pattern(Ls).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).optional()});return Ms.validateBySchema(e,t)}a($9,"dropComponentFileValidator");function Y9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(zu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ms.validateBySchema(e,t)}a(Y9,"getComponentFileValidator");function K9(e){let t=Ie.object({project:Ie.string().pattern(Ls).custom(Df.bind(null,!1)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME})});return Ms.validateBySchema(e,t)}a(K9,"addComponentValidator");function W9(e){let t=Ie.object({project:Ie.string().pattern(Ls).custom(Df.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME})});return Ms.validateBySchema(e,t)}a(W9,"dropCustomFunctionProjectValidator");function Q9(e){let t=Ie.object({project:Ie.string().pattern(Ls).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Ms.validateBySchema(e,t)}a(Q9,"packageComponentValidator");function z9(e){let t=Ie.object({project:Ie.string().pattern(Ls).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":jt.BAD_PACKAGE}),package:Ie.string().optional()});return Ms.validateBySchema(e,t)}a(z9,"deployComponentValidator")});var Pf=T((DEe,sv)=>{"use strict";var Lf=require("joi"),Mf=require("path"),jP=require("fs-extra"),{exec:J9}=require("child_process"),X9=require("util"),ZP=X9.promisify(J9),Ju=M(),{handleHDBError:wa,hdb_errors:j9}=Z(),{HTTP_STATUS_CODES:Ca}=j9,Xu=j(),Z9=rt(),Da=Y();Xu.initSync();var Eg=Xu.get(Ju.CONFIG_PARAMS.COMPONENTSROOT),ev="npm install --omit=dev --json",e7=`${ev} --dry-run`;sv.exports={installModules:s7,auditModules:i7,installAllRootModules:t7,uninstallRootModule:r7,linkHarperdb:n7};async function t7(e=!1){await Uf(),await ju(e?"npm install --ignore-scripts":"npm install",Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(t7,"installAllRootModules");async function r7(e){await ju(`npm uninstall ${e}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(r7,"uninstallRootModule");async function n7(){await Uf(),await ju(`npm link ${Ju.PACKAGE_ROOT}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(n7,"linkHarperdb");async function ju(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await ZP(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
12
|
-
`,""))}return n&&!n.includes("Debugger listening")&&
|
|
13
|
-
`,"")}a(ju,"runCommand");async function
|
|
10
|
+
`,"")}a(fL,"runCommand");async function pX(){try{await z3.access(CS)}catch{return!1}let e=await fL(`${CS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return J3.eq(t,hX)}a(pX,"checkNATSServerInstalled");async function US(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await uL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}$r.trace("create nats connection called");let i=await aX({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),$r.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&$r.error("Error with Nats client connection, connection closed",o),EL()}),i}a(US,"createConnection");function EL(){cn=void 0,io=void 0,oo=void 0,ao=void 0}a(EL,"clearClientCache");async function SX(){cn&&(await cn.drain(),cn=void 0,io=void 0,oo=void 0,ao=void 0)}a(SX,"closeConnection");var cn,ao;async function Pd(){return ao||(ao=US(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),cn=await ao),cn||ao}a(Pd,"getConnection");async function Ru(){if(io)return io;co(cn)&&await Pd();let{domain:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await cn.jetstreamManager({domain:e,timeout:6e4}),io}a(Ru,"getJetStreamManager");async function hL(){if(oo)return oo;co(cn)&&await Pd();let{domain:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=cn.jetstream({domain:e,timeout:6e4}),oo}a(hL,"getJetStream");async function or(){let e=cn||await Pd(),t=io||await Ru(),r=oo||await hL();return{connection:e,jsm:t,js:r}}a(or,"getNATSReferences");async function TX(e){let t=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await uL.getClusterUser(),s=await US(t,r,n),i=MS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=dL.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await DS.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(TX,"getServerList");async function PS(e,t){let{jsm:r}=await or(),n=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:lL.File,retention:_L.Limits,subjects:t,discard:cX.Old,max_msgs:s,max_bytes:i,max_age:n})}a(PS,"createLocalStream");async function mL(){let{jsm:e}=await or(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(mL,"listStreams");async function gX(e){let{jsm:t}=await or();await t.streams.delete(e)}a(gX,"deleteLocalStream");async function RX(e){let{connection:t}=await or(),r=[],n=MS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(dL.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(RX,"listRemoteStreams");async function AX(e,t=void 0,r=void 0){let{jsm:n,js:s}=await or(),i=oL(),o={durable_name:i,ack_policy:Md.Explicit};t&&(o.deliver_policy=Ud.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=LS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(ye.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(AX,"viewStream");async function*OX(e,t=void 0,r=void 0){let{jsm:n,js:s}=await or(),i=oL(),o={durable_name:i,ack_policy:Md.Explicit};t&&(o.deliver_policy=Ud.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=LS(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(ye.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(OX,"viewStreamIterator");async function bX(e,t,r,n){$r.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=pL(n,r);let{js:s}=await or(),i=await Ou(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:cL.encode(n);try{$r.trace(`publishToStream publishing to subject: ${o}`),fX(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return RL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){$r.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await PS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(bX,"publishToStream");function pL(e,t){t===void 0&&(t=lX());let r=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(ye.MSG_HEADERS.ORIGIN)&&r&&t.append(ye.MSG_HEADERS.ORIGIN,r),t}a(pL,"addNatsMsgHeader");function Au(e){e=e.toLowerCase();let t=gu.join(Ht.get(Pe.CONFIG_PARAMS.ROOTPATH),EX);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(IS)&&(IS={port:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.HUB,config_file:ye.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:gu.join(t,ye.PID_FILES.HUB),hdb_nats_path:t}),IS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(wS)&&(wS={port:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,config_file:ye.NATS_CONFIG_FILES.LEAF_SERVER,domain:Su.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,pid_file_path:gu.join(t,ye.PID_FILES.LEAF),hdb_nats_path:t}),wS;$r.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Au,"getServerConfig");async function NX(e){let{jsm:t}=await or(),r=await Ou();try{await t.streams.add({name:e.stream_name,storage:lL.File,retention:_L.Limits,max_age:iX,max_bytes:oX,subjects:[`${ye.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(n){if(n.code!=="400")throw n}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(n){if(n.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:Md.Explicit,durable_name:e.durable_name,deliver_policy:Ud.All,max_ack_pending:1e4});else throw n}}a(NX,"createWorkQueueStream");async function yX(){let{jsm:e}=await or();(await e.consumers.info(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&($r.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name),$r.info("Adding pull consumer to ingest stream"),await e.consumers.add(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:Md.Explicit,durable_name:ye.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:Ud.All,max_ack_pending:1e4}))}a(yX,"updateIngestStreamConsumer");async function SL(e,t,r){let{jsm:n}=await or(),s=await n.streams.info(t),i=TL(n.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=Ld.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(s.config.sources)||s.config.sources.length===0)s.config.sources=[];else for(let p=0,S=s.config.sources.length;p<S;p++)if(d=s.config.sources[p],f=p,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let p=`txn.${c}.${u}.${e}`;await n.streams.purge(t,{filter:p}),s.config.sources.splice(f,1),await n.streams.update(t,s.config)}let h={name:_,opt_start_time:o,filter_subject:`${ye.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),s.config.sources.push(h),await n.streams.update(t,s.config)}a(SL,"addSourceToWorkStream");function TL(e){return e.split(".")[1]}a(TL,"extractServerName");async function gL(e,t,r){let{jsm:n}=await or(),{schema:s,table:i}=r,o=`txn.${s}.${i}.${e}`;await n.streams.purge(t,{filter:o});let c=Ld.createNatsTableStreamName(s,i),u=await n.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await n.streams.update(t,u.config)}a(gL,"removeSourceFromWorkStream");async function wX(e,t,r=6e4,n=MS()){if(!DS.isObject(t))throw new Error("data param must be an object");let s=cL.encode(t),{connection:i}=await or(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return LS(c.data)}a(wX,"request");function vS(e){return new Promise(async(t,r)=>{let n=eX(CS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(vS,"reloadNATS");async function IX(){let{pid_file_path:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await vS(e)}a(IX,"reloadNATSHub");async function CX(){let{pid_file_path:e}=Au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await vS(e)}a(CX,"reloadNATSLeaf");function DX(e,t,r){let n;switch(e.code){case iL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case iL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(DX,"requestErrorHandler");async function LX(e,t){let r=t+ye.SERVER_SUFFIX.LEAF;await RL(async()=>{e.subscribe===!0?await SL(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await gL(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(LX,"updateWorkStream");function RL(e){return tX.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(RL,"exclusiveLock");async function AL(e,t){let r=Ld.createNatsTableStreamName(e,t),n=await Ou(),s=vX(e,t,n);await PS(r,[s])}a(AL,"createLocalTableStream");async function MX(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await AL(n,s)}}a(MX,"createTableStreams");async function OL(e,t,r=!1){if(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Ld.createNatsTableStreamName(e,t),{jsm:s}=await or();r?await s.streams.purge(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name):await s.streams.purge(n)}catch(n){if(n.message==="stream not found")$r.warn(n);else throw n}}a(OL,"purgeTableStream");async function UX(e,t){if(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await OL(e,t[r])}a(UX,"purgeSchemaTableStreams");async function PX(e){return(await Ru()).streams.info(e)}a(PX,"getStreamInfo");function vX(e,t,r){return`${ye.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(vX,"createSubjectName");async function Ou(){if(Tu)return Tu;if(Tu=(await Ru())?.nc?.info?.server_name,Tu===void 0)throw new Error("Unable to get jetstream manager server name");return Tu}a(Ou,"getJsmServerName");async function BX(){let e=await Ru(),t=await Ou(),r=await mL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=HX(n),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(s.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;$r.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else if(s.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;$r.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");$r.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l}await e.streams.update(s.name,s)}}}a(BX,"updateLocalStreams");function HX(e){let{config:t}=e,r=!1;if(t.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let n=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(HX,"updateStreamLimits")});var xd=T((Sde,IL)=>{"use strict";var _a=N_(),da=sL(),xX=W(),FX=require("uuid").v4,pde=require("clone"),Bd=Ts(),fa=U(),qX=require("util"),ai=In(),{handleHDBError:ar,hdb_errors:GX}=ee(),{HDB_ERROR_MSGS:vd,HTTP_STATUS_CODES:cr}=GX,{SchemaEventMsg:Hd}=bn(),NL=Ot(),{getDatabases:kX}=(Ne(),te(qe)),{transformReq:Ea}=J();IL.exports={createSchema:VX,createSchemaStructure:yL,createTable:$X,createTableStructure:wL,createAttribute:zX,dropSchema:YX,dropTable:KX,dropAttribute:WX,getBackup:JX};async function VX(e){let t=await yL(e);return Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema)),t}a(VX,"createSchema");async function yL(e){let t=_a.schema_object(e);if(t)throw ar(t,t.message,cr.BAD_REQUEST,void 0,void 0,!0);if(Ea(e),!await da.checkSchemaExists(e.schema))throw ar(new Error,vd.SCHEMA_EXISTS_ERR(e.schema),cr.BAD_REQUEST,fa.LOG_LEVELS.ERROR,vd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ai.createSchema(e),`database '${e.schema}' successfully created`}a(yL,"createSchemaStructure");async function $X(e){return Ea(e),e.hash_attribute=e.primary_key??e.hash_attribute,await wL(e)}a($X,"createTable");async function wL(e){let t=_a.create_table_object(e);if(t)throw ar(t,t.message,cr.BAD_REQUEST,void 0,void 0,!0);if(_a.validateTableResidence(e.residence),!await da.checkSchemaTableExists(e.schema,e.table))throw ar(new Error,vd.TABLE_EXISTS_ERR(e.schema,e.table),cr.BAD_REQUEST,fa.LOG_LEVELS.ERROR,vd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:FX(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ai.createTable(n,e);else throw ar(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",cr.BAD_REQUEST);else await ai.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(wL,"createTableStructure");async function YX(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=_a.schema_object(e),n=t??r;if(n)throw ar(n,n.message,cr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let s=await da.checkSchemaExists(e.schema);if(s)throw ar(new Error,s,cr.NOT_FOUND,fa.LOG_LEVELS.ERROR,s,!0);let i=await da.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ai.dropSchema(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema)),await NL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(YX,"dropSchema");async function KX(e){let t=_a.table_object(e);if(t)throw ar(t,t.message,cr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let r=await da.checkSchemaTableExists(e.schema,e.table);if(r)throw ar(new Error,r,cr.NOT_FOUND,fa.LOG_LEVELS.ERROR,r,!0);return await ai.dropTable(e),await NL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(KX,"dropTable");async function WX(e){let t=_a.attribute_object(e);if(t)throw ar(t,t.message,cr.BAD_REQUEST,void 0,void 0,!0);Ea(e);let r=await da.checkSchemaTableExists(e.schema,e.table);if(r)throw ar(new Error,r,cr.NOT_FOUND,fa.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw ar(new Error,"You cannot drop a hash attribute",cr.BAD_REQUEST,void 0,void 0,!0);if(fa.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw ar(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,cr.BAD_REQUEST,void 0,void 0,!0);try{return await ai.dropAttribute(e),QX(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw xX.error(`Got an error deleting attribute ${qX.inspect(e)}.`),n}}a(WX,"dropAttribute");function QX(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(QX,"dropAttributeFromGlobal");async function zX(e){Ea(e);let t=kX()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw ar(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,cr.BAD_REQUEST,void 0,void 0,!0);return await ai.createAttribute(e),Bd.signalSchemaChange(new Hd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(zX,"createAttribute");function JX(e){return ai.getBackup(e)}a(JX,"getBackup")});var DL=T((gde,CL)=>{"use strict";var{OPERATIONS_ENUM:XX}=U(),BS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=XX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};CL.exports=BS});var HS=T((Ode,vL)=>{"use strict";var jX=In(),Ade=DL(),Fd=J(),qd=U(),ZX=Z(),{handleHDBError:LL,hdb_errors:ej}=ee(),{HDB_ERROR_MSGS:ML,HTTP_STATUS_CODES:UL}=ej,tj=Object.values(qd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),PL="To use this operation audit log must be enabled in harperdb-config.yaml";vL.exports=rj;async function rj(e){if(Fd.isEmpty(e.schema))throw new Error(ML.SCHEMA_REQUIRED_ERR);if(Fd.isEmpty(e.table))throw new Error(ML.TABLE_REQUIRED_ERR);if(!ZX.get(qd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw LL(new Error,PL,UL.BAD_REQUEST,qd.LOG_LEVELS.ERROR,PL,!0);let t=Fd.checkSchemaTableExist(e.schema,e.table);if(t)throw LL(new Error,t,UL.NOT_FOUND,qd.LOG_LEVELS.ERROR,t,!0);if(!Fd.isEmpty(e.search_type)&&tj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await jX.readAuditLog(e)}a(rj,"readAuditLog")});var HL=T((Nde,BL)=>{"use strict";var{OPERATIONS_ENUM:nj}=U(),xS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=nj.GET_BACKUP,this.schema=t,this.table=r}};BL.exports=xS});var qL=T((Cde,FL)=>{"use strict";var sj=In(),wde=HL(),FS=J(),ij=U(),Ide=Z(),{handleHDBError:oj,hdb_errors:aj}=ee(),{HDB_ERROR_MSGS:xL,HTTP_STATUS_CODES:cj}=aj;FL.exports=uj;async function uj(e){if(FS.isEmpty(e.schema))throw new Error(xL.SCHEMA_REQUIRED_ERR);if(FS.isEmpty(e.table))throw new Error(xL.TABLE_REQUIRED_ERR);let t=FS.checkSchemaTableExist(e.schema,e.table);if(t)throw oj(new Error,t,cj.NOT_FOUND,ij.LOG_LEVELS.ERROR,t,!0);return await sj.getBackup(read_audit_log_object)}a(uj,"getBackup")});var KL=T((Lde,YL)=>{var ci=require("validate.js"),kL=Ze(),ha=U(),{handleHDBError:lj,hdb_errors:_j}=ee(),{HDB_ERROR_MSGS:ct,HTTP_STATUS_CODES:dj}=_j,qS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),fj={STRUCTURE_USER:"structure_user"},GL=Object.values(ha.ROLE_TYPES_ENUM),Ej="attribute_permissions",hj="attribute_name",{PERMS_CRUD_ENUM:ma}=ha,mj=[Ej,...Object.values(ma)],VL=[ma.READ,ma.INSERT,ma.UPDATE],pj=[hj,...VL];function Sj(e){let t=qS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,$L(e,t)}a(Sj,"addRoleValidation");function Tj(e){let t=qS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,$L(e,t)}a(Tj,"alterRoleValidation");function gj(e){let t=qS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,kL.validateObject(e,t)}a(gj,"dropRoleValidation");var Rj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function $L(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Rj.includes(n[o])||s.push(n[o]);s.length>0&&ft(ct.INVALID_ROLE_JSON_KEYS(s),r);let i=kL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{ft(o,r)}),e.permission){let o=Aj(e);o&&ft(o,r),GL.forEach(c=>{e.permission[c]&&!ci.isBoolean(e.permission[c])&&ft(ct.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(GL.indexOf(o)<0){if(o===fj.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||ft(ct.SCHEMA_NOT_FOUND(d),r)}continue}ft(ct.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){ft(ct.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){ft(ct.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{mj.includes(l)||ft(ct.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ma).forEach(l=>{ci.isDefined(_[l])?ci.isBoolean(_[l])||ft(ct.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):ft(ct.TABLE_PERM_MISSING(l),r,o,u)}),ci.isDefined(_.attribute_permissions)){if(!ci.isArray(_.attribute_permissions)){ft(ct.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{ft(ct.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(p=>{!pj.includes(p)&&p!==ma.DELETE&&ft(ct.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!ci.isDefined(E.attribute_name)){ft(ct.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){ft(ct.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}VL.forEach(p=>{ci.isDefined(E[p])?ci.isBoolean(E[p])||ft(ct.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):ft(ct.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;ft(ct.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return Oj(r)}a($L,"customValidate");YL.exports={addRoleValidation:Sj,alterRoleValidation:Tj,dropRoleValidation:gj};function Aj(e){let{operation:t,permission:r}=e;if(t===ha.OPERATIONS_ENUM.ADD_ROLE||t===ha.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return ct.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ha.ROLE_TYPES_ENUM.SUPER_USER:ha.ROLE_TYPES_ENUM.CLUSTER_USER;return ct.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Aj,"validateNoSUPerms");function Oj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:ct.ROLE_PERMS_ERROR,...e};return lj(new Error,n,dj.BAD_REQUEST)}else return null}a(Oj,"generateRolePermResponse");function ft(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(ft,"addPermError")});var KS=T((Ude,JL)=>{"use strict";var WL=rn(),QL=tn(),bj=Ki(),kS=KL(),VS=Ts(),Nj=require("uuid").v4,yj=require("util"),Gd=U(),wj=J(),$S=QL.searchByValue,Ij=QL.searchByHash,Cj=yj.promisify(bj.delete),Dj=Kn(),Lj=Xo(),{hdb_errors:Mj,handleHDBError:uo}=ee(),{HDB_ERROR_MSGS:zL,HTTP_STATUS_CODES:bu}=Mj,{UserEventMsg:YS}=bn();JL.exports={addRole:Uj,alterRole:Pj,dropRole:vj,listRoles:Bj};function GS(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(GS,"scrubRoleDetails");async function Uj(e){let t=kS.addRoleValidation(e);if(t)throw t;e=GS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await $S(r)||[])}catch(i){throw uo(i)}if(n&&n.length>0)throw uo(new Error,zL.ROLE_ALREADY_EXISTS(e.role),bu.CONFLICT,void 0,void 0,!0);e.id||(e.id=Nj());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await WL.insert(s),VS.signalUserChange(new YS(process.pid)),e=GS(e),e}a(Uj,"addRole");async function Pj(e){let t=kS.alterRoleValidation(e);if(t)throw t;e=GS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await WL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",bu.BAD_REQUEST,void 0,void 0,!0);return await VS.signalUserChange(new YS(process.pid)),e}a(Pj,"alterRole");async function vj(e){let t=kS.dropRoleValidation(e);if(t)throw uo(new Error,t,bu.BAD_REQUEST,void 0,void 0,!0);let r=new Lj(Gd.SYSTEM_SCHEMA_NAME,Gd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Ij(r));if(n.length===0)throw uo(new Error,zL.ROLE_NOT_FOUND,bu.NOT_FOUND,void 0,void 0,!0);let s=new Dj(Gd.SYSTEM_SCHEMA_NAME,Gd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await $S(s)),o=!1;if(wj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,bu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Cj(c),VS.signalUserChange(new YS(process.pid)),`${n[0].role} successfully deleted`}a(vj,"dropRole");async function Bj(){return $S({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Bj,"listRoles")});var eM=T((vde,ZL)=>{"use strict";var Hj=Z(),ui=require("joi"),xj=Ze(),XL=require("moment"),Fj=require("fs-extra"),WS=require("path"),qj=require("lodash"),Nu=U(),{LOG_LEVELS:lo}=U(),Gj="YYYY-MM-DD hh:mm:ss",kj=WS.resolve(__dirname,"../logs");ZL.exports=function(e){return xj.validateBySchema(e,Vj)};var Vj=ui.object({from:ui.custom(jL),until:ui.custom(jL),level:ui.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:ui.valid("asc","desc"),limit:ui.number().min(1),start:ui.number().min(0),log_name:ui.custom($j)});function jL(e,t){if(XL(e,XL.ISO_8601).format(Gj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(jL,"validateDatetime");function $j(e,t){if(qj.invert(Nu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=Hj.get(Nu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Nu.LOG_NAMES.HDB:e,i=s===Nu.LOG_NAMES.INSTALL?WS.join(kj,Nu.LOG_NAMES.INSTALL):WS.join(n,s);return Fj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a($j,"validateReadLogPath")});var zS=T((Hde,rM)=>{"use strict";var kd=U(),Yj=W(),Kj=Z(),Wj=eM(),QS=require("path"),tM=require("fs-extra"),{once:Qj}=require("events"),{handleHDBError:zj,hdb_errors:Jj}=ee(),{PACKAGE_ROOT:Xj}=U(),jj=QS.join(Xj,"logs"),Zj=1e3,eZ=200;rM.exports=tZ;async function tZ(e){let t=Wj(e);if(t)throw zj(t,t.message,Jj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Kj.get(kd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?kd.LOG_NAMES.HDB:e.log_name,s=n===kd.LOG_NAMES.INSTALL?QS.join(jj,kd.LOG_NAMES.INSTALL):QS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?Zj:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(tM.statSync(s).size-(h+5)*eZ,0));let S=tM.createReadStream(s,{start:p});S.on("error",v=>{Yj.error(v)});let O=0,g=[],R="",B;S.on("data",v=>{let M=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=R+v;let $=0,K;for(;(K=M.exec(v))&&!S.destroyed;){B&&(B.message=v.slice($,K.index),H(B));let[z,se,Te]=K,oe=Te.split("] ["),xe=oe[0],de=oe[1];oe.splice(0,2),B={timestamp:se,thread:xe,level:de,tags:oe,message:""},$=K.index+z.length}R=v.slice($)}),S.on("end",v=>{S.destroyed||B&&(B.message=R.trim(),H(B))}),S.resume();function H(v){let M,$,K;switch(!0){case(i&&c&&_):M=new Date(v.timestamp),$=new Date(u),K=new Date(l),v.level===o&&M>=$&&M<=K&&O<E?O++:v.level===o&&M>=$&&M<=K&&(li(v,f,g),O++,O===h&&S.destroy());break;case(i&&c):M=new Date(v.timestamp),$=new Date(u),v.level===o&&M>=$&&O<E?O++:v.level===o&&M>=$&&(li(v,f,g),O++,O===h&&S.destroy());break;case(i&&_):M=new Date(v.timestamp),K=new Date(l),v.level===o&&M<=K&&O<E?O++:v.level===o&&M<=K&&(li(v,f,g),O++,O===h&&S.destroy());break;case(c&&_):M=new Date(v.timestamp),$=new Date(u),K=new Date(l),M>=$&&M<=K&&O<E?O++:M>=$&&M<=K&&(li(v,f,g),O++,O===h&&S.destroy());break;case i:v.level===o&&O<E?O++:v.level===o&&(li(v,f,g),O++,O===h&&S.destroy());break;case c:M=new Date(v.timestamp),$=new Date(u),M>=$&&O<E?O++:M>=$&&O>=E&&(li(v,f,g),O++,O===h&&S.destroy());break;case _:M=new Date(v.timestamp),K=new Date(l),M<=K&&O<E?O++:M<=K&&O>=E&&(li(v,f,g),O++,O===h&&S.destroy());break;default:O<E?O++:(li(v,f,g),O++,O===h&&S.destroy())}}return a(H,"onLogMessage"),await Qj(S,"close"),g}a(tZ,"readLog");function li(e,t,r){t==="desc"?rZ(e,r):t==="asc"?nZ(e,r):r.push(e)}a(li,"pushLineToResult");function rZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(rZ,"insertDescending");function nZ(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(nZ,"insertAscending")});var Vd=T((kde,oM)=>{"use strict";var JS=require("joi"),{string:yu,boolean:nM,date:sZ}=JS.types(),iZ=Ze(),{validateSchemaExists:Fde,validateTableExists:qde,validateSchemaName:Gde}=$n(),oZ=U(),aZ=et(),sM=Z();sM.initSync();var cZ=yu.invalid(sM.get(oZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(aZ.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(),iM={operation:yu.valid("add_node","update_node","set_node_replication"),node_name:cZ,subscriptions:JS.array().items({table:yu.optional(),schema:yu.optional(),database:yu.optional(),subscribe:nM.required(),publish:nM.required().custom(lZ),start_time:sZ.iso()}).min(1).required()};function uZ(e){return iZ.validateBySchema(e,JS.object(iM))}a(uZ,"addUpdateNodeValidator");function lZ(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(lZ,"checkForFalsy");oM.exports={addUpdateNodeValidator:uZ,validation_schema:iM}});var cM=T(($de,aM)=>{var _Z=Ze(),dZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};aM.exports=function(e){return _Z.validateObject(e,dZ)}});var jS=T((Yde,uM)=>{"use strict";var fZ=U().OPERATIONS_ENUM,XS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=fZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};uM.exports=XS});var _M=T((Wde,lM)=>{"use strict";var EZ={OPERATION:"operation",REFRESH:"refresh"},ZS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},eT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};lM.exports={JWTTokens:ZS,TOKEN_TYPE_ENUM:EZ,JWTRSAKeys:eT}});var Cu=T((zde,hM)=>{"use strict";var Iu=require("jsonwebtoken"),tT=require("fs-extra"),rT=J(),un=U(),{handleHDBError:ur,hdb_errors:hZ}=ee(),{HTTP_STATUS_CODES:lr,AUTHENTICATION_ERROR_MSGS:_r}=hZ,wu=W(),dM=j_(),iT=nn(),mZ=rn().update,pZ=jS(),SZ=Ts(),{UserEventMsg:TZ}=bn(),_i=Z();_i.initSync();var nT=require("path"),{JWTTokens:gZ,JWTRSAKeys:RZ,TOKEN_TYPE_ENUM:$d}=_M(),AZ=_i.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?_i.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",OZ=_i.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?_i.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Yd="RS256",sT;hM.exports={createTokens:bZ,validateOperationToken:yZ,refreshOperationToken:NZ,validateRefreshToken:EM};async function bZ(e){if(rT.isEmpty(e)||typeof e!="object")throw ur(new Error,_r.INVALID_AUTH_OBJECT,lr.BAD_REQUEST,void 0,void 0,!0);if(rT.isEmpty(e.username))throw ur(new Error,_r.USERNAME_REQUIRED,lr.BAD_REQUEST,void 0,void 0,!0);if(rT.isEmpty(e.password))throw ur(new Error,_r.PASSWORD_REQUIRED,lr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await iT.findAndValidateUser(e.username,e.password),!t)throw ur(new Error,_r.INVALID_CREDENTIALS,lr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw wu.error(f),ur(new Error,_r.INVALID_CREDENTIALS,lr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Kd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await fM(i,r.private_key,r.passphrase),c=await Iu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:OZ,algorithm:Yd,subject:$d.REFRESH}),u=dM.hash(c),_=new pZ(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await mZ(_)}catch(f){wu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw ur(new Error,_r.REFRESH_TOKEN_SAVE_FAILED,lr.INTERNAL_SERVER_ERROR);return SZ.signalUserChange(new TZ(process.pid)),new gZ(o,c)}a(bZ,"createTokens");async function fM(e,t,r){return await Iu.sign(e,{key:t,passphrase:r},{expiresIn:AZ,algorithm:Yd,subject:$d.OPERATION})}a(fM,"signOperationToken");async function Kd(){if(sT===void 0)try{let e=nT.join(_i.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PASSPHRASE_NAME),t=nT.join(_i.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=nT.join(_i.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await tT.readFile(e)).toString(),s=(await tT.readFile(t)).toString(),i=(await tT.readFile(r)).toString();sT=new RZ(i,s,n)}catch(e){throw wu.error(e),ur(new Error,_r.NO_ENCRYPTION_KEYS,lr.INTERNAL_SERVER_ERROR)}return sT}a(Kd,"getJWTRSAKeys");async function NZ(e){if(!e)throw ur(new Error,_r.INVALID_BODY,lr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw ur(new Error,_r.REFRESH_TOKEN_REQUIRED,lr.BAD_REQUEST,void 0,void 0,!0);await EM(e.refresh_token);let t=await Kd(),r=await Iu.decode(e.refresh_token);return{operation_token:await fM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(NZ,"refreshOperationToken");async function yZ(e){try{let t=await Kd(),r=await Iu.verify(e,t.public_key,{algorithms:Yd,subject:$d.OPERATION});return await iT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw wu.warn(t),t.name&&t.name==="TokenExpiredError"?ur(new Error,_r.TOKEN_EXPIRED,lr.FORBIDDEN):ur(new Error,_r.INVALID_TOKEN,lr.UNAUTHORIZED)}}a(yZ,"validateOperationToken");async function EM(e){let t;try{let r=await Kd(),n=await Iu.verify(e,r.public_key,{algorithms:Yd,subject:$d.REFRESH});t=await iT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw wu.warn(r),r.name&&r.name==="TokenExpiredError"?ur(new Error,_r.TOKEN_EXPIRED,lr.FORBIDDEN):ur(new Error,_r.INVALID_TOKEN,lr.UNAUTHORIZED)}if(!dM.validate(t.refresh_token,e))throw ur(new Error,_r.INVALID_TOKEN,lr.UNAUTHORIZED);return t}a(EM,"validateRefreshToken")});var oT=T((jde,SM)=>{"use strict";var wZ=cM(),pa=require("passport"),IZ=require("passport-local").Strategy,CZ=require("passport-http").BasicStrategy,DZ=require("util"),LZ=nn(),pM=DZ.callbackify(LZ.findAndValidateUser),Xde=br(),MZ=U(),mM=Cu();pa.use(new IZ(function(e,t,r){pM(e,t,r)}));pa.use(new CZ(function(e,t,r){pM(e,t,r)}));pa.serializeUser(function(e,t){t(null,e)});pa.deserializeUser(function(e,t){t(null,e)});function UZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":pa.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===MZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?mM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):mM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:pa.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(UZ,"authorize");function PZ(e,t){let r=wZ(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(PZ,"checkPermissions");SM.exports={authorize:UZ,checkPermissions:PZ}});var Sa=T((efe,TM)=>{"use strict";var aT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},cT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};TM.exports={Node:aT,NodeSubscription:cT}});var RM=T((rfe,gM)=>{"use strict";var vZ=U().OPERATIONS_ENUM,uT=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=vZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};gM.exports=uT});var Du=T((sfe,AM)=>{"use strict";var lT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},_T=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};AM.exports={RemotePayloadObject:lT,RemotePayloadSubscription:_T}});var bM=T((ofe,OM)=>{"use strict";var dT=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};OM.exports=dT});var wM=T((_fe,yM)=>{"use strict";var BZ=bM(),cfe=lt(),NM=Ve(),HZ=W(),{getSchemaPath:ufe,getTransactionAuditStorePath:lfe}=Ye(),{getDatabases:xZ}=(Ne(),te(qe));yM.exports=FZ;async function FZ(e){let t=new BZ;try{let r=xZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await NM.environmentDataSize(schema_path,e.name),o=await NM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){HZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(FZ,"lmdbGetTableSize")});var CM=T((ffe,IM)=>{"use strict";var fT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};IM.exports=fT});var Ta=T((pfe,UM)=>{"use strict";var qZ=require("fs-extra"),GZ=require("path"),Wt=require("systeminformation"),di=W(),kZ=Ot(),ET=et(),Qd=U(),VZ=wM(),MM=Gi(),{getThreadInfo:DM}=je(),bT=Z();bT.initSync();var $Z=CM(),{openEnvironment:hfe}=Ve(),{getSchemaPath:mfe}=Ye(),{database:YZ}=(Ne(),te(qe)),Wd;UM.exports={getHDBProcessInfo:ST,getNetworkInfo:gT,getDiskInfo:TT,getMemoryInfo:pT,getCPUInfo:mT,getTimeInfo:hT,getSystemInformation:RT,systemInformation:KZ,getTableSize:AT,getMetrics:OT};function hT(){return Wt.time()}a(hT,"getTimeInfo");async function mT(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Wt.cpu();l.cpu_speed=await Wt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:O,...g}=await Wt.currentLoad();return g.cpus=[],O.forEach(R=>{let{raw_load:B,raw_load_idle:H,raw_load_irq:v,raw_load_nice:M,raw_load_system:$,raw_load_user:K,...z}=R;g.cpus.push(z)}),l.current_load=g,l}catch(e){return di.error(`error in getCPUInfo: ${e}`),{}}}a(mT,"getCPUInfo");async function pT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Wt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return di.error(`error in getMemoryInfo: ${e}`),{}}}a(pT,"getMemoryInfo");async function ST(){let e={core:[],clustering:[]};try{let t=await Wt.processes(),r;try{r=Number.parseInt(await qZ.readFile(GZ.join(bT.get(Qd.CONFIG_PARAMS.ROOTPATH),Qd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Qd.NODE_ERROR_CODES.ENOENT)di.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return di.error(`error in getHDBProcessInfo: ${t}`),e}}a(ST,"getHDBProcessInfo");async function TT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Wt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Wt.fsStats();return e.read_write=_,e.size=await Wt.fsSize(),e}catch(t){return di.error(`error in getDiskInfo: ${t}`),e}}a(TT,"getDiskInfo");async function gT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Wt.networkInterfaceDefault(),e.latency=await Wt.inetChecksite("google.com"),(await Wt.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=n;e.interfaces.push(f)}),(await Wt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return di.error(`error in getNetworkInfo: ${t}`),e}}a(gT,"getNetworkInfo");async function RT(){if(Wd!==void 0)return Wd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Wt.osInfo();e=c;let u=await Wt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Wd=e,Wd}catch(t){return di.error(`error in getSystemInformation: ${t}`),e}}a(RT,"getSystemInformation");async function AT(){let e=[],t=await MM.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await VZ(n));return e}a(AT,"getTableSize");async function OT(){let e=await MM.describeAll(),t={};for(let r in e){let n=t[r]={};for(let s in e[r])try{let i=YZ({database:r,table:s}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),n[s]=o}catch(i){di.notify(`Error getting stats for table ${s}: ${i}`)}}return t}a(OT,"getMetrics");async function LM(){if(bT.get(Qd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await kZ.getNATSReferences(),r=await t.streams.info(ET.WORK_QUEUE_CONSUMER_NAMES.stream_name),n=await e.consumers.get(ET.WORK_QUEUE_CONSUMER_NAMES.stream_name,ET.WORK_QUEUE_CONSUMER_NAMES.durable_name),s={ingest:{stream:{...r.state},consumer:{num_ack_pending:n._info.num_ack_pending,num_redelivered:n._info.num_redelivered,num_waiting:n._info.num_waiting,num_pending:n._info.num_pending}}};return r.sources&&(s.ingest.stream.sources=r.sources),s}}a(LM,"getNatsStreamInfo");async function KZ(e){let t=new $Z;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await RT(),t.time=hT(),t.cpu=await mT(),t.memory=await pT(),t.disk=await TT(),t.network=await gT(),t.harperdb_processes=await ST(),t.table_size=await AT(),t.metrics=await OT(),t.threads=await DM(),t.replication=await LM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await RT();break;case"time":t.time=hT();break;case"cpu":t.cpu=await mT();break;case"memory":t.memory=await pT();break;case"disk":t.disk=await TT();break;case"network":t.network=await gT();break;case"harperdb_processes":t.harperdb_processes=await ST();break;case"table_size":t.table_size=await AT();break;case"database_metrics":case"metrics":t.metrics=await OT();break;case"threads":t.threads=await DM();break;case"replication":t.replication=await LM();break;default:break}return t}a(KZ,"systemInformation")});var Jd=T((Tfe,PM)=>{"use strict";PM.exports={version:WZ,printVersion:QZ};var zd=pu();function WZ(){if(zd)return zd.version}a(WZ,"version");function QZ(){zd&&console.log(`HarperDB Version ${zd.version}`)}a(QZ,"printVersion")});var ys=T((Ofe,xM)=>{"use strict";var zZ=rn(),NT=J(),JZ=require("util"),_o=U(),vM=Z();vM.initSync();var XZ=oT(),BM=tn(),{Node:Rfe,NodeSubscription:Afe}=Sa(),jZ=Xo(),ZZ=RM(),{RemotePayloadObject:e5,RemotePayloadSubscription:t5}=Du(),{handleHDBError:r5,hdb_errors:n5}=ee(),{HTTP_STATUS_CODES:s5,HDB_ERROR_MSGS:i5}=n5,o5=Kn(),a5=Ta(),c5=Jd(),{getDatabases:u5}=(Ne(),te(qe)),l5=JZ.promisify(XZ.authorize),_5=BM.searchByHash,d5=BM.searchByValue;xM.exports={authHeaderToUser:f5,isEmpty:E5,getNodeRecord:h5,upsertNodeRecord:m5,buildNodePayloads:p5,checkClusteringEnabled:S5,getAllNodeRecords:T5,getSystemInfo:g5,reverseSubscription:HM};async function f5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await l5(t,null),e}a(f5,"authHeaderToUser");function E5(e){return e==null}a(E5,"isEmpty");async function h5(e){let t=new jZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return _5(t)}a(h5,"getNodeRecord");async function m5(e){let t=new ZZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return zZ.upsert(t)}a(m5,"upsertNodeRecord");function HM(e){if(NT.isEmpty(e.subscribe)||NT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(HM,"reverseSubscription");function p5(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=NT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=HM(c),E=u5()[u]?.[_],h=new t5(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new e5(r,t,s,n)}a(p5,"buildNodePayloads");function S5(){if(!vM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw r5(new Error,i5.CLUSTERING_NOT_ENABLED,s5.BAD_REQUEST,void 0,void 0,!0)}a(S5,"checkClusteringEnabled");async function T5(){let e=new o5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await d5(e))}a(T5,"getAllNodeRecords");async function g5(){let e=await a5.getSystemInformation();return{hdb_version:c5.version(),node_version:e.node_version,platform:e.platform}}a(g5,"getSystemInfo")});var yT=T((Nfe,KM)=>{"use strict";var Xd=Ot(),FM=J(),qM=et(),GM=U(),jd=W(),kM=xd(),R5=Ym(),{RemotePayloadObject:A5}=Du(),{handleHDBError:VM,hdb_errors:O5}=ee(),{HTTP_STATUS_CODES:$M}=O5,{NodeSubscription:YM}=Sa();KM.exports=b5;async function b5(e,t){let r;try{r=await Xd.request(`${t}.${qM.REQUEST_SUFFIX}`,new A5(GM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),jd.trace("Response from remote describe all request:",r)}catch(o){jd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Xd.requestErrorHandler(o,"add_node",t);throw VM(new Error,c,$M.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===qM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw VM(new Error,o,$M.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===GM.SYSTEM_SCHEMA_NAME){await Xd.createLocalTableStream(u,c);let h=new YM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=FM.doesSchemaExist(u),l=n[u]!==void 0,d=c?FM.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(jd.trace(`addNode creating schema: ${u}`),await kM.createSchema({operation:"create_schema",schema:u})),!d&&f){jd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new R5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await kM.createTable(h)}await Xd.createLocalTableStream(u,c);let E=new YM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(b5,"reviewSubscriptions")});var tf=T((wfe,zM)=>{"use strict";var{handleHDBError:Zd,hdb_errors:N5}=ee(),{HTTP_STATUS_CODES:ef}=N5,{addUpdateNodeValidator:y5}=Vd(),Lu=W(),QM=U(),WM=et(),w5=J(),wT=Ot(),Mu=ys(),I5=Z(),C5=yT(),{Node:D5,NodeSubscription:L5}=Sa(),{broadcast:M5}=je(),U5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",P5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",v5=I5.get(QM.CONFIG_PARAMS.CLUSTERING_NODENAME);zM.exports=B5;async function B5(e,t=!1){Lu.trace("addNode called with:",e),Mu.checkClusteringEnabled();let r=y5(e);if(r)throw Zd(r,r.message,ef.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Mu.getNodeRecord(n);if(!w5.isEmptyOrZeroLength(d))throw Zd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,ef.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await C5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=U5,o;let c=Mu.buildNodePayloads(s,v5,QM.OPERATIONS_ENUM.ADD_NODE,await Mu.getSystemInfo());Lu.trace("addNode sending remote payload:",c);let u;try{u=await wT.request(`${n}.${WM.REQUEST_SUFFIX}`,c)}catch(d){Lu.error(`addNode received error from request: ${d}`);let f=wT.requestErrorHandler(d,"add_node",n);throw Zd(new Error,f,ef.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===WM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${u.message}`;throw Zd(new Error,d,ef.INTERNAL_SERVER_ERROR,"error",d)}Lu.trace(u);let _=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];Lu.trace("Add node updating work stream for node:",n,"subscriptions:",E),await wT.updateWorkStream(E,n),s[d].start_time===void 0&&delete s[d].start_time,_.push(new L5(E.schema,E.table,E.publish,E.subscribe))}let l=new D5(n,_,u.system_info);return await Mu.upsertNodeRecord(l),M5({type:"nats_update"}),i.length>0?o.message=P5:o.message=`Successfully added '${n}' to manifest`,o}a(B5,"addNode")});var LT=T((Dfe,jM)=>{"use strict";var{handleHDBError:IT,hdb_errors:H5}=ee(),{HTTP_STATUS_CODES:CT}=H5,{addUpdateNodeValidator:x5}=Vd(),Uu=W(),XM=U(),JM=et(),Cfe=J(),DT=Ot(),Pu=ys(),F5=Z(),{cloneDeep:q5}=require("lodash"),G5=yT(),{Node:k5,NodeSubscription:V5}=Sa(),{broadcast:$5}=je(),Y5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",K5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",W5=F5.get(XM.CONFIG_PARAMS.CLUSTERING_NODENAME);jM.exports=Q5;async function Q5(e){Uu.trace("updateNode called with:",e),Pu.checkClusteringEnabled();let t=x5(e);if(t)throw IT(t,t.message,CT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Pu.getNodeRecord(r);s.length>0&&(n=q5(s));let{added:i,skipped:o}=await G5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=Y5,c;let u=Pu.buildNodePayloads(i,W5,XM.OPERATIONS_ENUM.UPDATE_NODE,await Pu.getSystemInfo());Uu.trace("updateNode sending remote payload:",u);let _;try{_=await DT.request(`${r}.${JM.REQUEST_SUFFIX}`,u)}catch(l){Uu.error(`updateNode received error from request: ${l}`);let d=DT.requestErrorHandler(l,"update_node",r);throw IT(new Error,d,CT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===JM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw IT(new Error,l,CT.INTERNAL_SERVER_ERROR,"error",l)}Uu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];Uu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await DT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return n||(n=[new k5(r,[],_.system_info)]),await z5(n[0],i,_.system_info),o.length>0?c.message=K5:c.message=`Successfully updated '${r}'`,c}a(Q5,"updateNode");async function z5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new V5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Pu.upsertNodeRecord(n),$5({type:"nats_update"})}a(z5,"updateNodeTable")});var nU=T((Mfe,rU)=>{"use strict";var tU=require("joi"),{string:ZM}=tU.types(),J5=Ze(),eU=U(),X5=Z(),j5=et();rU.exports=Z5;function Z5(e){let t=ZM.invalid(X5.get(eU.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(j5.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=tU.object({operation:ZM.valid(eU.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return J5.validateBySchema(e,r)}a(Z5,"removeNodeValidator")});var nf=T((Pfe,uU)=>{"use strict";var{handleHDBError:sU,hdb_errors:e8}=ee(),{HTTP_STATUS_CODES:iU}=e8,t8=nU(),vu=W(),oU=ys(),r8=J(),rf=U(),aU=et(),cU=Ot(),n8=Z(),{RemotePayloadObject:s8}=Du(),{NodeSubscription:i8}=Sa(),o8=xc(),a8=Ki(),{broadcast:c8}=je(),u8=n8.get(rf.CONFIG_PARAMS.CLUSTERING_NODENAME);uU.exports=l8;async function l8(e){vu.trace("removeNode called with:",e),oU.checkClusteringEnabled();let t=t8(e);if(t)throw sU(t,t.message,iU.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await oU.getNodeRecord(r);if(r8.isEmptyOrZeroLength(n))throw sU(new Error,`Node '${r}' was not found.`,iU.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new s8(rf.OPERATIONS_ENUM.REMOVE_NODE,u8,[]),i,o=!1;try{i=await cU.request(`${r}.${aU.REQUEST_SUFFIX}`,s),vu.trace("Remove node reply from remote node:",r,i)}catch(u){vu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];vu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new i8(l.schema,l.table,!1,!1);await cU.updateWorkStream(d,r)}let c=new o8(rf.SYSTEM_SCHEMA_NAME,rf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await a8.deleteRecord(c),c8({type:"nats_update"}),i?.status===aU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(vu.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(l8,"removeNode")});var dU=T((Bfe,_U)=>{"use strict";var lU=require("joi"),{string:_8,array:d8}=lU.types(),f8=Ze(),E8=Vd();_U.exports=h8;function h8(e){let t=lU.object({operation:_8.valid("configure_cluster").required(),connections:d8.items(E8.validation_schema).required()});return f8.validateBySchema(e,t)}a(h8,"configureClusterValidator")});var MT=T((xfe,pU)=>{"use strict";var m8=U(),sf=W(),p8=J(),S8=nf(),T8=tf(),fU=ys(),g8=dU(),{handleHDBError:EU,hdb_errors:R8}=ee(),{HTTP_STATUS_CODES:hU}=R8,A8="Configure cluster complete.",O8="Failed to configure the cluster. Check the logs for more details.",b8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";pU.exports=N8;async function N8(e){sf.trace("configure cluster called with:",e),fU.checkClusteringEnabled();let t=g8(e);if(t)throw EU(t,t.message,hU.BAD_REQUEST,void 0,void 0,!0);let r=await fU.getAllNodeRecords(),n=[];for(let f=0,E=r.length;f<E;f++)n.push(mU(S8,{operation:m8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let s=await Promise.allSettled(n);sf.trace("All results from configure_cluster remove node:",s);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(mU(T8,E,E.node_name))}let c=await Promise.allSettled(i);sf.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=s.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(sf.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let p=h?.value?.result;typeof p=="string"&&p.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(p8.isEmptyOrZeroLength(u))return{message:A8,connections:_};if(l)return{message:b8,failed_nodes:u,connections:_};throw EU(new Error,O8,hU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(N8,"configureCluster");async function mU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){throw{node_name:r,error:n}}}a(mU,"functionWrapper")});var TU=T((qfe,SU)=>{"use strict";var of=require("joi"),y8=Ze(),{validateSchemaExists:w8,validateTableExists:I8,validateSchemaName:C8}=$n(),D8=of.object({operation:of.string().valid("purge_stream"),schema:of.string().custom(w8).custom(C8).required(),table:of.string().custom(I8).required()});function L8(e){return y8.validateBySchema(e,D8)}a(L8,"purgeStreamValidator");SU.exports=L8});var UT=T((kfe,gU)=>{"use strict";var{handleHDBError:M8,hdb_errors:U8}=ee(),{HTTP_STATUS_CODES:P8}=U8,v8=TU(),B8=Ot(),H8=ys();gU.exports=x8;async function x8(e){if(e.purge_ingest!==!0){let s=v8(e);if(s)throw M8(s,s.message,P8.BAD_REQUEST,void 0,void 0,!0)}H8.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:n}=e;return await B8.purgeTableStream(t,r,n),n?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(x8,"purgeStream")});var BT=T(($fe,yU)=>{"use strict";var vT=ys(),F8=Ot(),OU=Z(),af=U(),fo=et(),q8=J(),PT=W(),{RemotePayloadObject:G8}=Du(),{ErrorCode:RU}=require("nats"),AU=OU.get(af.CONFIG_PARAMS.CLUSTERING_ENABLED),bU=OU.get(af.CONFIG_PARAMS.CLUSTERING_NODENAME);yU.exports={clusterStatus:k8,buildNodeStatus:NU};async function k8(){let e={node_name:bU,is_enabled:AU,connections:[]};if(!AU)return e;let t=await vT.getAllNodeRecords();if(q8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(NU(t[n],e.connections));return await Promise.allSettled(r),e}a(k8,"clusterStatus");async function NU(e,t){let r=e.name,n=new G8(af.OPERATIONS_ENUM.CLUSTER_STATUS,bU,void 0,await vT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await F8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,PT.error(`Error getting node status from ${r} `,s))}catch(u){PT.warn(`Error getting node status from ${r}`,u),u.code===RU.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===RU.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new V8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==af.PRE_4_0_0_VERSION&&await vT.upsertNodeRecord(u)}catch(u){PT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(NU,"buildNodeStatus");function V8(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(V8,"NodeStatusObject")});var xT=T((Kfe,wU)=>{"use strict";var{handleHDBError:$8,hdb_errors:Y8}=ee(),{HTTP_STATUS_CODES:K8}=Y8,W8=Ot(),Q8=ys(),HT=J(),cf=require("joi"),z8=Ze(),J8=2e3,X8=cf.object({timeout:cf.number().min(1),connected_nodes:cf.boolean(),routes:cf.boolean()});wU.exports=j8;async function j8(e){Q8.checkClusteringEnabled();let t=z8.validateBySchema(e,X8);if(t)throw $8(t,t.message,K8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||HT.autoCastBoolean(n),o=s===void 0||HT.autoCastBoolean(s),c={nodes:[]},u=await W8.getServerList(r??J8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(p=>({host:p.split(":")[0],port:HT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(j8,"clusterNetwork")});var LU=T((Qfe,DU)=>{"use strict";var FT=require("joi"),IU=Ze(),{route_constraints:CU}=Lp();DU.exports={setRoutesValidator:Z8,deleteRoutesValidator:e6};function Z8(e){let t=FT.object({server:FT.valid("hub","leaf").required(),routes:CU.required()});return IU.validateBySchema(e,t)}a(Z8,"setRoutesValidator");function e6(e){let t=FT.object({routes:CU.required()});return IU.validateBySchema(e,t)}a(e6,"deleteRoutesValidator")});var GT=T((Jfe,vU)=>{"use strict";var Eo=vr(),qT=J(),uf=U(),MU=LU(),{handleHDBError:UU,hdb_errors:t6}=ee(),{HTTP_STATUS_CODES:PU}=t6,r6="cluster routes successfully set",n6="cluster routes successfully deleted";vU.exports={setRoutes:s6,getRoutes:i6,deleteRoutes:o6};function s6(e){let t=MU.setRoutesValidator(e);if(t)throw UU(t,t.message,PU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=qT.autoCast(_.port);let l=n.some(f=>f.host===_.host&&f.port===_.port),d=s.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:r6,set:o,skipped:i}}a(s6,"setRoutes");function i6(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(i6,"getRoutes");function o6(e){let t=MU.deleteRoutesValidator(e);if(t)throw UU(t,t.message,PU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=n.length;E<h;E++){let p=n[E];if(d.host===p.host&&d.port===p.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=qT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=qT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(uf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:n6,deleted:i,skipped:o}}a(o6,"deleteRoutes")});var HU=T((jfe,BU)=>{"use strict";var Bu=require("alasql"),ho=require("recursive-iterator"),Un=W(),a6=J(),Hu=U(),kT=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,u6(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Hu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Hu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Hu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=c6(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!Hu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Bu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function c6(e){return e.filter(t=>t[Hu.PERMS_CRUD_ENUM.READ])}a(c6,"filterReadRestrictedAttrs");function u6(e,t,r,n,s){l6(e,t,r,n,s)}a(u6,"interpretAST");function xu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(xu,"addSchemaTableToMap");function l6(e,t,r,n,s){if(!e){Un.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Bu.yy.Insert?E6(e,t,r):e instanceof Bu.yy.Select?_6(e,t,r,n,s):e instanceof Bu.yy.Update?d6(e,t,r):e instanceof Bu.yy.Delete?f6(e,t,r):Un.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(l6,"getRecordAttributesAST");function _6(e,t,r,n,s){if(!e){Un.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(a6.isEmptyOrZeroLength(i)){Un.error("No schema specified");return}e.from.forEach(c=>{xu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),xu(c.table,t,r,n,s)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Un.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Un.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Un.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Un.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(_6,"getSelectAttributes");function d6(e,t,r){if(!e){Un.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;xu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.table.tableid,s,i.columnid,t,r)}a(d6,"getUpdateAttributes");function f6(e,t,r){if(!e){Un.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;xu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.table.tableid,s,i.columnid,t,r)}a(f6,"getDeleteAttributes");function E6(e,t,r){if(!e){Un.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;xu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.into.tableid,s,i.columnid,t,r)}a(E6,"getInsertAttributes");function VT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(VT,"pushAttribute");BU.exports=kT});var KT=T((eEe,GU)=>{var lf=Ji(),xU=require("chalk"),Yr=W(),FU=require("prompt"),{promisify:h6}=require("util"),$T=U(),m6=require("fs-extra"),p6=require("path"),S6=J(),T6=Jd(),qU=Z();qU.initSync();var g6=require("moment"),R6=h6(FU.get),A6=p6.join(qU.getHdbBasePath(),$T.LICENSE_KEY_DIR_NAME,$T.LICENSE_FILE_NAME,$T.LICENSE_FILE_NAME);GU.exports={getFingerprint:b6,setLicense:O6,parseLicense:YT,register:N6,getRegistrationInfo:w6};async function O6(e){if(e&&e.key&&e.company){try{Yr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await YT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Yr.error(r),Yr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(O6,"setLicense");async function b6(){let e={};try{e=await lf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Yr.error(r),Yr.error(t),new Error(r)}return e}a(b6,"getFingerprint");async function YT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Yr.info("Validating license input...");let r=lf.validateLicense(e,t);if(Yr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Yr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Yr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Yr.info("writing license to disk"),await m6.writeFile(A6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Yr.error("Failed to write License"),n}return"Registration successful."}a(YT,"parseLicense");async function N6(){let e=await y6();return YT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(N6,"register");async function y6(){let e=await lf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:xU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:xU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{FU.start()}catch(n){Yr.error(n)}let r;try{r=await R6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(y6,"promptForRegistration");async function w6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await lf.getLicense()}catch(r){throw Yr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(S6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=T6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=g6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(w6,"getRegistrationInfo")});var VU=T((rEe,kU)=>{"use strict";var I6=et(),WT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+I6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};kU.exports=WT});var KU=T((sEe,YU)=>{"use strict";var $U=et(),QT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+$U.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+$U.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};YU.exports=QT});var QU=T((oEe,WU)=>{"use strict";var zT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};WU.exports=zT});var JU=T((cEe,zU)=>{"use strict";var C6=et(),JT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+C6.SERVER_SUFFIX.ADMIN,this.password=r}};zU.exports=JT});var ZT=T((lEe,ZU)=>{"use strict";var ga=require("path"),ff=require("fs-extra"),D6=VU(),L6=KU(),M6=QU(),U6=JU(),XT=nn(),Aa=J(),dr=vr(),df=U(),Fu=et(),{CONFIG_PARAMS:ut}=df,qu=W(),Gu=Z(),XU=Os(),jT=Ot(),Ra="clustering",P6=1e4,jU=5;ZU.exports={generateNatsConfig:B6,removeNatsConfig:H6,getHubConfigPath:v6};function v6(){let e=Gu.get(ut.ROOTPATH);return ga.join(e,Ra,Fu.NATS_CONFIG_FILES.HUB_SERVER)}a(v6,"getHubConfigPath");async function B6(e=!1,t=void 0){Gu.initSync();let r=Gu.get(ut.ROOTPATH),n=ga.join(r,Ra,Fu.PID_FILES.HUB),s=ga.join(r,Ra,Fu.PID_FILES.LEAF),i=dr.getConfigFromFile(ut.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=ga.join(r,Ra,Fu.NATS_CONFIG_FILES.HUB_SERVER),c=ga.join(r,Ra,Fu.NATS_CONFIG_FILES.LEAF_SERVER),u=dr.getConfigFromFile(ut.CLUSTERING_TLS_CERTIFICATE),_=dr.getConfigFromFile(ut.CLUSTERING_TLS_PRIVATEKEY),l=dr.getConfigFromFile(ut.CLUSTERING_TLS_CERT_AUTH),d=dr.getConfigFromFile(ut.CLUSTERING_TLS_INSECURE),f=dr.getConfigFromFile(ut.CLUSTERING_TLS_VERIFY),E=dr.getConfigFromFile(ut.CLUSTERING_NODENAME),h=dr.getConfigFromFile(ut.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await jT.checkNATSServerInstalled()||Ef("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await XT.listUsers(),S=dr.getConfigFromFile(ut.CLUSTERING_USER),O=await XT.getClusterUser();(Aa.isEmpty(O)||O.active!==!0)&&Ef(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await _f(ut.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await _f(ut.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await _f(ut.CLUSTERING_HUBSERVER_NETWORK_PORT),await _f(ut.CLUSTERING_LEAFSERVER_NETWORK_PORT));let g=[],R=[];for(let[z,se]of p.entries())se.role.role===df.ROLE_TYPES_ENUM.CLUSTER_USER&&se.active&&(g.push(new U6(se.username,XU.decrypt(se.hash))),R.push(new M6(se.username,XU.decrypt(se.hash))));let B=[],{hub_routes:H}=dr.getClusteringRoutes();if(!Aa.isEmptyOrZeroLength(H))for(let z of H)B.push(`tls://${O.sys_name_encoded}:${O.uri_encoded_d_hash}@${z.host}:${z.port}`);let v=new D6(dr.getConfigFromFile(ut.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,dr.getConfigFromFile(ut.CLUSTERING_HUBSERVER_CLUSTER_NAME),dr.getConfigFromFile(ut.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),B,g,R);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=Aa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===df.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await ff.writeJson(o,v),qu.trace(`Hub server config written to ${o}`));let M=`tls://${O.sys_name_encoded}:${O.uri_encoded_d_hash}@0.0.0.0:${h}`,$=`tls://${O.uri_encoded_name}:${O.uri_encoded_d_hash}@0.0.0.0:${h}`,K=new L6(dr.getConfigFromFile(ut.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[M],[$],g,R,u,_,l,d);l==null&&delete K.tls.ca_file,(t===void 0||t===df.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await ff.writeJson(c,K),qu.trace(`Leaf server config written to ${c}`))}a(B6,"generateNatsConfig");async function _f(e){let t=Gu.get(e);return Aa.isEmpty(t)&&Ef(`port undefined for '${e}'`),await Aa.isPortTaken(t)&&Ef(`'${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(_f,"isPortAvailable");function Ef(e){let t=`Error generating clustering config: ${e}`;qu.error(t),console.error(t),process.exit(1)}a(Ef,"generateNatsConfigError");async function H6(e){let{port:t,config_file:r}=jT.getServerConfig(e),{username:n,decrypt_hash:s}=await XT.getClusterUser(),i=0,o=2e3;for(;i<jU;){try{let _=await jT.createConnection(t,n,s,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){qu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=jU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await Aa.async_set_timeout(o*(i*2))}let c="0".repeat(P6),u=ga.join(Gu.get(ut.ROOTPATH),Ra,r);await ff.writeFile(u,c),await ff.remove(u),qu.notify(e,"started.")}a(H6,"removeNatsConfig")});var iP=T((dEe,sP)=>{"use strict";var Kr=Z(),x6=Ji(),Se=U(),ku=et(),ws=require("path"),{PACKAGE_ROOT:mf}=U(),eP=Z(),hf=J(),Oa="/dev/null",F6=ws.join(mf,"launchServiceScripts"),tP=ws.join(mf,"utility/scripts"),q6=ws.join(tP,Se.HDB_RESTART_SCRIPT),rP=ws.resolve(mf,"dependencies",`${process.platform}-${process.arch}`,ku.NATS_BINARY_NAME);function nP(){let t=x6.licenseSearch().ram_allocation||Se.RAM_ALLOCATION_ENUM.DEFAULT,r=Se.MEM_SETTING_KEY+t,n={[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return hf.noBootFile()&&(n[Se.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=hf.getEnvCliRootPath()),{name:Se.PROCESS_DESCRIPTORS.HDB,script:Se.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:mf}}a(nP,"generateMainServerConfig");var G6=9930;function k6(){Kr.initSync(!0);let e=Kr.get(Se.CONFIG_PARAMS.ROOTPATH),t=ws.join(e,"clustering",ku.NATS_CONFIG_FILES.HUB_SERVER),r=ws.join(Kr.get(Se.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Se.LOG_NAMES.HDB),n=eP.get(Se.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[Kr.get(Se.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==G6?"-"+n:""),script:rP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Kr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Oa,i.error_file=Oa),i}a(k6,"generateNatsHubServerConfig");var V6=9940;function $6(){Kr.initSync(!0);let e=Kr.get(Se.CONFIG_PARAMS.ROOTPATH),t=ws.join(e,"clustering",ku.NATS_CONFIG_FILES.LEAF_SERVER),r=ws.join(Kr.get(Se.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Se.LOG_NAMES.HDB),n=eP.get(Se.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=ku.LOG_LEVEL_FLAGS[Kr.get(Se.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==V6?"-"+n:""),script:rP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Kr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Oa,i.error_file=Oa),i}a($6,"generateNatsLeafServerConfig");function Y6(){Kr.initSync();let e=ws.join(Kr.get(Se.CONFIG_PARAMS.LOGGING_ROOT),Se.LOG_NAMES.HDB),t={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:Se.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:F6,autorestart:!1};return Kr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Oa,t.error_file=Oa),t}a(Y6,"generateClusteringUpgradeV4ServiceConfig");function K6(){let e={[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.RESTART_HDB};return hf.noBootFile()&&(e[Se.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=hf.getEnvCliRootPath()),{...{name:Se.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:tP},script:q6}}a(K6,"generateRestart");function W6(){return{apps:[nP()]}}a(W6,"generateAllServiceConfigs");sP.exports={generateAllServiceConfigs:W6,generateMainServerConfig:nP,generateRestart:K6,generateNatsHubServerConfig:k6,generateNatsLeafServerConfig:$6,generateClusteringUpgradeV4ServiceConfig:Y6}});var TP=T((hEe,SP)=>{"use strict";var Ue=U(),Q6=J(),Is=ZT(),Vu=Ot(),es=et(),fi=iP(),pf=Z(),Ei=W(),z6=ys(),{startWorker:oP,onMessageFromWorkers:J6}=je(),X6=Ta(),EEe=require("util"),j6=require("child_process"),Z6=require("fs"),{execFile:e9}=j6,we;SP.exports={enterPM2Mode:t9,start:hi,stop:eg,reload:cP,restart:uP,list:tg,describe:_P,connect:Cs,kill:o9,startAllServices:a9,startService:rg,getUniqueServicesList:dP,restartAllServices:c9,isServiceRegistered:fP,reloadStopStart:EP,restartHdb:lP,deleteProcess:s9,startClusteringProcesses:mP,startClusteringThreads:pP,isHdbRestartRunning:i9,isClusteringRunning:l9,stopClustering:u9,reloadClustering:_9};var $u=!1;J6(e=>{e.type==="restart"&&pf.initSync(!0)});function t9(){$u=!0}a(t9,"enterPM2Mode");function Cs(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{Ei.setupConsoleLogging(),r&&t(r),e(n)})})}a(Cs,"connect");var fr,r9=10,aP;function hi(e,t=!1){if($u)return n9(e);let r=e9(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=fr.indexOf(r);o>-1&&fr.splice(o,1),!aP&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<r9&&(Z6.existsSync(Is.getHubConfigPath())?hi(e):(await Is.generateNatsConfig(!0),hi(e),await new Promise(c=>setTimeout(c,3e3)),await Is.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Is.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=pf.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&es.LOG_LEVEL_HIERARCHY[o]>=es.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===es.LOG_LEVELS.ERR||l===es.LOG_LEVELS.WRN?Ei.OUTPUTS.STDERR:Ei.OUTPUTS.STDOUT;Ei.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=es.LOG_LEVELS[f]}if(es.LOG_LEVEL_HIERARCHY[o]>=es.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===es.LOG_LEVELS.ERR||l===es.LOG_LEVELS.WRN?Ei.OUTPUTS.STDERR:Ei.OUTPUTS.STDOUT;Ei.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),fr=[],!fr&&!t){let i=a(()=>{aP=!0,fr&&(fr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}fr.push(r)}a(hi,"start");function n9(e){return new Promise(async(t,r)=>{try{await Cs()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(n9,"startWithPM2");function eg(e){if(!$u){for(let t of fr||[])t.name===e&&(fr.splice(fr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Cs()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(eg,"stop");function cP(e){return new Promise(async(t,r)=>{try{await Cs()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(cP,"reload");function uP(e){if(!$u)for(let t of fr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Cs()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(uP,"restart");function s9(e){return new Promise(async(t,r)=>{try{await Cs()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(s9,"deleteProcess");async function lP(){await hi(fi.generateRestart())}a(lP,"restartHdb");async function i9(){let e=await tg();for(let t in e)if(e[t].name===Ue.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(i9,"isHdbRestartRunning");function tg(){return new Promise(async(e,t)=>{try{await Cs()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(tg,"list");function _P(e){return new Promise(async(t,r)=>{try{await Cs()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(_P,"describe");function o9(){if(!$u){for(let e of fr||[])e.kill();fr=[];return}return new Promise(async(e,t)=>{try{await Cs()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(o9,"kill");async function a9(){try{await mP(),await pP(),await hi(fi.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(a9,"startAllServices");async function rg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ue.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=fi.generateMainServerConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=fi.generateNatsIngestServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=fi.generateNatsReplyServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=fi.generateNatsHubServerConfig(),await hi(r,t),await Is.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=fi.generateNatsLeafServerConfig(),await hi(r,t),await Is.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=fi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await hi(r)}catch(r){throw we?.disconnect(),r}}a(rg,"startService");async function dP(){try{let e=await tg(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(dP,"getUniqueServicesList");async function c9(e=[]){try{let t=!1,r=await dP();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Ue.PROCESS_DESCRIPTORS.HDB?t=!0:await uP(o))}t&&await EP(Ue.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(c9,"restartAllServices");async function fP(e){if(fr?.find(r=>r.name===e))return!0;let t=await X6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(fP,"isServiceRegistered");async function EP(e){let t=e===Ue.PROCESS_DESCRIPTORS.HDB?pf.get(Ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):pf.get(Ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await _P(e),n=Q6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await eg(e),await rg(e)):e===Ue.PROCESS_DESCRIPTORS.HDB?await lP():await cP(e)}a(EP,"reloadStopStart");var hP;async function mP(e=!1){for(let t in Ue.CLUSTERING_PROCESSES){let r=Ue.CLUSTERING_PROCESSES[t];await rg(r,e)}}a(mP,"startClusteringProcesses");async function pP(){hP=oP(Ue.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Vu.createWorkQueueStream(es.WORK_QUEUE_CONSUMER_NAMES),await Vu.updateIngestStreamConsumer(),await Vu.updateLocalStreams();let e=await z6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ue.PRE_4_0_0_VERSION){Ei.info("Starting clustering upgrade 4.0.0 process"),oP(Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(pP,"startClusteringThreads");async function u9(){for(let e in Ue.CLUSTERING_PROCESSES)if(e!==Ue.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ue.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await hP.terminate();else{let t=Ue.CLUSTERING_PROCESSES[e];await eg(t)}}a(u9,"stopClustering");async function l9(){for(let e in Ue.CLUSTERING_PROCESSES){let t=Ue.CLUSTERING_PROCESSES[e];if(await fP(t)===!1)return!1}return!0}a(l9,"isClusteringRunning");async function _9(){await Is.generateNatsConfig(!0),await Vu.reloadNATSHub(),await Vu.reloadNATSLeaf(),await Is.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Is.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(_9,"reloadClustering")});var Rf=T((pEe,yP)=>{"use strict";var d9=require("minimist"),{isMainThread:ig,parentPort:AP}=require("worker_threads"),nt=U(),{PROCESS_DESCRIPTORS_VALIDATE:Yu}=nt,ts=W(),og=J(),Sf=ZT(),ba=Ot(),ng=et(),OP=vr(),rs=TP(),gP=Ta(),f9=th(),{restartWorkers:Tf,onMessageByType:E9}=je(),{handleHDBError:h9,hdb_errors:m9}=ee(),{HTTP_STATUS_CODES:p9}=m9,gf=Z();gf.initSync();var Ku=`Restarting HarperDB. This may take up to ${nt.RESTART_TIMEOUT_MS/1e3} seconds.`,S9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",RP="Clustering is not enabled so cannot be restarted",T9="Invalid service",Na,ln;yP.exports={restart:bP,restartService:ag};ig&&E9(nt.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?ag({service:e.workerType}):bP({operation:"restart"})});async function bP(e){ln=Object.keys(e).length===0,Na=await rs.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR);let t=d9(process.argv);if(t.service){await ag(t);return}if(ln&&!Na){console.error(S9);return}if(ln&&console.log(Ku),Na){rs.enterPM2Mode(),ts.notify(Ku);let r=f9(Object.keys(nt.CONFIG_PARAM_MAP),!0);return og.isEmptyOrZeroLength(Object.keys(r))||OP.updateConfigValue(void 0,void 0,r,!0,!0),R9(),Ku}return ig?(ts.notify(Ku),setTimeout(()=>{Tf()},50)):AP.postMessage({type:nt.ITC_EVENT_TYPES.RESTART}),Ku}a(bP,"restart");async function ag(e){let{service:t}=e;if(nt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw h9(new Error,T9,p9.BAD_REQUEST,void 0,void 0,!0);if(Na=await rs.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR),!ig)return AP.postMessage({type:nt.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Yu.clustering:if(!gf.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=RP;break}ln&&console.log("Restarting clustering"),ts.notify("Restarting clustering"),await NP();break;case Yu.clustering_config:case Yu["clustering config"]:if(!gf.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=RP;break}ln&&console.log("Restarting clustering_config"),ts.notify("Restarting clustering_config"),await rs.reloadClustering();break;case"custom_functions":case"custom functions":case Yu.harperdb:case Yu.http_workers:if(ln&&!Na){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}ln&&console.log("Restarting http_workers"),ts.notify("Restarting http_workers"),ln?await rs.restart(nt.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Tf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(ts.error(r),ln&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(ag,"restartService");async function g9(){await ba.publishToStream(`${ng.SUBJECT_PREFIXES.TXN}.${ng.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,ng.WORK_QUEUE_CONSUMER_NAMES.stream_name,ba.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(g9,"postDummyNatsMsg");async function R9(){await NP(),await rs.restart(nt.HDB_PROC_DESCRIPTOR),await og.async_set_timeout(2e3),gf.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await sg(),ln&&(await ba.closeConnection(),process.exit(0))}a(R9,"restartPM2Mode");async function NP(){if(!OP.getConfigFromFile(nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await gP.getHDBProcessInfo()).clustering.length===0)ts.trace("Clustering not running, restart will start clustering services"),await Sf.generateNatsConfig(!0),await rs.startClusteringProcesses(),await rs.startClusteringThreads(),await sg(),ln&&await ba.closeConnection();else{await g9(),await Sf.generateNatsConfig(!0),Na?(ts.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await rs.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await rs.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await gP.getHDBProcessInfo()).clustering.forEach(s=>{ts.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await og.async_set_timeout(3e3),await sg(),await ba.updateLocalStreams(),ln&&await ba.closeConnection(),ts.trace("Restart clustering restarting ingest and reply service threads");let t=Tf(nt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Tf(nt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(NP,"restartClustering");async function sg(){await Sf.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Sf.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(sg,"removeNatsConfig")});var HP=T((gEe,BP)=>{"use strict";var TEe=require("lodash"),Er=U(),{handleHDBError:wP,hdb_errors:A9}=ee(),{HDB_ERROR_MSGS:O9,HTTP_STATUS_CODES:b9}=A9,cg=W();BP.exports={getRolePermissions:y9};var mo=Object.create(null),N9=a(e=>({key:e,perms:{}}),"perms_template_obj"),LP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),MP=a((e=!1,t=!1,r=!1,n=!1)=>({[Er.PERMS_CRUD_ENUM.READ]:e,[Er.PERMS_CRUD_ENUM.INSERT]:t,[Er.PERMS_CRUD_ENUM.UPDATE]:r,[Er.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),ug=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...MP(t,r,n,s)}),"table_perms_template"),IP=a((e,t=MP())=>({attribute_name:e,describe:vP(t),[Wu]:t[Wu],[lg]:t[lg],[_g]:t[_g]}),"attr_perms_template"),CP=a((e,t=!1)=>({attribute_name:e,describe:t,[Wu]:t}),"timestamp_attr_perms_template"),{READ:Wu,INSERT:lg,UPDATE:_g}=Er.PERMS_CRUD_ENUM,UP=Object.values(Er.PERMS_CRUD_ENUM),PP=[Wu,lg,_g];function y9(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[Er.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(mo[t]&&mo[t].key===n)return mo[t].perms;let s=w9(e,r);return mo[t]?mo[t].key=n:mo[t]=N9(n),mo[t].perms=s,s}catch(r){if(!e[Er.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Er.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Er.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw cg.error(n),cg.debug(r),wP(new Error,O9.OUTDATED_PERMS_TRANSLATION_ERROR,b9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
+
${r.stack}`;throw cg.error(n),wP(new Error)}}}a(y9,"getRolePermissions");function w9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Er.SYSTEM_SCHEMA_NAME]=n[Er.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=I9(t[i]);return}r[i]=LP(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=C9(c,u);r[i].describe||UP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=ug()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=ug()})}),r}a(w9,"translateRolePermissions");function I9(e){let t=LP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=ug(!0,!0,!0,!0,!0)}),t}a(I9,"createStructureUserPermissions");function C9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return Er.TIME_STAMP_NAMES.includes(d)&&(f=CP(d,l[Wu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=IP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=vP(l),s.attribute_permissions.push(l),c||D9(l,u)}else if(_!==o){let l;Er.TIME_STAMP_NAMES.includes(_)?l=CP(_):l=IP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=DP(s),s}else return e.describe=DP(e),e}a(C9,"getTableAttrPerms");function DP(e){return UP.filter(t=>e[t]).length>0}a(DP,"getSchemaTableDescribePerm");function vP(e){return PP.filter(t=>e[t]).length>0}a(vP,"getAttributeDescribePerm");function D9(e,t){PP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(D9,"checkForHashPerms")});var xP={};Fe(xP,{Headers:()=>mi});var mi,Af=Oe(()=>{mi=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];n?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var Qu={};Fe(Qu,{authentication:()=>KP,bypassAuth:()=>H9,login:()=>F9,logout:()=>q9,start:()=>x9});function H9(){YP=!0}async function KP(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?P9?U9:[]:M9?L9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new mi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Of&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Of&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Of){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let p=s.indexOf(";",h),S=s.indexOf("=",h);u=s.slice(S+1,p===-1?s.length:p),_=await qP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Nf.AuthAuditLog(E,h,xt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===xt.AUTH_AUDIT_STATUS.SUCCESS?FP.notify(S):FP.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let E=e.mtlsConfig.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=e.peerCertificate.subject.CN),e.user=await Xe.getUser(E,null,null))}let d;if(!e.user)if(n){if(d=po.get(n),!d){let[E,h]=n.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await Xe.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,bf.validateOperationToken)(h)}catch(O){if(O.message==="invalid token")try{return await(0,bf.validateRefreshToken)(h),c({status:-1})}catch{throw O}}break}}catch(O){return B9&&(po.get(h)||(po.set(h,h),l(p,xt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:pi({error:O.message},e)})}po.set(n,d),v9&&l(d.username,xt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await Xe.getUser(_.user,null,e):(YP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,kP.getSuperUser)());Of&&(e.session.update=function(E){if(!u){u=(0,VP.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):f?.headers?.set&&f.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,qP.put(E)},e.login=async function(E,h){e.user=await Xe.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&Qs.loginPath?(f.status=302,f.headers.set("Location",Qs.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new mi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function x9({server:e,port:t}){e.request(KP,{port:t||"all"}),GP||(GP=!0,setInterval(()=>{po=new Map},_n.get(xt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),$P.user.addListener(()=>{po=new Map}))}async function F9(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 q9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var kP,bf,VP,_n,xt,Nf,$P,FP,L9,M9,U9,P9,qP,Of,YP,v9,B9,po,GP,yf=Oe(()=>{kP=x(nn());zt();pc();bf=x(Cu());Ne();VP=require("uuid"),_n=x(Z()),xt=x(U()),Nf=x(W()),$P=x(Jc());Af();ya();FP=(0,Nf.loggerWithTag)("auth-event");_n.initSync();L9=_n.get(xt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),M9=_n.get(xt.CONFIG_PARAMS.HTTP_CORS),U9=_n.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),P9=_n.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),qP=at({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Of=_n.get(xt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,YP=_n.get(xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,v9=_n.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,B9=_n.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,po=new Map;Xe.onInvalidatedUser(()=>{po=new Map});a(H9,"bypassAuth");a(KP,"authentication");a(x9,"start");a(F9,"login");a(q9,"logout")});var ZP=T((CEe,jP)=>{"use strict";var Ie=require("joi"),WP=require("fs-extra"),QP=require("path"),Ls=Ze(),zP=Z(),JP=U(),XP=W(),{hdb_errors:G9}=ee(),{HDB_ERROR_MSGS:Qt}=G9,Ds=/^[a-zA-Z0-9-_]+$/;jP.exports={getDropCustomFunctionValidator:V9,setCustomFunctionValidator:$9,addComponentValidator:Q9,dropCustomFunctionProjectValidator:z9,packageComponentValidator:J9,deployComponentValidator:X9,setComponentFileValidator:Y9,getComponentFileValidator:W9,dropComponentFileValidator:K9};function wf(e,t,r){try{let n=zP.get(JP.CONFIG_PARAMS.COMPONENTSROOT),s=QP.join(n,t);return WP.existsSync(s)?e?t:r.message(Qt.PROJECT_EXISTS):e?r.message(Qt.NO_PROJECT):t}catch(n){return XP.error(n),r.message(Qt.VALIDATION_ERR)}}a(wf,"checkProjectExists");function zu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(zu,"checkFilePath");function k9(e,t,r,n){try{let s=zP.get(JP.CONFIG_PARAMS.COMPONENTSROOT),i=QP.join(s,e,t,r+".js");return WP.existsSync(i)?r:n.message(Qt.NO_FILE)}catch(s){return XP.error(s),n.message(Qt.VALIDATION_ERR)}}a(k9,"checkFileExists");function V9(e){let t=Ie.object({project:Ie.string().pattern(Ds).custom(wf.bind(null,!0)).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(Ds).custom(k9.bind(null,e.project,e.type)).custom(zu).required().messages({"string.pattern.base":Qt.BAD_FILE_NAME})});return Ls.validateBySchema(e,t)}a(V9,"getDropCustomFunctionValidator");function $9(e){let t=Ie.object({project:Ie.string().pattern(Ds).custom(wf.bind(null,!0)).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(zu).required(),function_content:Ie.string().required()});return Ls.validateBySchema(e,t)}a($9,"setCustomFunctionValidator");function Y9(e){let t=Ie.object({project:Ie.string().pattern(Ds).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ls.validateBySchema(e,t)}a(Y9,"setComponentFileValidator");function K9(e){let t=Ie.object({project:Ie.string().pattern(Ds).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).optional()});return Ls.validateBySchema(e,t)}a(K9,"dropComponentFileValidator");function W9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(zu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ls.validateBySchema(e,t)}a(W9,"getComponentFileValidator");function Q9(e){let t=Ie.object({project:Ie.string().pattern(Ds).custom(wf.bind(null,!1)).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME})});return Ls.validateBySchema(e,t)}a(Q9,"addComponentValidator");function z9(e){let t=Ie.object({project:Ie.string().pattern(Ds).custom(wf.bind(null,!0)).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME})});return Ls.validateBySchema(e,t)}a(z9,"dropCustomFunctionProjectValidator");function J9(e){let t=Ie.object({project:Ie.string().pattern(Ds).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Ls.validateBySchema(e,t)}a(J9,"packageComponentValidator");function X9(e){let t=Ie.object({project:Ie.string().pattern(Ds).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":Qt.BAD_PACKAGE}),package:Ie.string().optional()});return Ls.validateBySchema(e,t)}a(X9,"deployComponentValidator")});var Lf=T((LEe,ov)=>{"use strict";var If=require("joi"),Cf=require("path"),ev=require("fs-extra"),{exec:j9}=require("child_process"),Z9=require("util"),tv=Z9.promisify(j9),Ju=U(),{handleHDBError:wa,hdb_errors:e7}=ee(),{HTTP_STATUS_CODES:Ia}=e7,Xu=Z(),t7=Ze(),Ca=W();Xu.initSync();var dg=Xu.get(Ju.CONFIG_PARAMS.COMPONENTSROOT),rv="npm install --omit=dev --json",r7=`${rv} --dry-run`;ov.exports={installModules:o7,auditModules:a7,installAllRootModules:n7,uninstallRootModule:s7,linkHarperdb:i7};async function n7(e=!1){await Df(),await ju(e?"npm install --ignore-scripts":"npm install",Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(n7,"installAllRootModules");async function s7(e){await ju(`npm uninstall ${e}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(s7,"uninstallRootModule");async function i7(){await Df(),await ju(`npm link ${Ju.PACKAGE_ROOT}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(i7,"linkHarperdb");async function ju(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await tv(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
12
|
+
`,""))}return n&&!n.includes("Debugger listening")&&Ca.error("Error running NPM command:",e,n),Ca.trace(r,n),r?.replace(`
|
|
13
|
+
`,"")}a(ju,"runCommand");async function o7(e){Ca.info(`starting installModules for request: ${e}`);let t=iv(e);if(t)throw wa(t,t.message,Ia.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?r7:rv;await Df(),await sv(r);let i={};for(let o=0,c=r.length;o<c;o++){let u=r[o];i[u]={npm_output:null,npm_error:null};let _=Cf.join(dg,u),l,d=null;try{let{stdout:f,stderr:E}=await tv(s,{cwd:_});l=f?f.replace(`
|
|
14
14
|
`,""):null,d=E?E.replace(`
|
|
15
|
-
`,""):null}catch(f){f.stderr?i[u].npm_error=
|
|
16
|
-
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(tv,"parseNPMStdErr");async function i7(e){Da.info(`starting auditModules for request: ${e}`);let t=nv(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST);let{projects:r}=e;await Uf(),await rv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Mf.join(Eg,o);n[o]={npm_output:null,npm_error:null};try{let u=await ju("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=tv(u.stderr)}}return Da.info(`finished auditModules with response ${n}`),n}a(i7,"auditModules");async function Uf(){try{return await ju("npm -v"),!0}catch{throw wa(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ca.BAD_REQUEST,void 0,void 0,!0)}}a(Uf,"checkNPMInstalled");async function rv(e){if(!Array.isArray(e)||e.length===0)throw wa(new Error,"projects argument must be an array with at least 1 element",Ca.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Mf.join(Eg,i.toString());if(!await jP.pathExists(o)){t.push(i);continue}let u=Mf.join(o,"package.json");await jP.pathExists(u)||r.push(i)}if(t.length>0)throw wa(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ca.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw wa(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ca.BAD_REQUEST,void 0,void 0,!0)}a(rv,"checkProjectPaths");function nv(e){let t=Lf.object({projects:Lf.array().min(1).items(Lf.string()).required(),dry_run:Lf.boolean().default(!1)});return Z9.validateBySchema(e,t)}a(nv,"modulesValidator")});var mg=T((MEe,uv)=>{"use strict";var La=require("fs-extra"),hg=require("path"),vf=Y(),iv=J(),Bf=M(),cv=j(),o7=xr();uv.exports=a7;async function a7(){let e=c7(),t=cv.get(Bf.CONFIG_PARAMS.ROOTPATH),r=hg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Bf.PACKAGE_ROOT}},s=hg.join(t,"node_modules");await La.ensureDir(s);let i,o=!0,c=!1;try{i=await La.readJson(r)}catch(u){if(iv.isEmptyOrZeroLength(e))return;if(u.code!==Bf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!iv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await ov(_);n.dependencies[u]=l+_}if(!o){vf.notify("Installing components"),await av(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await ov(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(vf.notify("Removing component",u),c=!0);c&&(vf.notify("Updating components."),await av(r,n,i))}a(a7,"installComponents");function c7(){let e=o7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(c7,"getComponentsConfig");async function ov(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":hg.extname(e)||await La.pathExists(e)?"file:":"github:"}a(ov,"getPkgPrefix");async function av(e,t,r){vf.trace("npm installing components package.json",t),await La.writeFile(e,JSON.stringify(t,null," "));try{await Pf().installAllRootModules(cv.get(Bf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await La.writeFile(e,JSON.stringify(r,null," ")):await La.unlink(e),n}}a(av,"installPackages")});var Tg=T((vEe,fv)=>{"use strict";var ke=require("fs-extra"),pg=require("fast-glob"),Te=require("path"),_v=require("tar-fs"),PEe=require("uuid").v4,Sg=require("normalize-path"),ss=XP(),It=Y(),Qe=M(),St=j(),Zu=xr(),u7=J(),{PACKAGE_ROOT:l7}=M(),{handleHDBError:Bt,hdb_errors:_7}=Z(),{basename:d7}=require("path"),f7=mg(),dv=j(),E7=M(),{Readable:h7}=require("stream"),{isMainThread:m7}=require("worker_threads"),{HDB_ERROR_MSGS:So,HTTP_STATUS_CODES:Ht}=_7,p7=Te.join(l7,"application-template"),lv=Te.join(St.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function S7(){It.trace("getting custom api status");let e={};try{e={port:St.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Bt(new Error,So.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,It.ERR,t)}return e}a(S7,"customFunctionsStatus");function T7(){It.trace("getting custom api endpoints");let e={},t=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{pg.sync(Sg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:pg.sync(Sg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:pg.sync(Sg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Bt(new Error,So.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,It.ERR,r)}return e}a(T7,"getCustomFunctions");function g7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=ss.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("getting custom api endpoint file content");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw Bt(new Error,So.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,It.ERR,c)}}a(g7,"getCustomFunction");function R7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=ss.setCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("setting custom function file content");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return ke.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Bt(new Error,So.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,It.ERR,c)}}a(R7,"setCustomFunction");function A7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=ss.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("dropping custom function file");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return ke.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Bt(new Error,So.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,It.ERR,o)}}a(A7,"dropCustomFunction");function O7(e){e.project&&(e.project=Te.parse(e.project).name);let t=ss.addComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("adding component");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return ke.mkdirSync(s,{recursive:!0}),ke.copySync(p7,s),`Successfully added project: ${n}`}catch(s){throw Bt(new Error,So.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,It.ERR,s)}}a(O7,"addComponent");function b7(e){e.project&&(e.project=Te.parse(e.project).name);let t=ss.dropCustomFunctionProjectValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);It.trace("dropping custom function project");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=St.get(Qe.CONFIG_PARAMS.APPS);if(!u7.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return Zu.updateConfigValue(Qe.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Bt(new Error,So.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,It.ERR,i)}}a(b7,"dropCustomFunctionProject");async function N7(e){e.project&&(e.project=Te.parse(e.project).name);let t=ss.packageComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;It.trace("packaging component",n);let s;try{s=await ke.realpath(Te.join(r,n))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{s=await ke.realpath(Te.join(St.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await ke.ensureDir(lv);let i=Te.join(lv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),_v.pack(s,o).pipe(ke.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=ke.readFileSync(i,{encoding:"base64"});return await ke.remove(i),{project:n,payload:c}}a(N7,"packageComponent");async function y7(e){e.project&&(e.project=Te.parse(e.project).name);let t=ss.deployComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(It.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await ke.ensureDir(o);let f=h7.from(Buffer.from(s,"base64"));await new Promise((h,S)=>{f.pipe(_v.extract(o,{finish:h})).on("error",S)});let E=await ke.readdir(o);E.length===1&&E[0]==="package"&&(await ke.copy(Te.join(o,"package"),o),await ke.remove(Te.join(o,"package")))}if(await Zu.addConfig(n,{package:i}),!s){await f7();let f=dv.get(E7.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",n)}if(m7)return;let c=new Map;c.isWorker=!0;let u=(xf(),ee(Hf)),_;u.setErrorReporter(f=>_=f);let l=d7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return It.info("Installed component"),`Successfully deployed: ${n}`}a(y7,"deployComponent");async function I7(){let e=Zu.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await ke.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Te.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await ke.stat(d),E={name:Te.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return It.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(St.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(xf(),ee(Hf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(I7,"getComponents");async function w7(e){let t=ss.getComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let n=Zu.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(dv.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(Te.join(n,e.project,e.file));return{message:await ke.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(w7,"getComponentFile");async function C7(e){let t=ss.setComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(n),await ke.outputFile(n,e.payload,r)):await ke.ensureDir(n),"Successfully set component: "+e.file}a(C7,"setComponentFile");async function D7(e){let t=ss.dropComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(n)&&await ke.remove(n),Zu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(D7,"dropComponent");fv.exports={customFunctionsStatus:S7,getCustomFunctions:T7,getCustomFunction:g7,setCustomFunction:R7,dropCustomFunction:A7,addComponent:O7,dropCustomFunctionProject:b7,packageComponent:N7,deployComponent:y7,getComponents:I7,getComponentFile:w7,setComponentFile:C7,dropComponent:D7}});var gg=T((HEe,hv)=>{"use strict";var is=require("joi"),Ev=rt();hv.exports={readTransactionLogValidator:L7,deleteTransactionLogsBeforeValidator:M7};function L7(e){let t=is.object({schema:is.string().required(),table:is.string().required(),from:is.date().timestamp(),to:is.date().timestamp(),limit:is.number().min(1)});return Ev.validateBySchema(e,t)}a(L7,"readTransactionLogValidator");function M7(e){let t=is.object({schema:is.string().required(),table:is.string().required(),timestamp:is.date().timestamp().required()});return Ev.validateBySchema(e,t)}a(M7,"deleteTransactionLogsBeforeValidator")});var qf=T((FEe,gv)=>{"use strict";var Rg=M(),Ff=yt(),mv=J(),pv=j(),Sv=bs(),{handleHDBError:Ma,hdb_errors:U7}=Z(),{HTTP_STATUS_CODES:Ua}=U7,{readTransactionLogValidator:P7,deleteTransactionLogsBeforeValidator:v7}=gg(),Tv="This operation relies on clustering and cannot run with it disable.",B7="Logs successfully deleted from transaction log.",H7="All logs successfully deleted from transaction log.";gv.exports={readTransactionLog:x7,deleteTransactionLogsBefore:F7};async function*x7(e){let t=P7(e);if(t)throw Ma(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!pv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,Tv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=mv.checkSchemaTableExist(r,n);if(s)throw Ma(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=Sv.createNatsTableStreamName(r,n),o=await Ff.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===Rg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(x7,"readTransactionLog");async function F7(e){let t=v7(e);if(t)throw Ma(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!pv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ma(new Error,Tv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=mv.checkSchemaTableExist(r,n);if(i)throw Ma(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=Sv.createNatsTableStreamName(r,n),{jsm:c}=await Ff.getNATSReferences(),u=await Ff.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=B7,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=H7):d=(await Ff.viewStream(o,parseInt(s),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(F7,"deleteTransactionLogsBefore")});var Av=T((GEe,Rv)=>{"use strict";var Ag=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};Rv.exports=Ag});var bv=T((VEe,Ov)=>{"use strict";var Og=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Ov.exports=Og});var Ng=T((YEe,yv)=>{"use strict";var Nv=Av(),q7=bv(),{HDB_ERROR_MSGS:G7}=wr(),bg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=G7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new Nv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new q7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Nv(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};yv.exports=bg});var $f=T((WEe,kv)=>{"use strict";var yg=on(),Gf=sn(),pn=Gd(),rl=Gi(),Ig=Ki(),k7=FS(),V7=xL(),nl=cn(),kf=QS(),wt=Y(),$7=XS(),Y7=sf(),K7=UT(),W7=af(),Q7=PT(),z7=vT(),J7=xT(),X7=qT(),wg=VT(),Us=J(),j7=vU(),Cg=QT(),Cv=bf(),mn=M(),Dv=vP(),Z7=ga(),Lv=Cu(),Mv=(Cf(),ee(Qu)),Uv=xr(),Jr=Tg(),eee=require("alasql"),Pv=qf(),vv=Pf(),Bv=Ng(),{handleHDBError:Tr,hdb_errors:Hv}=Z(),{HDB_ERROR_MSGS:Vt,HTTP_STATUS_CODES:el}=Hv,q=new Map,xv="delete",gi="insert",Ps="read",To="update",tl="describe",Iv=rl.describeSchema.name,wv=rl.describeTable.name,Fv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},tee="catchup",ree="handleGetJob",nee="handleGetJobsByStartDate",Vf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},see=[pn.createTable.name,pn.createAttribute.name,pn.dropTable.name,pn.dropAttribute.name],qv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},K=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};q.set(yg.insert.name,new K(!1,[gi]));q.set(yg.update.name,new K(!1,[To]));q.set(yg.upsert.name,new K(!1,[gi,To]));q.set(Gf.searchByConditions.name,new K(!1,[Ps]));q.set(Gf.searchByHash.name,new K(!1,[Ps]));q.set(Gf.searchByValue.name,new K(!1,[Ps]));q.set(Gf.search.name,new K(!1,[Ps]));q.set(pn.createSchema.name,new K(!0,[]));q.set(pn.createTable.name,new K(!0,[]));q.set(pn.createAttribute.name,new K(!1,[gi]));q.set(pn.dropSchema.name,new K(!0,[]));q.set(pn.dropTable.name,new K(!0,[]));q.set(pn.dropAttribute.name,new K(!0,[]));q.set(rl.describeSchema.name,new K(!1,[Ps]));q.set(rl.describeTable.name,new K(!1,[Ps]));q.set(Ig.deleteRecord.name,new K(!1,[xv]));q.set(nl.addUser.name,new K(!0,[]));q.set(nl.alterUser.name,new K(!0,[]));q.set(nl.dropUser.name,new K(!0,[]));q.set(nl.listUsersExternal.name,new K(!0,[]));q.set(kf.listRoles.name,new K(!0,[]));q.set(kf.addRole.name,new K(!0,[]));q.set(kf.alterRole.name,new K(!0,[]));q.set(kf.dropRole.name,new K(!0,[]));q.set($7.name,new K(!0,[]));q.set(Y7.name,new K(!0,[]));q.set(K7.name,new K(!0,[]));q.set(W7.name,new K(!0,[]));q.set(Q7.name,new K(!0,[]));q.set(z7.name,new K(!0,[]));q.set(wg.setRoutes.name,new K(!0,[]));q.set(wg.getRoutes.name,new K(!0,[]));q.set(wg.deleteRoutes.name,new K(!0,[]));q.set(Uv.setConfiguration.name,new K(!0,[]));q.set(J7.clusterStatus.name,new K(!0,[]));q.set(X7.name,new K(!0,[]));q.set(Cg.getFingerprint.name,new K(!0,[]));q.set(Cg.setLicense.name,new K(!0,[]));q.set(Ig.deleteFilesBefore.name,new K(!0,[]));q.set(Ig.deleteAuditLogsBefore.name,new K(!0,[]));q.set(Cv.restart.name,new K(!0,[]));q.set(Cv.restartService.name,new K(!0,[]));q.set(k7.name,new K(!0,[]));q.set(V7.name,new K(!0,[Ps]));q.set(Z7.systemInformation.name,new K(!0,[]));q.set(Uv.getConfiguration.name,new K(!0,[]));q.set(Pv.readTransactionLog.name,new K(!0,[]));q.set(Pv.deleteTransactionLogsBefore.name,new K(!0,[]));q.set(vv.installModules.name,new K(!0,[]));q.set(vv.auditModules.name,new K(!0,[]));q.set(Lv.createTokens.name,new K(!1,[]));q.set(Lv.refreshOperationToken.name,new K(!1,[]));q.set(Mv.login.name,new K(!1,[]));q.set(Mv.logout.name,new K(!1,[]));q.set(Jr.customFunctionsStatus.name,new K(!0,[]));q.set(Jr.getCustomFunctions.name,new K(!0,[]));q.set(Jr.getComponents.name,new K(!0,[]));q.set(Jr.getComponentFile.name,new K(!0,[]));q.set(Jr.setComponentFile.name,new K(!0,[]));q.set(Jr.dropComponent.name,new K(!0,[]));q.set(Jr.getCustomFunction.name,new K(!0,[]));q.set(Jr.setCustomFunction.name,new K(!0,[]));q.set(Jr.dropCustomFunction.name,new K(!0,[]));q.set(Jr.addComponent.name,new K(!0,[]));q.set(Jr.dropCustomFunctionProject.name,new K(!0,[]));q.set(Jr.packageComponent.name,new K(!0,[]));q.set(Jr.deployComponent.name,new K(!0,[]));q.set(Cg.getRegistrationInfo.name,new K(!1,[]));q.set(nl.userInfo.name,new K(!1,[]));q.set(rl.describeAll.name,new K(!1,[]));q.set(ree,new K(!1,[]));q.set(nee,new K(!0,[]));q.set(tee,new K(!0,[]));q.set(Vf.CSV_DATA_LOAD,new K(!1,[gi,To]));q.set(Vf.CSV_URL_LOAD,new K(!1,[gi,To]));q.set(Vf.CSV_FILE_LOAD,new K(!1,[gi,To]));q.set(Vf.IMPORT_FROM_S3,new K(!1,[gi,To]));q.set(qv.EXPORT_TO_S3,new K(!0,[]));q.set(qv.EXPORT_LOCAL,new K(!0,[]));q.set(mn.VALID_SQL_OPS_ENUM.DELETE,new K(!1,[xv]));q.set(mn.VALID_SQL_OPS_ENUM.SELECT,new K(!1,[Ps]));q.set(mn.VALID_SQL_OPS_ENUM.INSERT,new K(!1,[gi]));q.set(mn.VALID_SQL_OPS_ENUM.UPDATE,new K(!1,[To]));kv.exports={verifyPerms:oee,verifyPermsAst:iee,verifyBulkLoadAttributePerms:cee};function iee(e,t,r){if(Us.isEmptyOrZeroLength(e))throw wt.info("verify_perms_ast has an empty user parameter"),Tr(new Error);if(Us.isEmptyOrZeroLength(t))throw wt.info("verify_perms_ast has an empty user parameter"),Tr(new Error);if(Us.isEmptyOrZeroLength(r))throw wt.info("verify_perms_ast has a null operation parameter"),Tr(new Error);try{let n=new Bv,s=new j7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw wt.info("No schemas defined in verifyPermsAst(), will not continue."),Tr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Fv[r])throw Tr(new Error,Vt.DROP_SYSTEM,el.FORBIDDEN);if(c&&!u)return null;let _=Dv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof eee.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=s.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=Gv(t,r,o,n);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=s.getAttributesBySchemaTableName(f,d[E]),S=Lg(t.role.permission,f,d[E]);Dg(h,S,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw Tr(n)}}a(iee,"verifyPermsAst");function oee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw wt.info("null required parameter in verifyPerms"),Tr(new Error,Vt.DEFAULT_INVALID_REQUEST,el.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new Bv;if(Us.isEmptyOrZeroLength(e.hdb_user.role)||Us.isEmptyOrZeroLength(e.hdb_user.role.permission))return wt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Vt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(mn.SYSTEM_SCHEMA_NAME)||s===mn.SYSTEM_SCHEMA_NAME;if(l&&Fv[r])throw Tr(new Error,Vt.DROP_SYSTEM,el.FORBIDDEN);if(u&&!l||_===!0&&(r===pn.createSchema.name||r===pn.dropSchema.name))return null;if(see.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=Dv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Iv||r===wv){if(s===mn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Vt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Iv&&(!d[s]||!d[s][tl]))return c.handleInvalidItem(Vt.SCHEMA_NOT_FOUND(s));if(r===wv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][tl]))return c.handleInvalidItem(Vt.TABLE_NOT_FOUND(s,i))}}let f=Gv(e.hdb_user,r,o,c,n);if(f)return f;if(q.get(r)&&q.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&mn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let S=[],p=d[s].tables[i];p[mn.PERMS_CRUD_ENUM.READ]&&(p.attribute_permissions.length>0?p.attribute_permissions.filter(A=>A[mn.PERMS_CRUD_ENUM.READ]).forEach(A=>{S.push(A.attribute_name)}):S=global.hdb_schema[s][i].attributes.map(g=>g.attribute),e.get_attributes=S)}let E=aee(e),h=Lg(e.hdb_user.role.permission,s,i);return Dg(E,h,r,i,s,c,n),c.getPermsResponse()}a(oee,"verifyPerms");function Gv(e,t,r,n,s){if(Us.arrayHasEmptyValues([e,t,r]))throw wt.info("hasPermissions has an invalid parameter"),Tr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||q.get(t).requires_su))return null;if(!q.get(t))throw wt.info(`operation ${t} not found.`),Tr(new Error,Vt.OP_NOT_FOUND(t),el.BAD_REQUEST);if(q.get(t)&&q.get(t).requires_su)return wt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Vt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][tl]===!1){n.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[tl]===!1)n.addInvalidItem(Vt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=q.get(t).perms;!Us.isEmpty(s)&&E.includes(s)&&(E=[s]);for(let h=0;h<E.length;h++){let S=E[h],p=d[S];(p==null||p===!1)&&(wt.info(`Required ${S} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(S))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=Vt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw wt.error(E),wt.error(f),Tr(Hv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Gv,"hasPermissions");function Dg(e,t,r,n,s,i,o){if(!e||!t)throw wt.info("no attributes specified in checkAttributePerms."),Tr(new Error);let c=q.get(r).perms;if(!c||c==="")throw wt.info(`no permissions found for ${r} in checkAttributePerms().`),Tr(new Error);if(Us.isEmptyOrZeroLength(t))return wt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[tl]===!1){i.addInvalidItem(Vt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(mn.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Ps)throw Tr(new Error,Vt.SYSTEM_TIMESTAMP_PERMS_ERR,el.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(Vt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Dg,"checkAttributePerms");function aee(e){let t=new Set;try{if(e.action)return t;if(e.operation===mn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){wt.info(r)}return t}a(aee,"getRecordAttributes");function Lg(e,t,r){let n=new Map;if(Us.isEmpty(e))return wt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{wt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Lg,"getAttributePermissions");function cee(e,t,r,n,s,i,o){let c=new Set(i),u=Lg(e,n,s);Dg(c,u,t,s,n,o,r)}a(cee,"verifyBulkLoadAttributePerms")});var Kf=T((zEe,Wv)=>{"use strict";Wv.exports={evaluateSQL:Ree,processAST:Kv,convertSQLToAST:Yv,checkASTPermissions:$v};var uee=on(),Vv=require("util"),lee=Vv.callbackify(uee.insert),_ee=sn().search,dee=zD().update,fee=Vv.callbackify(dee),Eee=XD().convertDelete,Ri=require("alasql"),hee=$f(),Yf=Y(),mee=V_(),pee=J(),sl=M(),{hdb_errors:See,handleHDBError:Mg}=Z(),{HTTP_STATUS_CODES:Ug}=See;mee(Ri);var Tee=403,gee="There was a problem performing this insert. Please check the logs and try again.",Pg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Ree(e,t){let r=e.parsed_sql_object;if(!r){r=Yv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ri.yy.Insert?n=s.into.databaseid:s instanceof Ri.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ri.yy.Update||s instanceof Ri.yy.Delete?n=s.table.databaseid:Yf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ri.yy.Select)&&pee.isEmptyOrZeroLength(n))return t("No schema specified",null)}Kv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Ree,"evaluateSQL");function $v(e,t){let r;try{r=hee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a($v,"checkASTPermissions");function Yv(e){let t=new Pg;if(!e)throw Mg(new Error,"The 'sql' parameter is missing from the request body",Ug.BAD_REQUEST);try{let r=e.trim(),n=Ri.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
17
|
-
`);throw n[1]?Mg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ug.BAD_REQUEST):Mg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ug.BAD_REQUEST)}return t}a(Yv,"convertSQLToAST");function Kv(e,t,r){try{let n=Aee;if(!e.bypass_auth&&!t.permissions_checked){let i=$v(e,t);if(i&&i.length>0)return r(Tee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case sl.VALID_SQL_OPS_ENUM.SELECT:n=_ee,s=t.ast.statements[0];break;case sl.VALID_SQL_OPS_ENUM.INSERT:n=Oee;break;case sl.VALID_SQL_OPS_ENUM.UPDATE:n=fee;break;case sl.VALID_SQL_OPS_ENUM.DELETE:n=Eee;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(Kv,"processAST");function Aee(e,t){Yf.info(e),t("unknown sql statement")}a(Aee,"nullFunction");function Oee({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=bee(i,e.values)}catch(o){return r(o)}lee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Yf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Oee,"convertInsert");function bee(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ri.compile(`SELECT ${s.toString()} AS [${sl.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Yf.error(r),new Error(gee)}}a(bee,"createDataObjects")});var vg=T((XEe,zv)=>{"use strict";var{S3:Nee,GetObjectCommand:yee}=require("@aws-sdk/client-s3");zv.exports={getFileStreamFromS3:Iee,getS3AuthObj:Qv};async function Iee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Qv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new yee(r))).Body}a(Iee,"getFileStreamFromS3");function Qv(e,t,r){return new Nee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Qv,"getS3AuthObj")});var Wf=T((ZEe,s0)=>{"use strict";var Hg=sn(),wee=Kf(),Cee=vg(),{AsyncParser:Dee,Transform:Lee}=require("json2csv"),ol=require("stream"),Xr=J(),Bg=require("fs-extra"),Mee=require("path"),Sn=Y(),{promisify:jv}=require("util"),il=J(),{handleHDBError:Tt,hdb_errors:Uee}=Z(),{HDB_ERROR_MSGS:gr,HTTP_STATUS_CODES:gt}=Uee,{streamAsJSON:Pee}=(bS(),ee($D)),{Upload:vee}=require("@aws-sdk/lib-storage"),Jv=["search_by_value","search_by_hash","sql","search_by_conditions"],Xv=["json","csv"],Zv="json",e0="csv",Bee="Successfully exported JSON locally.",Hee="Successfully exported CSV locally.",xee=1e3,Fee=Hg.searchByHash,qee=Hg.searchByValue,Gee=jv(wee.evaluateSQL),kee=jv(ol.finished);s0.exports={export_to_s3:Kee,export_local:Vee,toCsvStream:t0};async function Vee(e){Sn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=r0(e);if(!Xr.isEmpty(t))throw Sn.error(t),Tt(new Error,t,gt.BAD_REQUEST,void 0,void 0,!0);if(Xr.isEmpty(e.path))throw Sn.error(gr.MISSING_VALUE("path")),Tt(new Error,gr.MISSING_VALUE("path"),gt.BAD_REQUEST,void 0,void 0,!0);let r=(Xr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Mee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Xr.buildFolderPath(e.path,r);await $ee(e.path);let s=await n0(e);return await Yee(n,e.format,s)}a(Vee,"export_local");async function $ee(e){if(Sn.trace("in confirmPath"),Xr.isEmptyOrZeroLength(e))throw Tt(new Error,`Invalid path: ${e}`,gt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Bg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,Sn.error(n),Tt(new Error,n,gt.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 Sn.error(r),Tt(new Error,r,gt.BAD_REQUEST,void 0,void 0,!0)}return!0}a($ee,"confirmPath");async function Yee(e,t,r){if(Sn.trace("in saveToLocal"),il.isEmptyOrZeroLength(e))throw Tt(new Error,gr.INVALID_VALUE("file_path"),gt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmptyOrZeroLength(t))throw Tt(new Error,gr.INVALID_VALUE("Source format"),gt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmpty(r))throw Tt(new Error,gr.NOT_FOUND("Data"),gt.BAD_REQUEST,void 0,void 0,!0);if(t===Zv){let n=Bg.createWriteStream(e);return Pee(r).pipe(n),await kee(n),{message:Bee,path:e}}else if(t===e0){let n=Bg.createWriteStream(e),s=ol.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Dee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Hee,path:e}}throw Tt(new Error,gr.INVALID_VALUE("format"),gt.BAD_REQUEST)}a(Yee,"saveToLocal");async function Kee(e){if(!e.s3||Object.keys(e.s3).length===0)throw Tt(new Error,gr.MISSING_VALUE("S3 object"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Tt(new Error,gr.MISSING_VALUE("aws_access_key_id"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Tt(new Error,gr.MISSING_VALUE("aws_secret_access_key"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.bucket))throw Tt(new Error,gr.MISSING_VALUE("bucket"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.key))throw Tt(new Error,gr.MISSING_VALUE("key"),gt.BAD_REQUEST);if(Xr.isEmptyOrZeroLength(e.s3.region))throw Tt(new Error,gr.MISSING_VALUE("region"),gt.BAD_REQUEST);let t=r0(e);if(!Xr.isEmpty(t))throw Tt(new Error,t,gt.BAD_REQUEST);Sn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await n0(e)}catch(u){throw Sn.error(u),u}let n,s=await Cee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new ol.PassThrough;if(e.format===e0){i=e.s3.key+".csv";let u=t0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===Zv){i=e.s3.key+".json";let u=new ol.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%xee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Tt(new Error,gr.INVALID_VALUE("format"),gt.BAD_REQUEST);return new vee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Kee,"export_to_s3");function t0(e,t){let r=ol.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new Lee(n,s);return r.pipe(i)}a(t0,"toCsvStream");function r0(e){if(Sn.trace("in exportCoreValidation"),Xr.isEmpty(e.format))return"format missing";if(Xv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${Xv.join(", ")}`;let t=e.search_operation.operation;if(Xr.isEmpty(t))return"search_operation.operation missing";if(Jv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${Jv.join(", ")}`}a(r0,"exportCoreValidation");async function n0(e){Sn.trace("in getRecords");let t,r;if(il.isEmpty(e.search_operation)||il.isEmptyOrZeroLength(e.search_operation.operation))throw Tt(new Error,gr.INVALID_VALUE("Search operation"),gt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=qee;break;case"search_by_hash":t=Fee;break;case"search_by_conditions":t=Hg.searchByConditions;break;case"sql":t=Gee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Sn.error(r),Tt(new Error,r,gt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(n0,"getRecords")});var d0={};qe(d0,{contentTypes:()=>kg,findBestSerializer:()=>zf,getDeserializer:()=>Ro,registerContentHandlers:()=>Vg,serialize:()=>Jf,serializeMessage:()=>Ti});function Wee(e){try{return e?.[0]===123?Gg(e):e}catch{return e}}function Vg(e){e.register(zee,{serializers:[{regex:/^application\/json$/,serializer:mu},{regex:/^application\/cbor$/,serializer:function(t){return new go.EncoderStream(cl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Qf.Readable.from((0,os.encodeIter)(t,cl)):(0,os.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,os.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,go.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function zf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let S=h.indexOf("=");f[h.substring(0,S)]=h.substring(S+1)}d=+f.q;let E=xt.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(xt.keys()).join(", "))}};n=xt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Jf(e,t,r){let n=o0&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=zf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,vs.createBrotliCompress)({params:{[vs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?vs.constants.BROTLI_MODE_TEXT:vs.constants.BROTLI_MODE_GENERIC,[vs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>o0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,vs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function Ti(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return al(e);let r=t.serialize;if(r)return r(e);let n=zf(t);return r=t.serialize=n.serializer.serialize,r(e)}function Jee(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function Ro(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=xt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=xt.get(e)?.deserialize||a0(e,n);return o=>Jee(o).then(i)}return e&&xt.get(e)?.deserialize||a0(e,n)}function a0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Gg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Xee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var xg,os,go,vs,Qf,c0,Fg,qg,u0,l0,al,Gg,cl,xt,kg,i0,_0,Qee,zee,o0,Ia=Re(()=>{bS();xg=B(Wf()),os=require("msgpackr"),go=require("cbor-x"),vs=require("zlib"),Qf=require("stream");Zt();c0=require("../index"),Fg=B(j()),qg=B(M()),u0=B(require("yaml")),l0=Fg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,al=l0?so:JSON.stringify,Gg=l0?OS:JSON.parse,cl={useRecords:!1,useToJSON:!0},xt=new Map,kg=xt;ut.contentTypes=kg;(0,c0._assignPackageExport)("contentTypes",kg);xt.set("application/json",{serializeStream:mu,serialize:al,deserialize:Gg,q:.8});i0=new go.Encoder(cl);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new go.EncoderStream(cl).end(e)},serialize:i0.encode,deserialize:i0.decode,q:1});xt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Qf.Readable.from((0,os.encodeIter)(e,cl)):(0,os.pack)(e)},serialize:os.pack,deserialize:os.unpack,q:.9});xt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(e,e?.getColumns?.())},q:.1});xt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});xt.set("text/yaml",{serialize(e){return u0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});xt.set("text/event-stream",{serializeStream:function(e){return Qf.Readable.from(Xee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
15
|
+
`,""):null}catch(f){f.stderr?i[u].npm_error=nv(f.stderr):i[u].npm_error=f.message;continue}try{i[u].npm_output=JSON.parse(l)}catch{i[u].npm_output=l}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return Ca.info(`finished installModules with response ${i}`),i}a(o7,"installModules");function nv(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
|
|
16
|
+
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(nv,"parseNPMStdErr");async function a7(e){Ca.info(`starting auditModules for request: ${e}`);let t=iv(e);if(t)throw wa(t,t.message,Ia.BAD_REQUEST);let{projects:r}=e;await Df(),await sv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Cf.join(dg,o);n[o]={npm_output:null,npm_error:null};try{let u=await ju("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=nv(u.stderr)}}return Ca.info(`finished auditModules with response ${n}`),n}a(a7,"auditModules");async function Df(){try{return await ju("npm -v"),!0}catch{throw wa(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ia.BAD_REQUEST,void 0,void 0,!0)}}a(Df,"checkNPMInstalled");async function sv(e){if(!Array.isArray(e)||e.length===0)throw wa(new Error,"projects argument must be an array with at least 1 element",Ia.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Cf.join(dg,i.toString());if(!await ev.pathExists(o)){t.push(i);continue}let u=Cf.join(o,"package.json");await ev.pathExists(u)||r.push(i)}if(t.length>0)throw wa(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ia.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw wa(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ia.BAD_REQUEST,void 0,void 0,!0)}a(sv,"checkProjectPaths");function iv(e){let t=If.object({projects:If.array().min(1).items(If.string()).required(),dry_run:If.boolean().default(!1)});return t7.validateBySchema(e,t)}a(iv,"modulesValidator")});var Eg=T((UEe,_v)=>{"use strict";var Da=require("fs-extra"),fg=require("path"),Mf=W(),av=J(),Uf=U(),lv=Z(),c7=vr();_v.exports=u7;async function u7(){let e=l7(),t=lv.get(Uf.CONFIG_PARAMS.ROOTPATH),r=fg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Uf.PACKAGE_ROOT}},s=fg.join(t,"node_modules");await Da.ensureDir(s);let i,o=!0,c=!1;try{i=await Da.readJson(r)}catch(u){if(av.isEmptyOrZeroLength(e))return;if(u.code!==Uf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!av.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await cv(_);n.dependencies[u]=l+_}if(!o){Mf.notify("Installing components"),await uv(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await cv(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Mf.notify("Removing component",u),c=!0);c&&(Mf.notify("Updating components."),await uv(r,n,i))}a(u7,"installComponents");function l7(){let e=c7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(l7,"getComponentsConfig");async function cv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":fg.extname(e)||await Da.pathExists(e)?"file:":"github:"}a(cv,"getPkgPrefix");async function uv(e,t,r){Mf.trace("npm installing components package.json",t),await Da.writeFile(e,JSON.stringify(t,null," "));try{await Lf().installAllRootModules(lv.get(Uf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Da.writeFile(e,JSON.stringify(r,null," ")):await Da.unlink(e),n}}a(uv,"installPackages")});var pg=T((BEe,hv)=>{"use strict";var Ge=require("fs-extra"),hg=require("fast-glob"),Re=require("path"),fv=require("tar-fs"),vEe=require("uuid").v4,mg=require("normalize-path"),ns=ZP(),bt=W(),$e=U(),Et=Z(),Zu=vr(),_7=J(),{PACKAGE_ROOT:d7}=U(),{handleHDBError:Mt,hdb_errors:f7}=ee(),{basename:E7}=require("path"),h7=Eg(),Ev=Z(),m7=U(),{Readable:p7}=require("stream"),{isMainThread:S7}=require("worker_threads"),{HDB_ERROR_MSGS:So,HTTP_STATUS_CODES:Ut}=f7,T7=Re.join(d7,"application-template"),dv=Re.join(Et.get($e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function g7(){bt.trace("getting custom api status");let e={};try{e={port:Et.get($e.CONFIG_PARAMS.HTTP_PORT),directory:Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Mt(new Error,So.FUNCTION_STATUS,Ut.INTERNAL_SERVER_ERROR,bt.ERR,t)}return e}a(g7,"customFunctionsStatus");function R7(){bt.trace("getting custom api endpoints");let e={},t=Et.get($e.CONFIG_PARAMS.COMPONENTSROOT);try{hg.sync(mg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:hg.sync(mg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:hg.sync(mg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Mt(new Error,So.GET_FUNCTIONS,Ut.INTERNAL_SERVER_ERROR,bt.ERR,r)}return e}a(R7,"getCustomFunctions");function A7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=ns.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);bt.trace("getting custom api endpoint file content");let r=Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Re.join(r,n,s,i+".js");try{return Ge.readFileSync(o,{encoding:"utf8"})}catch(c){throw Mt(new Error,So.GET_FUNCTION,Ut.INTERNAL_SERVER_ERROR,bt.ERR,c)}}a(A7,"getCustomFunction");function O7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=ns.setCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);bt.trace("setting custom function file content");let r=Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Ge.outputFileSync(Re.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Mt(new Error,So.SET_FUNCTION,Ut.INTERNAL_SERVER_ERROR,bt.ERR,c)}}a(O7,"setCustomFunction");function b7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=ns.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);bt.trace("dropping custom function file");let r=Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Ge.unlinkSync(Re.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Mt(new Error,So.DROP_FUNCTION,Ut.INTERNAL_SERVER_ERROR,bt.ERR,o)}}a(b7,"dropCustomFunction");function N7(e){e.project&&(e.project=Re.parse(e.project).name);let t=ns.addComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);bt.trace("adding component");let r=Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Re.join(r,n);return Ge.mkdirSync(s,{recursive:!0}),Ge.copySync(T7,s),`Successfully added project: ${n}`}catch(s){throw Mt(new Error,So.ADD_FUNCTION,Ut.INTERNAL_SERVER_ERROR,bt.ERR,s)}}a(N7,"addComponent");function y7(e){e.project&&(e.project=Re.parse(e.project).name);let t=ns.dropCustomFunctionProjectValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);bt.trace("dropping custom function project");let r=Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Et.get($e.CONFIG_PARAMS.APPS);if(!_7.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return Zu.updateConfigValue($e.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Re.join(r,n);return Ge.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Mt(new Error,So.DROP_FUNCTION_PROJECT,Ut.INTERNAL_SERVER_ERROR,bt.ERR,i)}}a(y7,"dropCustomFunctionProject");async function w7(e){e.project&&(e.project=Re.parse(e.project).name);let t=ns.packageComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;bt.trace("packaging component",n);let s;try{s=await Ge.realpath(Re.join(r,n))}catch(u){if(u.code!==$e.NODE_ERROR_CODES.ENOENT)throw u;try{s=await Ge.realpath(Re.join(Et.get($e.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===$e.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Ge.ensureDir(dv);let i=Re.join(dv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Re.join(s,"node_modules"))}),fv.pack(s,o).pipe(Ge.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Ge.readFileSync(i,{encoding:"base64"});return await Ge.remove(i),{project:n,payload:c}}a(w7,"packageComponent");async function I7(e){e.project&&(e.project=Re.parse(e.project).name);let t=ns.deployComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(bt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Re.join(r,n),i="file:"+o,await Ge.ensureDir(o);let f=p7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{f.pipe(fv.extract(o,{finish:h})).on("error",p)});let E=await Ge.readdir(o);E.length===1&&E[0]==="package"&&(await Ge.copy(Re.join(o,"package"),o),await Ge.remove(Re.join(o,"package")))}if(await Zu.addConfig(n,{package:i}),!s){await h7();let f=Ev.get(m7.CONFIG_PARAMS.ROOTPATH);o=Re.join(f,"node_modules",n)}if(S7)return;let c=new Map;c.isWorker=!0;let u=(vf(),te(Pf)),_;u.setErrorReporter(f=>_=f);let l=E7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return bt.info("Installed component"),`Successfully deployed: ${n}`}a(I7,"deployComponent");async function C7(){let e=Zu.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await Ge.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Re.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await Ge.stat(d),E={name:Re.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return bt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),{name:Et.get($e.CONFIG_PARAMS.COMPONENTSROOT).split(Re.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Re.join(Et.get($e.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(vf(),te(Pf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(C7,"getComponents");async function D7(e){let t=ns.getComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let n=Zu.getConfigObj()[e.project]||e.project==="harperdb"?Re.join(Ev.get($e.CONFIG_PARAMS.ROOTPATH),"node_modules"):Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ge.stat(Re.join(n,e.project,e.file));return{message:await Ge.readFile(Re.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===$e.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Re.join(e.project,e.file)}'`):i}}a(D7,"getComponentFile");async function L7(e){let t=ns.setComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Re.join(Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Ge.ensureFile(n),await Ge.outputFile(n,e.payload,r)):await Ge.ensureDir(n),"Successfully set component: "+e.file}a(L7,"setComponentFile");async function M7(e){let t=ns.dropComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=e.file?Re.join(e.project,e.file):e.project,n=Re.join(Et.get($e.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ge.pathExists(n)&&await Ge.remove(n),Zu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(M7,"dropComponent");hv.exports={customFunctionsStatus:g7,getCustomFunctions:R7,getCustomFunction:A7,setCustomFunction:O7,dropCustomFunction:b7,addComponent:N7,dropCustomFunctionProject:y7,packageComponent:w7,deployComponent:I7,getComponents:C7,getComponentFile:D7,setComponentFile:L7,dropComponent:M7}});var Sg=T((xEe,pv)=>{"use strict";var ss=require("joi"),mv=Ze();pv.exports={readTransactionLogValidator:U7,deleteTransactionLogsBeforeValidator:P7};function U7(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 mv.validateBySchema(e,t)}a(U7,"readTransactionLogValidator");function P7(e){let t=ss.object({schema:ss.string().required(),table:ss.string().required(),timestamp:ss.date().timestamp().required()});return mv.validateBySchema(e,t)}a(P7,"deleteTransactionLogsBeforeValidator")});var Hf=T((qEe,Av)=>{"use strict";var Tg=U(),Bf=Ot(),Sv=J(),Tv=Z(),gv=Os(),{handleHDBError:La,hdb_errors:v7}=ee(),{HTTP_STATUS_CODES:Ma}=v7,{readTransactionLogValidator:B7,deleteTransactionLogsBeforeValidator:H7}=Sg(),Rv="This operation relies on clustering and cannot run with it disable.",x7="Logs successfully deleted from transaction log.",F7="All logs successfully deleted from transaction log.";Av.exports={readTransactionLog:q7,deleteTransactionLogsBefore:G7};async function*q7(e){let t=B7(e);if(t)throw La(t,t.message,Ma.BAD_REQUEST,void 0,void 0,!0);if(!Tv.get(Tg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw La(new Error,Rv,Ma.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Sv.checkSchemaTableExist(r,n);if(s)throw La(new Error,s,Ma.NOT_FOUND,void 0,void 0,!0);let i=gv.createNatsTableStreamName(r,n),o=await Bf.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===Tg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(q7,"readTransactionLog");async function G7(e){let t=H7(e);if(t)throw La(t,t.message,Ma.BAD_REQUEST,void 0,void 0,!0);if(!Tv.get(Tg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw La(new Error,Rv,Ma.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Sv.checkSchemaTableExist(r,n);if(i)throw La(new Error,i,Ma.NOT_FOUND,void 0,void 0,!0);let o=gv.createNatsTableStreamName(r,n),{jsm:c}=await Bf.getNATSReferences(),u=await Bf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=x7,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=F7):d=(await Bf.viewStream(o,parseInt(s),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(G7,"deleteTransactionLogsBefore")});var bv=T((kEe,Ov)=>{"use strict";var gg=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};Ov.exports=gg});var yv=T(($Ee,Nv)=>{"use strict";var Rg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Nv.exports=Rg});var Og=T((KEe,Iv)=>{"use strict";var wv=bv(),k7=yv(),{HDB_ERROR_MSGS:V7}=br(),Ag=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=V7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new wv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new k7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new wv(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};Iv.exports=Ag});var Gf=T((QEe,$v)=>{"use strict";var bg=rn(),xf=tn(),fn=xd(),rl=Gi(),Ng=Ki(),$7=HS(),Y7=qL(),nl=nn(),Ff=KS(),Nt=W(),K7=zS(),W7=tf(),Q7=LT(),z7=nf(),J7=MT(),X7=UT(),j7=BT(),Z7=xT(),yg=GT(),Ms=J(),eee=HU(),wg=KT(),Lv=Rf(),dn=U(),Mv=HP(),tee=Ta(),Uv=Cu(),Pv=(yf(),te(Qu)),vv=vr(),Wr=pg(),ree=require("alasql"),Bv=Hf(),Hv=Lf(),xv=Og(),{handleHDBError:hr,hdb_errors:Fv}=ee(),{HDB_ERROR_MSGS:Ft,HTTP_STATUS_CODES:el}=Fv,k=new Map,qv="delete",Si="insert",Us="read",To="update",tl="describe",Cv=rl.describeSchema.name,Dv=rl.describeTable.name,Gv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},nee="catchup",see="handleGetJob",iee="handleGetJobsByStartDate",qf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},oee=[fn.createTable.name,fn.createAttribute.name,fn.dropTable.name,fn.dropAttribute.name],kv={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}};k.set(bg.insert.name,new Q(!1,[Si]));k.set(bg.update.name,new Q(!1,[To]));k.set(bg.upsert.name,new Q(!1,[Si,To]));k.set(xf.searchByConditions.name,new Q(!1,[Us]));k.set(xf.searchByHash.name,new Q(!1,[Us]));k.set(xf.searchByValue.name,new Q(!1,[Us]));k.set(xf.search.name,new Q(!1,[Us]));k.set(fn.createSchema.name,new Q(!0,[]));k.set(fn.createTable.name,new Q(!0,[]));k.set(fn.createAttribute.name,new Q(!1,[Si]));k.set(fn.dropSchema.name,new Q(!0,[]));k.set(fn.dropTable.name,new Q(!0,[]));k.set(fn.dropAttribute.name,new Q(!0,[]));k.set(rl.describeSchema.name,new Q(!1,[Us]));k.set(rl.describeTable.name,new Q(!1,[Us]));k.set(Ng.deleteRecord.name,new Q(!1,[qv]));k.set(nl.addUser.name,new Q(!0,[]));k.set(nl.alterUser.name,new Q(!0,[]));k.set(nl.dropUser.name,new Q(!0,[]));k.set(nl.listUsersExternal.name,new Q(!0,[]));k.set(Ff.listRoles.name,new Q(!0,[]));k.set(Ff.addRole.name,new Q(!0,[]));k.set(Ff.alterRole.name,new Q(!0,[]));k.set(Ff.dropRole.name,new Q(!0,[]));k.set(K7.name,new Q(!0,[]));k.set(W7.name,new Q(!0,[]));k.set(Q7.name,new Q(!0,[]));k.set(z7.name,new Q(!0,[]));k.set(J7.name,new Q(!0,[]));k.set(X7.name,new Q(!0,[]));k.set(yg.setRoutes.name,new Q(!0,[]));k.set(yg.getRoutes.name,new Q(!0,[]));k.set(yg.deleteRoutes.name,new Q(!0,[]));k.set(vv.setConfiguration.name,new Q(!0,[]));k.set(j7.clusterStatus.name,new Q(!0,[]));k.set(Z7.name,new Q(!0,[]));k.set(wg.getFingerprint.name,new Q(!0,[]));k.set(wg.setLicense.name,new Q(!0,[]));k.set(Ng.deleteFilesBefore.name,new Q(!0,[]));k.set(Ng.deleteAuditLogsBefore.name,new Q(!0,[]));k.set(Lv.restart.name,new Q(!0,[]));k.set(Lv.restartService.name,new Q(!0,[]));k.set($7.name,new Q(!0,[]));k.set(Y7.name,new Q(!0,[Us]));k.set(tee.systemInformation.name,new Q(!0,[]));k.set(vv.getConfiguration.name,new Q(!0,[]));k.set(Bv.readTransactionLog.name,new Q(!0,[]));k.set(Bv.deleteTransactionLogsBefore.name,new Q(!0,[]));k.set(Hv.installModules.name,new Q(!0,[]));k.set(Hv.auditModules.name,new Q(!0,[]));k.set(Uv.createTokens.name,new Q(!1,[]));k.set(Uv.refreshOperationToken.name,new Q(!1,[]));k.set(Pv.login.name,new Q(!1,[]));k.set(Pv.logout.name,new Q(!1,[]));k.set(Wr.customFunctionsStatus.name,new Q(!0,[]));k.set(Wr.getCustomFunctions.name,new Q(!0,[]));k.set(Wr.getComponents.name,new Q(!0,[]));k.set(Wr.getComponentFile.name,new Q(!0,[]));k.set(Wr.setComponentFile.name,new Q(!0,[]));k.set(Wr.dropComponent.name,new Q(!0,[]));k.set(Wr.getCustomFunction.name,new Q(!0,[]));k.set(Wr.setCustomFunction.name,new Q(!0,[]));k.set(Wr.dropCustomFunction.name,new Q(!0,[]));k.set(Wr.addComponent.name,new Q(!0,[]));k.set(Wr.dropCustomFunctionProject.name,new Q(!0,[]));k.set(Wr.packageComponent.name,new Q(!0,[]));k.set(Wr.deployComponent.name,new Q(!0,[]));k.set(wg.getRegistrationInfo.name,new Q(!1,[]));k.set(nl.userInfo.name,new Q(!1,[]));k.set(rl.describeAll.name,new Q(!1,[]));k.set(see,new Q(!1,[]));k.set(iee,new Q(!0,[]));k.set(nee,new Q(!0,[]));k.set(qf.CSV_DATA_LOAD,new Q(!1,[Si,To]));k.set(qf.CSV_URL_LOAD,new Q(!1,[Si,To]));k.set(qf.CSV_FILE_LOAD,new Q(!1,[Si,To]));k.set(qf.IMPORT_FROM_S3,new Q(!1,[Si,To]));k.set(kv.EXPORT_TO_S3,new Q(!0,[]));k.set(kv.EXPORT_LOCAL,new Q(!0,[]));k.set(dn.VALID_SQL_OPS_ENUM.DELETE,new Q(!1,[qv]));k.set(dn.VALID_SQL_OPS_ENUM.SELECT,new Q(!1,[Us]));k.set(dn.VALID_SQL_OPS_ENUM.INSERT,new Q(!1,[Si]));k.set(dn.VALID_SQL_OPS_ENUM.UPDATE,new Q(!1,[To]));$v.exports={verifyPerms:cee,verifyPermsAst:aee,verifyBulkLoadAttributePerms:lee};function aee(e,t,r){if(Ms.isEmptyOrZeroLength(e))throw Nt.info("verify_perms_ast has an empty user parameter"),hr(new Error);if(Ms.isEmptyOrZeroLength(t))throw Nt.info("verify_perms_ast has an empty user parameter"),hr(new Error);if(Ms.isEmptyOrZeroLength(r))throw Nt.info("verify_perms_ast has a null operation parameter"),hr(new Error);try{let n=new xv,s=new eee(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Nt.info("No schemas defined in verifyPermsAst(), will not continue."),hr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Gv[r])throw hr(new Error,Ft.DROP_SYSTEM,el.FORBIDDEN);if(c&&!u)return null;let _=Mv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof ree.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=s.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=Vv(t,r,o,n);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=s.getAttributesBySchemaTableName(f,d[E]),p=Cg(t.role.permission,f,d[E]);Ig(h,p,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw hr(n)}}a(aee,"verifyPermsAst");function cee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Nt.info("null required parameter in verifyPerms"),hr(new Error,Ft.DEFAULT_INVALID_REQUEST,el.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new xv;if(Ms.isEmptyOrZeroLength(e.hdb_user.role)||Ms.isEmptyOrZeroLength(e.hdb_user.role.permission))return Nt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Ft.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(dn.SYSTEM_SCHEMA_NAME)||s===dn.SYSTEM_SCHEMA_NAME;if(l&&Gv[r])throw hr(new Error,Ft.DROP_SYSTEM,el.FORBIDDEN);if(u&&!l||_===!0&&(r===fn.createSchema.name||r===fn.dropSchema.name))return null;if(oee.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=Mv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Cv||r===Dv){if(s===dn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Ft.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Cv&&(!d[s]||!d[s][tl]))return c.handleInvalidItem(Ft.SCHEMA_NOT_FOUND(s));if(r===Dv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][tl]))return c.handleInvalidItem(Ft.TABLE_NOT_FOUND(s,i))}}let f=Vv(e.hdb_user,r,o,c,n);if(f)return f;if(k.get(r)&&k.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&dn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[dn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(g=>g[dn.PERMS_CRUD_ENUM.READ]).forEach(g=>{p.push(g.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(O=>O.attribute),e.get_attributes=p)}let E=uee(e),h=Cg(e.hdb_user.role.permission,s,i);return Ig(E,h,r,i,s,c,n),c.getPermsResponse()}a(cee,"verifyPerms");function Vv(e,t,r,n,s){if(Ms.arrayHasEmptyValues([e,t,r]))throw Nt.info("hasPermissions has an invalid parameter"),hr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||k.get(t).requires_su))return null;if(!k.get(t))throw Nt.info(`operation ${t} not found.`),hr(new Error,Ft.OP_NOT_FOUND(t),el.BAD_REQUEST);if(k.get(t)&&k.get(t).requires_su)return Nt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Ft.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][tl]===!1){n.addInvalidItem(Ft.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Ft.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[tl]===!1)n.addInvalidItem(Ft.TABLE_NOT_FOUND(u,l));else try{let f=[],E=k.get(t).perms;!Ms.isEmpty(s)&&E.includes(s)&&(E=[s]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(Nt.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=Ft.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Nt.error(E),Nt.error(f),hr(Fv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(Vv,"hasPermissions");function Ig(e,t,r,n,s,i,o){if(!e||!t)throw Nt.info("no attributes specified in checkAttributePerms."),hr(new Error);let c=k.get(r).perms;if(!c||c==="")throw Nt.info(`no permissions found for ${r} in checkAttributePerms().`),hr(new Error);if(Ms.isEmptyOrZeroLength(t))return Nt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[tl]===!1){i.addInvalidItem(Ft.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(dn.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Us)throw hr(new Error,Ft.SYSTEM_TIMESTAMP_PERMS_ERR,el.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(Ft.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Ig,"checkAttributePerms");function uee(e){let t=new Set;try{if(e.action)return t;if(e.operation===dn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){Nt.info(r)}return t}a(uee,"getRecordAttributes");function Cg(e,t,r){let n=new Map;if(Ms.isEmpty(e))return Nt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{Nt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Cg,"getAttributePermissions");function lee(e,t,r,n,s,i,o){let c=new Set(i),u=Cg(e,n,s);Ig(c,u,t,s,n,o,r)}a(lee,"verifyBulkLoadAttributePerms")});var Vf=T((JEe,zv)=>{"use strict";zv.exports={evaluateSQL:Oee,processAST:Qv,convertSQLToAST:Wv,checkASTPermissions:Kv};var _ee=rn(),Yv=require("util"),dee=Yv.callbackify(_ee.insert),fee=tn().search,Eee=XD().update,hee=Yv.callbackify(Eee),mee=ZD().convertDelete,Ti=require("alasql"),pee=Gf(),kf=W(),See=G_(),Tee=J(),sl=U(),{hdb_errors:gee,handleHDBError:Dg}=ee(),{HTTP_STATUS_CODES:Lg}=gee;See(Ti);var Ree=403,Aee="There was a problem performing this insert. Please check the logs and try again.",Mg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Oee(e,t){let r=e.parsed_sql_object;if(!r){r=Wv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ti.yy.Insert?n=s.into.databaseid:s instanceof Ti.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ti.yy.Update||s instanceof Ti.yy.Delete?n=s.table.databaseid:kf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ti.yy.Select)&&Tee.isEmptyOrZeroLength(n))return t("No schema specified",null)}Qv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Oee,"evaluateSQL");function Kv(e,t){let r;try{r=pee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Kv,"checkASTPermissions");function Wv(e){let t=new Mg;if(!e)throw Dg(new Error,"The 'sql' parameter is missing from the request body",Lg.BAD_REQUEST);try{let r=e.trim(),n=Ti.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
17
|
+
`);throw n[1]?Dg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Lg.BAD_REQUEST):Dg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Lg.BAD_REQUEST)}return t}a(Wv,"convertSQLToAST");function Qv(e,t,r){try{let n=bee;if(!e.bypass_auth&&!t.permissions_checked){let i=Kv(e,t);if(i&&i.length>0)return r(Ree,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case sl.VALID_SQL_OPS_ENUM.SELECT:n=fee,s=t.ast.statements[0];break;case sl.VALID_SQL_OPS_ENUM.INSERT:n=Nee;break;case sl.VALID_SQL_OPS_ENUM.UPDATE:n=hee;break;case sl.VALID_SQL_OPS_ENUM.DELETE:n=mee;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(Qv,"processAST");function bee(e,t){kf.info(e),t("unknown sql statement")}a(bee,"nullFunction");function Nee({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=yee(i,e.values)}catch(o){return r(o)}dee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){kf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Nee,"convertInsert");function yee(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ti.compile(`SELECT ${s.toString()} AS [${sl.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw kf.error(r),new Error(Aee)}}a(yee,"createDataObjects")});var Ug=T((jEe,Xv)=>{"use strict";var{S3:wee,GetObjectCommand:Iee}=require("@aws-sdk/client-s3");Xv.exports={getFileStreamFromS3:Cee,getS3AuthObj:Jv};async function Cee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Jv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Iee(r))).Body}a(Cee,"getFileStreamFromS3");function Jv(e,t,r){return new wee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Jv,"getS3AuthObj")});var $f=T((ehe,o0)=>{"use strict";var vg=tn(),Dee=Vf(),Lee=Ug(),{AsyncParser:Mee,Transform:Uee}=require("json2csv"),ol=require("stream"),Qr=J(),Pg=require("fs-extra"),Pee=require("path"),En=W(),{promisify:e0}=require("util"),il=J(),{handleHDBError:ht,hdb_errors:vee}=ee(),{HDB_ERROR_MSGS:mr,HTTP_STATUS_CODES:mt}=vee,{streamAsJSON:Bee}=(AS(),te(KD)),{Upload:Hee}=require("@aws-sdk/lib-storage"),jv=["search_by_value","search_by_hash","sql","search_by_conditions"],Zv=["json","csv"],t0="json",r0="csv",xee="Successfully exported JSON locally.",Fee="Successfully exported CSV locally.",qee=1e3,Gee=vg.searchByHash,kee=vg.searchByValue,Vee=e0(Dee.evaluateSQL),$ee=e0(ol.finished);o0.exports={export_to_s3:Qee,export_local:Yee,toCsvStream:n0};async function Yee(e){En.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=s0(e);if(!Qr.isEmpty(t))throw En.error(t),ht(new Error,t,mt.BAD_REQUEST,void 0,void 0,!0);if(Qr.isEmpty(e.path))throw En.error(mr.MISSING_VALUE("path")),ht(new Error,mr.MISSING_VALUE("path"),mt.BAD_REQUEST,void 0,void 0,!0);let r=(Qr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Pee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Qr.buildFolderPath(e.path,r);await Kee(e.path);let s=await i0(e);return await Wee(n,e.format,s)}a(Yee,"export_local");async function Kee(e){if(En.trace("in confirmPath"),Qr.isEmptyOrZeroLength(e))throw ht(new Error,`Invalid path: ${e}`,mt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Pg.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,En.error(n),ht(new Error,n,mt.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 En.error(r),ht(new Error,r,mt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Kee,"confirmPath");async function Wee(e,t,r){if(En.trace("in saveToLocal"),il.isEmptyOrZeroLength(e))throw ht(new Error,mr.INVALID_VALUE("file_path"),mt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmptyOrZeroLength(t))throw ht(new Error,mr.INVALID_VALUE("Source format"),mt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmpty(r))throw ht(new Error,mr.NOT_FOUND("Data"),mt.BAD_REQUEST,void 0,void 0,!0);if(t===t0){let n=Pg.createWriteStream(e);return Bee(r).pipe(n),await $ee(n),{message:xee,path:e}}else if(t===r0){let n=Pg.createWriteStream(e),s=ol.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Mee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Fee,path:e}}throw ht(new Error,mr.INVALID_VALUE("format"),mt.BAD_REQUEST)}a(Wee,"saveToLocal");async function Qee(e){if(!e.s3||Object.keys(e.s3).length===0)throw ht(new Error,mr.MISSING_VALUE("S3 object"),mt.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw ht(new Error,mr.MISSING_VALUE("aws_access_key_id"),mt.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw ht(new Error,mr.MISSING_VALUE("aws_secret_access_key"),mt.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.bucket))throw ht(new Error,mr.MISSING_VALUE("bucket"),mt.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.key))throw ht(new Error,mr.MISSING_VALUE("key"),mt.BAD_REQUEST);if(Qr.isEmptyOrZeroLength(e.s3.region))throw ht(new Error,mr.MISSING_VALUE("region"),mt.BAD_REQUEST);let t=s0(e);if(!Qr.isEmpty(t))throw ht(new Error,t,mt.BAD_REQUEST);En.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await i0(e)}catch(u){throw En.error(u),u}let n,s=await Lee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new ol.PassThrough;if(e.format===r0){i=e.s3.key+".csv";let u=n0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===t0){i=e.s3.key+".json";let u=new ol.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%qee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw ht(new Error,mr.INVALID_VALUE("format"),mt.BAD_REQUEST);return new Hee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Qee,"export_to_s3");function n0(e,t){let r=ol.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new Uee(n,s);return r.pipe(i)}a(n0,"toCsvStream");function s0(e){if(En.trace("in exportCoreValidation"),Qr.isEmpty(e.format))return"format missing";if(Zv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${Zv.join(", ")}`;let t=e.search_operation.operation;if(Qr.isEmpty(t))return"search_operation.operation missing";if(jv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${jv.join(", ")}`}a(s0,"exportCoreValidation");async function i0(e){En.trace("in getRecords");let t,r;if(il.isEmpty(e.search_operation)||il.isEmptyOrZeroLength(e.search_operation.operation))throw ht(new Error,mr.INVALID_VALUE("Search operation"),mt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=kee;break;case"search_by_hash":t=Gee;break;case"search_by_conditions":t=vg.searchByConditions;break;case"sql":t=Vee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,En.error(r),ht(new Error,r,mt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(i0,"getRecords")});var E0={};Fe(E0,{contentTypes:()=>qg,findBestSerializer:()=>Kf,getDeserializer:()=>Ro,registerContentHandlers:()=>Gg,serialize:()=>Wf,serializeMessage:()=>pi});function zee(e){try{return e?.[0]===123?Fg(e):e}catch{return e}}function Gg(e){e.register(Xee,{serializers:[{regex:/^application\/json$/,serializer:mu},{regex:/^application\/cbor$/,serializer:function(t){return new go.EncoderStream(cl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Yf.Readable.from((0,is.encodeIter)(t,cl)):(0,is.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Bg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,is.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,go.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Kf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=Pt.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(Pt.keys()).join(", "))}};n=Pt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Wf(e,t,r){let n=c0&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=Kf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Ps.createBrotliCompress)({params:{[Ps.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Ps.constants.BROTLI_MODE_TEXT:Ps.constants.BROTLI_MODE_GENERIC,[Ps.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>c0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Ps.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function pi(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return al(e);let r=t.serialize;if(r)return r(e);let n=Kf(t);return r=t.serialize=n.serializer.serialize,r(e)}function jee(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function Ro(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Pt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Pt.get(e)?.deserialize||u0(e,n);return o=>jee(o).then(i)}return e&&Pt.get(e)?.deserialize||u0(e,n)}function u0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Fg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Zee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var Bg,is,go,Ps,Yf,l0,Hg,xg,_0,d0,al,Fg,cl,Pt,qg,a0,f0,Jee,Xee,c0,ya=Oe(()=>{AS();Bg=x($f()),is=require("msgpackr"),go=require("cbor-x"),Ps=require("zlib"),Yf=require("stream");zt();l0=require("../index"),Hg=x(Z()),xg=x(U()),_0=x(require("yaml")),d0=Hg.default.get(xg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,al=d0?so:JSON.stringify,Fg=d0?RS:JSON.parse,cl={useRecords:!1,useToJSON:!0},Pt=new Map,qg=Pt;Xe.contentTypes=qg;(0,l0._assignPackageExport)("contentTypes",qg);Pt.set("application/json",{serializeStream:mu,serialize:al,deserialize:Fg,q:.8});a0=new go.Encoder(cl);Pt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new go.EncoderStream(cl).end(e)},serialize:a0.encode,deserialize:a0.decode,q:1});Pt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Yf.Readable.from((0,is.encodeIter)(e,cl)):(0,is.pack)(e)},serialize:is.pack,deserialize:is.unpack,q:.9});Pt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Bg.toCsvStream)(e,e?.getColumns?.())},q:.1});Pt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});Pt.set("text/yaml",{serialize(e){return _0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Pt.set("text/event-stream",{serializeStream:function(e){return Yf.Readable.from(Zee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
18
18
|
`),e.data){let r=e.data;typeof r=="object"&&(r=al(r)),t+="data: "+r+`
|
|
19
19
|
`}return e.id&&(t+="id: "+e.id+`
|
|
20
20
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
@@ -23,5 +23,8 @@ var Zx=Object.create;var za=Object.defineProperty;var eF=Object.getOwnPropertyDe
|
|
|
23
23
|
|
|
24
24
|
`:`data: ${e}
|
|
25
25
|
|
|
26
|
-
`},compressible:!1,q:.8});xt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});_0={type:"application/json",serializeStream:mu,serialize:al,deserialize:Wee,q:.8};xt.set("*/*",_0);xt.set("",_0);a(Wee,"tryJSONParse");a(Vg,"registerContentHandlers");Qee=require("fastify-plugin"),zee=Qee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=zf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(zf,"findBestSerializer");o0=Fg.default.get(qg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Jf,"serialize");a(Ti,"serializeMessage");a(Jee,"streamToBuffer");a(Ro,"getDeserializer");a(a0,"deserializerUnknownType");a(Xee,"transformIterable")});function S0(e){let t={openapi:jee,info:{title:"HarperDB HTTP REST interface",version:(0,p0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,{attributes:i,primaryKey:o,prototype:c}=n.Resource;if(o=o??"id",!o)continue;let u={},_=[];if(i)for(let{type:A,name:b}of i)u[b]=new m0(f0[A],A),_.push(new Kg(b,"query",u[b]));let l=Object.keys(u),d=new Kg(o,"path",new m0(f0.ID,"ID"));d.required=!0,d.description="primary key of record";let f=new Kg("property","path",{enum:l});f.required=!0,t.components.schemas[s]=new tte(u);let E=c.post!==Resource.prototype.post||c.update,h=c.hasOwnProperty("put"),S=c.hasOwnProperty("get"),p=c.hasOwnProperty("delete"),g="/"+s+"/";E&&(t.paths[g]={},t.paths[g].post=new Zee(s,r,"create a new record auto-assigning a primary key")),S&&(t.paths[g]||(t.paths[g]={}),t.paths[g].get=new $g(_,r,{200:new Yg({$ref:Xf+s})},"search for records by the specified property name and value")),p&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new h0(_,r,"delete all the records that match the provided query",{204:new E0})),g="/"+s+"/{"+o+"}",S&&(t.paths[g]={},t.paths[g].get=new $g([d],r,{200:new Yg({$ref:Xf+s})},"retrieve a record by its primary key")),h&&(t.paths[g]||(t.paths[g]={}),t.paths[g].put=new ete([d],r,s,"create or update the record with the URL path that maps to the record's primary key")),p&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new h0([d],r,"delete a record with the given primary key",{204:new E0})),S&&f.schema.enum.length>0&&(g="/"+s+"/{"+o+"}.{property}",t.paths[g]={},t.paths[g].get=new $g([d,f],r,{200:new Yg({enum:l})},"used to retrieve the specified property of the specified record"))}return t}function Zee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Xf+e}}}},this.security=t,this.responses={200:{description:Wg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function $g(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Yg(e){this.description=Wg,this.content={"application/json":{schema:e}}}function E0(){this.description="successfully processed request, no content returned to client"}function ete(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Xf+r}}}},this.responses={200:{description:Wg}}}function h0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function tte(e){this.type="object",this.properties=e}function m0(e,t){this.type=e,this.format=t}function Kg(e,t,r){this.name=e,this.in=t,this.schema=r}var p0,jee,f0,Xf,Wg,T0=Re(()=>{p0=B(Zd()),jee="3.0.3",f0={ID:"string",Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",Any:"string",BigInt:"integer"},Xf="#/components/schemas/",Wg="successful operation";a(S0,"generateJsonApi");a(Zee,"Post");a($g,"Get");a(Yg,"Response200");a(E0,"Response204");a(ete,"Put");a(h0,"Delete");a(tte,"ResourceSchema");a(m0,"Type");a(Kg,"Parameter")});var Zf={};qe(Zf,{start:()=>ste});async function nte(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&__(e);let s=new Si;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==g0){let h=jf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Xe(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=Ro(r["content-type"],!0)(e.body)}catch(h){throw new ll.ClientError(h,400)}if(e.authorize=!0,i===g0&&n==="GET")return S0(jf);switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new ll.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new ll.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,Qg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){rte[0]=d;let h=String.fromCharCode(34,($t[0]&63)+62,($t[0]>>6)+($t[1]<<2&63)+62,($t[1]>>4)+($t[2]<<4&63)+62,($t[2]>>2)+62,($t[3]&63)+62,($t[3]>>6)+($t[4]<<2&63)+62,($t[4]>>4)+($t[5]<<4&63)+62,($t[5]>>2)+62,($t[6]&63)+62,($t[6]>>6)+($t[7]<<2&63)+62,34),S=r["if-none-match"];S&&h==S?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),Qg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let f={status:l,headers:s,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=Jf(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?Ao.warn(i):Ao.info(i):Ao.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Jf(i.contentType?i:i.toString(),e,o),o}}function ste(e){Qg=e,!R0&&(R0=!0,jf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return nte(t,r)}),e.server.ws(async(t,r,n)=>{ul++;let s=new An;A0||(A0=!0,eu(l=>{ul>0&&l.push({metric:"ws-connections",connections:ul,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ao.warn(l)});let o;t.on("message",a(function(d){o||(o=Ro(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{ul--,un(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=jf.getMatch(u);if(un(!!_,"connection","ws","connect"),!_)t.send(Ti(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Gr(h=>({count:h.count,total:ul}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Xe(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ti(E.value,r);t.send(h),Gr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var Ao,ll,$t,rte,Qg,g0,R0,jf,A0,ul,O0=Re(()=>{Ia();Ns();Ao=B(Y()),ll=B(Z());d_();uc();Ui();Nf();T0();$t=new Uint8Array(8),rte=new Float64Array($t.buffer,0,1),Qg={},g0="openapi";a(nte,"http");ul=0;a(ste,"start")});var zg=T((Ehe,b0)=>{var{recordAction:eE,recordActionBinary:ite}=(Ns(),ee(tu)),ote=require("fastify-plugin"),ate=200;b0.exports=ote(function(e,t,r){e.addHook("onResponse",async(n,s)=>{s.getResponseTime()}),e.addHook("onSend",async(n,s,i)=>{let o=s.getResponseTime(),c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),eE(o,"duration",_,d,l),ite(s.raw.statusCode<400,"success",_,d,l);let f=ate;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{eE(performance.now()-c,"transfer",_,d,l),eE(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,eE(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Zg=T((hhe,C0)=>{var iE=require("clone"),oE=rt(),cte=J(),nE=M(),ute=Y(),tE=require("fs"),Jg=require("joi"),{string:sE}=Jg.types(),{hdb_errors:lte,handleHDBError:_l}=Z(),{HDB_ERROR_MSGS:_te,HTTP_STATUS_CODES:rE}=lte,{common_validators:Pa}=Yn(),N0=1e9,y0=" is required",dte=["insert","update","upsert"],Xg={database:{presence:!1,format:Pa.schema_format,length:Pa.schema_length},schema:{presence:!1,format:Pa.schema_format,length:Pa.schema_length},table:{presence:!0,format:Pa.schema_format,length:Pa.schema_length},action:{inclusion:{within:dte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},fte={schema:sE.required(),table:sE.required(),action:sE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Ete,AWS_SECRET:hte,AWS_BUCKET:mte,AWS_FILE_KEY:pte,REGION:Ste}=nE.S3_BUCKET_AUTH_KEYS,Tte={s3:{presence:!0},[`s3.${Ete}`]:{presence:!0,type:"String"},[`s3.${hte}`]:{presence:!0,type:"String"},[`s3.${mte}`]:{presence:!0,type:"String"},[`s3.${pte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Ste}`]:{presence:!0,type:"String"}},I0=iE(Xg);I0.data.presence={message:y0};var w0=iE(Xg);w0.file_path.presence={message:y0};var gte=Object.assign(iE(Xg),Tte),jg=iE(fte);jg.csv_url=sE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();jg.passthrough_headers=Jg.object();function Rte(e){let t=oE.validateObject(e,I0);return aE(e,t)}a(Rte,"dataObject");function Ate(e){let t=oE.validateBySchema(e,Jg.object(jg));return aE(e,t)}a(Ate,"urlObject");function Ote(e){let t=oE.validateObject(e,w0);return aE(e,t)}a(Ote,"fileObject");function bte(e){let t=oE.validateObject(e,gte);return aE(e,t)}a(bte,"s3FileObject");function aE(e,t){if(!t){let r=cte.checkGlobalSchemaTable(e.schema,e.table);if(r)return _l(new Error,r,rE.BAD_REQUEST);if(e.operation===nE.OPERATIONS_ENUM.CSV_FILE_LOAD){try{tE.accessSync(e.file_path,tE.constants.R_OK|tE.constants.F_OK)}catch(n){return n.code===nE.NODE_ERROR_CODES.ENOENT?_l(n,`No such file or directory ${n.path}`,rE.BAD_REQUEST):n.code===nE.NODE_ERROR_CODES.EACCES?_l(n,`Permission denied ${n.path}`,rE.BAD_REQUEST):_l(n)}try{let n=tE.statSync(e.file_path).size;if(n>N0)return _l(new Error,_te.MAX_FILE_SIZE_ERR(n,N0),rE.BAD_REQUEST)}catch(n){ute.error(n),console.error(n)}}}return t}a(aE,"postValidateChecks");C0.exports={dataObject:Rte,urlObject:Ate,fileObject:Ote,s3FileObject:bte}});var eR=T((phe,D0)=>{"use strict";var dl=Y(),cE=M();async function Nte(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===cE.OPERATIONS_ENUM.INSERT||t.operation===cE.OPERATIONS_ENUM.UPDATE||t.operation===cE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===cE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(dl.info(i.message),i):i.http_resp_msg?(dl.error(`Error calling operation: ${e.name}`),dl.error(i.http_resp_msg),i):(dl.error(`Error calling operation: ${e.name}`),dl.error(i),i)}}a(Nte,"callOperationFunctionAsAwait");D0.exports={callOperationFunctionAsAwait:Nte}});var M0=T((The,L0)=>{"use strict";var tR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},rR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};L0.exports={BulkLoadFileObject:tR,BulkLoadDataObject:rR}});var P0=T((Rhe,U0)=>{"use strict";var nR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};U0.exports=nR});var uR=T((Ihe,X0)=>{"use strict";var uE=on(),_E=Zg(),yte=require("needle"),Hn=M(),Ohe=nt(),va=J(),{handleHDBError:at,hdb_errors:V0}=Z(),{HTTP_STATUS_CODES:Yt,HDB_ERROR_MSGS:Ct,CHECK_LOGS_WRAPPER:bo}=V0,Ba=Y(),sR=require("papaparse");va.promisifyPapaParse();var xn=require("fs-extra"),Ite=require("path"),{chain:v0}=require("stream-chain"),B0=require("stream-json/streamers/StreamArray"),H0=require("stream-json/utils/Batch"),x0=require("stream-chain/utils/comp"),{finished:F0}=require("stream"),wte=j(),$0=eR(),Cte=vg(),{BulkLoadFileObject:oR,BulkLoadDataObject:Dte}=M0(),aR=Ng(),{verifyBulkLoadAttributePerms:Y0}=$f(),bhe=P0(),Nhe=yt(),yhe=bs(),{databases:Lte}=(Oe(),ee(Ge)),{coerceType:Mte}=(Td(),ee(iS)),q0="No records parsed from csv file.",Oo=`${wte.get("HDB_ROOT")}/tmp`,{schema_regex:Ute}=Yn(),G0=1024*1024*2,k0=5e3,Pte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};X0.exports={csvDataLoad:vte,csvURLLoad:Bte,csvFileLoad:Hte,importFromS3:xte};async function vte(e,t){let r=_E.dataObject(e);if(r)throw at(r,r.message,Yt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=Q0(e.schema,e.table),i=sR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:iR.bind(null,s),dynamicTyping:!1}),o=new aR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&Y0(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw at(new Error,c,Yt.BAD_REQUEST,void 0,void 0,!0);let u=new Dte(e.action,e.schema,e.table,i.data);return n=await $0.callOperationFunctionAsAwait(z0,u,null),n.message===q0?q0:J0(n.records,n.number_written)}catch(s){throw No(s)}}a(vte,"csvDataLoad");async function Bte(e){let t=_E.urlObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Oo}/${r}`;try{await Fte(e,r)}catch(s){throw Ba.error(Ct.DOWNLOAD_FILE_ERR(r)+" - "+s),at(s,bo(Ct.DOWNLOAD_FILE_ERR(r)))}try{let s=new oR(this.job_operation_function.name,e.action,e.schema,e.table,n,Hn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await cR(s);return await lE(n),i}catch(s){throw await lE(n),No(s)}}a(Bte,"csvURLLoad");async function Hte(e){let t=_E.fileObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r=new oR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Hn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await cR(r)}catch(n){throw No(n)}}a(Hte,"csvFileLoad");async function xte(e){let t=_E.s3FileObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Ite.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Oo}/${s}`;let i=new oR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await qte(s,e);let o=await cR(i);return await lE(r),o}catch(n){throw await lE(r),No(n)}}a(xte,"importFromS3");async function Fte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await yte("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw at(n,s,n.statusCode,Hn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}kte(r,e.csv_url),await Gte(t,r.raw)}a(Fte,"downloadCSVFile");async function qte(e,t){try{let r=`${Oo}/${e}`;await xn.mkdirp(Oo),await xn.writeFile(`${Oo}/${e}`,"",{flag:"a+"});let n=await xn.createWriteStream(r),s=await Cte.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){Ba.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ba.error(Ct.S3_DOWNLOAD_ERR+" - "+r),at(r,bo(Ct.S3_DOWNLOAD_ERR))}}a(qte,"downloadFileFromS3");async function Gte(e,t){try{await xn.mkdirp(Oo),await xn.writeFile(`${Oo}/${e}`,t)}catch(r){throw Ba.error(Ct.WRITE_TEMP_FILE_ERR),at(r,bo(Ct.DEFAULT_BULK_LOAD_ERR))}}a(Gte,"writeFileToTempFolder");async function lE(e){if(e)try{await xn.access(e),await xn.unlink(e)}catch{Ba.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(lE,"deleteTempFile");function kte(e,t){if(e.statusCode!==V0.HTTP_STATUS_CODES.OK)throw at(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Yt.BAD_REQUEST);if(!Pte[e.headers["content-type"]])throw at(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Yt.BAD_REQUEST);if(!e.raw)throw at(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Yt.BAD_REQUEST)}a(kte,"validateURLResponse");async function cR(e){try{let t;switch(e.file_type){case Hn.VALID_S3_FILE_TYPES.CSV:t=await Vte(e);break;case Hn.VALID_S3_FILE_TYPES.JSON:t=await $te(e);break;default:throw at(new Error,Ct.DEFAULT_BULK_LOAD_ERR,Yt.BAD_REQUEST,Hn.LOG_LEVELS.ERROR,Ct.INVALID_FILE_EXT_ERR(e))}return J0(t.records,t.number_written)}catch(t){throw No(t)}}a(cR,"fileLoad");async function K0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await uE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&Y0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=at(c);r(u)}}a(K0,"validateChunk");async function W0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;va.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!va.isEmpty(c)&&!va.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await $0.callOperationFunctionAsAwait(z0,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=at(c,bo(Ct.INSERT_CSV_ERR),Yt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Ct.INSERT_CSV_ERR+" - "+c);r(u)}}a(W0,"insertChunk");async function Vte(e){let t={records:0,number_written:0},r=Q0(e.schema,e.table);try{let n=new aR,s=xn.createReadStream(e.file_path,{highWaterMark:G0});s.setEncoding("utf8"),await sR.parsePromise(s,K0.bind(null,e,n),iR.bind(null,r));let i=n.getPermsResponse();if(i)throw at(new Error,i,Yt.BAD_REQUEST);return s=xn.createReadStream(e.file_path,{highWaterMark:G0}),s.setEncoding("utf8"),await sR.parsePromise(s,W0.bind(null,e,t),iR.bind(null,r)),s.destroy(),t}catch(n){throw at(n,bo(Ct.PAPA_PARSE_ERR),Yt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Ct.PAPA_PARSE_ERR+n)}}a(Vte,"callPapaParse");function Q0(e,t){let r=Lte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Mte(i,s));return n}a(Q0,"createTransformMap");function iR(e,t,r){let n=e.get(r);return n?n(t):va.autoCast(t)}a(iR,"typeFunction");async function $te(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new aR,s=v0([xn.createReadStream(e.file_path,{encoding:"utf-8"}),B0.withParser(),c=>c.value,new H0({batchSize:k0}),x0(async c=>{await K0(e,n,r,c)})]);await new Promise((c,u)=>{F0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw at(new Error,i,Yt.BAD_REQUEST);let o=v0([xn.createReadStream(e.file_path,{encoding:"utf-8"}),B0.withParser(),c=>c.value,new H0({batchSize:k0}),x0(async c=>{await W0(e,t,r,c)})]);return await new Promise((c,u)=>{F0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw at(n,bo(Ct.INSERT_JSON_ERR),Yt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Ct.INSERT_JSON_ERR+n)}}a($te,"insertJson");async function z0(e){let t={};try{e.data&&e.data.length>0&&Yte(e.data[0])?t=await Kte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ba.info(t.message))}catch(r){throw No(r)}return t}a(z0,"callBulkFileLoad");function Yte(e){let t=Object.keys(e);for(let r of t)if(!Ute.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Yte,"validateColumnNames");async function Kte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=uE.insert;break;case"update":i=uE.update;break;case"upsert":i=uE.upsert;break;default:throw at(new Error,Ct.INVALID_ACTION_PARAM_ERR(n),Yt.BAD_REQUEST,Hn.LOG_LEVELS.ERROR,Ct.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=va.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw No(o)}}a(Kte,"bulkFileLoad");function J0(e,t){return`successfully loaded ${t} of ${e} records`}a(J0,"buildResponseMsg");function No(e){return at(e,bo(Ct.DEFAULT_BULK_LOAD_ERR),Yt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Ct.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(No,"buildTopLevelErrMsg")});var Z0=T((Che,j0)=>{"use strict";var lR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};j0.exports=lR});var rB=T((Lhe,tB)=>{"use strict";var Wte=M(),eB=require("moment"),Qte=require("uuid").v4,_R=class{static{a(this,"JobObject")}constructor(){this.id=Qte(),this.type=void 0,this.start_datetime=eB().valueOf(),this.created_datetime=eB().valueOf(),this.end_datetime=void 0,this.status=Wte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};tB.exports=_R});var dR=T((Uhe,cB)=>{"use strict";var zte=require("uuid").v4,iB=on(),oB=sn(),Jte=Wn(),Xte=jo(),jte=Z0(),ct=M(),Zte=rB(),ere=eT(),Tn=Y(),tre=yc(),Ha=J(),{promisify:rre}=require("util"),yo=require("moment"),nre=Kf(),dE=Zg(),nB=Op(),{deleteTransactionLogsBeforeValidator:sre}=gg(),{handleHDBError:ire,hdb_errors:ore}=Z(),{HTTP_STATUS_CODES:are}=ore,sB=oB.searchByValue,cre=oB.searchByHash,ure=iB.insert,lre=rre(nre.evaluateSQL),_re=iB.update;cB.exports={addJob:Ere,updateJob:mre,handleGetJob:dre,handleGetJobsByStartDate:fre,getJobById:aB};async function dre(e){try{let t=await aB(e.id);return Ha.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 Tn.error("There was an error getting job",t),new Error(r)}}a(dre,"handleGetJob");async function fre(e){try{let t=await hre(e);if(Tn.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=yo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=yo(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 Tn.error(r),new Error(r)}}a(fre,"handleGetJobsByStartDate");async function Ere(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ha.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Tn.info(l),t.error=l,t}if(!ct.JOB_TYPE_ENUM[e.operation])return Tn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case ct.OPERATIONS_ENUM.CSV_FILE_LOAD:n=dE.fileObject(e);break;case ct.OPERATIONS_ENUM.CSV_URL_LOAD:n=dE.urlObject(e);break;case ct.OPERATIONS_ENUM.CSV_DATA_LOAD:n=dE.dataObject(e);break;case ct.OPERATIONS_ENUM.IMPORT_FROM_S3:n=dE.s3FileObject(e);break;case ct.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ct.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=nB(e,"date");break;case ct.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=nB(e,"timestamp");break;case ct.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=sre(e);break;default:break}if(n)throw ire(n,n.message,are.BAD_REQUEST,void 0,void 0,!0);let s=new Zte;s.type=e.operation===ct.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ct.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new Jte(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await sB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Tn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=zte();try{o=await sB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Tn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Tn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new tre(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await ure(u)}catch(l){return Tn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,Tn.trace(l)}return t}a(Ere,"addJob");async function hre(e){let t=yo(e.from_date,yo.ISO_8601),r=yo(e.to_date,yo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new jte(n,e.hdb_user);try{return await lre(s)}catch(i){throw Tn.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(hre,"getJobsInDateRange");async function aB(e){if(Ha.isEmptyOrZeroLength(e))return Ha.errorizeMessage("Invalid job ID specified.");let t=new Xte(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await cre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Tn.error(n),Ha.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(aB,"getJobById");async function mre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ha.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ct.JOB_STATUS_ENUM.COMPLETE||e.status===ct.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=yo().valueOf());let t=new ere(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await _re(t),r}a(mre,"updateJob")});var EB=T((vhe,fB)=>{"use strict";var uB=J(),Rr=M(),pre=require("moment"),fE=uR(),EE=Y(),lB=dR(),_B=Wf(),dB=Ki(),Sre=tt(),Tre=qf(),fR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function gre(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(uB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(uB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Rr.JOB_TYPE_ENUM.csv_file_load:await Bs(e,fE.csvFileLoad);break;case Rr.JOB_TYPE_ENUM.csv_url_load:await Bs(e,fE.csvURLLoad);break;case Rr.JOB_TYPE_ENUM.csv_data_load:await Bs(e,fE.csvDataLoad);break;case Rr.JOB_TYPE_ENUM.import_from_s3:await Bs(e,fE.importFromS3);break;case Rr.JOB_TYPE_ENUM.empty_trash:break;case Rr.JOB_TYPE_ENUM.export_local:await Bs(e,_B.export_local);break;case Rr.JOB_TYPE_ENUM.export_to_s3:await Bs(e,_B.export_to_s3);break;case Rr.JOB_TYPE_ENUM.delete_files_before:case Rr.JOB_TYPE_ENUM.delete_records_before:await Bs(e,dB.deleteFilesBefore);break;case Rr.JOB_TYPE_ENUM.delete_audit_logs_before:await Bs(e,dB.deleteAuditLogsBefore);break;case Rr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Bs(e,Tre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(gre,"parseMessage");async function Bs(e,t){try{e.job.status=Rr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=pre().valueOf(),await lB.updateJob(e.job),await Rre(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):EE.error(`There was an error running ${t.name} job with id ${e.job.id}`),EE.error(n),e.job.message=n,e.job.status=Rr.JOB_STATUS_ENUM.ERROR;try{await lB.updateJob(e.job)}catch(s){throw EE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Bs,"runJob");async function Rre(e){EE.trace("launching job thread:",e),Sre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Rr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Rre,"launchJobThread");fB.exports={parseMessage:gre,RunnerMessage:fR}});var mB=T((Hhe,hB)=>{"use strict";var ER=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};hB.exports=ER});var UB=T((Fhe,gR)=>{"use strict";var SE=sn(),pR=Kf(),hE=uR(),Hs=Gd(),mE=Gi(),El=Ki(),Are=FS(),fl=cn(),pE=QS(),Kt=Tg(),Dt=Y(),Ore=XS(),bre=sf(),pB=UT(),Nre=af(),yre=PT(),Ire=vT(),wre=xT(),Cre=qT(),hR=VT(),SB=Wf(),Dre=$f(),SR=dR(),F=M(),{hdb_errors:ml,handleHDBError:hl}=Z(),{HTTP_STATUS_CODES:TB}=ml,mR=QT(),gB=bf(),CB=require("util"),xa=on(),Lre=ti(),Mre=ga(),RB=EB(),AB=Cu(),OB=(Cf(),ee(Qu)),bB=xr(),NB=qf(),yB=Pf(),{setServerUtilities:Ure}=(Td(),ee(iS)),{CONTEXT:Pre}=(On(),ee(Vh)),{_assignPackageExport:vre}=require("../index"),{transformReq:Bre}=J(),{server:Hre}=(Zt(),ee(yi)),xre=eR(),IB=SE.searchByHash,Fre=SE.searchByValue,qre=CB.promisify(SE.search),Gre=CB.promisify(pR.evaluateSQL),kre={[F.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.CREATE_TABLE]:!0,[F.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[F.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.DROP_TABLE]:!0,[F.OPERATIONS_ENUM.DROP_SCHEMA]:!0},V=mB();async function DB(e,t){try{if(e.body.operation!=="read_log"&&(Dt.log_level===F.LOG_LEVELS.INFO||Dt.log_level===F.LOG_LEVELS.DEBUG||Dt.log_level===F.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;Dt.info(o)}}catch(n){Dt.error(n)}let r=await xre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return kre[e.body.operation]&&Lre.setSchemaDataToGlobal(n=>{n&&Dt.error(n)}),r}a(DB,"processLocalTransaction");var wB=$re();gR.exports={chooseOperation:LB,getOperationFunction:MB,operation:TR,processLocalTransaction:DB};Ure(gR.exports);Hre.operation=TR;function LB(e){let t;try{t=MB(e)}catch(s){throw Dt.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=pR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=pR.checkASTPermissions(e,i);if(o)throw Dt.error(`${TB.FORBIDDEN} from operation ${e.operation}`),Dt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),hl(new Error,o,ml.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==F.OPERATIONS_ENUM.LOGIN&&e.operation!==F.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Dre.verifyPerms(i,s);if(o)throw Dt.error(`${TB.FORBIDDEN} from operation ${e.operation}`),Dt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),hl(new Error,o,ml.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw hl(s,"There was an error when trying to choose an operation path")}return r}a(LB,"chooseOperation");function MB(e){if(Dt.trace(`getOperationFunction with operation: ${e.operation}`),wB.has(e.operation))return wB.get(e.operation);throw hl(new Error,ml.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),ml.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(MB,"getOperationFunction");vre("operation",TR);function TR(e,t){e.hdb_user=this[Pre]?.user,e.bypass_auth=!t;let r=LB(e);return DB({body:e},r)}a(TR,"operation");async function Vre(e){Dt.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await xa.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await xa.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await xa.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await El.deleteRecord(i);break;default:Dt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Dt.info("Invalid operation in transaction"),Dt.error(o)}}a(Vre,"catchup");async function as(e){Bre(e);let t,r;try{r=await SR.addJob(e),t=r.createdJob,Dt.info("addJob result",r);let n=new RB.RunnerMessage(t,e);return await RB.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw Dt.error(s),hl(n,s)}}a(as,"executeJob");function $re(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new V(xa.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new V(xa.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new V(xa.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new V(SE.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new V(IB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new V(IB)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new V(Fre)),e.set(F.OPERATIONS_ENUM.SEARCH,new V(qre)),e.set(F.OPERATIONS_ENUM.SQL,new V(Gre)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new V(as,hE.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new V(as,hE.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new V(as,hE.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new V(as,hE.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new V(Hs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new V(Hs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new V(Hs.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new V(Hs.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new V(Hs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new V(Hs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new V(Hs.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new V(Hs.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new V(mE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new V(mE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new V(mE.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new V(mE.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new V(El.deleteRecord)),e.set(F.OPERATIONS_ENUM.ADD_USER,new V(fl.addUser)),e.set(F.OPERATIONS_ENUM.ALTER_USER,new V(fl.alterUser)),e.set(F.OPERATIONS_ENUM.DROP_USER,new V(fl.dropUser)),e.set(F.OPERATIONS_ENUM.LIST_USERS,new V(fl.listUsersExternal)),e.set(F.OPERATIONS_ENUM.LIST_ROLES,new V(pE.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new V(pE.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new V(pE.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new V(pE.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new V(fl.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new V(Ore)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new V(bre)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new V(pB)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new V(pB)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new V(Nre)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new V(yre)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new V(Ire)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new V(bB.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new V(wre.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new V(Cre)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new V(hR.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new V(hR.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new V(hR.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new V(as,SB.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new V(as,El.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new V(as,El.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new V(as,SB.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new V(SR.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new V(SR.handleGetJob)),e.set(F.OPERATIONS_ENUM.GET_FINGERPRINT,new V(mR.getFingerprint)),e.set(F.OPERATIONS_ENUM.SET_LICENSE,new V(mR.setLicense)),e.set(F.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new V(mR.getRegistrationInfo)),e.set(F.OPERATIONS_ENUM.RESTART,new V(gB.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new V(gB.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new V(Vre)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new V(Mre.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new V(as,El.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new V(Are)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new V(AB.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new V(AB.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new V(OB.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new V(OB.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new V(bB.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new V(Kt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new V(Kt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new V(Kt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new V(Kt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new V(Kt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new V(Kt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new V(Kt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new V(Kt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new V(Kt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new V(Kt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new V(Kt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new V(Kt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new V(Kt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new V(Kt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new V(Kt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new V(Kt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new V(NB.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new V(as,NB.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new V(yB.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new V(yB.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new V(Hs.getBackup)),e}a($re,"initializeOperationFunctionMap")});var gE=T((Ghe,BB)=>{"use strict";var RR=M(),Yre=J(),pl=Y(),{handleHDBError:AR,hdb_errors:TE}=Z(),{isMainThread:Kre}=require("worker_threads"),{Readable:Wre}=require("stream"),PB=require("os"),Qre=require("util"),zre=cT(),Jre=Qre.promisify(zre.authorize),vB=UB(),{createGzip:Xre,constants:jre}=require("zlib");function Zre(e){let t=`Found an uncaught exception with message: ${e.message}. ${PB.EOL}Stack: ${e.stack} ${PB.EOL}Terminating ${Kre?"HDB":"thread"}.`;console.error(t),pl.fatal(t),process.exit(1)}a(Zre,"handleServerUncaughtException");function ene(e,t,r){if(pl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:TE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(ene,"serverErrorHandler");function tne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=AR(new Error,"Invalid JSON.",TE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Yre.isEmpty(e.body.operation)){let n=AR(new Error,"Request body must include an 'operation' property.",TE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(tne,"reqBodyValidationHandler");function rne(e,t,r){let n;e.body.operation!==RR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==RR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==RR.OPERATIONS_ENUM.LOGOUT?Jre(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{pl.warn(s),pl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(AR(s,i,TE.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(rne,"authHandler");async function nne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=vB.chooseOperation(e.body);let s=await vB.processLocalTransaction(e,n);if(s instanceof Wre&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(Xre({level:jre.Z_BEST_SPEED})))}return s}catch(s){throw pl.error(s),s}}a(nne,"handlePostRequest");BB.exports={authHandler:rne,handlePostRequest:nne,handleServerUncaughtException:Zre,serverErrorHandler:ene,reqBodyValidationHandler:tne}});var qB=T((Vhe,FB)=>{"use strict";var sne=require("fastify-plugin"),{handlePostRequest:HB,authHandler:ine,reqBodyValidationHandler:one}=gE();async function ane(e){e.decorate("hdbCore",{preValidation:[one,ine],request:t=>xB(HB(t,response)),requestWithoutAuthentication:(t,r)=>xB(HB(t,r,!0))})}a(ane,"hdbCore");async function xB(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(xB,"convertAsyncIterators");FB.exports=sne(ane)});var VB=T((Khe,kB)=>{"use strict";var Yhe=require("fs"),OR=j();OR.initSync();var{CONFIG_PARAMS:GB}=M(),cne=1024*1024*1024;function une(e){let t=OR.get(GB.HTTP_TIMEOUT),r=OR.get(GB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:cne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(une,"getServerOptions");kB.exports=une});var KB=T((Qhe,YB)=>{"use strict";var bR=j();bR.initSync();var{CONFIG_PARAMS:$B}=M();function lne(){let e=bR.get($B.HTTP_CORSACCESSLIST),t=bR.get($B.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(lne,"getCORSOptions");YB.exports=lne});var zB=T((Jhe,QB)=>{"use strict";var WB=j();WB.initSync();var _ne=M();function dne(){return WB.get(_ne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(dne,"getHeaderTimeoutConfig");QB.exports=dne});var yR={};qe(yR,{customFunctionsServer:()=>hne,ready:()=>lH,start:()=>Ene});function Ene(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){xs||(xs=uH(t),ut.http((await xs).server));let o=await xs,c=(0,NR.dirname)(s),u=(0,NR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!JB.has(c)){JB.add(c);try{o.register(pne(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:lH}}async function hne(){try{Ve.info("In Custom Functions Fastify server"+process.cwd()),Ve.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ve.debug(`Custom Functions server process ${process.pid} starting up.`),await mne();let e=rH.get(nH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=xs=await uH(e)}catch(r){throw Ve.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ve.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ve.error(`Custom Functions ${process.pid} Error: ${e}`),Ve.error(e),process.exit(1)}}async function mne(){try{Ve.info("Custom Functions starting configuration."),await sH.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function pne(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,XB.existsSync)(e)&&r.register(tH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ve.error(s.message):s&&Ve.error(s),o()})}catch(n){Ve.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function uH(e){Ve.info("Custom Functions starting buildServer.");let t=(0,iH.default)(e),r=(0,jB.default)(t);r.server.headersTimeout=(0,aH.default)(),r.setErrorHandler(cH.serverErrorHandler);let n=(0,oH.default)();return n&&r.register(ZB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(eH.default),await r.register(fne),await r.after(),Vg(r),Ve.info("Custom Functions completed buildServer."),r}function lH(){if(xs)return xs.then?xs.then(e=>e.ready()):xs.ready()}var NR,XB,jB,ZB,eH,tH,rH,nH,Ve,fne,sH,iH,oH,aH,cH,xs,JB,_H=Re(()=>{NR=require("path"),XB=require("fs"),jB=B(require("fastify")),ZB=B(require("@fastify/cors")),eH=B(zg()),tH=B(require("@fastify/autoload")),rH=B(j()),nH=B(M()),Ve=B(Y()),fne=B(qB()),sH=B(cn()),iH=B(VB()),oH=B(KB()),aH=B(zB()),cH=B(gE());Ia();Zt();JB=new Set;a(Ene,"start");a(hne,"customFunctionsServer");a(mne,"setUp");a(pne,"buildRouteFolder");a(uH,"buildServer");a(lH,"ready")});var IR={};qe(IR,{start:()=>Sne});function Sne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,mH.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){fH||(fH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=dH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,EH.default)(s,(0,hH.realpathSync)(o))}}return i(s)},{runFirst:!0})),dH.set(r,n)}}}var EH,hH,mH,dH,fH,pH=Re(()=>{EH=B(require("send")),hH=require("fs"),mH=B(require("serve-static")),dH=new Map;a(Sne,"start")});var LR={};qe(LR,{Request:()=>wR,createReuseportFd:()=>RE});var SH,wR,CR,DR,RE,AE=Re(()=>{SH=require("os"),wR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new DR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get body(){return this.#e||(this.#e=new CR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},CR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},DR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,SH.platform)()!="win32"&&(RE=require("node-unix-socket").createReuseportFd)});var AH=T((cme,RH)=>{"use strict";var Tne=require("cluster"),Io=j();Io.initSync();var gH=M(),nme=require("util"),Fs=Y(),sme=require("fs"),gne=require("fastify"),ime=pu(),Rne=require("@fastify/cors"),Ane=require("@fastify/compress"),One=require("@fastify/static"),bne=zg(),Nne=require("path"),{PACKAGE_ROOT:yne}=M(),Ine=ti(),wne=J(),Cne=cn(),Dne=Ji(),{server:Lne}=(Zt(),ee(yi)),{node_request_key:ome}=(AE(),ee(LR)),{authHandler:Mne,handlePostRequest:Une,serverErrorHandler:Pne,reqBodyValidationHandler:vne}=gE(),ame=require("net"),{registerContentHandlers:Bne}=(Ia(),ee(d0)),Hne=6e4,xne=1024*1024*1024,Fne="TRUE",{CONFIG_PARAMS:Sl}=gH,Fa;RH.exports={hdbServer:TH,start:TH};async function TH(e){try{Fs.info("In Fastify server"+process.cwd()),Fs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Fs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Tne.isMaster,await qne();let t=e.securePort>0;Fa=Gne(t),await Fa.ready(),e||(e={}),e.isOperationsServer=!0;try{Lne.http(Fa.server,e),Fa.server.closeIdleConnections||await Fa.listen({port:0,host:"::"})}catch(r){throw Fa.close(),Fs.error(r),Fs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Fs.fatal(t),process.exit(1)}}a(TH,"operationsServer");async function qne(){Fs.trace("Configuring HarperDB process."),Ine.setSchemaDataToGlobal(),await Cne.setUsersToGlobal(),await Dne.getLicense()}a(qne,"setUp");function Gne(e){Fs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=kne(e),r=gne(t);r.server.headersTimeout=$ne(),r.setErrorHandler(Pne);let n=Vne();n&&r.register(Rne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(bne),r.register(Ane),r.register(One,{root:Nne.join(yne,"studio/build-local")}),Bne(r);let s=Io.get(gH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!wne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[vne,Mne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Une(i,o)}),r.get("/health",()=>"HarperDB is running."),Fs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Gne,"buildServer");function kne(e){let t=Io.get(Sl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Io.get(Sl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:xne,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(kne,"getServerOptions");function Vne(){let e=Io.get(Sl.OPERATIONSAPI_NETWORK_CORS),t=Io.get(Sl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Fne)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(Vne,"getCORSOpts");function $ne(){return Io.get(Sl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Hne}a($ne,"getHeaderTimeoutConfig")});var MH=T((fme,LH)=>{"use strict";var{decode:Yne}=require("msgpackr"),{isMainThread:lme,parentPort:Kne,threadId:_me}=require("worker_threads"),UR=yt(),qs=nt(),Wne=M(),Ai=Y(),OH=j(),NH=M();tt();var Qne=bs(),{recordAction:zne,recordActionBinary:Jne}=(Ns(),ee(tu)),{publishToStream:Xne}=UR,{ConsumerEvents:jne}=require("nats"),dme={durable:qs.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:qs.WORK_QUEUE_CONSUMER_NAMES.deliver_group},Zne,ese,tse,yH,IH;LH.exports={initialize:PR,workQueueListener:DH,setSubscription:rse,setIgnoreOrigin:sse,getDatabaseSubscriptions:nse};async function PR(){IH=!0,Ai.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await UR.getNATSReferences();Zne=e,ese=e.info.server_name,tse=t,yH=r}a(PR,"initialize");var bE=new Map;function rse(e,t,r){let n=bE.get(e);n||bE.set(e,n=new Map),n.set(t,r),IH||PR().then(DH)}a(rse,"setSubscription");function nse(){return bE}a(nse,"getDatabaseSubscriptions");var wH;function sse(e){wH=e}a(sse,"setIgnoreOrigin");var CH=100,bH=new Array(CH),OE=0;async function DH(){let e=await yH.consumers.get(qs.WORK_QUEUE_CONSUMER_NAMES.stream_name,qs.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(Kne?.on("message",async n=>{let{type:s}=n;s===NH.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let n of await r.status())if(n.type===jne.HeartbeatsMissed){let s=n.data;Ai.trace(`${s} clustering ingest consumer heartbeats missed`),s===2&&(Ai.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let n of r)await bH[OE],bH[OE]=ise(n).catch(s=>{Ai.error(s)}),++OE>=CH&&(OE=0)}catch(n){Ai.error("Error consuming clustering ingest, restarting consumer",n)}UR.clearClientCache(),await PR()}}a(DH,"workQueueListener");async function ise(e){let t=Yne(e.data);zne(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,n=!1,s=OH.get(Wne.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(qs.MSG_HEADERS.TRANSACTED_NODES)&&r.values(qs.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(qs.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!wH),Jne(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(qs.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Ai.trace("processing message:",o,c,_,(l?"records: "+l.map(b=>b?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Ai.trace(`messageProcessor nats msg id: ${e.headers.get(qs.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:S,user:p,node_name:g}=f||{},A=bE.get(c)?.get(_);if(!A)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,A.send(t);else if(l.length===1&&!u)A.send({type:MR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:S,table:_,onCommit:h,user:p,nodeName:g});else{let b=l.map((v,G)=>({type:MR(o),value:v,expiresAt:E,id:d?.[G],table:_}));for(;u;)b.push({type:MR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;A.send({type:"transaction",writes:b,table:_,timestamp:S,onCommit:h,user:p,nodeName:g})}OH.get(NH.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Xne(e.subject.split(".").slice(0,-1).join("."),Qne.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Ai.error(o)}e.ack()}a(ise,"messageProcessor");function MR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(MR,"convertOperation")});var qR={};qe(qR,{disableNATS:()=>ase,publishToStream:()=>CE,setNATSReplicator:()=>vR,setPublishToStream:()=>cse,setSubscription:()=>FR,start:()=>ose});function ose(){yE.default.get(IE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&lse()}function ase(e=!0){HH=e}function cse(e,t){CE=e,FR=t}function lse(){if(HH||process.env._DISABLE_NATS)return;let e=Cn(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];vR(s,r,i)}}lS((r,n)=>{vR(r.tableName,r.databaseName,r),n&&FH(r)}),!UH&&(UH=!0)}function vR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Ft{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Ce],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Ce]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Ce],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Ce],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Ce]})}static defineSchema(i){FH(i)}static subscribe(){let i=new An;return FR(t,e,i),i}static subscribeOnThisThread(i){return i<use}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new NE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=xH;return i}a(n,"getNATSTransaction")}function FH(e){let t=yE.default.get(IE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);CE(`${HR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,xR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var PH,HR,xR,vH,BH,yE,IE,wE,HH,CE,FR,use,xH,UH,NE,BR,qH=Re(()=>{Oe();On();PH=B(yt()),HR=B(nt()),xR=B(bs());uc();vH=B(MH()),BH=B(Cr()),yE=B(j()),IE=B(M()),wE=B(Y());a(ose,"start");a(ase,"disableNATS");CE=PH.publishToStream,FR=vH.setSubscription;a(cse,"setPublishToStream");use=2;a(lse,"assignReplicationSource");a(vR,"setNATSReplicator");a(FH,"publishSchema");NE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=yE.default.get(IE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(wE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(CE(`${HR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,xR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw wE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},BR=class extends NE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,BH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};xH=new BR});var WR=T(Co=>{"use strict";var{isMainThread:_se,parentPort:Rl,threadId:Tl}=require("worker_threads"),{Socket:dse,createServer:fse}=require("net"),{createServer:Ese,IncomingMessage:hse}=require("http"),{createServer:mse}=require("https"),{readFileSync:qa,unlinkSync:GH,existsSync:pse}=require("fs"),Fn=Y(),$e=j(),Ar=M(),{server:ME}=(Zt(),ee(yi)),{WebSocketServer:Sse}=require("ws"),{createServer:Tse}=require("tls"),{getTicketKeys:gse,restartNumber:Rse,getWorkerIndex:kH}=tt(),{Headers:WH}=(Nf(),ee(BP)),{recordAction:gl,recordActionBinary:Ase}=(Ns(),ee(tu)),{Request:QH,createReuseportFd:VH}=(AE(),ee(LR)),{checkMemoryLimit:Ose}=Ji(),zH=require("tls"),$H=zH.createSecureContext;zH.createSecureContext=function(e){if(!e.cert||!e.key)return $H(e);let t={...e};delete t.key,delete t.cert;let r=$H(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){Rse<=1&&Fn.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:gme,CONFIG_PARAMS:bse}=Ar;$e.initSync();var Nse=$e.get(bse.HTTP_SESSIONAFFINITY),cs={};Co.registerServer=YR;Co.httpServer=KR;Co.deliverSocket=$R;Co.startServers=JH;Co.when_components_loaded=null;ME.http=KR;ME.request=Cse;ME.socket=Dse;ME.ws=Lse;var GR=[],DE=[],yse,wo={},LE={},Ise=[],kR=[];function JH(){return Co.when_components_loaded=UE().loadRootComponents(!0).then(()=>{Rl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)$R(n,r,s);else if(t.requestId)wse(t);else if(t.type===Ar.ITC_EVENT_TYPES.SHUTDOWN){Fn.trace("received shutdown request",Tl);for(let i in cs){let o=cs[i],c;o.closeIdleConnections&&(setInterval(()=>{o.closeIdleConnections()},25).unref(),setTimeout(()=>{o.closeAllConnections(),Fn.info("Closed all http connections",i,Tl)},4e3).unref()),o.close?.(()=>{if($e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&kH()==0)try{GH($e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,Tl),o.cantCleanupProperly||Fn.warn("Had to forcefully exit the thread",Tl),process.exit(0)},5e3).unref()})}if(process.env.DEV_MODE)try{require("inspector").close()}catch(i){console.error("Could not close debugger",i)}}}).ref();let e=[];if(VH&&!Nse)for(let t in cs){let r=cs[t];if(isNaN(t)&&kH()==0){pse(t)&&GH(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),Fn.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=VH(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),Fn.trace("Listening on port "+t,Tl)}).on("error",i)}))}Promise.all(e).then(()=>{Rl?.postMessage({type:Ar.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(JH,"startServers");_se||JH();function $R(e,t,r){let n=e?.read?e:new dse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=cs[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=cs[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Fn.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a($R,"deliverSocket");var YH=new Map;function wse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=YH.get(s),r){case"connection":i=$R(void 0,t),YH.set(s,i),i.write=(c,u,_)=>(Rl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Rl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Rl.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(wse,"proxyRequest");function YR(e,t,r=!0){!+t&&t!==$e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt($e.get(Ar.CONFIG_PARAMS.HTTP_PORT),10));let n=cs[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",KH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else cs[t]=e;e.on("unhandled",KH)}a(YR,"registerServer");function XH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],$e.get(Ar.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:$e.get(Ar.CONFIG_PARAMS.HTTP_PORT),secure:$e.get(Ar.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),$e.get(Ar.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:$e.get(Ar.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&$e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:$e.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(XH,"getPorts");function KR(e,t){for(let{port:r,secure:n}of XH(t))jH(r,n,t?.isOperationsServer),typeof e=="function"?kR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,YR(e,r,!1)),LE[r]=VR(kR,r),yse=VR(Ise,r)}a(KR,"httpServer");function jH(e,t,r){if(!wo[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:$e.get(n+"_keepAliveTimeout"),headersTimeout:$e.get(n+"_headersTimeout"),requestTimeout:$e.get(n+"_timeout")},i=$e.get(n+"_mtls");if(t){n=r?"operationsApi_":"";let c=$e.get(n+"tls_privateKey"),u=$e.get(n+"tls_certificate"),_=$e.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:qa(c),ciphers:$e.get("tls_ciphers"),cert:qa(u),ca:_&&qa(_),requestCert:!!i,ticketKeys:gse()})}let o=Ose();wo[e]=(t?mse:Ese)(s,async(c,u)=>{try{let l=performance.now(),d=new QH(c,u);r&&(d.isOperationsServer=!0);let f=await LE[e](d);if(!f){if(d._nodeResponse.statusCode)return;f=ZH(d)}if(o?f.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):f.headers?.set?.("Server","HarperDB"),f.status===-1){for(let v of f.headers||[])u.setHeader(v[0],v[1]);return c.baseRequest=d,u.baseResponse=f,wo[e].emit("unhandled",c,u)}let E=f.status||200,h=performance.now(),S=h-l,p=f.body,g;if(!f.handlesHeaders){let v=f.headers||new WH;if(p?p.length>=0&&(typeof p=="string"?v.set("Content-Length",Buffer.byteLength(p)):v.set("Content-Length",p.length),g=!0):(v.set("Content-Length","0"),g=!0),v.append){let G=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(G+=", miss"),v.append("Server-Timing",G,!0)}u.writeHead(E,v&&(v[Symbol.iterator]?Array.from(v):v)),g&&u.end(p)}let A=d.handlerPath,b=d.method;if(gl(S,"duration",A,b,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),Ase(E<400,"success",A,b),!g)if(p?.pipe){p.pipe(u),p.destroy&&u.on("close",()=>{p.destroy()});let v=0;p.on("data",G=>{v+=G.length}),p.on("end",()=>{gl(performance.now()-h,"transfer",A,b),gl(v,"bytes-sent",A,b)})}else p?.then?p.then(v=>{u.end(v)},_):u.end(p)}catch(l){_(l)}function _(l){let d=l.headers;u.writeHead(l.statusCode||500,d&&(d[Symbol.iterator]?Array.from(d):d)),u.end(l.toString()),l.statusCode?l.statusCode===500?Fn.warn(l):Fn.info(l):Fn.error(l)}a(_,"onError")}),t&&(wo[e].on("secureConnection",c=>{c._parent.startTime&&gl(performance.now()-c._parent.startTime,"tls-handshake",e),gl(c.isSessionReused(),"tls-reused",e)}),wo[e].isSecure=!0),YR(wo[e],e)}return wo[e]}a(jH,"getHTTPServer");function VR(e,t){let r=ZH;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(VR,"makeCallbackChain");function ZH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new WH}}a(ZH,"unhandled");function Cse(e,t){KR(e,{requestOnly:!0,...t})}a(Cse,"onRequest");function Dse(e,t){let r;if(t.securePort){let n=$e.get("tls_privateKey"),s=$e.get("tls_certificate"),i=t.mtls?.certificateAuthority||$e.get("tls_certificateAuthority");r=Tse({ciphers:$e.get("tls_ciphers"),key:qa(n),cert:qa(s),ca:i&&qa(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),cs[t.securePort]=r}return t.port&&(r=fse(e),cs[t.port]=r),r}a(Dse,"onSocket");Object.defineProperty(hse.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function Lse(e,t){for(let{port:r,secure:n}of XH(t)){DE[r]||(DE[r]=new Sse({server:jH(r,n)}),DE[r].on("connection",async(i,o)=>{try{let c=new QH(o);c.isWebSocket=!0;let u=LE[r](c),_=o.headers["sec-websocket-protocol"]||"";for(let l=0;l<GR.length;l++){let d=GR[l];if(d.protocol){if(d.protocol===_){d.listener(i,c,u);break}}else d.listener(i,c,u)}}catch(c){Fn.warn("Error handling WebSocket connection",c)}}),DE[r].on("error",i=>{console.log("Error in setting up WebSocket server",i)}));let s=t?.subProtocol||"";GR.push({listener:e,protocol:s}),LE[r]=VR(kR,r)}}a(Lse,"onWebSocket");function KH(e,t){t.writeHead(404),t.end(`Not found
|
|
27
|
-
`)}a(KH,"defaultNotFound")});async function nx({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await QR.getResource(e,{});s=new XR(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await QR.get(e);i&&i.delete()}s=new vE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Al.put(n)),s}function zR(){return PE++,PE>65500&&(PE=1),PE}function JR(e,t,r=e){let{topic:n,retain:s}=e;e.data=t,e.async=!0,e.authorize=!0;let i=Js.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Xe(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var ex,Do,tx,rx,QR,Al,PE,vE,XR,sx=Re(()=>{Oe();pc();ex=B(Cr()),Do=B(Y());Ui();tx=B(tt()),rx=B(WR());Zt();QR=_t({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"}]}}]}),Al=_t({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,tx.getWorkerIndex)()===0&&(async()=>{await rx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Al.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await ut.getUser(r.user.username)),Xe(r,()=>{try{JR(r,t)}finally{Al.delete(e.id,r)}})}})();a(nx,"getSession");PE=1;a(zR,"getNextMessageId");vE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(g=>g.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Do.trace)("Resuming subscription from",s,"from",o);let E=Js.getMatch(_);if(!E){let g=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw g.statusCode=404,g}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let g=f.url.slice(1);if(g.indexOf("#")>-1&&g.indexOf("#")!==g.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,g.indexOf("+")===g.length-1)f.onlyChildren=!0,f.url="/"+g.slice(0,g.length-1);else{let A=g.split("/"),b;for(let H=0;H<A.length;H++)if(A[H].indexOf("+")>-1)if(A[H]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&b)throw new Error("Filters can not be combined");let v=!0;A[A.length-1]==="#"&&(A.length--,v=!1),b&&(n=a(H=>{let P=H.id;if(!Array.isArray(P)||v&&P.length!==A.length)return!1;for(let z=0;z<A.length;z++)if(A[z]!=="+"&&A[z]!==P[z])return!1;return!0},"filter"));let G=A.indexOf("+");f.url="/"+(G>-1?A.slice(0,G):A).concat("").join("/")}}let h=E.path,S=E.Resource,p=await Xe(f,async()=>{let g=await S.subscribe(f);if(!g)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!g[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let A of g)try{let b;if(A.type&&A.type!=="put"&&A.type!=="delete"&&A.type!=="message"&&A.type!=="patch"||n&&!n(A))continue;r?(A.topic=s,b=this.needsAcknowledge(A)):(A.acknowledge?.(),b=zR());let v=A.id;Array.isArray(v)&&(v=ko(v)),v==null&&(v=""),this.listener(h+"/"+v,A.value,b,t)}catch(b){(0,Do.warn)(b)}})(),g});return p.topic=s,p.qos=t.qos,this.subscriptions.push(p),p}resume(){}needsAcknowledge(t){let r=zR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,JR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Xe(r,async()=>{if(!t){let n=await Al.get(this.sessionId,r);n?.doesExist()&&await JR(n,n.data,r)}await Al.delete(this.sessionId,r)}).catch(n=>{(0,Do.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(JR,"publish");XR=class extends vE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=zR(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Do.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,ex.getNextMonotonicTime)()),(0,Do.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),QR.put(this.sessionRecord)),t.qos}}});var jR={};qe(jR,{bypassAuth:()=>Mse,start:()=>Use});function Mse(){ux=!0}function Use({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=ax(_,(h,S)=>{if(_.send(h),S&&_._socket.writableNeedDrain)return new Promise(p=>this._socket.once("drain",p))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,Or.info)("WebSocket error",h)})}},{subProtocol:"mqtt"})),(t||s)&&(c=e.socket(async _=>{let l;if(u){if(_.authorized)try{let E=u.user;l!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,Or.error)(E)}else if(u.required)return(0,Or.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&ux&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,cx.getSuperUser)());let{onMessage:d,onClose:f}=ax(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Or.info)("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function ax(e,t,r,n,s){ox||(ox=!0,eu(d=>{BE>0&&d.push({metric:"mqtt-connections",connections:BE,byThread:!0})}));let i;BE++;let o,c={protocolVersion:4},u=(0,xE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){BE--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),un(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await ut.getUser(d.username,d.password.toString(),r),(0,HE.get)(us.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ix.notify({username:n.username,status:us.AUTH_AUDIT_STATUS.SUCCESS,type:us.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,HE.get)(us.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&ix.error({username:n.username,status:us.AUTH_AUDIT_STATUS.FAILURE,type:us.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return un(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let b=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?b(d.will.payload):void 0,delete d.will.payload}o=nx({user:n,...d}),o=await o,s.sessions.add(o)}catch(b){return(0,Or.error)(b),un(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:b.code||5,returnCode:b.code||128})}un(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((b,v,G,H)=>{try{let P=b.indexOf("/",1),z=P>0?b.slice(0,P):b;f({cmd:"publish",topic:b,payload:E(v),messageId:G||Math.floor(Math.random()*1e8),qos:H.qos},z)}catch(P){(0,Or.error)(P),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let b of d.subscriptions){let v;try{v=(await o.addSubscription(b,b.qos>=1)).qos||0}catch(G){(0,Or.error)(G),v=c.protocolVersion<5?128:G.statusCode===403?135:G.statusCode===404?143:128}h.push(v)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let b=[];for(let v of d.unsubscriptions)b.push(o.removeSubscription(v)?0:17);f({cmd:"unsuback",granted:b,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let S=d.qos===2?"pubrec":"puback",p=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type"))),g=d.payload?.length>0?p(d.payload):void 0,A;try{A=await o.publish(d,g)}catch(b){(0,Or.warn)(b),d.qos>0&&f({cmd:S,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:S,messageId:d.messageId,reasonCode:A===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),un(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Or.error)(h),f({cmd:"disconnect"})}function f(h,S){let p=(0,xE.generate)(h,c);t(p),Gr(p.length,"bytes-sent",S,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ti(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var xE,cx,HE,us,Or,ix,ux,ox,BE,lx=Re(()=>{xE=require("mqtt-packet");sx();cx=B(cn());Ia();Ns();Zt();HE=B(j()),us=B(M()),Or=B(Y()),ix=(0,Or.loggerWithTag)("auth-event"),ux=(0,HE.get)(us.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Mse,"bypassAuth");a(Use,"start");BE=0;a(ax,"onSocket")});var Hf={};qe(Hf,{component_errors:()=>ka,loadComponent:()=>FE,loadComponentDirectories:()=>Tx,setErrorReporter:()=>Hse});function Tx(e,t){t&&(eA=t),e&&(tA=e);let r=[];if((0,qn.existsSync)(ZR)){let s=(0,qn.readdirSync)(ZR,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Rt.join)(ZR,o);r.push(FE(c,eA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(FE(n,eA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{Sx=!0})}function Hse(e){bl=e}async function FE(e,t,r,n,s,i){if(!dx.has(e)){dx.set(e,!0),s&&(tA=s);try{let o;n&&(ka=new Map);let c=(0,Rt.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,qn.existsSync)(c)?o=n?(0,px.getConfigObj)():(0,fx.parseDocument)((0,qn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=rA;let u=[],_=n;for(let l in o){let d=o[l];if(ka.set(n?l:(0,Rt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let A=e,b;for(;!(0,qn.existsSync)(b=(0,Rt.join)(A,"node_modules",l));)if(A=(0,Rt.dirname)(A),A.length<(0,mx.getHdbBasePath)().length){b=null;break}if(b)f=await FE(b,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=Bse[l];if(!f)continue;u.push(f);let h=a(A=>(A.origin=r,_t(A)),"ensureTable"),S=d.network||(d.port||d.securePort)&&d,p=S?.securePort||S?.https&&S.port,g=!S?.https&&S?.port;if(Ga.isMainThread&&(f=await f.startOnMainThread?.({server:ut,ensureTable:h,port:g,securePort:p,resources:t,...d})||f,n&&S))for(let A of[g,p])try{if(+A&&!_x.includes(A)){let b=nA.get(sA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);b&&Ol.default.warn("Session affinity is not recommended and may cause memory leaks"),(b||!RE)&&(_x.push(A),iA(A,b))}}catch(b){console.error("Error listening on socket",A,b,l)}if(t.isWorker&&(f=await f.start?.({server:ut,ensureTable:h,port:g,securePort:p,resources:t,...d})||f),tA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,hx.handleHDBError)("Can not reference parent directories");let A=(0,Rt.join)(e,d.files).replace(/\\/g,"/"),b=A.indexOf("/*");if(b>-1&&d.files!==rA[l]?.files&&!(0,qn.existsSync)(A.slice(0,b)))throw new Error(`The path '${A.slice(0,b)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let v=(0,Rt.basename)(e),G=d.path||"/";G=G.startsWith("/")?G:G.startsWith("./")?"/"+v+G.slice(2):G==="."?"/"+v:"/"+v+"/"+G;let H,P,z;if(d.root){let Q=d.root;Q.startsWith("/")&&(Q=Q.slice(1)),Q.endsWith("/")&&(Q=Q.slice(0,-1)),Q+="/",P=(0,Rt.join)(e,Q)}else(z=A.indexOf("/*"))>-1&&(P=A.slice(0,z+1),H=(0,Rt.relative)(e,P));let W=!1;if(Ga.isMainThread&&f.setupDirectory&&(W=await f.setupDirectory?.(G,P,t)),t.isWorker&&f.handleDirectory&&(W=await f.handleDirectory?.(G,P,t)),W)continue;for(let Q of await(0,Ex.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:se,dirent:pe}=Q;_=!0;let oe=(0,Rt.relative)(e,se).replace(/\\/g,"/");if(H)if(oe.startsWith(H))oe=oe.slice(H.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${oe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let Fe=G+(G.endsWith("/")?"":"/")+oe;try{if(pe.isFile()){let ce=await vse(se);Ga.isMainThread&&await f.setupFile?.(ce,Fe,se,t),t.isWorker&&await f.handleFile?.(ce,Fe,se,t)}else Ga.isMainThread&&await f.setupDirectory?.(Fe,se,t),t.isWorker&&await f.handleDirectory?.(Fe,se,t)}catch(ce){ce.message=`Could not load ${pe.isFile()?"file":"directory"} '${se}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${ce.message}`,bl?.(ce),((0,Va.getWorkerIndex)()===0?console:Ol.default).error(ce),t.set(d.path||"/",new Nl(ce)),ka.set(n?l:(0,Rt.basename)(e),ce.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Rt.basename)(e)}' due to: ${h.message}`,bl?.(h),((0,Va.getWorkerIndex)()===0?console:Ol.default).error(h),t.set(d.path||"/",new Nl(h),null,!0),ka.set(n?l:(0,Rt.basename)(e),h.message)}}if(Ga.isMainThread&&!Sx&&i&&(0,Va.watchDir)(e,async()=>Tx()),o.extensionModule)return await Md((0,Rt.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;bl?.(new Error(l)),((0,Va.getWorkerIndex)()===0?console:Ol.default).error(l),ka.set((0,Rt.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,bl?.(o),t.set("",new Nl(o))}}}var qn,Rt,Ga,fx,nA,sA,Ex,Va,Ol,hx,mx,Pse,px,vse,ZR,tA,Sx,eA,ka,Bse,rA,_x,dx,bl,Nl,xf=Re(()=>{qn=require("fs"),Rt=require("path"),Ga=require("worker_threads"),fx=require("yaml"),nA=B(j()),sA=B(M());MD();BD();HD();O0();_H();pH();Ex=B(require("fast-glob")),Va=B(tt()),Ol=B(Y());pS();Zt();hx=B(Z());On();Oe();oA();mx=B(j()),Pse=B(AH());Cf();qH();lx();px=B(xr());AE();({readFile:vse}=qn.promises),ZR=nA.get(sA.CONFIG_PARAMS.COMPONENTSROOT),tA=new Map,ka=new Map;a(Tx,"loadComponentDirectories");Bse={REST:Zf,rest:Zf,graphqlSchema:mS,jsResource:TS,fastifyRoutes:yR,login:RS,static:IR,operationsApi:Pse,customFunctions:{},http:{},clustering:qR,authentication:Qu,mqtt:jR},rA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(rA,"static",{value:{files:"web/**"}});_x=[],dx=new Map;a(Hse,"setErrorReporter");a(FE,"loadComponent");Nl=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 UE=T((Kme,Rx)=>{var{isMainThread:gx}=require("worker_threads"),{getTables:xse}=(Oe(),ee(Ge)),{loadComponentDirectories:Fse,loadComponent:qse}=(xf(),ee(Hf)),{resetResources:Gse}=(pc(),ee(ob)),kse=mg(),Vse=xr(),{dirname:$se}=require("path"),{getConnection:Yse}=yt(),Kse=j(),Wse=M(),aA=new Map;async function Qse(e=!1){!gx&&Kse.get(Wse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Yse();try{gx&&await kse()}catch(n){console.error(n)}let t=Gse();xse(),t.isWorker=e,await qse($se(Vse.getConfigFilePath()),t,"hdb",!0,aA),await Fse(aA,t);let r=[];for(let[n]of aA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Qse,"loadRootComponents");Rx.exports.loadRootComponents=Qse});var tt=T((Qme,bi)=>{"use strict";var{Worker:zse,MessageChannel:Jse,parentPort:ls,isMainThread:dA,threadId:Xse,workerData:Gs}=require("worker_threads"),{PACKAGE_ROOT:jse}=M(),{join:Nx,isAbsolute:Zse,extname:eie}=require("path"),{server:yx}=(Zt(),ee(yi)),{watch:tie,readdir:rie}=require("fs/promises"),{totalmem:Ax}=require("os"),yl=M(),Ix=j(),ks=Y(),{randomBytes:nie}=require("crypto"),{_assignPackageExport:sie}=require("../index"),iie=M(),Ox=1024*1024,Oi=[],gn=[],oie=50,fA=1e4,aie="restart",wx="request_thread_info",Cx="resource_report",Dx="thread_info",Lx="added-port",cie="ack",cA;sie("threads",gn);bi.exports={startWorker:uA,restartWorkers:hA,shutdownWorkers:fie,workers:Oi,setMonitorListener:Rie,onMessageFromWorkers:Eie,onMessageByType:Hx,broadcast:mie,broadcastWithAcknowledgement:Sie,setChildListenerByType:die,getWorkerIndex:Mx,getWorkerCount:Ux,getTicketKeys:Px,setMainIsWorker:lie,setTerminateTimeout:uie,restartNumber:Gs?.restartNumber||1};gn.onMessageByType=Hx;gn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=gn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var EA;function uie(e){fA=e}a(uie,"setTerminateTimeout");function Mx(){return Gs?Gs.workerIndex:EA?0:void 0}a(Mx,"getWorkerIndex");function Ux(){return Gs?Gs.workerCount:EA?1:void 0}a(Ux,"getWorkerCount");function lie(e){EA=e}a(lie,"setMainIsWorker");var qE;function Px(){return qE||(qE=dA?nie(48):Gs.ticketKeys,qE)}a(Px,"getTicketKeys");Object.defineProperty(yx,"workerIndex",{get(){return Mx()}});Object.defineProperty(yx,"workerCount",{get(){return Ux()}});var vx={[wx](e,t){Tie(t)},[Cx](e,t){gie(t,e)}};function uA(e,t={}){let r=process.constrainedMemory?.()||Ax();r=Math.min(r,Ax(),2e4*Ox);let n=Ix.get(yl.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/Ox/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of gn){let _=new Jse;_.existingPort=u,i.push(_),o.push(_.port2)}eie(e)||(e+=".js");let c=new zse(Zse(e)?e:Nx(jse,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:t.threadCount,name:t.name,restartNumber:bi.exports.restartNumber,ticketKeys:Px()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Lx,port:u,threadId:c.threadId},[u]);return kE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>uA(e,t),c.on("error",u=>{console.error("Worker error:",u),ks.error("Worker error:",u)}),c.on("exit",u=>{Oi.splice(Oi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<oie?(t.unexpectedRestarts=c.unexpectedRestarts+1,uA(e,t)):ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{vx[u.type]?.(u,c)}),Oi.push(c),Oie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(uA,"startWorker");var _ie=[yl.THREAD_TYPES.HTTP];async function hA(e=null,t=2,r=!0){if(dA){if(r){let{loadRootComponents:o}=UE();await o()}bi.exports.restartNumber++,t<1&&(t=t*Oi.length);let n=[],s=[];for(let o of Oi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:bi.exports.restartNumber,type:yl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=_ie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),fA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===iie.ITC_EVENT_TYPES.CHILD_STARTED&&(ks.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");ks.trace("Waiting for worker to start",_.threadId),_.on("message",f)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=bf();r&&(e==="http"||!e)&&Ix.get(yl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ls.postMessage({type:aie,workerType:e})}a(hA,"restartWorkers");function die(e,t){vx[e]=t}a(die,"setChildListenerByType");function fie(e){return hA(e,1/0,!1)}a(fie,"shutdownWorkers");var Bx=[];function Eie(e){Bx.push(e)}a(Eie,"onMessageFromWorkers");var lA=new Map;function Hx(e,t){let r=lA.get(e);r||lA.set(e,r=[]),r.push(t)}a(Hx,"onMessageByType");var hie=10;async function mie(e){let t=0;for(let r of gn)try{r.postMessage(e),t++>hie&&(t=0,await new Promise(setImmediate))}catch(n){ks.error("Unable to send message to worker",n)}}a(mie,"broadcast");var GE=new Map,pie=1;function Sie(e){return new Promise(t=>{let r=0;for(let n of gn)try{let s=pie++,i=a(()=>{GE.delete(s),--r===0&&t(),n!==ls&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,GE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of GE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){ks.error("Unable to send message to worker",s)}r===0&&t()})}a(Sie,"broadcastWithAcknowledgement");function Tie(e){e.postMessage({type:Dx,workers:xx()})}a(Tie,"sendThreadInfo");function xx(){let e=Date.now();return Oi.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(xx,"getChildWorkerInfo");function gie(e,t){e.resources=t,e.resources.updated=Date.now()}a(gie,"recordResourceReport");var _A;function Rie(e){_A=e}a(Rie,"setMonitorListener");var Aie=1e3,bx=!1;function Oie(){bx||(bx=!0,setInterval(()=>{for(let e of Oi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}_A&&_A()},Aie).unref())}a(Oie,"startMonitoring");var bie=1e3;if(ls){kE(ls);for(let e=0,t=Gs.addPorts.length;e<t;e++){let r=Gs.addPorts[e];r.threadId=Gs.addThreadIds[e],kE(r)}setInterval(()=>{let e=process.memoryUsage();ls.postMessage({type:Cx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},bie).unref(),cA=a(()=>new Promise((e,t)=>{ls.on("message",r),ls.postMessage({type:wx});function r(n){n.type===Dx&&(ls.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else cA=xx;bi.exports.getThreadInfo=cA;function kE(e,t){gn.push(e),e.on("message",r=>{if(r.type===Lx)r.port.threadId=r.threadId,kE(r.port);else if(r.type===cie){let n=GE.get(r.id);n&&n()}else{for(let s of Bx)s(r,e);let n=lA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){ks.error(i)}}}).on("close",()=>{gn.splice(gn.indexOf(e),1)}).on("exit",()=>{gn.splice(gn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(kE,"addPort");if(dA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await rie(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(Nx(n,i.name));try{for await(let{filename:i}of tie(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await hA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");bi.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else ls.on("message",async e=>{let{type:t}=e;t===yl.ITC_EVENT_TYPES.SHUTDOWN&&(bi.exports.restartNumber=e.restartNumber,ls.unref(),setTimeout(()=>{ks.warn("Thread did not voluntarily terminate",Xse),process.exit(0)},fA).unref())})});var Kx={};qe(Kx,{startHTTPThreads:()=>yie,startSocketServer:()=>iA,updateWorkerIdleness:()=>Yx});async function yie(e=2,t){if(t)pA(0,1,!0);else{let{loadRootComponents:n}=UE();if(e===0)return(0,Ni.setMainIsWorker)(!0),await WR().startServers(),Promise.resolve([]);await n()}let r=(0,kx.checkMemoryLimit)();r&&!process.env.DEV_MODE&&(console.error(r),setInterval(()=>{KE.notify(r)},Nie).unref());for(let n=0;n<e;n++)pA(n,e);return Promise.all($x)}function pA(e,t=1,r){if(mA++,(0,Ni.startWorker)("server/threads/threadServer.js",{name:YE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===YE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});$x.push(s),await s,$a.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=$E.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=$a.indexOf(n);o>-1&&$a.splice(o,1)}if(a(i,"removeWorker"),Ya){let o=Ya;Ya=[];for(let c of o)Vx[c.localPort](null,c)}}}),r){let n=setInterval(()=>{SA?SA=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Ni.shutdownWorkers)(),mA=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function iA(e=0,t){if(typeof e=="string")try{(0,WE.existsSync)(e)&&(0,WE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Iie:r=wie(t):r=TA;let n=(0,Ka.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=Vx[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),SA=!0,r(o,(c,u)=>{if(!c){if(Fx){let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});Fx.deliverSocket(l,e,u),l.resume()}else mA>0?(Ya.length===0&&setTimeout(()=>{Ya.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,Ya.push(o)):(console.log("start up a dynamic thread to handle request"),pA(0));Gr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});Lie(l,c,e)}Gr(!0,"socket-routed")})};let s=pu();KE.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function TA(e,t){let r,n=0;for(let s of $a){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=VE)return VE=i,t(r);n=i}VE=0,t(r)}function Iie(e,t){let r={};e.getpeername(r);let n=r.address,s=Wa.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);TA(e,o=>{Wa.set(n,{worker:o,lastUsed:i}),t(o)})}function wie(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Ka.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Wa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);TA(n,d=>{Wa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Yx(){VE=0;for(let e of $a)e.expectedIdle=e.recentELU.idle+Cie,e.requests=1;$a.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Lie(e,t,r){let n=Die++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),$E.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),$E.delete(n)),s.event=="destroy"&&(e.destroy(),$E.delete(n))})}var Ni,Ka,YE,KE,WE,Gx,kx,$a,Ya,Vx,Fx,mA,$x,Nie,SA,VE,qx,Wa,Cie,$E,Die,oA=Re(()=>{Ni=B(tt()),Ka=require("net"),YE=B(M()),KE=B(Y()),WE=require("fs");Ns();Gx=require("worker_threads"),kx=B(Ji()),$a=[],Ya=[],Vx=[],mA=0,$x=[];Gx.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});Nie=6e5;a(yie,"startHTTPThreads");a(pA,"startHTTPWorker");a(iA,"startSocketServer");VE=0;a(TA,"findMostIdleWorker");qx=36e5,Wa=new Map;a(Iie,"findByRemoteAddressAffinity");a(wie,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Wa)r.lastUsed+qx<e&&Wa.delete(t)},qx).unref();Cie=1e3;a(Yx,"updateWorkerIdleness");(0,Ni.setMonitorListener)(Yx);$E=new Map,Die=1;a(Lie,"proxySocket")});th();var{startHTTPThreads:Mie,startSocketServer:Wx}=(oA(),ee(Kx));Mie(0,!0);Wx(9925);Wx(9926);
|
|
26
|
+
`},compressible:!1,q:.8});Pt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});f0={type:"application/json",serializeStream:mu,serialize:al,deserialize:zee,q:.8};Pt.set("*/*",f0);Pt.set("",f0);a(zee,"tryJSONParse");a(Gg,"registerContentHandlers");Jee=require("fastify-plugin"),Xee=Jee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Kf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Kf,"findBestSerializer");c0=Hg.default.get(xg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Wf,"serialize");a(pi,"serializeMessage");a(jee,"streamToBuffer");a(Ro,"getDeserializer");a(u0,"deserializerUnknownType");a(Zee,"transformIterable")});function T0(e){let t={openapi:ete,info:{title:"HarperDB HTTP REST interface",version:(0,S0.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:B,elements:H,relationship:v,definition:M}of o){if(v)R==="array"?_[B]={type:"array",items:{$ref:gi+H.type}}:_[B]={$ref:gi+R};else{let $=M??H?.definition;if($){if(!t.components.schemas[$.type]){let K={};$.properties.forEach(z=>{K[z.name]=new Yg(kg[z.type],z.type)}),t.components.schemas[$.type]=new p0(K)}R==="array"?_[B]={type:"array",items:{$ref:gi+$.type}}:_[B]={$ref:gi+$.type}}else R==="array"?H.type==="Any"||H.type=="ID"?_[B]={type:"array",items:{format:H.type}}:_[B]={type:"array",items:new Yg(kg[H.type],H.type)}:R==="Any"||R=="ID"?_[B]={format:R}:_[B]=new Yg(kg[R],R)}l.push(new Kg(B,"query",_[B]))}let d=Object.keys(_),f=new Kg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Kg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new p0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",O=typeof u.delete=="function",g="/"+s+"/";h&&(t.paths[g]={},t.paths[g].post=new tte(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[g]||(t.paths[g]={}),t.paths[g].get=new Vg(l,r,{200:new $g({$ref:gi+i})},"search for records by the specified property name and value pairs")),O&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new m0(l,r,"delete all the records that match the provided query",{204:new h0})),g="/"+s+"/{"+c+"}",S&&(t.paths[g]={},t.paths[g].get=new Vg([f],r,{200:new $g({$ref:gi+i})},"retrieve a record by its primary key")),p&&(t.paths[g]||(t.paths[g]={}),t.paths[g].put=new rte([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),O&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new m0([f],r,"delete a record with the given primary key",{204:new h0})),S&&E.schema.enum.length>0&&(g="/"+s+"/{"+c+"}.{property}",t.paths[g]={},t.paths[g].get=new Vg([f,E],r,{200:new $g({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function tte(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:gi+e}}}},this.security=t,this.responses={200:{description:Wg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Vg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function $g(e){this.description=Wg,this.content={"application/json":{schema:e}}}function h0(){this.description="successfully processed request, no content returned to client"}function rte(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:gi+r}}}},this.responses={200:{description:Wg}}}function m0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function p0(e){this.type="object",this.properties=e}function Yg(e,t){this.type=e,this.format=t}function Kg(e,t,r){this.name=e,this.in=t,this.schema=r}var S0,ete,kg,gi,Wg,g0=Oe(()=>{S0=x(Jd()),ete="3.0.3",kg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},gi="#/components/schemas/",Wg="successful operation";a(T0,"generateJsonApi");a(tte,"Post");a(Vg,"Get");a($g,"Response200");a(h0,"Response204");a(rte,"Put");a(m0,"Delete");a(p0,"ResourceSchema");a(Yg,"Type");a(Kg,"Parameter")});var zf={};Fe(zf,{start:()=>ite});async function ste(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&u_(e);let s=new mi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==R0){let h=Qf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Ke(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=Ro(r["content-type"],!0)(e.body)}catch(h){throw new Ua.ClientError(h,400)}if(e.authorize=!0,i===R0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return T0(Qf);throw new Ua.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new Ua.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ua.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,Qg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){nte[0]=d;let h=String.fromCharCode(34,(qt[0]&63)+62,(qt[0]>>6)+(qt[1]<<2&63)+62,(qt[1]>>4)+(qt[2]<<4&63)+62,(qt[2]>>2)+62,(qt[3]&63)+62,(qt[3]>>6)+(qt[4]<<2&63)+62,(qt[4]>>4)+(qt[5]<<4&63)+62,(qt[5]>>2)+62,(qt[6]&63)+62,(qt[6]>>6)+(qt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),Qg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let f={status:l,headers:s,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=Wf(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?Ao.warn(i):Ao.info(i):Ao.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Wf(i.contentType?i:i.toString(),e,o),o}}function ite(e){Qg=e,!A0&&(A0=!0,Qf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return ste(t,r)}),e.server.ws(async(t,r,n)=>{ul++;let s=new Tn;O0||(O0=!0,eu(l=>{ul>0&&l.push({metric:"ws-connections",connections:ul,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ao.warn(l)});let o;t.on("message",a(function(d){o||(o=Ro(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{ul--,sn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=Qf.getMatch(u);if(sn(!!_,"connection","ws","connect"),!_)t.send(pi(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,xr(h=>({count:h.count,total:ul}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Ke(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=pi(E.value,r);t.send(h),xr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var Ao,Ua,qt,nte,Qg,R0,A0,Qf,O0,ul,b0=Oe(()=>{ya();bs();Ao=x(W()),Ua=x(ee());l_();uc();Ui();Af();g0();qt=new Uint8Array(8),nte=new Float64Array(qt.buffer,0,1),Qg={},R0="openapi";a(ste,"http");ul=0;a(ite,"start")});var zg=T((hhe,N0)=>{var{recordAction:Jf,recordActionBinary:ote}=(bs(),te(tu)),ate=require("fastify-plugin"),cte=200;N0.exports=ate(function(e,t,r){e.addHook("onResponse",async(n,s)=>{s.getResponseTime()}),e.addHook("onSend",async(n,s,i)=>{let o=s.getResponseTime(),c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Jf(o,"duration",_,d,l),ote(s.raw.statusCode<400,"success",_,d,l);let f=cte;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Jf(performance.now()-c,"transfer",_,d,l),Jf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Jf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var tR=T((She,C0)=>{var eE=require("clone"),tE=Ze(),ute=J(),jf=U(),mhe=W(),Jg=require("fs"),jg=require("joi"),{string:Zf}=jg.types(),{hdb_errors:lte,handleHDBError:Xf}=ee(),{HDB_ERROR_MSGS:phe,HTTP_STATUS_CODES:Xg}=lte,{common_validators:Pa}=$n(),y0=" is required",_te=["insert","update","upsert"],Zg={database:{presence:!1,format:Pa.schema_format,length:Pa.schema_length},schema:{presence:!1,format:Pa.schema_format,length:Pa.schema_length},table:{presence:!0,format:Pa.schema_format,length:Pa.schema_length},action:{inclusion:{within:_te,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},dte={schema:Zf.required(),table:Zf.required(),action:Zf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:fte,AWS_SECRET:Ete,AWS_BUCKET:hte,AWS_FILE_KEY:mte,REGION:pte}=jf.S3_BUCKET_AUTH_KEYS,Ste={s3:{presence:!0},[`s3.${fte}`]:{presence:!0,type:"String"},[`s3.${Ete}`]:{presence:!0,type:"String"},[`s3.${hte}`]:{presence:!0,type:"String"},[`s3.${mte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${pte}`]:{presence:!0,type:"String"}},w0=eE(Zg);w0.data.presence={message:y0};var I0=eE(Zg);I0.file_path.presence={message:y0};var Tte=Object.assign(eE(Zg),Ste),eR=eE(dte);eR.csv_url=Zf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();eR.passthrough_headers=jg.object();function gte(e){let t=tE.validateObject(e,w0);return rE(e,t)}a(gte,"dataObject");function Rte(e){let t=tE.validateBySchema(e,jg.object(eR));return rE(e,t)}a(Rte,"urlObject");function Ate(e){let t=tE.validateObject(e,I0);return rE(e,t)}a(Ate,"fileObject");function Ote(e){let t=tE.validateObject(e,Tte);return rE(e,t)}a(Ote,"s3FileObject");function rE(e,t){if(!t){let r=ute.checkGlobalSchemaTable(e.schema,e.table);if(r)return Xf(new Error,r,Xg.BAD_REQUEST);if(e.operation===jf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{Jg.accessSync(e.file_path,Jg.constants.R_OK|Jg.constants.F_OK)}catch(n){return n.code===jf.NODE_ERROR_CODES.ENOENT?Xf(n,`No such file or directory ${n.path}`,Xg.BAD_REQUEST):n.code===jf.NODE_ERROR_CODES.EACCES?Xf(n,`Permission denied ${n.path}`,Xg.BAD_REQUEST):Xf(n)}}return t}a(rE,"postValidateChecks");C0.exports={dataObject:gte,urlObject:Rte,fileObject:Ate,s3FileObject:Ote}});var rR=T((ghe,D0)=>{"use strict";var ll=W(),nE=U();async function bte(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===nE.OPERATIONS_ENUM.INSERT||t.operation===nE.OPERATIONS_ENUM.UPDATE||t.operation===nE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===nE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ll.info(i.message),i):i.http_resp_msg?(ll.error(`Error calling operation: ${e.name}`),ll.error(i.http_resp_msg),i):(ll.error(`Error calling operation: ${e.name}`),ll.error(i),i)}}a(bte,"callOperationFunctionAsAwait");D0.exports={callOperationFunctionAsAwait:bte}});var M0=T((Ahe,L0)=>{"use strict";var nR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},sR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};L0.exports={BulkLoadFileObject:nR,BulkLoadDataObject:sR}});var P0=T((bhe,U0)=>{"use strict";var iR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};U0.exports=iR});var _R=T((Dhe,X0)=>{"use strict";var sE=rn(),oE=tR(),Nte=require("needle"),Pn=U(),yhe=et(),va=J(),{handleHDBError:st,hdb_errors:V0}=ee(),{HTTP_STATUS_CODES:Gt,HDB_ERROR_MSGS:yt,CHECK_LOGS_WRAPPER:bo}=V0,Ba=W(),oR=require("papaparse");va.promisifyPapaParse();var vn=require("fs-extra"),yte=require("path"),{chain:v0}=require("stream-chain"),B0=require("stream-json/streamers/StreamArray"),H0=require("stream-json/utils/Batch"),x0=require("stream-chain/utils/comp"),{finished:F0}=require("stream"),wte=Z(),$0=rR(),Ite=Ug(),{BulkLoadFileObject:cR,BulkLoadDataObject:Cte}=M0(),uR=Og(),{verifyBulkLoadAttributePerms:Y0}=Gf(),whe=P0(),Ihe=Ot(),Che=Os(),{databases:Dte}=(Ne(),te(qe)),{coerceType:Lte}=(pd(),te(rS)),q0="No records parsed from csv file.",Oo=`${wte.get("HDB_ROOT")}/tmp`,{schema_regex:Mte}=$n(),G0=1024*1024*2,k0=5e3,Ute={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};X0.exports={csvDataLoad:Pte,csvURLLoad:vte,csvFileLoad:Bte,importFromS3:Hte};async function Pte(e,t){let r=oE.dataObject(e);if(r)throw st(r,r.message,Gt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=Q0(e.schema,e.table),i=oR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:aR.bind(null,s),dynamicTyping:!1}),o=new uR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&Y0(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 st(new Error,c,Gt.BAD_REQUEST,void 0,void 0,!0);let u=new Cte(e.action,e.schema,e.table,i.data);return n=await $0.callOperationFunctionAsAwait(z0,u,null),n.message===q0?q0:J0(n.records,n.number_written)}catch(s){throw No(s)}}a(Pte,"csvDataLoad");async function vte(e){let t=oE.urlObject(e);if(t)throw st(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Oo}/${r}`;try{await xte(e,r)}catch(s){throw Ba.error(yt.DOWNLOAD_FILE_ERR(r)+" - "+s),st(s,bo(yt.DOWNLOAD_FILE_ERR(r)))}try{let s=new cR(this.job_operation_function.name,e.action,e.schema,e.table,n,Pn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await lR(s);return await iE(n),i}catch(s){throw await iE(n),No(s)}}a(vte,"csvURLLoad");async function Bte(e){let t=oE.fileObject(e);if(t)throw st(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r=new cR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Pn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await lR(r)}catch(n){throw No(n)}}a(Bte,"csvFileLoad");async function Hte(e){let t=oE.s3FileObject(e);if(t)throw st(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=yte.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Oo}/${s}`;let i=new cR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Fte(s,e);let o=await lR(i);return await iE(r),o}catch(n){throw await iE(r),No(n)}}a(Hte,"importFromS3");async function xte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Nte("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw st(n,s,n.statusCode,Pn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}Gte(r,e.csv_url),await qte(t,r.raw)}a(xte,"downloadCSVFile");async function Fte(e,t){try{let r=`${Oo}/${e}`;await vn.mkdirp(Oo),await vn.writeFile(`${Oo}/${e}`,"",{flag:"a+"});let n=await vn.createWriteStream(r),s=await Ite.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){Ba.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ba.error(yt.S3_DOWNLOAD_ERR+" - "+r),st(r,bo(yt.S3_DOWNLOAD_ERR))}}a(Fte,"downloadFileFromS3");async function qte(e,t){try{await vn.mkdirp(Oo),await vn.writeFile(`${Oo}/${e}`,t)}catch(r){throw Ba.error(yt.WRITE_TEMP_FILE_ERR),st(r,bo(yt.DEFAULT_BULK_LOAD_ERR))}}a(qte,"writeFileToTempFolder");async function iE(e){if(e)try{await vn.access(e),await vn.unlink(e)}catch{Ba.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(iE,"deleteTempFile");function Gte(e,t){if(e.statusCode!==V0.HTTP_STATUS_CODES.OK)throw st(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Gt.BAD_REQUEST);if(!Ute[e.headers["content-type"]])throw st(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Gt.BAD_REQUEST);if(!e.raw)throw st(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Gt.BAD_REQUEST)}a(Gte,"validateURLResponse");async function lR(e){try{let t;switch(e.file_type){case Pn.VALID_S3_FILE_TYPES.CSV:t=await kte(e);break;case Pn.VALID_S3_FILE_TYPES.JSON:t=await Vte(e);break;default:throw st(new Error,yt.DEFAULT_BULK_LOAD_ERR,Gt.BAD_REQUEST,Pn.LOG_LEVELS.ERROR,yt.INVALID_FILE_EXT_ERR(e))}return J0(t.records,t.number_written)}catch(t){throw No(t)}}a(lR,"fileLoad");async function K0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await sE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&Y0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=st(c);r(u)}}a(K0,"validateChunk");async function W0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;va.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!va.isEmpty(c)&&!va.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await $0.callOperationFunctionAsAwait(z0,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=st(c,bo(yt.INSERT_CSV_ERR),Gt.INTERNAL_SERVER_ERROR,Pn.LOG_LEVELS.ERROR,yt.INSERT_CSV_ERR+" - "+c);r(u)}}a(W0,"insertChunk");async function kte(e){let t={records:0,number_written:0},r=Q0(e.schema,e.table);try{let n=new uR,s=vn.createReadStream(e.file_path,{highWaterMark:G0});s.setEncoding("utf8"),await oR.parsePromise(s,K0.bind(null,e,n),aR.bind(null,r));let i=n.getPermsResponse();if(i)throw st(new Error,i,Gt.BAD_REQUEST);return s=vn.createReadStream(e.file_path,{highWaterMark:G0}),s.setEncoding("utf8"),await oR.parsePromise(s,W0.bind(null,e,t),aR.bind(null,r)),s.destroy(),t}catch(n){throw st(n,bo(yt.PAPA_PARSE_ERR),Gt.INTERNAL_SERVER_ERROR,Pn.LOG_LEVELS.ERROR,yt.PAPA_PARSE_ERR+n)}}a(kte,"callPapaParse");function Q0(e,t){let r=Dte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Lte(i,s));return n}a(Q0,"createTransformMap");function aR(e,t,r){let n=e.get(r);return n?n(t):va.autoCast(t)}a(aR,"typeFunction");async function Vte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new uR,s=v0([vn.createReadStream(e.file_path,{encoding:"utf-8"}),B0.withParser(),c=>c.value,new H0({batchSize:k0}),x0(async c=>{await K0(e,n,r,c)})]);await new Promise((c,u)=>{F0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw st(new Error,i,Gt.BAD_REQUEST);let o=v0([vn.createReadStream(e.file_path,{encoding:"utf-8"}),B0.withParser(),c=>c.value,new H0({batchSize:k0}),x0(async c=>{await W0(e,t,r,c)})]);return await new Promise((c,u)=>{F0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw st(n,bo(yt.INSERT_JSON_ERR),Gt.INTERNAL_SERVER_ERROR,Pn.LOG_LEVELS.ERROR,yt.INSERT_JSON_ERR+n)}}a(Vte,"insertJson");async function z0(e){let t={};try{e.data&&e.data.length>0&&$te(e.data[0])?t=await Yte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ba.info(t.message))}catch(r){throw No(r)}return t}a(z0,"callBulkFileLoad");function $te(e){let t=Object.keys(e);for(let r of t)if(!Mte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a($te,"validateColumnNames");async function Yte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=sE.insert;break;case"update":i=sE.update;break;case"upsert":i=sE.upsert;break;default:throw st(new Error,yt.INVALID_ACTION_PARAM_ERR(n),Gt.BAD_REQUEST,Pn.LOG_LEVELS.ERROR,yt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=va.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw No(o)}}a(Yte,"bulkFileLoad");function J0(e,t){return`successfully loaded ${t} of ${e} records`}a(J0,"buildResponseMsg");function No(e){return st(e,bo(yt.DEFAULT_BULK_LOAD_ERR),Gt.INTERNAL_SERVER_ERROR,Pn.LOG_LEVELS.ERROR,yt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(No,"buildTopLevelErrMsg")});var Z0=T((Mhe,j0)=>{"use strict";var dR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};j0.exports=dR});var rB=T((Phe,tB)=>{"use strict";var Kte=U(),eB=require("moment"),Wte=require("uuid").v4,fR=class{static{a(this,"JobObject")}constructor(){this.id=Wte(),this.type=void 0,this.start_datetime=eB().valueOf(),this.created_datetime=eB().valueOf(),this.end_datetime=void 0,this.status=Kte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};tB.exports=fR});var ER=T((Bhe,cB)=>{"use strict";var Qte=require("uuid").v4,iB=rn(),oB=tn(),zte=Kn(),Jte=Xo(),Xte=Z0(),it=U(),jte=rB(),Zte=jS(),hn=W(),ere=yc(),Ha=J(),{promisify:tre}=require("util"),yo=require("moment"),rre=Vf(),aE=tR(),nB=gp(),{deleteTransactionLogsBeforeValidator:nre}=Sg(),{handleHDBError:sre,hdb_errors:ire}=ee(),{HTTP_STATUS_CODES:ore}=ire,sB=oB.searchByValue,are=oB.searchByHash,cre=iB.insert,ure=tre(rre.evaluateSQL),lre=iB.update;cB.exports={addJob:fre,updateJob:hre,handleGetJob:_re,handleGetJobsByStartDate:dre,getJobById:aB};async function _re(e){try{let t=await aB(e.id);return Ha.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 hn.error("There was an error getting job",t),new Error(r)}}a(_re,"handleGetJob");async function dre(e){try{let t=await Ere(e);if(hn.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=yo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=yo(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 hn.error(r),new Error(r)}}a(dre,"handleGetJobsByStartDate");async function fre(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ha.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return hn.info(l),t.error=l,t}if(!it.JOB_TYPE_ENUM[e.operation])return hn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case it.OPERATIONS_ENUM.CSV_FILE_LOAD:n=aE.fileObject(e);break;case it.OPERATIONS_ENUM.CSV_URL_LOAD:n=aE.urlObject(e);break;case it.OPERATIONS_ENUM.CSV_DATA_LOAD:n=aE.dataObject(e);break;case it.OPERATIONS_ENUM.IMPORT_FROM_S3:n=aE.s3FileObject(e);break;case it.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case it.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=nB(e,"date");break;case it.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=nB(e,"timestamp");break;case it.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=nre(e);break;default:break}if(n)throw sre(n,n.message,ore.BAD_REQUEST,void 0,void 0,!0);let s=new jte;s.type=e.operation===it.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?it.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new zte(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await sB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return hn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Qte();try{o=await sB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return hn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return hn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new ere(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await cre(u)}catch(l){return hn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,hn.trace(l)}return t}a(fre,"addJob");async function Ere(e){let t=yo(e.from_date,yo.ISO_8601),r=yo(e.to_date,yo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new Xte(n,e.hdb_user);try{return await ure(s)}catch(i){throw hn.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(Ere,"getJobsInDateRange");async function aB(e){if(Ha.isEmptyOrZeroLength(e))return Ha.errorizeMessage("Invalid job ID specified.");let t=new Jte(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await are(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return hn.error(n),Ha.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(aB,"getJobById");async function hre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ha.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===it.JOB_STATUS_ENUM.COMPLETE||e.status===it.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=yo().valueOf());let t=new Zte(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await lre(t),r}a(hre,"updateJob")});var EB=T((xhe,fB)=>{"use strict";var uB=J(),pr=U(),mre=require("moment"),cE=_R(),uE=W(),lB=ER(),_B=$f(),dB=Ki(),pre=je(),Sre=Hf(),hR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Tre(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(uB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(uB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case pr.JOB_TYPE_ENUM.csv_file_load:await vs(e,cE.csvFileLoad);break;case pr.JOB_TYPE_ENUM.csv_url_load:await vs(e,cE.csvURLLoad);break;case pr.JOB_TYPE_ENUM.csv_data_load:await vs(e,cE.csvDataLoad);break;case pr.JOB_TYPE_ENUM.import_from_s3:await vs(e,cE.importFromS3);break;case pr.JOB_TYPE_ENUM.empty_trash:break;case pr.JOB_TYPE_ENUM.export_local:await vs(e,_B.export_local);break;case pr.JOB_TYPE_ENUM.export_to_s3:await vs(e,_B.export_to_s3);break;case pr.JOB_TYPE_ENUM.delete_files_before:case pr.JOB_TYPE_ENUM.delete_records_before:await vs(e,dB.deleteFilesBefore);break;case pr.JOB_TYPE_ENUM.delete_audit_logs_before:await vs(e,dB.deleteAuditLogsBefore);break;case pr.JOB_TYPE_ENUM.delete_transaction_logs_before:await vs(e,Sre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Tre,"parseMessage");async function vs(e,t){try{e.job.status=pr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=mre().valueOf(),await lB.updateJob(e.job),await gre(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):uE.error(`There was an error running ${t.name} job with id ${e.job.id}`),uE.error(n),e.job.message=n,e.job.status=pr.JOB_STATUS_ENUM.ERROR;try{await lB.updateJob(e.job)}catch(s){throw uE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(vs,"runJob");async function gre(e){uE.trace("launching job thread:",e),pre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[pr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(gre,"launchJobThread");fB.exports={parseMessage:Tre,RunnerMessage:hR}});var mB=T((qhe,hB)=>{"use strict";var mR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};hB.exports=mR});var UB=T((khe,AR)=>{"use strict";var fE=tn(),TR=Vf(),lE=_R(),Bs=xd(),_E=Gi(),dl=Ki(),Rre=HS(),_l=nn(),dE=KS(),kt=pg(),wt=W(),Are=zS(),Ore=tf(),pB=LT(),bre=nf(),Nre=MT(),yre=UT(),wre=BT(),Ire=xT(),pR=GT(),SB=$f(),Cre=Gf(),gR=ER(),q=U(),{hdb_errors:El,handleHDBError:fl}=ee(),{HTTP_STATUS_CODES:TB}=El,SR=KT(),gB=Rf(),CB=require("util"),xa=rn(),Dre=Zs(),Lre=Ta(),RB=EB(),AB=Cu(),OB=(yf(),te(Qu)),bB=vr(),NB=Hf(),yB=Lf(),{setServerUtilities:Mre}=(pd(),te(rS)),{CONTEXT:Ure}=(gn(),te(qh)),{_assignPackageExport:Pre}=require("../index"),{transformReq:vre}=J(),{server:Bre}=(zt(),te(yi)),Hre=rR(),wB=fE.searchByHash,xre=fE.searchByValue,Fre=CB.promisify(fE.search),qre=CB.promisify(TR.evaluateSQL),Gre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},V=mB();async function DB(e,t){try{if(e.body.operation!=="read_log"&&(wt.log_level===q.LOG_LEVELS.INFO||wt.log_level===q.LOG_LEVELS.DEBUG||wt.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;wt.info(o)}}catch(n){wt.error(n)}let r=await Hre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Gre[e.body.operation]&&Dre.setSchemaDataToGlobal(n=>{n&&wt.error(n)}),r}a(DB,"processLocalTransaction");var IB=Vre();AR.exports={chooseOperation:LB,getOperationFunction:MB,operation:RR,processLocalTransaction:DB};Mre(AR.exports);Bre.operation=RR;function LB(e){let t;try{t=MB(e)}catch(s){throw wt.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=TR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=TR.checkASTPermissions(e,i);if(o)throw wt.error(`${TB.FORBIDDEN} from operation ${e.operation}`),wt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),fl(new Error,o,El.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Cre.verifyPerms(i,s);if(o)throw wt.error(`${TB.FORBIDDEN} from operation ${e.operation}`),wt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),fl(new Error,o,El.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw fl(s,"There was an error when trying to choose an operation path")}return r}a(LB,"chooseOperation");function MB(e){if(wt.trace(`getOperationFunction with operation: ${e.operation}`),IB.has(e.operation))return IB.get(e.operation);throw fl(new Error,El.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),El.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(MB,"getOperationFunction");Pre("operation",RR);function RR(e,t){e.hdb_user=this[Ure]?.user,e.bypass_auth=!t;let r=LB(e);return DB({body:e},r)}a(RR,"operation");async function kre(e){wt.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await xa.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await xa.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await xa.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await dl.deleteRecord(i);break;default:wt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){wt.info("Invalid operation in transaction"),wt.error(o)}}a(kre,"catchup");async function os(e){vre(e);let t,r;try{r=await gR.addJob(e),t=r.createdJob,wt.info("addJob result",r);let n=new RB.RunnerMessage(t,e);return await RB.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw wt.error(s),fl(n,s)}}a(os,"executeJob");function Vre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new V(xa.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new V(xa.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new V(xa.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new V(fE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new V(wB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new V(wB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new V(xre)),e.set(q.OPERATIONS_ENUM.SEARCH,new V(Fre)),e.set(q.OPERATIONS_ENUM.SQL,new V(qre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new V(os,lE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new V(os,lE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new V(os,lE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new V(os,lE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new V(Bs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new V(Bs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new V(Bs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new V(Bs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new V(Bs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new V(Bs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new V(Bs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new V(Bs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new V(_E.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new V(_E.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new V(_E.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new V(_E.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new V(dl.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new V(_l.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new V(_l.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new V(_l.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new V(_l.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new V(dE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new V(dE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new V(dE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new V(dE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new V(_l.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new V(Are)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new V(Ore)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new V(pB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new V(pB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new V(bre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new V(Nre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new V(yre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new V(bB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new V(wre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new V(Ire)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new V(pR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new V(pR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new V(pR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new V(os,SB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new V(os,dl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new V(os,dl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new V(os,SB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new V(gR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new V(gR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new V(SR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new V(SR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new V(SR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new V(gB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new V(gB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new V(kre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new V(Lre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new V(os,dl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new V(Rre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new V(AB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new V(AB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new V(OB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new V(OB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new V(bB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new V(kt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new V(kt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new V(kt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new V(kt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new V(kt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new V(kt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new V(kt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new V(kt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new V(kt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new V(kt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new V(kt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new V(kt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new V(kt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new V(kt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new V(kt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new V(kt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new V(NB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new V(os,NB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new V(yB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new V(yB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new V(Bs.getBackup)),e}a(Vre,"initializeOperationFunctionMap")});var hE=T(($he,BB)=>{"use strict";var OR=U(),$re=J(),hl=W(),{handleHDBError:bR,hdb_errors:EE}=ee(),{isMainThread:Yre}=require("worker_threads"),{Readable:Kre}=require("stream"),PB=require("os"),Wre=require("util"),Qre=oT(),zre=Wre.promisify(Qre.authorize),vB=UB(),{createGzip:Jre,constants:Xre}=require("zlib");function jre(e){let t=`Found an uncaught exception with message: ${e.message}. ${PB.EOL}Stack: ${e.stack} ${PB.EOL}Terminating ${Yre?"HDB":"thread"}.`;console.error(t),hl.fatal(t),process.exit(1)}a(jre,"handleServerUncaughtException");function Zre(e,t,r){if(hl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:EE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(Zre,"serverErrorHandler");function ene(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=bR(new Error,"Invalid JSON.",EE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if($re.isEmpty(e.body.operation)){let n=bR(new Error,"Request body must include an 'operation' property.",EE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(ene,"reqBodyValidationHandler");function tne(e,t,r){let n;e.body.operation!==OR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==OR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==OR.OPERATIONS_ENUM.LOGOUT?zre(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{hl.warn(s),hl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(bR(s,i,EE.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(tne,"authHandler");async function rne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=vB.chooseOperation(e.body);let s=await vB.processLocalTransaction(e,n);if(s instanceof Kre&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(Jre({level:Xre.Z_BEST_SPEED})))}return s}catch(s){throw hl.error(s),s}}a(rne,"handlePostRequest");BB.exports={authHandler:tne,handlePostRequest:rne,handleServerUncaughtException:jre,serverErrorHandler:Zre,reqBodyValidationHandler:ene}});var qB=T((Khe,FB)=>{"use strict";var nne=require("fastify-plugin"),{handlePostRequest:HB,authHandler:sne,reqBodyValidationHandler:ine}=hE();async function one(e){e.decorate("hdbCore",{preValidation:[ine,sne],request:t=>xB(HB(t,response)),requestWithoutAuthentication:(t,r)=>xB(HB(t,r,!0))})}a(one,"hdbCore");async function xB(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(xB,"convertAsyncIterators");FB.exports=nne(one)});var VB=T((zhe,kB)=>{"use strict";var Qhe=require("fs"),NR=Z();NR.initSync();var{CONFIG_PARAMS:GB}=U(),ane=1024*1024*1024;function cne(e){let t=NR.get(GB.HTTP_TIMEOUT),r=NR.get(GB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:ane,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(cne,"getServerOptions");kB.exports=cne});var KB=T((Xhe,YB)=>{"use strict";var yR=Z();yR.initSync();var{CONFIG_PARAMS:$B}=U();function une(){let e=yR.get($B.HTTP_CORSACCESSLIST),t=yR.get($B.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(une,"getCORSOptions");YB.exports=une});var zB=T((Zhe,QB)=>{"use strict";var WB=Z();WB.initSync();var lne=U();function _ne(){return WB.get(lne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(_ne,"getHeaderTimeoutConfig");QB.exports=_ne});var IR={};Fe(IR,{customFunctionsServer:()=>Ene,ready:()=>lH,start:()=>fne});function fne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){Hs||(Hs=uH(t),Xe.http((await Hs).server));let o=await Hs,c=(0,wR.dirname)(s),u=(0,wR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!JB.has(c)){JB.add(c);try{o.register(mne(c,u))}catch(_){if(_.message==="Root plugin has already booted")ke.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:lH}}async function Ene(){try{ke.info("In Custom Functions Fastify server"+process.cwd()),ke.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),ke.debug(`Custom Functions server process ${process.pid} starting up.`),await hne();let e=rH.get(nH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=Hs=await uH(e)}catch(r){throw ke.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw ke.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){ke.error(`Custom Functions ${process.pid} Error: ${e}`),ke.error(e),process.exit(1)}}async function hne(){try{ke.info("Custom Functions starting configuration."),await sH.setUsersToGlobal(),ke.info("Custom Functions completed configuration.")}catch(e){ke.error(e)}}function mne(e,t){return async function(r){try{ke.info("Custom Functions starting buildRoutes"),ke.trace("Loading fastify routes folder "+e),(0,XB.existsSync)(e)&&r.register(tH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:ke.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?ke.error(s.message):s&&ke.error(s),o()})}catch(n){ke.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function uH(e){ke.info("Custom Functions starting buildServer.");let t=(0,iH.default)(e),r=(0,jB.default)(t);r.server.headersTimeout=(0,aH.default)(),r.setErrorHandler(cH.serverErrorHandler);let n=(0,oH.default)();return n&&r.register(ZB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(eH.default),await r.register(dne),await r.after(),Gg(r),ke.info("Custom Functions completed buildServer."),r}function lH(){if(Hs)return Hs.then?Hs.then(e=>e.ready()):Hs.ready()}var wR,XB,jB,ZB,eH,tH,rH,nH,ke,dne,sH,iH,oH,aH,cH,Hs,JB,_H=Oe(()=>{wR=require("path"),XB=require("fs"),jB=x(require("fastify")),ZB=x(require("@fastify/cors")),eH=x(zg()),tH=x(require("@fastify/autoload")),rH=x(Z()),nH=x(U()),ke=x(W()),dne=x(qB()),sH=x(nn()),iH=x(VB()),oH=x(KB()),aH=x(zB()),cH=x(hE());ya();zt();JB=new Set;a(fne,"start");a(Ene,"customFunctionsServer");a(hne,"setUp");a(mne,"buildRouteFolder");a(uH,"buildServer");a(lH,"ready")});var CR={};Fe(CR,{start:()=>pne});function pne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,mH.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){fH||(fH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=dH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,EH.default)(s,(0,hH.realpathSync)(o))}}return i(s)},{runFirst:!0})),dH.set(r,n)}}}var EH,hH,mH,dH,fH,pH=Oe(()=>{EH=x(require("send")),hH=require("fs"),mH=x(require("serve-static")),dH=new Map;a(pne,"start")});var UR={};Fe(UR,{Request:()=>DR,createReuseportFd:()=>mE});var SH,DR,LR,MR,mE,pE=Oe(()=>{SH=require("os"),DR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new MR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new LR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},LR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},MR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,SH.platform)()!="win32"&&(mE=require("node-unix-socket").createReuseportFd)});var AH=T((_me,RH)=>{"use strict";var Sne=require("cluster"),wo=Z();wo.initSync();var gH=U(),ome=require("util"),xs=W(),ame=require("fs"),Tne=require("fastify"),cme=pu(),gne=require("@fastify/cors"),Rne=require("@fastify/compress"),Ane=require("@fastify/static"),One=zg(),bne=require("path"),{PACKAGE_ROOT:Nne}=U(),yne=Zs(),wne=J(),Ine=nn(),Cne=Ji(),{server:Dne}=(zt(),te(yi)),{node_request_key:ume}=(pE(),te(UR)),{authHandler:Lne,handlePostRequest:Mne,serverErrorHandler:Une,reqBodyValidationHandler:Pne}=hE(),lme=require("net"),{registerContentHandlers:vne}=(ya(),te(E0)),Bne=6e4,Hne=1024*1024*1024,xne="TRUE",{CONFIG_PARAMS:ml}=gH,Fa;RH.exports={hdbServer:TH,start:TH};async function TH(e){try{xs.info("In Fastify server"+process.cwd()),xs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),xs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Sne.isMaster,await Fne();let t=e.securePort>0;Fa=qne(t),await Fa.ready(),e||(e={}),e.isOperationsServer=!0;try{Dne.http(Fa.server,e),Fa.server.closeIdleConnections||await Fa.listen({port:0,host:"::"})}catch(r){throw Fa.close(),xs.error(r),xs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),xs.fatal(t),process.exit(1)}}a(TH,"operationsServer");async function Fne(){xs.trace("Configuring HarperDB process."),yne.setSchemaDataToGlobal(),await Ine.setUsersToGlobal(),await Cne.getLicense()}a(Fne,"setUp");function qne(e){xs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Gne(e),r=Tne(t);r.server.headersTimeout=Vne(),r.setErrorHandler(Une);let n=kne();n&&r.register(gne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(One),r.register(Rne),r.register(Ane,{root:bne.join(Nne,"studio/build-local")}),vne(r);let s=wo.get(gH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!wne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Pne,Lne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Mne(i,o)}),r.get("/health",()=>"HarperDB is running."),xs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(qne,"buildServer");function Gne(e){let t=wo.get(ml.OPERATIONSAPI_NETWORK_TIMEOUT),r=wo.get(ml.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Hne,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Gne,"getServerOptions");function kne(){let e=wo.get(ml.OPERATIONSAPI_NETWORK_CORS),t=wo.get(ml.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===xne)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(kne,"getCORSOpts");function Vne(){return wo.get(ml.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Bne}a(Vne,"getHeaderTimeoutConfig")});var MH=T((mme,LH)=>{"use strict";var{decode:$ne}=require("msgpackr"),{isMainThread:fme,parentPort:Yne,threadId:Eme}=require("worker_threads"),vR=Ot(),Fs=et(),Kne=U(),Ri=W(),OH=Z(),NH=U();je();var Wne=Os(),{recordAction:Qne,recordActionBinary:zne}=(bs(),te(tu)),{publishToStream:Jne}=vR,{ConsumerEvents:Xne}=require("nats"),hme={durable:Fs.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Fs.WORK_QUEUE_CONSUMER_NAMES.deliver_group},jne,Zne,ese,yH,wH;LH.exports={initialize:BR,workQueueListener:DH,setSubscription:tse,setIgnoreOrigin:nse,getDatabaseSubscriptions:rse};async function BR(){wH=!0,Ri.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await vR.getNATSReferences();jne=e,Zne=e.info.server_name,ese=t,yH=r}a(BR,"initialize");var TE=new Map;function tse(e,t,r){let n=TE.get(e);n||TE.set(e,n=new Map),n.set(t,r),wH||BR().then(DH)}a(tse,"setSubscription");function rse(){return TE}a(rse,"getDatabaseSubscriptions");var IH;function nse(e){IH=e}a(nse,"setIgnoreOrigin");var CH=100,bH=new Array(CH),SE=0;async function DH(){let e=await yH.consumers.get(Fs.WORK_QUEUE_CONSUMER_NAMES.stream_name,Fs.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(Yne?.on("message",async n=>{let{type:s}=n;s===NH.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let n of await r.status())if(n.type===Xne.HeartbeatsMissed){let s=n.data;Ri.trace(`${s} clustering ingest consumer heartbeats missed`),s===2&&(Ri.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let n of r)await bH[SE],bH[SE]=sse(n).catch(s=>{Ri.error(s)}),++SE>=CH&&(SE=0)}catch(n){Ri.error("Error consuming clustering ingest, restarting consumer",n)}vR.clearClientCache(),await BR()}}a(DH,"workQueueListener");async function sse(e){let t=$ne(e.data);Qne(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,n=!1,s=OH.get(Kne.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Fs.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Fs.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(Fs.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!IH),zne(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(Fs.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Ri.trace("processing message:",o,c,_,(l?"records: "+l.map(R=>R?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Ri.trace(`messageProcessor nats msg id: ${e.headers.get(Fs.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:O}=f||{},g=TE.get(c)?.get(_);if(!g)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,g.send(t);else if(l.length===1&&!u)g.send({type:PR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:O});else{let R=l.map((B,H)=>({type:PR(o),value:B,expiresAt:E,id:d?.[H],table:_}));for(;u;)R.push({type:PR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;g.send({type:"transaction",writes:R,table:_,timestamp:p,onCommit:h,user:S,nodeName:O})}OH.get(NH.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Jne(e.subject.split(".").slice(0,-1).join("."),Wne.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Ri.error(o)}e.ack()}a(sse,"messageProcessor");function PR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(PR,"convertOperation")});var kR={};Fe(kR,{disableNATS:()=>ose,publishToStream:()=>bE,setNATSReplicator:()=>HR,setPublishToStream:()=>ase,setSubscription:()=>GR,start:()=>ise});function ise(){RE.default.get(AE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&use()}function ose(e=!0){HH=e}function ase(e,t){bE=e,GR=t}function use(){if(HH||process.env._DISABLE_NATS)return;let e=yn(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];HR(s,r,i)}}aS((r,n)=>{HR(r.tableName,r.databaseName,r),n&&FH(r)}),!UH&&(UH=!0)}function HR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends vt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[De],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[De]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[De],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[De],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[De]})}static defineSchema(i){FH(i)}static subscribe(){let i=new Tn;return GR(t,e,i),i}static subscribeOnThisThread(i){return i<cse}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new gE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=xH;return i}a(n,"getNATSTransaction")}function FH(e){let t=RE.default.get(AE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);bE(`${FR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,qR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var PH,FR,qR,vH,BH,RE,AE,OE,HH,bE,GR,cse,xH,UH,gE,xR,qH=Oe(()=>{Ne();gn();PH=x(Ot()),FR=x(et()),qR=x(Os());uc();vH=x(MH()),BH=x(Nr()),RE=x(Z()),AE=x(U()),OE=x(W());a(ise,"start");a(ose,"disableNATS");bE=PH.publishToStream,GR=vH.setSubscription;a(ase,"setPublishToStream");cse=2;a(use,"assignReplicationSource");a(HR,"setNATSReplicator");a(FH,"publishSchema");gE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=RE.default.get(AE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(OE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(bE(`${FR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,qR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw OE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},xR=class extends gE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,BH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};xH=new xR});var zR=T(Io=>{"use strict";var{isMainThread:lse,parentPort:Sl,threadId:NE}=require("worker_threads"),{Socket:_se,createServer:dse}=require("net"),{createServer:fse,IncomingMessage:Ese}=require("http"),{createServer:hse}=require("https"),{readFileSync:qa,unlinkSync:GH,existsSync:mse}=require("fs"),mn=W(),He=Z(),Sr=U(),{server:IE}=(zt(),te(yi)),{WebSocketServer:pse}=require("ws"),{createServer:Sse}=require("tls"),{getTicketKeys:Tse,restartNumber:gse,getWorkerIndex:kH}=je(),{Headers:WH}=(Af(),te(xP)),{recordAction:pl,recordActionBinary:Rse}=(bs(),te(tu)),{Request:QH,createReuseportFd:VH}=(pE(),te(UR)),{checkMemoryLimit:Ase}=Ji(),zH=require("tls"),$H=zH.createSecureContext;zH.createSecureContext=function(e){if(!e.cert||!e.key)return $H(e);let t={...e};delete t.key,delete t.cert;let r=$H(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){gse<=1&&mn.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:Ome,CONFIG_PARAMS:Ose}=Sr;He.initSync();var bse=He.get(Ose.HTTP_SESSIONAFFINITY),as={};Io.registerServer=WR;Io.httpServer=QR;Io.deliverSocket=KR;Io.startServers=JH;Io.when_components_loaded=null;IE.http=QR;IE.request=Ise;IE.socket=Cse;IE.ws=Dse;var VR={},yE={},Nse,Ai={},wE={},yse=[],$R=[];function JH(){return Io.when_components_loaded=CE().loadRootComponents(!0).then(()=>{Sl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)KR(n,r,s);else if(t.requestId)wse(t);else if(t.type===Sr.ITC_EVENT_TYPES.SHUTDOWN){mn.trace("received shutdown request",NE);for(let i in as){let o=as[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(f=>f.description.includes("connections")),l=0,d=setInterval(()=>{l++;let f=l>=100,E=o[_][f?"all":"idle"]();if(E.length===0){f&&clearInterval(d);return}l===1?mn.info(`Closing ${E.length} idle connections`):f&&mn.warn(`Forcefully closing ${E.length} active connections`);for(let h=0,p=E.length;h<p;h++){let S=E[h].socket;S._httpMessage&&!S._httpMessage.finished&&!f||(f?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
|
|
27
|
+
Connection: close\r
|
|
28
|
+
\r
|
|
29
|
+
`))}},25).unref()}o.close?.(()=>{if(He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&kH()==0)try{GH(He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,NE),o.cantCleanupProperly||mn.warn("Had to forcefully exit the thread",NE),process.exit(0)},5e3).unref()})}if(process.env.DEV_MODE)try{require("inspector").close()}catch(i){console.error("Could not close debugger",i)}}}).ref();let e=[];if(VH&&!bse)for(let t in as){let r=as[t];if(isNaN(t)&&kH()==0){mse(t)&&GH(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),mn.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=VH(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),mn.trace("Listening on port "+t,NE)}).on("error",i)}))}Promise.all(e).then(()=>{Sl?.postMessage({type:Sr.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(JH,"startServers");lse||JH();function KR(e,t,r){let n=e?.read?e:new _se({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=as[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=as[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(mn.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(KR,"deliverSocket");var YH=new Map;function wse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=YH.get(s),r){case"connection":i=KR(void 0,t),YH.set(s,i),i.write=(c,u,_)=>(Sl.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Sl.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Sl.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(wse,"proxyRequest");function WR(e,t,r=!0){!+t&&t!==He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(He.get(Sr.CONFIG_PARAMS.HTTP_PORT),10));let n=as[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",KH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else as[t]=e;e.on("unhandled",KH)}a(WR,"registerServer");function XH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],He.get(Sr.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:He.get(Sr.CONFIG_PARAMS.HTTP_PORT),secure:He.get(Sr.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),He.get(Sr.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:He.get(Sr.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(XH,"getPorts");function QR(e,t){for(let{port:r,secure:n}of XH(t))jH(r,n,t?.isOperationsServer),typeof e=="function"?$R[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,WR(e,r,!1)),wE[r]=YR($R,r),Nse=YR(yse,r)}a(QR,"httpServer");function jH(e,t,r){if(!Ai[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:He.get(n+"_keepAliveTimeout"),headersTimeout:He.get(n+"_headersTimeout"),requestTimeout:He.get(n+"_timeout")},i=He.get(n+"_mtls"),o=He.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=He.get(n+"tls_privateKey"),_=He.get(n+"tls_certificate"),l=He.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:qa(u),ciphers:He.get("tls_ciphers"),cert:qa(_),ca:l&&qa(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:Tse()})}let c=Ase();Ai[e]=(t?hse:fse)(s,async(u,_)=>{try{let d=performance.now(),f=new QH(u,_);r&&(f.isOperationsServer=!0);let E=await wE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=ZH(f)}if(c?E.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):E.headers?.set?.("Server","HarperDB"),E.status===-1){for(let H of E.headers||[])_.setHeader(H[0],H[1]);return u.baseRequest=f,_.baseResponse=E,Ai[e].emit("unhandled",u,_)}let h=E.status||200,p=performance.now(),S=p-d,O=E.body,g;if(!E.handlesHeaders){let H=E.headers||new WH;if(O?O.length>=0&&(typeof O=="string"?H.set("Content-Length",Buffer.byteLength(O)):H.set("Content-Length",O.length),g=!0):(H.set("Content-Length","0"),g=!0),H.append){let v=`hdb;dur=${S.toFixed(2)}`;E.wasCacheMiss&&(v+=", miss"),H.append("Server-Timing",v,!0)}_.writeHead(h,H&&(H[Symbol.iterator]?Array.from(H):H)),g&&_.end(O)}let R=f.handlerPath,B=f.method;if(pl(S,"duration",R,B,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),Rse(h<400,"success",R,B),!g)if(O?.pipe){O.pipe(_),O.destroy&&_.on("close",()=>{O.destroy()});let H=0;O.on("data",v=>{H+=v.length}),O.on("end",()=>{pl(performance.now()-p,"transfer",R,B),pl(H,"bytes-sent",R,B)})}else O?.then?O.then(H=>{_.end(H)},l):_.end(O)}catch(d){l(d)}function l(d){let f=d.headers;_.writeHead(d.statusCode||500,f&&(f[Symbol.iterator]?Array.from(f):f)),_.end(d.toString()),d.statusCode?d.statusCode===500?mn.warn(d):mn.info(d):mn.error(d)}a(l,"onError")}),i&&(Ai[e].mtlsConfig=i),t&&(Ai[e].on("secureConnection",u=>{u._parent.startTime&&pl(performance.now()-u._parent.startTime,"tls-handshake",e),pl(u.isSessionReused(),"tls-reused",e)}),Ai[e].isSecure=!0),WR(Ai[e],e)}return Ai[e]}a(jH,"getHTTPServer");function YR(e,t){let r=ZH;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(YR,"makeCallbackChain");function ZH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new WH}}a(ZH,"unhandled");function Ise(e,t){QR(e,{requestOnly:!0,...t})}a(Ise,"onRequest");function Cse(e,t){let r;if(t.securePort){let n=He.get("tls_privateKey"),s=He.get("tls_certificate"),i=t.mtls?.certificateAuthority||He.get("tls_certificateAuthority");r=Sse({ciphers:He.get("tls_ciphers"),key:qa(n),cert:qa(s),ca:i&&qa(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),as[t.securePort]=r}return t.port&&(r=dse(e),as[t.port]=r),r}a(Cse,"onSocket");Object.defineProperty(Ese.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 Dse(e,t){let r;for(let{port:n,secure:s}of XH(t)){yE[n]||(yE[n]=new pse({server:r=jH(n,s)}),yE[n].on("connection",async(c,u)=>{try{let _=new QH(u);_.isWebSocket=!0;let l=wE[n](_),d=u.headers["sec-websocket-protocol"]||"",f=VR[n];if(d){let E;for(let h=0;h<f.length;h++){let p=f[h];p.protocol===d&&(E=!0,p.listener(c,_,l))}if(E)return}for(let E=0;E<f.length;E++){let h=f[E];h.protocol||h.listener(c,_,l)}}catch(_){mn.warn("Error handling WebSocket connection",_)}}),yE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=VR[n];o||(o=VR[n]=[]),o.push({listener:e,protocol:i}),wE[n]=YR($R,n)}return r}a(Dse,"onWebSocket");function KH(e,t){t.writeHead(404),t.end(`Not found
|
|
30
|
+
`)}a(KH,"defaultNotFound")});async function nx({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await JR.getResource(e,{});s=new ZR(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await JR.get(e);i&&i.delete()}s=new LE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Tl.put(n)),s}function XR(){return DE++,DE>65500&&(DE=1),DE}function jR(e,t,r=e){let{topic:n,retain:s}=e;e.data=t,e.async=!0,e.authorize=!0;let i=Qs.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Ke(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var ex,Co,tx,rx,JR,Tl,DE,LE,ZR,sx=Oe(()=>{Ne();pc();ex=x(Nr()),Co=x(W());Ui();tx=x(je()),rx=x(zR());zt();JR=at({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"}]}}]}),Tl=at({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,tx.getWorkerIndex)()===0&&(async()=>{await rx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Tl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await Xe.getUser(r.user.username)),Ke(r,()=>{try{jR(r,t)}finally{Tl.delete(e.id,r)}})}})();a(nx,"getSession");DE=1;a(XR,"getNextMessageId");LE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(O=>O.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Co.trace)("Resuming subscription from",s,"from",o);let E=Qs.getMatch(_);if(!E){let O=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw O.statusCode=404,O}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let O=f.url.slice(1);if(O.indexOf("#")>-1&&O.indexOf("#")!==O.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,O.indexOf("+")===O.length-1)f.onlyChildren=!0,f.url="/"+O.slice(0,O.length-1);else{let g=O.split("/"),R;for(let v=0;v<g.length;v++)if(g[v].indexOf("+")>-1)if(g[v]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&R)throw new Error("Filters can not be combined");let B=!0;g[g.length-1]==="#"&&(g.length--,B=!1),R&&(n=a(v=>{let M=v.id;if(!Array.isArray(M)||B&&M.length!==g.length)return!1;for(let $=0;$<g.length;$++)if(g[$]!=="+"&&g[$]!==M[$])return!1;return!0},"filter"));let H=g.indexOf("+");f.url="/"+(H>-1?g.slice(0,H):g).concat("").join("/")}}let h=E.path,p=E.Resource,S=await Ke(f,async()=>{let O=await p.subscribe(f);if(!O)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!O[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let g of O)try{let R;if(g.type&&g.type!=="put"&&g.type!=="delete"&&g.type!=="message"&&g.type!=="patch"||n&&!n(g))continue;r?(g.topic=s,R=this.needsAcknowledge(g)):(g.acknowledge?.(),R=XR());let B=g.id;Array.isArray(B)&&(B=Go(B)),B==null&&(B=""),this.listener(h+"/"+B,g.value,R,t)}catch(R){(0,Co.warn)(R)}})(),O});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=XR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,jR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Ke(r,async()=>{if(!t){let n=await Tl.get(this.sessionId,r);n?.doesExist()&&await jR(n,n.data,r)}await Tl.delete(this.sessionId,r)}).catch(n=>{(0,Co.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(jR,"publish");ZR=class extends LE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=XR(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Co.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,ex.getNextMonotonicTime)()),(0,Co.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),JR.put(this.sessionRecord)),t.qos}}});var eA={};Fe(eA,{bypassAuth:()=>Lse,start:()=>Mse});function Lse(){ux=!0}function Mse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=ax(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,Tr.info)("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(u){if(_.authorized)try{let E=u.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,Tr.error)(E)}else if(u.required)return(0,Tr.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&ux&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,cx.getSuperUser)());let{onMessage:d,onClose:f}=ax(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Tr.info)("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function ax(e,t,r,n,s){ox||(ox=!0,eu(d=>{ME>0&&d.push({metric:"mqtt-connections",connections:ME,byThread:!0})}));let i;ME++;let o,c={protocolVersion:4},u=(0,PE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){ME--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),sn(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await Xe.getUser(d.username,d.password.toString(),r),(0,UE.get)(cs.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ix.notify({username:n.username,status:cs.AUTH_AUDIT_STATUS.SUCCESS,type:cs.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,UE.get)(cs.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&ix.error({username:n.username,status:cs.AUTH_AUDIT_STATUS.FAILURE,type:cs.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return sn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let R=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?R(d.will.payload):void 0,delete d.will.payload}o=nx({user:n,...d}),o=await o,s.sessions.add(o)}catch(R){return(0,Tr.error)(R),sn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:R.code||5,returnCode:R.code||128})}sn(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((R,B,H,v)=>{try{let M=R.indexOf("/",1),$=M>0?R.slice(0,M):R;f({cmd:"publish",topic:R,payload:E(B),messageId:H||Math.floor(Math.random()*1e8),qos:v.qos},$)}catch(M){(0,Tr.error)(M),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let R of d.subscriptions){let B;try{B=(await o.addSubscription(R,R.qos>=1)).qos||0}catch(H){(0,Tr.error)(H),B=c.protocolVersion<5?128:H.statusCode===403?135:H.statusCode===404?143:128}h.push(B)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let R=[];for(let B of d.unsubscriptions)R.push(o.removeSubscription(B)?0:17);f({cmd:"unsuback",granted:R,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let p=d.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type"))),O=d.payload?.length>0?S(d.payload):void 0,g;try{g=await o.publish(d,O)}catch(R){(0,Tr.warn)(R),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:g===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),sn(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Tr.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,PE.generate)(h,c);t(S),xr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return pi(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var PE,cx,UE,cs,Tr,ix,ux,ox,ME,lx=Oe(()=>{PE=require("mqtt-packet");sx();cx=x(nn());ya();bs();zt();UE=x(Z()),cs=x(U()),Tr=x(W()),ix=(0,Tr.loggerWithTag)("auth-event"),ux=(0,UE.get)(cs.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Lse,"bypassAuth");a(Mse,"start");ME=0;a(ax,"onSocket")});var Pf={};Fe(Pf,{component_errors:()=>ka,loadComponent:()=>vE,loadComponentDirectories:()=>Tx,setErrorReporter:()=>Bse});function Tx(e,t){t&&(rA=t),e&&(nA=e);let r=[];if((0,Bn.existsSync)(tA)){let s=(0,Bn.readdirSync)(tA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,pt.join)(tA,o);r.push(vE(c,rA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(vE(n,rA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{Sx=!0})}function Bse(e){Rl=e}async function vE(e,t,r,n,s,i){if(!dx.has(e)){dx.set(e,!0),s&&(nA=s);try{let o;n&&(ka=new Map);let c=(0,pt.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,Bn.existsSync)(c)?o=n?(0,px.getConfigObj)():(0,fx.parseDocument)((0,Bn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=sA;let u=[],_=n;for(let l in o){let d=o[l];if(ka.set(n?l:(0,pt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let g=e,R;for(;!(0,Bn.existsSync)(R=(0,pt.join)(g,"node_modules",l));)if(g=(0,pt.dirname)(g),g.length<(0,mx.getHdbBasePath)().length){R=null;break}if(R)f=await vE(R,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=vse[l];if(!f)continue;u.push(f);let h=a(g=>(g.origin=r,at(g)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,O=!p?.https&&p?.port;if(Ga.isMainThread&&(f=await f.startOnMainThread?.({server:Xe,ensureTable:h,port:O,securePort:S,resources:t,...d})||f,n&&p))for(let g of[O,S])try{if(+g&&!_x.includes(g)){let R=iA.get(oA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);R&&gl.default.warn("Session affinity is not recommended and may cause memory leaks"),(R||!mE)&&(_x.push(g),aA(g,R))}}catch(R){console.error("Error listening on socket",g,R,l)}if(t.isWorker&&(f=await f.start?.({server:Xe,ensureTable:h,port:O,securePort:S,resources:t,...d})||f),nA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,hx.handleHDBError)("Can not reference parent directories");let g=(0,pt.join)(e,d.files).replace(/\\/g,"/"),R=g.indexOf("/*");if(R>-1&&d.files!==sA[l]?.files&&!(0,Bn.existsSync)(g.slice(0,R)))throw new Error(`The path '${g.slice(0,R)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let B=(0,pt.basename)(e),H=d.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+B+H.slice(2):H==="."?"/"+B:"/"+B+"/"+H;let v,M,$;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",M=(0,pt.join)(e,z)}else($=g.indexOf("/*"))>-1&&(M=g.slice(0,$+1),v=(0,pt.relative)(e,M));let K=!1;if(Ga.isMainThread&&f.setupDirectory&&(K=await f.setupDirectory?.(H,M,t)),t.isWorker&&f.handleDirectory&&(K=await f.handleDirectory?.(H,M,t)),K)continue;for(let z of await(0,Ex.default)(g,{onlyFiles:!1,objectMode:!0})){let{path:se,dirent:Te}=z;_=!0;let oe=(0,pt.relative)(e,se).replace(/\\/g,"/");if(v)if(oe.startsWith(v))oe=oe.slice(v.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${oe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let xe=H+(H.endsWith("/")?"":"/")+oe;try{if(Te.isFile()){let de=await Pse(se);Ga.isMainThread&&await f.setupFile?.(de,xe,se,t),t.isWorker&&await f.handleFile?.(de,xe,se,t)}else Ga.isMainThread&&await f.setupDirectory?.(xe,se,t),t.isWorker&&await f.handleDirectory?.(xe,se,t)}catch(de){de.message=`Could not load ${Te.isFile()?"file":"directory"} '${se}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${de.message}`,Rl?.(de),((0,Va.getWorkerIndex)()===0?console:gl.default).error(de),t.set(d.path||"/",new Al(de)),ka.set(n?l:(0,pt.basename)(e),de.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,pt.basename)(e)}' due to: ${h.message}`,Rl?.(h),((0,Va.getWorkerIndex)()===0?console:gl.default).error(h),t.set(d.path||"/",new Al(h),null,!0),ka.set(n?l:(0,pt.basename)(e),h.message)}}if(Ga.isMainThread&&!Sx&&i&&(0,Va.watchDir)(e,async()=>Tx()),o.extensionModule)return await Cd((0,pt.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;Rl?.(new Error(l)),((0,Va.getWorkerIndex)()===0?console:gl.default).error(l),ka.set((0,pt.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Rl?.(o),t.set("",new Al(o))}}}var Bn,pt,Ga,fx,iA,oA,Ex,Va,gl,hx,mx,Use,px,Pse,tA,nA,Sx,rA,ka,vse,sA,_x,dx,Rl,Al,vf=Oe(()=>{Bn=require("fs"),pt=require("path"),Ga=require("worker_threads"),fx=require("yaml"),iA=x(Z()),oA=x(U());PD();xD();FD();b0();_H();pH();Ex=x(require("fast-glob")),Va=x(je()),gl=x(W());hS();zt();hx=x(ee());gn();Ne();cA();mx=x(Z()),Use=x(AH());yf();qH();lx();px=x(vr());pE();({readFile:Pse}=Bn.promises),tA=iA.get(oA.CONFIG_PARAMS.COMPONENTSROOT),nA=new Map,ka=new Map;a(Tx,"loadComponentDirectories");vse={REST:zf,rest:zf,graphqlSchema:ES,jsResource:pS,fastifyRoutes:IR,login:TS,static:CR,operationsApi:Use,customFunctions:{},http:{},clustering:kR,authentication:Qu,mqtt:eA},sA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(sA,"static",{value:{files:"web/**"}});_x=[],dx=new Map;a(Bse,"setErrorReporter");a(vE,"loadComponent");Al=class extends vt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var CE=T((zme,Rx)=>{var{isMainThread:gx}=require("worker_threads"),{getTables:Hse}=(Ne(),te(qe)),{loadComponentDirectories:xse,loadComponent:Fse}=(vf(),te(Pf)),{resetResources:qse}=(pc(),te(cb)),Gse=Eg(),kse=vr(),{dirname:Vse}=require("path"),{getConnection:$se}=Ot(),Yse=Z(),Kse=U(),uA=new Map;async function Wse(e=!1){!gx&&Yse.get(Kse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&$se();try{gx&&await Gse()}catch(n){console.error(n)}let t=qse();Hse(),t.isWorker=e,await Fse(Vse(kse.getConfigFilePath()),t,"hdb",!0,uA),await xse(uA,t);let r=[];for(let[n]of uA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Wse,"loadRootComponents");Rx.exports.loadRootComponents=Wse});var je=T((Xme,bi)=>{"use strict";var{Worker:Qse,MessageChannel:zse,parentPort:us,isMainThread:EA,threadId:Jse,workerData:qs}=require("worker_threads"),{PACKAGE_ROOT:Xse}=U(),{join:Nx,isAbsolute:jse,extname:Zse}=require("path"),{server:yx}=(zt(),te(yi)),{watch:eie,readdir:tie}=require("fs/promises"),{totalmem:Ax}=require("os"),Ol=U(),wx=Z(),Gs=W(),{randomBytes:rie}=require("crypto"),{_assignPackageExport:nie}=require("../index"),sie=U(),Ox=1024*1024,Oi=[],pn=[],iie=50,hA=1e4,oie="restart",Ix="request_thread_info",Cx="resource_report",Dx="thread_info",Lx="added-port",aie="ack",lA;nie("threads",pn);bi.exports={startWorker:_A,restartWorkers:pA,shutdownWorkers:die,workers:Oi,setMonitorListener:gie,onMessageFromWorkers:fie,onMessageByType:xx,broadcast:hie,broadcastWithAcknowledgement:pie,setChildListenerByType:_ie,getWorkerIndex:Mx,getWorkerCount:Ux,getTicketKeys:vx,setMainIsWorker:uie,setTerminateTimeout:cie,restartNumber:qs?.restartNumber||1};pn.onMessageByType=xx;pn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=pn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var mA;function cie(e){hA=e}a(cie,"setTerminateTimeout");function Mx(){return qs?qs.workerIndex:mA?0:void 0}a(Mx,"getWorkerIndex");function Ux(){return qs?qs.workerCount:mA?1:void 0}a(Ux,"getWorkerCount");function uie(e){mA=e}a(uie,"setMainIsWorker");var Px=1,BE;function vx(){return BE||(BE=EA?rie(48):qs.ticketKeys,BE)}a(vx,"getTicketKeys");Object.defineProperty(yx,"workerIndex",{get(){return Mx()}});Object.defineProperty(yx,"workerCount",{get(){return Ux()}});var Bx={[Ix](e,t){Sie(t)},[Cx](e,t){Tie(t,e)}};function _A(e,t={}){let r=process.constrainedMemory?.()||Ax();r=Math.min(r,Ax(),2e4*Ox);let n=wx.get(Ol.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/Ox/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of pn){let _=new zse;_.existingPort=u,i.push(_),o.push(_.port2)}Zse(e)||(e+=".js");let c=new Qse(jse(e)?e:Nx(Xse,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:Px=t.threadCount,name:t.name,restartNumber:bi.exports.restartNumber,ticketKeys:vx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Lx,port:u,threadId:c.threadId},[u]);return xE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>_A(e,t),c.on("error",u=>{console.error("Worker error:",u),Gs.error("Worker error:",u)}),c.on("exit",u=>{Oi.splice(Oi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<iie?(t.unexpectedRestarts=c.unexpectedRestarts+1,_A(e,t)):Gs.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{Bx[u.type]?.(u,c)}),Oi.push(c),Aie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(_A,"startWorker");var lie=[Ol.THREAD_TYPES.HTTP];async function pA(e=null,t=Math.max(Px>3,1),r=!0){if(EA){if(r){let{loadRootComponents:o}=CE();await o()}bi.exports.restartNumber++,t<1&&(t=t*Oi.length);let n=[],s=[];for(let o of Oi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Gs.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:bi.exports.restartNumber,type:Ol.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=lie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),hA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===sie.ITC_EVENT_TYPES.CHILD_STARTED&&(Gs.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");Gs.trace("Waiting for worker to start",_.threadId),_.on("message",f)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=Rf();r&&(e==="http"||!e)&&wx.get(Ol.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else us.postMessage({type:oie,workerType:e})}a(pA,"restartWorkers");function _ie(e,t){Bx[e]=t}a(_ie,"setChildListenerByType");function die(e){return pA(e,1/0,!1)}a(die,"shutdownWorkers");var Hx=[];function fie(e){Hx.push(e)}a(fie,"onMessageFromWorkers");var dA=new Map;function xx(e,t){let r=dA.get(e);r||dA.set(e,r=[]),r.push(t)}a(xx,"onMessageByType");var Eie=10;async function hie(e){let t=0;for(let r of pn)try{r.postMessage(e),t++>Eie&&(t=0,await new Promise(setImmediate))}catch(n){Gs.error("Unable to send message to worker",n)}}a(hie,"broadcast");var HE=new Map,mie=1;function pie(e){return new Promise(t=>{let r=0;for(let n of pn)try{let s=mie++,i=a(()=>{HE.delete(s),--r===0&&t(),n!==us&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,HE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of HE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Gs.error("Unable to send message to worker",s)}r===0&&t()})}a(pie,"broadcastWithAcknowledgement");function Sie(e){e.postMessage({type:Dx,workers:Fx()})}a(Sie,"sendThreadInfo");function Fx(){let e=Date.now();return Oi.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(Fx,"getChildWorkerInfo");function Tie(e,t){e.resources=t,e.resources.updated=Date.now()}a(Tie,"recordResourceReport");var fA;function gie(e){fA=e}a(gie,"setMonitorListener");var Rie=1e3,bx=!1;function Aie(){bx||(bx=!0,setInterval(()=>{for(let e of Oi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}fA&&fA()},Rie).unref())}a(Aie,"startMonitoring");var Oie=1e3;if(us){xE(us);for(let e=0,t=qs.addPorts.length;e<t;e++){let r=qs.addPorts[e];r.threadId=qs.addThreadIds[e],xE(r)}setInterval(()=>{let e=process.memoryUsage();us.postMessage({type:Cx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Oie).unref(),lA=a(()=>new Promise((e,t)=>{us.on("message",r),us.postMessage({type:Ix});function r(n){n.type===Dx&&(us.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else lA=Fx;bi.exports.getThreadInfo=lA;function xE(e,t){pn.push(e),e.on("message",r=>{if(r.type===Lx)r.port.threadId=r.threadId,xE(r.port);else if(r.type===aie){let n=HE.get(r.id);n&&n()}else{for(let s of Hx)s(r,e);let n=dA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Gs.error(i)}}}).on("close",()=>{pn.splice(pn.indexOf(e),1)}).on("exit",()=>{pn.splice(pn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(xE,"addPort");if(EA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await tie(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(Nx(n,i.name));try{for await(let{filename:i}of eie(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await pA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");bi.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else us.on("message",async e=>{let{type:t}=e;t===Ol.ITC_EVENT_TYPES.SHUTDOWN&&(bi.exports.restartNumber=e.restartNumber,us.unref(),setTimeout(()=>{Gs.warn("Thread did not voluntarily terminate",Jse),process.exit(0)},hA).unref())})});var Wx={};Fe(Wx,{startHTTPThreads:()=>Nie,startSocketServer:()=>aA,updateWorkerIdleness:()=>Kx});async function Nie(e=2,t){if(t)TA(0,1,!0);else{let{loadRootComponents:n}=CE();if(e===0)return(0,Ni.setMainIsWorker)(!0),await zR().startServers(),Promise.resolve([]);await n()}let r=(0,Vx.checkMemoryLimit)();r&&!process.env.DEV_MODE&&(console.error(r),setInterval(()=>{kE.notify(r)},bie).unref());for(let n=0;n<e;n++)TA(n,e);return Promise.all(Yx)}function TA(e,t=1,r){if(SA++,(0,Ni.startWorker)("server/threads/threadServer.js",{name:GE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===GE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Yx.push(s),await s,$a.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=qE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=$a.indexOf(n);o>-1&&$a.splice(o,1)}if(a(i,"removeWorker"),Ya){let o=Ya;Ya=[];for(let c of o)$x[c.localPort](null,c)}}}),r){let n=setInterval(()=>{gA?gA=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Ni.shutdownWorkers)(),SA=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function aA(e=0,t){if(typeof e=="string")try{(0,VE.existsSync)(e)&&(0,VE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=yie:r=wie(t):r=RA;let n=(0,Ka.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=$x[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),gA=!0,r(o,(c,u)=>{if(!c){if(qx){let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});qx.deliverSocket(l,e,u),l.resume()}else SA>0?(Ya.length===0&&setTimeout(()=>{Ya.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,Ya.push(o)):(console.log("start up a dynamic thread to handle request"),TA(0));xr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});Die(l,c,e)}xr(!0,"socket-routed")})};let s=pu();kE.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function RA(e,t){let r,n=0;for(let s of $a){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=FE)return FE=i,t(r);n=i}FE=0,t(r)}function yie(e,t){let r={};e.getpeername(r);let n=r.address,s=Wa.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);RA(e,o=>{Wa.set(n,{worker:o,lastUsed:i}),t(o)})}function wie(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Ka.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Wa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);RA(n,d=>{Wa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Kx(){FE=0;for(let e of $a)e.expectedIdle=e.recentELU.idle+Iie,e.requests=1;$a.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Die(e,t,r){let n=Cie++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),qE.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),qE.delete(n)),s.event=="destroy"&&(e.destroy(),qE.delete(n))})}var Ni,Ka,GE,kE,VE,kx,Vx,$a,Ya,$x,qx,SA,Yx,bie,gA,FE,Gx,Wa,Iie,qE,Cie,cA=Oe(()=>{Ni=x(je()),Ka=require("net"),GE=x(U()),kE=x(W()),VE=require("fs");bs();kx=require("worker_threads"),Vx=x(Ji()),$a=[],Ya=[],$x=[],SA=0,Yx=[];kx.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});bie=6e5;a(Nie,"startHTTPThreads");a(TA,"startHTTPWorker");a(aA,"startSocketServer");FE=0;a(RA,"findMostIdleWorker");Gx=36e5,Wa=new Map;a(yie,"findByRemoteAddressAffinity");a(wie,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Wa)r.lastUsed+Gx<e&&Wa.delete(t)},Gx).unref();Iie=1e3;a(Kx,"updateWorkerIdleness");(0,Ni.setMonitorListener)(Kx);qE=new Map,Cie=1;a(Die,"proxySocket")});XE();var{startHTTPThreads:Lie,startSocketServer:Qx}=(cA(),te(Wx));Lie(0,!0);Qx(9925);Qx(9926);
|