harperdb 4.3.0-alpha.2 → 4.3.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +54 -54
- package/bin/lite.js +18 -18
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +17 -17
- package/launchServiceScripts/launchNatsReplyService.js +17 -17
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +17 -17
- package/npm-shrinkwrap.json +48 -48
- package/package.json +2 -2
- package/resources/RecordEncoder.d.ts +1 -0
- package/resources/search.d.ts +10 -1
- package/server/jobs/jobProcess.js +17 -17
- package/server/threads/threadServer.js +17 -17
- 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 +2 -0
- package/utility/scripts/restartHdb.js +17 -17
- package/studio/build-local/static/js/main.824bbe07.js +0 -2
- /package/studio/build-local/static/js/{main.824bbe07.js.LICENSE.txt → main.67d8f5e6.js.LICENSE.txt} +0 -0
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
"use strict";var gq=Object.create;var ja=Object.defineProperty;var Rq=Object.getOwnPropertyDescriptor;var Aq=Object.getOwnPropertyNames;var Oq=Object.getPrototypeOf,bq=Object.prototype.hasOwnProperty;var a=(e,t)=>ja(e,"name",{value:t,configurable:!0});var Ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$e=(e,t)=>{for(var r in t)ja(e,r,{get:t[r],enumerable:!0})},CA=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Aq(t))!bq.call(e,n)&&n!==r&&ja(e,n,{get:()=>t[n],enumerable:!(s=Rq(t,n))||s.enumerable});return e};var v=(e,t,r)=>(r=e!=null?gq(Oq(e)):{},CA(t||!e||!e.__esModule?ja(r,"default",{value:e,enumerable:!0}):r,e)),ee=e=>CA(ja({},"__esModule",{value:!0}),e);var UA=T((Yoe,LA)=>{var Nq=require("fast-glob"),{statSync:ih,existsSync:oh,readFileSync:yq,writeFileSync:Iq}=require("fs"),{spawnSync:wq,spawn:Cq,execFileSync:$oe}=require("child_process"),{isMainThread:Dq}=require("worker_threads"),{join:Wn,relative:DA}=require("path"),{PACKAGE_ROOT:Os}=D(),{tmpdir:Lq,platform:Uq}=require("os");require("source-map-support").install();var Mq=["resources","server","dataLayer","components"],Za="ts-build",ah,Pq=__filename.endsWith("tsBuild.js");if(Pq){if(Dq){let r;try{ih(Wn(Os,Za)),r=!0}catch{}if(r)for(let s of Nq.sync(Mq.map(n=>n+"/**/*.ts"),{cwd:Os})){let n=0,i=0;try{n=ih(Wn(Os,s)).mtimeMs-5e3,i=ih(Wn(Os,Za,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),ah=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),ah=!0;if(ah){let s=Wn(Os,"node_modules/.bin/tsc");Uq()==="win32"&&(s+=".cmd");let n=wq(s,{cwd:Os});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=Wn(Lq(),"harperdb-tsc.pid"),o;if(oh(i))try{process.kill(+yq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Cq(s,["--watch"],{cwd:Os,detached:!0,stdio:"ignore"});Iq(i,c.pid.toString()),c.unref()}}}}let e=LA.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(Os)&&!s[0].includes("node_modules")){let i=DA(Os,s[0]),o;i.startsWith(Za)?o=Wn(Os,DA(Za,i)):o=Wn(Os,Za,i);let c=Wn(o,r),u=c+".js";if(oh(u))return u;if(c.includes(".")&&oh(c))return c}return t(r,s,n)}}});var D=T((Qoe,KA)=>{"use strict";var jr=require("path"),vq=require("fs"),{relative:Koe,join:Woe}=jr,{existsSync:Bq}=vq;function Hq(){let e=__dirname;for(;!Bq(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(Hq,"getHDBPackageRoot");var Qn=Hq(),MA="js",ql=MA,xq="harperdb-config.yaml",qq="defaultConfig.yaml",Fq="hdb",PA=`harperdb.${ql}`,vA=`customFunctionsServer.${ql}`,Gq=`restartHdb.${ql}`,uh="HarperDB",xl="Custom Functions",Fl="Clustering Hub",Gl="Clustering Leaf",kq="Clustering Ingest Service",Vq="Clustering Reply Service",$q="foreground.pid",Yq="hdb.pid",Kq="data",Wq={HDB:uh,CLUSTERING_HUB:Fl,CLUSTERING_LEAF:Gl,CLUSTERING_INGEST_SERVICE:kq,CLUSTERING_REPLY_SERVICE:Vq,CUSTOM_FUNCTIONS:xl,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},Qq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},zq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Jq={harperdb:uh,"clustering hub":Fl,"clustering leaf":Gl,"custom functions":xl,custom_functions:xl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},Xq={CLUSTERING_HUB_PROC_DESCRIPTOR:Fl,CLUSTERING_LEAF_PROC_DESCRIPTOR:Gl},ch={HDB:jr.join(Qn,"server/harperdb"),CUSTOM_FUNCTIONS:jr.join(Qn,"server/customFunctions"),CLUSTERING_HUB:jr.join(Qn,"server/nats"),CLUSTERING_LEAF:jr.join(Qn,"server/nats")},jq={HDB:jr.join(ch.HDB,PA),CUSTOM_FUNCTIONS:jr.join(ch.CUSTOM_FUNCTIONS,vA)},Zq={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:jr.join(Qn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:jr.join(Qn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:jr.join(Qn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},eF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},BA="support@harperdb.io",tF="customer-success@harperdb.io",HA=1,rF=4141,xA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",sF="https://www.harperdb.io/product",nF=`For support, please submit a request at ${xA} or contact ${BA}`,qA=`For license support, please contact ${tF}`,iF="None of the specified records were found.",oF="hash attribute not found",aF=`Your current license only supports ${HA} role. ${qA}`,cF="Your current license only supports 3 connections to a node.",uF="127.0.0.1",lF=1,_F=/^\.$/,dF=/^\.\.$/,fF="U+002E",EF=/\//g,hF="U+002F",mF=/U\+002F/g,pF=/^U\+002E$/,SF=/^U\+002EU\+002E$/,TF="d",gF=999999,RF="*",AF="--max-old-space-size=",OF="system",bF="__hdb_hash",NF=".harperdb",yF=".hdb",IF="keys",wF="hdb_boot_properties.file",CF=".updateConfig.json",DF="SIGTSTP",LF=24,UF=6e4,MF=448,PF="blob",vF="trash",BF="database",HF="schema",xF="transactions",qF=".count",FF="id",GF="PROCESS_NAME",FA={SETTINGS_PATH_KEY:"settings_path"},GA=require("lodash"),kF={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"},VF={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},$F={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},YF={JOB_TABLE_NAME:"hdb_job",NODE_TABLE_NAME:"hdb_nodes",ATTRIBUTE_TABLE_NAME:"hdb_attribute",LICENSE_TABLE_NAME:"hdb_license",ROLE_TABLE_NAME:"hdb_role",SCHEMA_TABLE_NAME:"hdb_schema",TABLE_TABLE_NAME:"hdb_table",USER_TABLE_NAME:"hdb_user",INFO_TABLE_NAME:"hdb_info"},KF={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},yr="hdb_internal:",WF={CREATE_SCHEMA:yr+"create_schema",CREATE_TABLE:yr+"create_table",CREATE_ATTRIBUTE:yr+"create_attribute",ADD_USER:yr+"add_user",ALTER_USER:yr+"alter_user",DROP_USER:yr+"drop_user",HDB_NODES:yr+"hdb_nodes",HDB_USERS:yr+"hdb_users",HDB_WORKERS:yr+"hdb_workers",CATCHUP:yr+"catchup",SCHEMA_CATCHUP:yr+"schema_catchup",WORKER_ROOM:yr+"cluster_workers"},QF={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"},zF="060493.ks",JF=".license",XF={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"},jF={CSV:".csv",JSON:".json"},ZF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},eG={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},ec={};ec[X.INSERT]=X.INSERT;ec[X.UPDATE]=X.UPDATE;ec[X.UPSERT]=X.UPSERT;ec[X.DELETE]=X.DELETE;var ve=Object.create(null);ve[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;ve[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;ve[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;ve[X.READ_LOG]=X.READ_LOG;ve[X.ADD_NODE]=X.ADD_NODE;ve[X.LIST_USERS]=X.LIST_USERS;ve[X.LIST_ROLES]=X.LIST_ROLES;ve[X.USER_INFO]=X.USER_INFO;ve[X.SQL]=X.SQL;ve[X.GET_JOB]=X.GET_JOB;ve[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;ve[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;ve[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;ve[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;ve[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;ve[X.REMOVE_NODE]=X.REMOVE_NODE;ve[X.RESTART]=X.RESTART;ve[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;ve[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;ve[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;ve[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;ve[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;ve[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;ve[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;ve[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;ve[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var tG={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"},rG={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},kA={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"},sG=GA.invert(kA),nG={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:FA.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 iG={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},oG={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"},aG={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"},cG={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},uG={VERSION_DEFAULT:"2.2.0"},lG={DEVELOPMENT:8192,DEFAULT:512},_G={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"},dG={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"},fG={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},$A={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},EG=Symbol("metadata"),hG="__clustering__",mG=Object.values($A),pG=15984864e5,YA={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},SG=GA.invert(YA),TG={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"},gG=111,RG=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
4
|
-
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,s])=>({pid:Number.parseInt(r,10),name:ek.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(nk,"findPs")});var mt=T((rae,uO)=>{"use strict";var ik="__dbis__",ok="__txns__",ak="__environment_name__",ck="__dbi_defintion__",uk={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"},lk=["__createdtime__","__updatedtime__"],_k="\uFFFF",cO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},dk=Object.values(cO);uO.exports={AUDIT_STORE_NAME:ok,INTERNAL_DBIS_NAME:ik,DBI_DEFINITION_NAME:ck,SEARCH_TYPES:uk,TIMESTAMP_NAMES:lk,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:ak,TRANSACTIONS_DBI_NAMES_ENUM:cO,TRANSACTIONS_DBIS:dk,OVERFLOW_MARKER:_k}});var Ir=T((sae,SO)=>{"use strict";var lO=D(),_O=mt(),dO={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},fO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),EO={500:fO("There was an error processing your request."),400:"Invalid request"},fk=EO[dO.INTERNAL_SERVER_ERROR],Ek={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.`},hk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},mk={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"},pk={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${_O.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${_O.INTERNAL_DBIS_NAME}`,START_VALUE_REQUIRED:"start_value is required",END_VALUE_REQUIRED:"end_value is required",CANNOT_COMPARE_STRING_TO_NUMERIC_KEYS:"cannot compare a string to numeric keys",END_VALUE_MUST_BE_GREATER_THAN_START_VALUE:"end_value must be greater than or equal to start_value",UNKNOWN_SEARCH_TYPE:"unknown search type",CANNOT_DROP_TABLE_HASH_ATTRIBUTE:"cannot drop a table's hash attribute"},Sk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${lO.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 ${lO.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"},hO={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"},Tk={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."},gk={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`},Rk={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"},Ak={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Ok={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`},mO={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.`},pO={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}`},bk={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."},Nk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},yk={...hO,...mk,...Ek,...Tk,...gk,...Rk,...Ak,...Ok,...Sk,...mO,...pO,...bk,...Nk,...hk};SO.exports={CHECK_LOGS_WRAPPER:fO,HDB_ERROR_MSGS:yk,DEFAULT_ERROR_MSGS:EO,DEFAULT_ERROR_RESP:fk,HTTP_STATUS_CODES:dO,LMDB_ERRORS_ENUM:pk,AUTHENTICATION_ERROR_MSGS:hO,VALIDATION_ERROR_MSGS:mO,ITC_ERRORS:pO}});var Z=T((iae,RO)=>{"use strict";var Ho=Ir(),Ik=G(),wk=D(),Kl=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,TO),this.statusCode=s||Ho.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Ho.DEFAULT_ERROR_MSGS[s]?Ho.DEFAULT_ERROR_MSGS[s]:Ho.DEFAULT_ERROR_MSGS[Ho.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&Ik[n](i)}},Sh=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}},Th=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function TO(e,t,r,s=wk.LOG_LEVELS.ERROR,n=null,i=!1){if(gO(e))return e;let o=new Kl(e,t,r,s,n);return i&&delete o.stack,o}a(TO,"handleHDBError");function gO(e){return e.__proto__.constructor.name===Kl.name}a(gO,"isHDBError");RO.exports={isHDBError:gO,handleHDBError:TO,ClientError:Sh,ServerError:Th,hdb_errors:Ho}});var ze=T((aae,wO)=>{"use strict";var lc=D(),Ck=z(),rr=j(),_c=require("path"),Dk=require("minimist"),AO=require("fs-extra"),OO=require("lodash");rr.initSync();var{CONFIG_PARAMS:zn,DATABASES_PARAM_CONFIG:oc,SYSTEM_SCHEMA_NAME:Wl}=lc,ac,cc,uc;function bO(){if(ac!==void 0)return ac;if(rr.getHdbBasePath()!==void 0)return ac=rr.get(zn.STORAGE_PATH)||_c.join(rr.getHdbBasePath(),lc.DATABASES_DIR_NAME),ac}a(bO,"getBaseSchemaPath");function NO(){if(cc!==void 0)return cc;if(rr.getHdbBasePath()!==void 0)return cc=IO(Wl),cc}a(NO,"getSystemSchemaPath");function yO(){if(uc!==void 0)return uc;if(rr.getHdbBasePath()!==void 0)return uc=rr.get(lc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||_c.join(rr.getHdbBasePath(),lc.TRANSACTIONS_DIR_NAME),uc}a(yO,"getTransactionAuditStoreBasePath");function Lk(e,t){let r=rr.get(zn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||_c.join(yO(),e.toString())}a(Lk,"getTransactionAuditStorePath");function IO(e,t){e=e.toString(),t=t&&t.toString();let r=rr.get(lc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||_c.join(bO(),e)}a(IO,"getSchemaPath");function Uk(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,Dk(process.argv));let s=r[zn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!Ck.isObject(s))throw o;i=s}for(let o of i){let c=o[Wl];if(!c)continue;let u=rr.get(zn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[oc.PATH];if(_)return OO.set(u,[Wl,oc.TABLES,t,oc.PATH],_),rr.setProperty(zn.DATABASES,u),_;let l=c?.[oc.PATH];if(l)return OO.set(u,[Wl,oc.PATH],l),rr.setProperty(zn.DATABASES,u),l}}let n=r[zn.STORAGE_PATH.toUpperCase()];if(n){if(!AO.pathExistsSync(n))throw new Error(n+" does not exist");let i=_c.join(n,e);return AO.mkdirsSync(i),rr.setProperty(zn.STORAGE_PATH,n),i}return NO()}a(Uk,"initSystemSchemaPaths");function Mk(){ac=void 0,cc=void 0,uc=void 0}a(Mk,"resetPaths");wO.exports={getBaseSchemaPath:bO,getSystemSchemaPath:NO,getTransactionAuditStorePath:Lk,getTransactionAuditStoreBasePath:yO,getSchemaPath:IO,initSystemSchemaPaths:Uk,resetPaths:Mk}});var wr=T((_ae,MO)=>{"use strict";var Pk=Ir().LMDB_ERRORS_ENUM,uae=require("lmdb"),vk=mt(),lae=require("buffer").Buffer,{OVERFLOW_MARKER:CO,MAX_SEARCH_KEY_LENGTH:Ql}=vk,DO=["number","string","symbol","boolean","bigint"];function Bk(e){if(e=e?.primaryStore||e,!e)throw new Error(Pk.ENV_REQUIRED)}a(Bk,"validateEnv");function Hk(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(Hk,"stringifyData");function xk(e){return e instanceof Date?e.valueOf():e}a(xk,"convertKeyValueToWrite");function qk(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(DO.includes(typeof e))return e.length>Ql?[e.slice(0,Ql)+CO]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if(DO.includes(typeof i))i.length>Ql?r.push(i.slice(0,Ql)+CO):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(qk,"getIndexedValues");var zl=0,LO=0;function UO(){LO=Date.now()-performance.now()}a(UO,"adjustStartTime");UO();var Fk=6e4;setInterval(UO,Fk).unref();function Gk(){let e=performance.now()+LO;return e>zl?(zl=e,e):(zl+=488e-6,zl)}a(Gk,"getNextMonotonicTime");MO.exports={validateEnv:Bk,stringifyData:Hk,convertKeyValueToWrite:xk,getNextMonotonicTime:Gk,getIndexedValues:qk}});var PO,bs,gh,dc=Ae(()=>{PO=require("events"),bs=class extends PO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new gh;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)}},gh=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 Li={};$e(Li,{server:()=>_t});var vO,_t,sr=Ae(()=>{vO=require("../index"),_t={};(0,vO._assignPackageExport)("server",_t)});var Ah={};$e(Ah,{loadGQLSchema:()=>$k,start:()=>Rh,startOnMainThread:()=>Vk});function Rh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),n)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let K=function(q){if(q.kind==="NonNullType"){let Y=K(q.type);return Y.nullable=!1,Y}if(q.kind==="ListType")return{type:"array",elements:K(q.type)};let Q={type:q.name?.value};return Object.defineProperty(Q,"location",{value:q.loc.startToken}),Q};a(K,"getProperty");let R=S.name.value,I=[],w={table:null,database:null,properties:I};f.set(R,w);for(let q of S.directives){if(q.name.value==="table"){for(let P of q.arguments)w[P.name.value]=P.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=R),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,E.push(w)}if(q.name.value==="sealed"&&(w.sealed=!0),q.name.value==="export"){w.export=!0;for(let P of q.arguments)P.name.value==="name"&&(w.export={name:P.value.value})}}let B=!1;for(let q of S.fields){let P=K(q.type);P.name=q.name.value,I.push(P);for(let Q of q.directives)if(Q.name.value==="primaryKey")B?console.warn("Can not define two attributes as a primary key"):(P.isPrimaryKey=!0,B=!0);else if(Q.name.value==="indexed")P.indexed=!0;else if(Q.name.value==="relationship"){let Y={};for(let J of Q.arguments)Y[J.name.value]=J.value.value;P.relationship=Y}else if(Q.name.value==="createdTime")P.assignCreatedTime=!0;else if(Q.name.value==="updatedTime")P.assignUpdatedTime=!0;else if(Q.name.value==="expiresAt")P.expiresAt=!0;else if(Q.name.value==="allow"){let Y=P.authorizedRoles=[];for(let J of Q.arguments)J.name.value==="role"&&Y.push(J.value.value)}}w.type=R,R==="Query"&&(h=w)}function p(S){let R=f.get(S.type);R?(Object.defineProperty(S,"properties",{value:R.properties}),Object.defineProperty(S,"definition",{value:R})):S.type==="array"?p(S.elements):kk.includes(S.type)||(0,BO.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${n}`)}a(p,"connectPropertyType");for(let S of f.values())for(let R of S.properties)p(R);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Jl.dirname)(s),S.tableClass):i.set((0,Jl.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass));if(h)for(let S of h.properties){let R=f.get(S.type);if(!R)throw new Error(`${S.type} was not found as a Query export`);i.set((0,Jl.dirname)(s)+"/"+S.name,R.tableClass)}}}var Jl,BO,kk,Vk,$k,HO=Ae(()=>{Jl=require("path");ge();BO=v(Ye()),kk=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Rh,"start");Vk=Rh,$k=Rh({ensureTable:dt}).handleFile});async function Xl(e){return Yk?(fc||(fc=Kk(Qk)),(await(await fc).import(e)).namespace):import(e)}async function Kk(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),fc=new Compartment({console,Math,Date,fetch:Wk,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,qO.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:qt,tables:Cr,databases:st})}};let s=await(0,xO.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),fc}function Wk(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 Qk(){return{Resource:qt,tables:Cr}}var xO,qO,Yk,fc,Oh=Ae(()=>{Ns();ge();xO=require("fs/promises"),qO=require("path"),Yk=!1;a(Xl,"secureImport");a(Kk,"getCompartment");a(Wk,"secureOnlyFetch");a(Qk,"getGlobalVars")});var Nh={};$e(Nh,{handleFile:()=>zk});async function zk(e,t,r,s){let n=new Map,i=(0,FO.pathToFileURL)(r).toString(),o=await Xl(i);u(o.default)&&s.set((0,bh.dirname)(t),o.default),c(o,(0,bh.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?s.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),n}var FO,bh,GO=Ae(()=>{FO=require("url");Oh();bh=require("path");a(zk,"handleFile")});var Ih={};$e(Ih,{start:()=>Jk});function Jk({resources:e}){e.set("login",yh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var yh,kO=Ae(()=>{Ns();a(Jk,"start");yh=class extends qt{static{a(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:o}=r;return{data:await s.login(n,i)}}}});var zO={};$e(zO,{parse:()=>Ch,streamAsJSON:()=>Ec,stringify:()=>Ui});function Ec(e){return new wh({value:e})}function VO(e){return console.error(e),JSON.stringify(e.toString())}function $O(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Ui(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===WO)return QO(e);if(t.resolution)return t.resolution.then(()=>Ui(e));throw t}}function QO(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let s=0;s<e.length;s++)s>0&&(r+=","),r+=QO(e[s]);return r+"]"}else{r="{";let s=!0;for(let n in e)s?s=!1:r+=",",r+=JSON.stringify(n)+":"+Ui(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Ch(e){return Zk.test(e)?Xk.parse(e):JSON.parse(e)}var YO,KO,Xk,jk,WO,wh,Zk,Dh=Ae(()=>{YO=require("stream"),KO=v(require("json-bigint-fixes")),Xk=(0,KO.default)({useNativeBigInt:!0}),jk=1e4,WO={};BigInt.prototype.toJSON=function(){throw WO};a(Ec,"streamAsJSON");wh=class extends YO.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else n?n=!1:yield",",yield*this.serialize(o.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),VO)}catch(n){yield VO(n)}else yield Ui(t)}else yield Ui(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);$O(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>jk?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 $O(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let s of this.activeIterators)t?s.throw(t):s.return();r()}};a(VO,"handleError");a($O,"when");a(Ui,"stringify");a(QO,"jsStringify");Zk=/-?\d{16,}/;a(Ch,"parse")});var cb=T((Iae,ab)=>{"use strict";var Lh=require("recursive-iterator"),eV=require("alasql"),Uh=require("clone"),JO=z(),{handleHDBError:XO,hdb_errors:tV}=Z(),{HDB_ERROR_MSGS:jO,HTTP_STATUS_CODES:ZO}=tV,{getDatabases:rV}=(ge(),ee(xe)),sV=["DISTINCT_ARRAY"],eb=Symbol("validateTables"),Mh=Symbol("validateTable"),yae=Symbol("getAllColumns"),tb=Symbol("validateAllColumns"),jl=Symbol("findColumn"),rb=Symbol("validateOrderBy"),hc=Symbol("validateSegment"),Ph=Symbol("validateColumn"),sb=Symbol("setColumnsForTable"),nb=Symbol("checkColumnsForAsterisk"),ib=Symbol("validateGroupBy"),ob=Symbol("hasColumns"),vh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[eb](),this[nb](),this[tb]()}[eb](){if(this[ob]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Mh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Mh](t.table)})}}[ob](){let t=!1,r=new Lh(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Mh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=rV();if(!r[t.databaseid])throw XO(new Error,jO.SCHEMA_NOT_FOUND(t.databaseid),ZO.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw XO(new Error,jO.TABLE_NOT_FOUND(t.databaseid,t.tableid),ZO.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=Uh(n);i.table=Uh(t),this.attributes.push(i)})}[jl](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)}[nb](){let t=new Lh(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[sb](r.tableid)}[sb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new eV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[tb](){this[hc](this.statement.columns,!1),this[hc](this.statement.joins,!1),this[hc](this.statement.where,!1),this[ib](this.statement.group,!1),this[hc](this.statement.order,!0)}[hc](t,r){if(!t)return;let s=new Lh(t),n=[];for(let{node:i,path:o}of s)!JO.isEmpty(i)&&!JO.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[rb](i):n.push(this[Ph](i)));return n}[ib](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&sV.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=Uh(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[jl](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[jl](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[rb](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[Ph](t)}[Ph](t){let r=this[jl](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};ab.exports=vh});var lb=T((Cae,ub)=>{"use strict";var Bh=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")}};ub.exports=Bh});var db=T((Lae,_b)=>{"use strict";var Hh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};_b.exports=Hh});var pb={};$e(pb,{HAS_EXPIRATION:()=>Vh,LAST_TIMESTAMP_PLACEHOLDER:()=>Sc,LOCAL_TIMESTAMP:()=>nV,METADATA:()=>mc,NO_TIMESTAMP:()=>xh,PENDING_LOCAL_TIME:()=>$h,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>kh,RecordEncoder:()=>Gh,TIMESTAMP_ASSIGN_LAST:()=>oV,TIMESTAMP_ASSIGN_NEW:()=>hb,TIMESTAMP_ASSIGN_PREVIOUS:()=>mb,TIMESTAMP_PLACEHOLDER:()=>Zl,TIMESTAMP_RECORD_PREVIOUS:()=>qh,getUpdateRecord:()=>Yh,handleLocalTimeForGets:()=>s_});function cV(){return pc[0]=pc[0]^64,iV.getFloat64(0)}function s_(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?.[mc];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?.[mc]>=0?c.value:c};let s=e.getRange;e.getRange=function(i){let o=s.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[mc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let n=e.useReadTransaction();if(n.done(),!n.done.isTracked){let i=n.constructor,o=n.use,c=n.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Mi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Mi.length;u++){let _=Mi[u].deref();(!_||_===this||_.isDone||_.isCommitted)&&Mi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Yh(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?xo=i?.localTime?qh|mb:xh:xo=u?i?.localTime?qh|16384:hb|16384:xh,l>0&&(c|=Vh),t_=c,Fh=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:xo>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(s,n,h);if(u){let R=_?.user?.username;if(E&&(e_=e.encoder.encode(E)),f&&i?.localTime){let I=i?.localTime,w=r.get(I);if(w){let B=Pt(w).previousLocalTime;return r.put(I,r_(o,t,s,B,R,d,e_),{ifVersion:p}),S}}r.put(Sc,r_(o,t,s,i?.localTime?1:0,R,d,e_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+s+" options: "+h,S}}}var fb,Eb,Zl,Sc,kh,nV,mc,pc,iV,xh,hb,oV,mb,qh,Vh,$h,aV,e_,xo,t_,Fh,Gh,Pae,Mi,Tc=Ae(()=>{fb=require("msgpackr");Pi();Eb=v(G()),Zl=new Uint8Array([1,1,1,1,4,64,0,0]),Sc=new Uint8Array([1,1,1,1,1,0,0,0]),kh=new Uint8Array([1,1,1,1,3,64,0,0]),nV=Symbol("local-timestamp"),mc=Symbol("metadata"),pc=new Uint8Array(8),iV=new DataView(pc.buffer,0,8),xh=0,hb=0,oV=1,mb=3,qh=4,Vh=16,$h=1,xo=0,t_=-1,Fh=0,Gh=class extends fb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,n){if(xo||t_>=0){let i=0,o=xo;o&&(i+=8,xo=0);let c=t_,u=Fh;c>=0&&(i+=2,t_=-1,u&&(i+=8,Fh=0));let _=aV=r.call(this,s,n|2048|i);e_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(Zl[4]=o,Zl[5]=o>>8,_.set(Zl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,s,n)}}decode(t,r){let s=r?.start||0,n=r>-1?r:r?.end||t.length,i=t[s],o=0;try{if(i<32&&n>2){let c=s,u;if(i===2){if(t.copy)t.copy(pc,0,c),c+=8;else for(let d=0;d<8;d++)pc[d]=t[c++];u=cV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Vh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,n),n-c);return{localTime:u,value:l,[mc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(cV,"getTimestamp");Pae=Map.prototype.get;a(s_,"handleLocalTimeForGets");Mi=[];setInterval(()=>{for(let e=0;e<Mi.length;e++){let t=Mi[e].deref();!t||t.isDone||t.isCommitted?Mi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&Eb.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(Yh,"getUpdateRecord")});var n_=T((Bae,Sb)=>{"use strict";var Wh=j(),Qh=D(),{RecordEncoder:uV}=(Tc(),ee(pb));Wh.initSync();var lV=Wh.get(Qh.CONFIG_PARAMS.STORAGE_COMPRESSION),_V=Wh.get(Qh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,dV=Qh.UPDATES_PROPERTY,Kh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=lV&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=_V&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:uV},this.alwaysLazyProperty=s=>s===dV)}};Sb.exports=Kh});var o_=T((xae,gb)=>{"use strict";var qo=j(),gc=D();qo.initSync();var fV=qo.get(gc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||qo.get(gc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||qo.get(gc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Tb=qo.get(gc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),EV=qo.get(gc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),i_=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=fV,this.noFSAccess=!0,Tb!==void 0&&(this.overlappingSync=Tb),this.noReadAhead=EV}};gb.exports=i_;i_.MAX_DBS=1e4});var Ke=T((Fae,Db)=>{"use strict";var Jh=require("lmdb"),ys=require("fs-extra"),Dr=require("path"),a_=wr(),Ob=G(),nr=Ir().LMDB_ERRORS_ENUM,c_=db(),Xh=n_(),bb=o_(),Jn=mt(),Rb=D(),{table:hV,resetDatabases:mV}=(ge(),ee(xe)),Ab=j(),Is=Jn.INTERNAL_DBIS_NAME,Nb=Jn.DBI_DEFINITION_NAME,pV="data.mdb",SV="lock.mdb",Rc=".mdb",TV="-lock",zh=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=Zr(t,r),this.key_type=this.dbi[Jn.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Jn.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!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 u_(e,t){if(e===void 0)throw new Error(nr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(nr.ENV_NAME_REQUIRED)}a(u_,"pathEnvNameValidation");async function jh(e,t,r=!0){try{await ys.access(e)}catch(s){throw s.code==="ENOENT"?new Error(nr.INVALID_BASE_PATH):s}try{let s=Dr.join(e,t+Rc);return await ys.access(s,ys.constants.R_OK|ys.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await ys.access(Dr.join(e,t,pV),ys.constants.R_OK|ys.constants.F_OK),Dr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(nr.INVALID_ENVIRONMENT)}else throw new Error(nr.INVALID_ENVIRONMENT);throw s}}a(jh,"validateEnvironmentPath");function l_(e,t){if(a_.validateEnv(e),t===void 0)throw new Error(nr.DBI_NAME_REQUIRED)}a(l_,"validateEnvDBIName");async function gV(e,t,r=!1,s=!1){u_(e,t);let n=Dr.basename(e);t=t.toString();let i=Ab.get(Rb.CONFIG_PARAMS.DATABASES);i||Ab.setProperty(Rb.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await jh(e,t,s),yb(e,t,r)}catch(o){if(o.message===nr.INVALID_ENVIRONMENT){let c=Dr.join(e,t);await ys.mkdirp(s?c:e);let u=new bb(s?c:c+Rc,!1),_=Jh.open(u);_.dbis=Object.create(null);let l=new Xh(!1);_.openDB(Is,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=Zh(e,t,r);return _[Jn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(gV,"createEnvironment");async function RV(e,t,r,s=!0){u_(e,t),t=t.toString();let n=Dr.join(e,t);return hV({table:t,database:Dr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(RV,"copyEnvironment");async function yb(e,t,r=!1){u_(e,t),t=t.toString();let s=Zh(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await jh(e,t),i=Dr.join(e,t+Rc),o=n!=i,c=new bb(n,o),u=Jh.open(c);u.dbis=Object.create(null);let _=wb(u);for(let l=0;l<_.length;l++)Zr(u,_[l]);return u[Jn.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(yb,"openEnvironment");async function AV(e,t,r=!1){u_(e,t),t=t.toString();let s=Dr.join(e,t+Rc),n=await jh(e,t);if(global.lmdb_map!==void 0){let i=Zh(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Ib(o),delete global.lmdb_map[i]}}await ys.remove(n),await ys.remove(n===s?n+TV:Dr.join(Dr.dirname(n),SV))}a(AV,"deleteEnvironment");async function Ib(e){a_.validateEnv(e);let t=e[Jn.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Ib,"closeEnvironment");function Zh(e,t,r=!1){let n=`${Dr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(Zh,"getCachedEnvironmentName");function OV(e){a_.validateEnv(e);let t=Object.create(null),r=Zr(e,Is);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==Is)try{t[s]=Object.assign(new c_,n)}catch{Ob.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(OV,"listDBIDefinitions");function wb(e){a_.validateEnv(e);let t=[],r=Zr(e,Is);for(let{key:s}of r.getRange({start:!1}))s!==Is&&t.push(s);return t}a(wb,"listDBIs");function bV(e,t){let s=Zr(e,Is).getEntry(t),n=new c_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Ob.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(bV,"getDBIDefinition");function Cb(e,t,r,s=!r){if(l_(e,t),t=t.toString(),t===Is)throw new Error(nr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Zr(e,t)}catch(n){if(n.message===nr.DBI_DOES_NOT_EXIST){let i=new Xh(r,s===!0),o=e.openDB(t,i),c=new c_(r===!0,s);return o[Nb]=c,Zr(e,Is).putSync(t,c),e.dbis[t]=o,o}throw n}}a(Cb,"createDBI");function Zr(e,t){if(l_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Is?r=bV(e,t):r=new c_,r===void 0)throw new Error(nr.DBI_DOES_NOT_EXIST);let s;try{let n=new Xh(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(nr.DBI_DOES_NOT_EXIST):n}return s[Nb]=r,e.dbis[t]=s,s}a(Zr,"openDBI");function NV(e,t){l_(e,t),t=t.toString();let r=Zr(e,t),s=r.getStats();return r[Jn.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(NV,"statDBI");async function yV(e,t){try{let r=Dr.join(e,t+Rc);return(await ys.stat(r)).size}catch{throw new Error(nr.INVALID_ENVIRONMENT)}}a(yV,"environmentDataSize");function IV(e,t){if(l_(e,t),t=t.toString(),t===Is)throw new Error(nr.CANNOT_DROP_INTERNAL_DBIS_NAME);Zr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Zr(e,Is).removeSync(t)}a(IV,"dropDBI");function wV(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{Zr(e,i)}catch(o){if(o.message===nr.DBI_DOES_NOT_EXIST)Cb(e,i,i!==t,i===t),s=!0;else throw o}}s&&mV()}a(wV,"initializeDBIs");Db.exports={openDBI:Zr,openEnvironment:yb,createEnvironment:gV,listDBIs:wb,listDBIDefinitions:OV,createDBI:Cb,dropDBI:IV,statDBI:NV,deleteEnvironment:AV,initializeDBIs:wV,TransactionCursor:zh,environmentDataSize:yV,copyEnvironment:RV,closeEnvironment:Ib}});var Ub=T((kae,Lb)=>{"use strict";var em=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};Lb.exports=em});var Pb=T(($ae,Mb)=>{"use strict";var tm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};Mb.exports=tm});var Bb=T((Kae,vb)=>{"use strict";var rm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};vb.exports=rm});var Fo=T((Xae,qb)=>{"use strict";var CV=Ke(),DV=Ub(),LV=Pb(),UV=Bb(),$s=wr(),Ac=Ir().LMDB_ERRORS_ENUM,MV=mt(),Sn=D(),PV=z(),vV=require("uuid"),Qae=require("lmdb"),{handleHDBError:BV,hdb_errors:HV}=Z(),{OVERFLOW_MARKER:zae,MAX_SEARCH_KEY_LENGTH:Jae}=MV,Hb=j();Hb.initSync();var __=Hb.get(Sn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),sm=Sn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,vi=Sn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function xV(e,t,r,s,n=$s.getNextMonotonicTime()){am(e,t,r,s),nm(e,t,r);let i=new DV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];xb(_,!0,n);let l=qV(e,t,r,_),d=_[t];o.push(l),c.push(d)}return im(o,c,s,i,n)}a(xV,"insertRecords");function qV(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Sn.FUNC_VAL],s[o]=c)}let u=$s.getIndexedValues(c),_=e.dbis[o];if(u){__&&_.prefetch(u.map(l=>({key:l,value:n})),d_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],n)}}__&&e.dbis[t].prefetch([n],d_),e.dbis[t].put(n,s,s[vi])})}a(qV,"insertRecord");function FV(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(FV,"removeSkippedRecords");function xb(e,t,r){let s=r>0;(s||!Number.isInteger(e[vi]))&&(e[vi]=r||(r=$s.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[sm]))&&(e[sm]=r||$s.getNextMonotonicTime()):delete e[sm]}a(xb,"setTimestamps");function nm(e,t,r){r.indexOf(Sn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Sn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Sn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Sn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),CV.initializeDBIs(e,t,r)}a(nm,"initializeTransaction");async function GV(e,t,r,s,n=$s.getNextMonotonicTime()){am(e,t,r,s),nm(e,t,r);let i=new LV,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=om(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return im(c,u,s,i,n,o)}a(GV,"updateRecords");async function kV(e,t,r,s,n=$s.getNextMonotonicTime()){try{am(e,t,r,s)}catch(u){throw BV(u,u.message,HV.HTTP_STATUS_CODES.BAD_REQUEST)}nm(e,t,r);let i=new UV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;PV.isEmpty(_[t])?(l=vV.v4(),_[t]=l):l=_[t];let d=om(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return im(o,c,s,i,n)}a(kV,"upsertRecords");async function im(e,t,r,s,n,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||$s.getNextMonotonicTime(),FV(r,i),s}a(im,"finalizeWrite");function om(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(xb(r,!l,o),Number.isInteger(r[vi])&&_[vi]>r[vi])return!1;l&&n.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let R=_[h];if(typeof p=="function"){let w=p([[_]]);Array.isArray(w)&&(p=w[0][Sn.FUNC_VAL],r[h]=p)}if(p===R)continue;let I=$s.getIndexedValues(R);if(I){__&&S.prefetch(I.map(w=>({key:w,value:s})),d_);for(let w=0,B=I.length;w<B;w++)S.remove(I[w],s)}if(I=$s.getIndexedValues(p),I){__&&S.prefetch(I.map(w=>({key:w,value:s})),d_);for(let w=0,B=I.length;w<B;w++)S.put(I[w],s)}}let E=Object.assign({},_,r);c.put(s,E,E[vi])},"do_put");return u?d=c.ifVersion(s,u.version,f):d=c.ifNoExists(s,f),d.then(E=>E?!0:om(e,t,r,s,n,i,o))}a(om,"updateUpsertRecord");function VV(e,t,r){if($s.validateEnv(e),t===void 0)throw new Error(Ac.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Ac.WRITE_ATTRIBUTES_REQUIRED):new Error(Ac.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(VV,"validateBasic");function am(e,t,r,s){if(VV(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Ac.RECORDS_REQUIRED):new Error(Ac.RECORDS_MUST_BE_ARRAY)}a(am,"validateWrite");function d_(){}a(d_,"noop");qb.exports={insertRecords:xV,updateRecords:GV,upsertRecords:kV}});var Bi=T((Zae,$V)=>{$V.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 Ks=T((ece,kb)=>{"use strict";var Gb=z(),Fb=D(),Go=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Ys=require("joi"),Xn={schema_format:{pattern:Go,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},YV=Ys.alternatives(Ys.string().min(1).max(Xn.schema_length.maximum).pattern(Go).messages({"string.pattern.base":"{:#label} "+Xn.schema_format.message}),Ys.number(),Ys.array()).required(),KV=Ys.alternatives(Ys.string().min(1).max(Xn.schema_length.maximum).pattern(Go).messages({"string.pattern.base":"{:#label} "+Xn.schema_format.message}),Ys.number()),WV=Ys.alternatives(Ys.string().min(1).max(Xn.schema_length.maximum).pattern(Go).messages({"string.pattern.base":"{:#label} "+Xn.schema_format.message}),Ys.number()).required();function QV(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>Xn.schema_length.maximum?`'${e}' maximum of 250 characters`:Go.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(QV,"checkValidTable");function zV(e,t){return Gb.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(zV,"validateSchemaExists");function JV(e,t){let r=t.state.ancestors[0].schema;return Gb.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(JV,"validateTableExists");function XV(e,t){return e.toLowerCase()===Fb.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Fb.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(XV,"validateSchemaName");kb.exports={common_validators:Xn,schema_regex:Go,hdb_schema_table:YV,validateSchemaExists:zV,validateTableExists:JV,validateSchemaName:XV,checkValidTable:QV,hdb_database:KV,hdb_table:WV}});var Je=T((rce,Vb)=>{"use strict";var ir=require("validate.js");ir.validators.type=function(e,t,r,s){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};Vb.exports={validateObject:jV,validateObjectAsync:ZV,validateBySchema:e$};function jV(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(jV,"validateObject");async function ZV(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await ir.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(ZV,"validateObjectAsync");function e$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(e$,"validateBySchema")});var f_=T((nce,$b)=>{var{common_validators:Ws}=Ks(),bc=Je(),Oc="is required",pt={database:{presence:!1,format:Ws.schema_format,length:Ws.schema_length},schema:{presence:!1,format:Ws.schema_format,length:Ws.schema_length},table:{presence:!0,format:Ws.schema_format,length:Ws.schema_length},attribute:{presence:!0,format:Ws.schema_format,length:Ws.schema_length},hash_attribute:{presence:!0,format:Ws.schema_format,length:Ws.schema_length}};function Nc(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(Nc,"makeAttributesStrings");function t$(e){return e=Nc(e),pt.table.presence=!1,pt.attribute.presence=!1,pt.hash_attribute.presence=!1,bc.validateObject(e,pt)}a(t$,"schema_object");function r$(e){return e=Nc(e),pt.table.presence={message:Oc},pt.attribute.presence=!1,pt.hash_attribute.presence=!1,bc.validateObject(e,pt)}a(r$,"table_object");function s$(e){return e=Nc(e),pt.table.presence={message:Oc},pt.attribute.presence=!1,bc.validateObject(e,pt)}a(s$,"create_table_object");function n$(e){return e=Nc(e),pt.table.presence={message:Oc},pt.attribute.presence={message:Oc},pt.hash_attribute.presence=!1,bc.validateObject(e,pt)}a(n$,"attribute_object");function i$(e){return e=Nc(e),pt.table.presence={message:Oc},pt.attribute.presence=!1,pt.hash_attribute.presence=!1,bc.validateObject(e,pt)}a(i$,"describe_table");function o$(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(o$,"validateTableResidence");$b.exports={schema_object:t$,create_table_object:s$,table_object:r$,attribute_object:n$,describe_table:i$,validateTableResidence:o$}});var Kb=T((oce,Yb)=>{"use strict";var a$=require("uuid"),cm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||a$.v4(),this.schema_table=`${this.schema}.${this.table}`}};Yb.exports=cm});var E_=T((cce,Wb)=>{"use strict";var c$=Kb(),um=class extends c${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};Wb.exports=um});var zb=T((lce,Qb)=>{"use strict";Qb.exports=l$;var u$="inserted";function l$(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===u$?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(l$,"returnObject")});var h_=T((dce,eN)=>{"use strict";var _$=D(),lm=Ke(),d$=Fo(),{getSystemSchemaPath:f$,getSchemaPath:E$}=ze(),h$=Bi(),m$=f_(),p$=E_(),S$=zb(),{handleHDBError:Jb,hdb_errors:jb}=Z(),Xb=z(),{HTTP_STATUS_CODES:T$}=jb,_m=h$.hdb_attribute,Zb=[];for(let e=0;e<_m.attributes.length;e++)Zb.push(_m.attributes[e].attribute);var g$="inserted";eN.exports=R$;async function R$(e){let t=m$.attribute_object(e);if(t)throw Jb(new Error,t.message,jb.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&Xb.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Jb(new Error,r,T$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Xb.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new p$(e.schema,e.table,e.attribute,e.id);try{let i=await lm.openEnvironment(E$(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}`);lm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await lm.openEnvironment(f$(),_$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await d$.insertRecords(o,_m.hash_attribute,Zb,[n]);return S$(g$,c,{records:[n]},u)}catch(i){throw i}}a(R$,"lmdbCreateAttribute")});var fm=T((Ece,rN)=>{var{hdb_table:A$,hdb_database:tN}=Ks(),O$=Je(),dm=require("joi"),b$={undefined:"undefined",null:"null"},N$=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||b$[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),y$=dm.object({database:tN,schema:tN,table:A$,records:dm.array().items(dm.object().custom(N$)).required()});rN.exports=function(e){return O$.validateBySchema(e,y$)}});var yc=T((pce,nN)=>{"use strict";var Tn=z(),sN=G(),mce=fm(),{getDatabases:I$}=(ge(),ee(xe)),{ClientError:Hi}=Z();nN.exports=w$;function w$(e){if(Tn.isEmpty(e))throw new Hi("invalid update parameters defined.");if(Tn.isEmptyOrZeroLength(e.schema))throw new Hi("invalid schema specified.");if(Tn.isEmptyOrZeroLength(e.table))throw new Hi("invalid table specified.");if(!Array.isArray(e.records))throw new Hi("records must be an array");let t=I$()[e.schema]?.[e.table];if(Tn.isEmpty(t))throw new Hi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Tn.isEmptyOrZeroLength(o[r]))throw sN.error("a valid hash attribute must be provided with update record:",o),new Hi("a valid hash attribute must be provided with update record, check log for more info");if(!Tn.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw sN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Hi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Tn.isEmpty(o[r])&&o[r]!==""&&s.has(Tn.autoCast(o[r]))&&(o.skip=!0),s.add(Tn.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(w$,"insertUpdateValidate")});var Ic=T((Tce,iN)=>{"use strict";var C$=D().OPERATIONS_ENUM,Em=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=C$.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};iN.exports=Em});var Lc=T((Ace,oN)=>{"use strict";var Rce=Ic(),m_=D(),mm=z(),hm=G(),D$=require("uuid"),{handleHDBError:wc,hdb_errors:L$}=Z(),{HDB_ERROR_MSGS:Cc,HTTP_STATUS_CODES:Dc}=L$;oN.exports=U$;function U$(e,t,r){for(let n=0;n<t.length;n++)M$(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];P$(i,r,e.operation)}}a(U$,"processRows");function M$(e){if(Buffer.byteLength(String(e))>m_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw wc(new Error,Cc.ATTR_NAME_LENGTH_ERR(e),Dc.BAD_REQUEST,void 0,void 0,!0);if(mm.isEmptyOrZeroLength(e)||mm.isEmpty(e.trim()))throw wc(new Error,Cc.ATTR_NAME_NULLISH_ERR,Dc.BAD_REQUEST,void 0,void 0,!0)}a(M$,"validateAttribute");function P$(e,t,r){if(!e.hasOwnProperty(t)||mm.isEmptyOrZeroLength(e[t])){if(r===m_.OPERATIONS_ENUM.INSERT||r===m_.OPERATIONS_ENUM.UPSERT){e[t]=D$.v4();return}throw hm.error("Update transaction aborted due to record with no hash value:",e),wc(new Error,Cc.RECORD_MISSING_HASH_ERR,Dc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>m_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw hm.error(e),wc(new Error,Cc.HASH_VAL_LENGTH_ERR,Dc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw hm.error(e),wc(new Error,Cc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Dc.BAD_REQUEST,void 0,void 0,!0)}a(P$,"validateHash")});var cN=T((bce,aN)=>{"use strict";var pm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};aN.exports=pm});var _N=T((yce,lN)=>{"use strict";var Sm=Ke(),v$=G(),uN=Ir().LMDB_ERRORS_ENUM;lN.exports=B$;async function B$(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 Sm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==uN.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Sm.closeEnvironment(global.lmdb_map[s]),await Sm.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==uN.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){v$.error(t)}}a(B$,"cleanLMDBMap")});var gn=T((wce,hN)=>{"use strict";var Uc=require("crypto"),H$=j(),{CONFIG_PARAMS:x$}=D(),fN="aes-256-cbc",q$=32,F$=16,Tm=64,EN=32,G$=Tm+EN,dN=new Map;hN.exports={encrypt:k$,decrypt:V$,createNatsTableStreamName:$$};function k$(e){let t=Uc.randomBytes(q$),r=Uc.randomBytes(F$),s=Uc.createCipheriv(fN,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(k$,"encrypt");function V$(e){let t=e.substr(0,Tm),r=e.substr(Tm,EN),s=e.substr(G$,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Uc.createDecipheriv(fN,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(V$,"decrypt");function $$(e,t){let r=H$.get(x$.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=dN.get(r);return s||(s=Uc.createHash("md5").update(r).digest("hex"),dN.set(r,s)),s}a($$,"createNatsTableStreamName")});var jn=T((Lce,pN)=>{"use strict";var Dce=es(),p_=G(),mN=f_(),Y$=gn(),S_=z(),{handleHDBError:T_,hdb_errors:K$}=Z(),{HDB_ERROR_MSGS:g_,HTTP_STATUS_CODES:gm}=K$,W$=j();W$.initSync();var{getDatabases:Rm}=(ge(),ee(xe));pN.exports={describeAll:Q$,describeTable:R_,describeSchema:z$};async function Q$(e){try{let t=S_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=Rm(),i={},o={},c=[],u=e?.exact_count;for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let d=n[l];for(let f in d)try{let E;if(t||s)E=await R_({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 R_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){p_.error(E)}}let _={};for(let l in c)t||s?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return p_.error("Got an error in describeAll"),p_.error(t),T_(new Error,g_.DESCRIBE_ALL_ERR)}}a(Q$,"describeAll");async function R_(e,t){S_.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=mN.describe_table(e);if(i)throw i;let c=Rm()[r];if(!c)throw T_(new Error,g_.SCHEMA_NOT_FOUND(e.schema),gm.NOT_FOUND);let u=c[s];if(!u)throw T_(new Error,g_.TABLE_NOT_FOUND(e.schema,e.table),gm.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(n){let f={};n.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=Y$.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){p_.warn(`unable to stat table dbi due to ${f}`)}return d}a(R_,"descTable");async function z$(e){S_.transformReq(e);let t=mN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=Rm()[s];if(!i)throw T_(new Error,g_.SCHEMA_NOT_FOUND(e.schema),gm.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),S_.isEmpty(u)||u.describe){let _=await R_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(z$,"describeSchema")});var Rn=T((vce,AN)=>{var J$=Bi(),{callbackify:TN,promisify:X$}=require("util"),{getDatabases:gN}=(ge(),ee(xe));AN.exports={setSchemaDataToGlobal:SN,getTableSchema:j$,getSystemSchema:Z$,setSchemaDataToGlobalAsync:X$(SN)};var RN=jn(),Mce=TN(RN.describeAll),Pce=TN(RN.describeTable);function SN(e){global.hdb_schema=gN(),e&&e()}a(SN,"setSchemaDataToGlobal");function j$(e,t,r){let s=gN()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}a(j$,"getTableSchema");function Z$(){return J$}a(Z$,"getSystemSchema")});var Lr=T((Hce,yN)=>{"use strict";var O_=fm(),Ft=z(),e1=require("util"),b_=ws(),t1=Rn(),ON=G(),{handleHDBError:xi,hdb_errors:r1}=Z(),{HTTP_STATUS_CODES:qi}=r1,s1=e1.promisify(t1.getTableSchema),n1="updated",bN="inserted",NN="upserted";yN.exports={insert:o1,update:a1,upsert:c1,validation:i1,flush:u1};async function i1(e){if(Ft.isEmpty(e))throw new Error("invalid update parameters defined.");if(Ft.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Ft.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await s1(e.schema,e.table),r=O_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Ft.isEmptyOrZeroLength(c[s]))throw ON.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(!Ft.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw ON.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!Ft.isEmpty(c[s])&&c[s]!==""&&n.has(Ft.autoCast(c[s]))&&(c.skip=!0),n.add(Ft.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(i1,"validation");async function o1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=O_(e);if(t)throw xi(new Error,t.message,qi.BAD_REQUEST);Ft.transformReq(e);let r=Ft.checkSchemaTableExist(e.schema,e.table);if(r)throw xi(new Error,r,qi.BAD_REQUEST);let s=await b_.createRecords(e);return A_(bN,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(o1,"insertData");async function a1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=O_(e);if(t)throw xi(new Error,t.message,qi.BAD_REQUEST);Ft.transformReq(e);let r=Ft.checkSchemaTableExist(e.schema,e.table);if(r)throw xi(new Error,r,qi.BAD_REQUEST);let s=await b_.updateRecords(e);return Ft.isEmpty(s.existing_rows)?A_(n1,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):A_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(a1,"updateData");async function c1(e){if(e.operation!=="upsert")throw xi(new Error,"invalid operation, must be upsert",qi.INTERNAL_SERVER_ERROR);let t=O_(e);if(t)throw xi(new Error,t.message,qi.BAD_REQUEST);Ft.transformReq(e);let r=Ft.checkSchemaTableExist(e.schema,e.table);if(r)throw xi(new Error,r,qi.BAD_REQUEST);let s=await b_.upsertRecords(e);return A_(NN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(c1,"upsertData");function A_(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===bN?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===NN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(A_,"returnObject");function u1(e){return Ft.transformReq(e),b_.flush(e.schema,e.table)}a(u1,"flush")});var Om=T((qce,CN)=>{var l1=Je(),Am=require("joi"),{hdb_table:_1,hdb_database:IN}=Ks(),wN={schema:IN,database:IN,table:_1},d1={date:Am.date().iso().required()},f1={timestamp:Am.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};CN.exports=function(e,t){let r=t==="timestamp"?{...wN,...f1}:{...wN,...d1},s=Am.object(r);return l1.validateBySchema(e,s)}});var UN=T((Fce,LN)=>{var E1=Je(),bm=require("joi"),{hdb_table:h1,hdb_database:DN}=Ks(),m1=bm.object({schema:DN,database:DN,table:h1,hash_values:bm.array().required(),ids:bm.array()});LN.exports=function(e){return E1.validateBySchema(e,m1)}});var PN=T((Gce,MN)=>{"use strict";var Nm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},ym=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}},Im=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};MN.exports={InsertObject:Nm,NoSQLSeachObject:ym,DeleteResponseObject:Im}});var ti=T((Vce,qN)=>{"use strict";var BN=Om(),p1=UN(),Fi=z(),vN=require("moment"),HN=G(),{promisify:S1,callbackify:T1}=require("util"),Gi=D(),g1=Rn(),wm=S1(g1.getTableSchema),Cm=ws(),{DeleteResponseObject:R1}=PN(),{handleHDBError:Zn,hdb_errors:A1}=Z(),{HDB_ERROR_MSGS:N_,HTTP_STATUS_CODES:ei}=A1,O1="records successfully deleted",b1=T1(xN);qN.exports={delete:b1,deleteRecord:xN,deleteFilesBefore:N1,deleteAuditLogsBefore:y1};async function N1(e){let t=BN(e,"date");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(Fi.transformReq(e),!vN(e.date,vN.ISO_8601).isValid())throw Zn(new Error,N_.INVALID_DATE,ei.BAD_REQUEST,Gi.LOG_LEVELS.ERROR,N_.INVALID_DATE,!0);let s=Fi.checkSchemaTableExist(e.schema,e.table);if(s)throw Zn(new Error,s,ei.NOT_FOUND,Gi.LOG_LEVELS.ERROR,s,!0);let n=await Cm.deleteRecordsBefore(e);if(await wm(e.schema,e.table),HN.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(N1,"deleteFilesBefore");async function y1(e){let t=BN(e,"timestamp");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(Fi.transformReq(e),isNaN(e.timestamp))throw Zn(new Error,N_.INVALID_VALUE("Timestamp"),ei.BAD_REQUEST,Gi.LOG_LEVELS.ERROR,N_.INVALID_VALUE("Timestamp"),!0);let r=Fi.checkSchemaTableExist(e.schema,e.table);if(r)throw Zn(new Error,r,ei.NOT_FOUND,Gi.LOG_LEVELS.ERROR,r,!0);let s=await Cm.deleteAuditLogsBefore(e);return await wm(e.schema,e.table),HN.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(y1,"deleteAuditLogsBefore");async function xN(e){e.ids&&(e.hash_values=e.ids);let t=p1(e);if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);Fi.transformReq(e);let r=Fi.checkSchemaTableExist(e.schema,e.table);if(r)throw Zn(new Error,r,ei.NOT_FOUND,Gi.LOG_LEVELS.ERROR,r,!0);try{await wm(e.schema,e.table);let s=await Cm.deleteRecords(e);return Fi.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${O1}`),s}catch(s){if(s.message===Gi.SEARCH_NOT_FOUND_MESSAGE){let n=new R1;return n.message=Gi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(xN,"deleteRecord")});var y_=T((Yce,kN)=>{var I1=require("crypto"),FN=9;function w1(e){let t=D1(FN),r=GN(e+t);return t+r}a(w1,"createHash");function C1(e,t){let r=e?.substr(0,FN),s=r+GN(t+r);return e===s}a(C1,"validateHash");function D1(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(D1,"generateSalt");function GN(e){return I1.createHash("md5").update(e).digest("hex")}a(GN,"md5");kN.exports={hash:w1,validate:C1}});var $N=T((Wce,VN)=>{var Dm=Je(),Qt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function L1(e){return Qt.password.presence=!0,Qt.username.presence=!0,Qt.role.presence=!0,Qt.active.presence=!0,Dm.validateObject(e,Qt)}a(L1,"addUserValidation");function U1(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Dm.validateObject(e,Qt)}a(U1,"alterUserValidation");function M1(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Dm.validateObject(e,Qt)}a(M1,"dropUserValidation");VN.exports={addUserValidation:L1,alterUserValidation:U1,dropUserValidation:M1}});var qe=T((Jce,KN)=>{"use strict";var{platform:zce}=require("os"),P1="nats-server.zip",Lm="nats-server",v1=process.platform==="win32"?`${Lm}.exe`:Lm,Um="HDB",B1=/^[^\s.,*>]+$/,YN="__request__",H1=a(e=>`${e}.${YN}`,"REQUEST_SUBJECT"),x1={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},q1={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},F1={HUB:"hub.pid",LEAF:"leaf.pid"},G1={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},k1={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Um,deliver_subject:"__HDB__.WORKQUEUE"},V1={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Um,deliver_subject:"HDB.SCHEMAQUEUE"},$1={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Um,deliver_subject:"HDB.USERQUEUE"},Y1={SUCCESS:"success",ERROR:"error"},K1={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},W1={TXN:"txn",MSGID:"msgid"},ko={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},Q1={[ko.ERR]:1,[ko.WRN]:2,[ko.INF]:3,[ko.DBG]:4,[ko.TRC]:5},z1={debug:"-D",trace:"-DVV"};KN.exports={NATS_SERVER_ZIP:P1,NATS_SERVER_NAME:Lm,NATS_BINARY_NAME:v1,PID_FILES:F1,NATS_CONFIG_FILES:q1,SERVER_SUFFIX:G1,WORK_QUEUE_CONSUMER_NAMES:k1,SCHEMA_QUEUE_CONSUMER_NAMES:V1,USER_QUEUE_CONSUMER_NAMES:$1,NATS_TERM_CONSTRAINTS_RX:B1,REQUEST_SUFFIX:YN,UPDATE_REMOTE_RESPONSE_STATUSES:Y1,CLUSTER_STATUS_STATUSES:K1,REQUEST_SUBJECT:H1,SUBJECT_PREFIXES:W1,MSG_HEADERS:x1,LOG_LEVELS:ko,LOG_LEVEL_FLAGS:z1,LOG_LEVEL_HIERARCHY:Q1}});var QN=T((jce,WN)=>{"use strict";var J1={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
|
|
1
|
+
"use strict";var xq=Object.create;var Xa=Object.defineProperty;var qq=Object.getOwnPropertyDescriptor;var Fq=Object.getOwnPropertyNames;var Gq=Object.getPrototypeOf,kq=Object.prototype.hasOwnProperty;var a=(e,t)=>Xa(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),We=(e,t)=>{for(var r in t)Xa(e,r,{get:t[r],enumerable:!0})},xA=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fq(t))!kq.call(e,n)&&n!==r&&Xa(e,n,{get:()=>t[n],enumerable:!(s=qq(t,n))||s.enumerable});return e};var B=(e,t,r)=>(r=e!=null?xq(Gq(e)):{},xA(t||!e||!e.__esModule?Xa(r,"default",{value:e,enumerable:!0}):r,e)),ee=e=>xA(Xa({},"__esModule",{value:!0}),e);var GA=T((Eae,FA)=>{var Vq=require("fast-glob"),{statSync:uh,existsSync:lh,readFileSync:$q,writeFileSync:Yq}=require("fs"),{spawnSync:Kq,spawn:Wq,execFileSync:fae}=require("child_process"),{isMainThread:Qq}=require("worker_threads"),{join:Wn,relative:qA}=require("path"),{PACKAGE_ROOT:As}=L(),{tmpdir:zq,platform:Jq}=require("os");require("source-map-support").install();var jq=["resources","server","dataLayer","components"],Za="ts-build",_h,Xq=__filename.endsWith("tsBuild.js");if(Xq){if(Qq){let r;try{uh(Wn(As,Za)),r=!0}catch{}if(r)for(let s of Vq.sync(jq.map(n=>n+"/**/*.ts"),{cwd:As})){let n=0,i=0;try{n=uh(Wn(As,s)).mtimeMs-5e3,i=uh(Wn(As,Za,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),_h=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),_h=!0;if(_h){let s=Wn(As,"node_modules/.bin/tsc");Jq()==="win32"&&(s+=".cmd");let n=Kq(s,{cwd:As});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=Wn(zq(),"harperdb-tsc.pid"),o;if(lh(i))try{process.kill(+$q(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Wq(s,["--watch"],{cwd:As,detached:!0,stdio:"ignore"});Yq(i,c.pid.toString()),c.unref()}}}}let e=FA.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(As)&&!s[0].includes("node_modules")){let i=qA(As,s[0]),o;i.startsWith(Za)?o=Wn(As,qA(Za,i)):o=Wn(As,Za,i);let c=Wn(o,r),u=c+".js";if(lh(u))return u;if(c.includes(".")&&lh(c))return c}return t(r,s,n)}}});var L=T((pae,tO)=>{"use strict";var es=require("path"),Zq=require("fs"),{relative:hae,join:mae}=es,{existsSync:eF}=Zq;function tF(){let e=__dirname;for(;!eF(es.join(e,"package.json"));){let t=es.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(tF,"getHDBPackageRoot");var Qn=tF(),kA="js",xl=kA,rF="harperdb-config.yaml",sF="defaultConfig.yaml",nF="hdb",VA=`harperdb.${xl}`,$A=`customFunctionsServer.${xl}`,iF=`restartHdb.${xl}`,fh="HarperDB",Hl="Custom Functions",ql="Clustering Hub",Fl="Clustering Leaf",oF="Clustering Ingest Service",aF="Clustering Reply Service",cF="foreground.pid",uF="hdb.pid",lF="data",_F={HDB:fh,CLUSTERING_HUB:ql,CLUSTERING_LEAF:Fl,CLUSTERING_INGEST_SERVICE:oF,CLUSTERING_REPLY_SERVICE:aF,CUSTOM_FUNCTIONS:Hl,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"},dF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},fF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},EF={harperdb:fh,"clustering hub":ql,"clustering leaf":Fl,"custom functions":Hl,custom_functions:Hl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},hF={CLUSTERING_HUB_PROC_DESCRIPTOR:ql,CLUSTERING_LEAF_PROC_DESCRIPTOR:Fl},dh={HDB:es.join(Qn,"server/harperdb"),CUSTOM_FUNCTIONS:es.join(Qn,"server/customFunctions"),CLUSTERING_HUB:es.join(Qn,"server/nats"),CLUSTERING_LEAF:es.join(Qn,"server/nats")},mF={HDB:es.join(dh.HDB,VA),CUSTOM_FUNCTIONS:es.join(dh.CUSTOM_FUNCTIONS,$A)},pF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:es.join(Qn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:es.join(Qn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:es.join(Qn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},SF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},YA="support@harperdb.io",TF="customer-success@harperdb.io",KA=1,gF=4141,WA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",RF="https://www.harperdb.io/product",AF=`For support, please submit a request at ${WA} or contact ${YA}`,QA=`For license support, please contact ${TF}`,OF="None of the specified records were found.",bF="hash attribute not found",NF=`Your current license only supports ${KA} role. ${QA}`,yF="Your current license only supports 3 connections to a node.",wF="127.0.0.1",IF=1,CF=/^\.$/,DF=/^\.\.$/,LF="U+002E",MF=/\//g,UF="U+002F",PF=/U\+002F/g,vF=/^U\+002E$/,BF=/^U\+002EU\+002E$/,HF="d",xF=999999,qF="*",FF="--max-old-space-size=",GF="system",kF="__hdb_hash",VF=".harperdb",$F=".hdb",YF="keys",KF="hdb_boot_properties.file",WF=".updateConfig.json",QF="SIGTSTP",zF=24,JF=6e4,jF=448,XF="blob",ZF="trash",eG="database",tG="schema",rG="transactions",sG=".count",nG="id",iG="PROCESS_NAME",zA={SETTINGS_PATH_KEY:"settings_path"},JA=require("lodash"),oG={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"},aG={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},cG={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},uG={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"},lG={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},wr="hdb_internal:",_G={CREATE_SCHEMA:wr+"create_schema",CREATE_TABLE:wr+"create_table",CREATE_ATTRIBUTE:wr+"create_attribute",ADD_USER:wr+"add_user",ALTER_USER:wr+"alter_user",DROP_USER:wr+"drop_user",HDB_NODES:wr+"hdb_nodes",HDB_USERS:wr+"hdb_users",HDB_WORKERS:wr+"hdb_workers",CATCHUP:wr+"catchup",SCHEMA_CATCHUP:wr+"schema_catchup",WORKER_ROOM:wr+"cluster_workers"},dG={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"},fG="060493.ks",EG=".license",hG={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},j={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"},mG={CSV:".csv",JSON:".json"},pG={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},SG={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},ec={};ec[j.INSERT]=j.INSERT;ec[j.UPDATE]=j.UPDATE;ec[j.UPSERT]=j.UPSERT;ec[j.DELETE]=j.DELETE;var He=Object.create(null);He[j.DESCRIBE_ALL]=j.DESCRIBE_ALL;He[j.DESCRIBE_TABLE]=j.DESCRIBE_TABLE;He[j.DESCRIBE_SCHEMA]=j.DESCRIBE_SCHEMA;He[j.READ_LOG]=j.READ_LOG;He[j.ADD_NODE]=j.ADD_NODE;He[j.LIST_USERS]=j.LIST_USERS;He[j.LIST_ROLES]=j.LIST_ROLES;He[j.USER_INFO]=j.USER_INFO;He[j.SQL]=j.SQL;He[j.GET_JOB]=j.GET_JOB;He[j.SEARCH_JOBS_BY_START_DATE]=j.SEARCH_JOBS_BY_START_DATE;He[j.DELETE_FILES_BEFORE]=j.DELETE_FILES_BEFORE;He[j.EXPORT_LOCAL]=j.EXPORT_LOCAL;He[j.EXPORT_TO_S3]=j.EXPORT_TO_S3;He[j.CLUSTER_STATUS]=j.CLUSTER_STATUS;He[j.REMOVE_NODE]=j.REMOVE_NODE;He[j.RESTART]=j.RESTART;He[j.CUSTOM_FUNCTIONS_STATUS]=j.CUSTOM_FUNCTIONS_STATUS;He[j.GET_CUSTOM_FUNCTIONS]=j.GET_CUSTOM_FUNCTIONS;He[j.GET_CUSTOM_FUNCTION]=j.GET_CUSTOM_FUNCTION;He[j.SET_CUSTOM_FUNCTION]=j.SET_CUSTOM_FUNCTION;He[j.DROP_CUSTOM_FUNCTION]=j.DROP_CUSTOM_FUNCTION;He[j.ADD_CUSTOM_FUNCTION_PROJECT]=j.ADD_CUSTOM_FUNCTION_PROJECT;He[j.DROP_CUSTOM_FUNCTION_PROJECT]=j.DROP_CUSTOM_FUNCTION_PROJECT;He[j.PACKAGE_CUSTOM_FUNCTION_PROJECT]=j.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[j.DEPLOY_CUSTOM_FUNCTION_PROJECT]=j.DEPLOY_CUSTOM_FUNCTION_PROJECT;var TG={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"},gG={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},jA={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"},RG=JA.invert(jA),AG={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"},XA={settings_path:zA.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];XA[t.toLowerCase()]=t}var OG={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},bG={csv_file_load:"csv_file_load",csv_data_load:j.CSV_DATA_LOAD,csv_url_load:j.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"},NG={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"},yG={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},wG={VERSION_DEFAULT:"2.2.0"},IG={DEVELOPMENT:8192,DEFAULT:512},CG={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"},DG={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"},LG={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},ZA={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},MG=Symbol("metadata"),UG="__clustering__",PG=Object.values(ZA),vG=15984864e5,eO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},BG=JA.invert(eO),HG={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"},xG=111,qG=`\r
|
|
2
|
+
`,FG={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},GG=["*","%"],kG="unauthorized_access",VG="func_val",$G={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},YG={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},KG={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"},WG={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},QG={HTTP:"http"},zG={STOPPED:"stopped",ONLINE:"online"},JG="3.x.x",jG={SUCCESS:"success",FAILURE:"failure"},XG={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};tO.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:YA,HDB_SUPPORT_URL:WA,HDB_PRICING_URL:RF,SUPPORT_HELP_MSG:AF,LICENSE_HELP_MSG:QA,HDB_PROC_NAME:VA,HDB_PROC_DESCRIPTOR:fh,CLUSTERING_LEAF_PROC_DESCRIPTOR:Fl,CLUSTERING_HUB_PROC_DESCRIPTOR:ql,SYSTEM_SCHEMA_NAME:GF,HASH_FOLDER_NAME:kF,HDB_HOME_DIR_NAME:VF,UPDATE_FILE_NAME:WF,LICENSE_KEY_DIR_NAME:YF,BOOT_PROPS_FILE_NAME:KF,JOB_TYPE_ENUM:bG,JOB_STATUS_ENUM:hG,SYSTEM_TABLE_NAMES:uG,SYSTEM_TABLE_HASH_ATTRIBUTES:lG,OPERATIONS_ENUM:j,VALID_S3_FILE_TYPES:mG,S3_BUCKET_AUTH_KEYS:pG,VALID_SQL_OPS_ENUM:SG,GEO_CONVERSION_ENUM:gG,HDB_SETTINGS_NAMES:jA,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:RG,SERVICE_ACTIONS_ENUM:TG,CLUSTER_MESSAGE_TYPE_ENUM:NG,CLUSTER_CONNECTION_DIRECTION_ENUM:yG,CLUSTER_EVENTS_DEFS_ENUM:CG,PERIOD_REGEX:CF,DOUBLE_PERIOD_REGEX:DF,UNICODE_PERIOD:LF,FORWARD_SLASH_REGEX:MF,UNICODE_FORWARD_SLASH:UF,ESCAPED_FORWARD_SLASH_REGEX:PF,ESCAPED_PERIOD_REGEX:vF,ESCAPED_DOUBLE_PERIOD_REGEX:BF,REG_KEY_FILE_NAME:fG,RESTART_TIMEOUT_MS:JF,HDB_FILE_PERMISSIONS:jF,DATABASES_DIR_NAME:eG,LEGACY_DATABASES_DIR_NAME:tG,TRANSACTIONS_DIR_NAME:rG,LIMIT_COUNT_NAME:sG,ID_ATTRIBUTE_STRING:nG,INSERT_MODULE_ENUM:aG,UPGRADE_JSON_FIELD_NAMES_ENUM:cG,RESTART_CODE:QF,RESTART_CODE_NUM:zF,CLUSTER_OPERATIONS:ec,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:dG,HDB_INTERNAL_SC_CHANNEL_PREFIX:wr,INTERNAL_SC_CHANNELS:_G,CLUSTERING_MESSAGE_TYPES:HG,HDB_FILE_SUFFIX:$F,BLOB_FOLDER_NAME:XF,HDB_TRASH_DIR:ZF,ORIGINATOR_SET_VALUE:xG,LICENSE_VALUES:wG,RAM_ALLOCATION_ENUM:IG,TIME_STAMP_NAMES_ENUM:ZA,TIME_STAMP_NAMES:PG,PERMS_UPDATE_RELEASE_TIMESTAMP:vG,SEARCH_NOT_FOUND_MESSAGE:OF,SEARCH_ATTRIBUTE_NOT_FOUND:bF,LICENSE_ROLE_DENIED_RESPONSE:NF,LICENSE_MAX_CONNS_REACHED:yF,BASIC_LICENSE_MAX_NON_CU_ROLES:KA,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:gF,VALUE_SEARCH_COMPARATORS:eO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:BG,LICENSE_FILE_NAME:EG,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:DG,NEW_LINE:qG,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:IF,MOMENT_DAYS_TAG:HF,API_TURNOVER_SEC:xF,LOOPBACK:wF,CODE_EXTENSION:xl,WILDCARD_SEARCH_VALUE:qF,NODE_ERROR_CODES:LG,JAVASCRIPT_EXTENSION:kA,PERMS_CRUD_ENUM:FG,UNAUTHORIZED_PERMISSION_NAME:kG,SEARCH_WILDCARDS:GG,FUNC_VAL:VG,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:$G,JWT_ENUM:YG,CLUSTERING_FLAG:UG,ITC_EVENT_TYPES:KG,CUSTOM_FUNCTION_PROC_NAME:$A,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Hl,SERVICES:WG,THREAD_TYPES:QG,MEM_SETTING_KEY:FF,HDB_RESTART_SCRIPT:iF,PROCESS_DESCRIPTORS:_F,SERVICE_SERVERS:mF,SERVICE_SERVERS_CWD:dh,PROCESS_DESCRIPTORS_VALIDATE:EF,LAUNCH_SERVICE_SCRIPTS:pF,LOG_LEVELS:fF,PROCESS_NAME_ENV_PROP:iG,LOG_NAMES:dF,PM2_PROCESS_STATUSES:zG,CONFIG_PARAM_MAP:XA,CONFIG_PARAMS:C,HDB_CONFIG_FILE:rF,HDB_DEFAULT_CONFIG_FILE:sF,ROLE_TYPES_ENUM:SF,BOOT_PROP_PARAMS:zA,INSTALL_PROMPTS:oG,HDB_ROOT_DIR_NAME:nF,CLUSTERING_PROCESSES:hF,FOREGROUND_PID_FILE:cF,PACKAGE_ROOT:Qn,PRE_4_0_0_VERSION:JG,DATABASES_PARAM_CONFIG:OG,METADATA_PROPERTY:MG,AUTH_AUDIT_STATUS:jG,AUTH_AUDIT_TYPES:XG,HDB_PID_FILE:uF,DEFAULT_DATABASE_NAME:lF,LEGACY_CONFIG_PARAMS:AG};GA()});var Eh=T((Tae,nO)=>{"use strict";var rO=require("minimist");nO.exports=ZG;function ZG(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=sO(process.env),s=sO(rO(process.argv))):(r=process.env,s=rO(process.argv));let n={};for(let i=0,o=e.length;i<o;i++){let c=e[i];s[c]!==void 0?n[c]=s[c].toString().trim():r[c]!==void 0&&(n[c]=r[c].toString().trim())}return n}a(ZG,"assignCMDENVVariables");function sO(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(sO,"objKeysToLowerCase")});var V=T((Rae,Rh)=>{"use strict";var Ci=require("fs-extra"),{workerData:ek,threadId:tk}=require("worker_threads"),hn=require("path"),aO=require("yaml"),cO=require("properties-reader"),Ot=L(),iO=Eh(),rk=require("os"),{PACKAGE_ROOT:mh}=L(),{_assignPackageExport:sk}=require("../index"),rc={};for(let e in console)rc[e]||(rc[e]=console[e]);var er={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},uO={STDOUT:"stdOut",STDERR:"stdErr"},nk=hn.join(mh,"logs"),ik=hn.join(mh,"config/yaml/",Ot.HDB_DEFAULT_CONFIG_FILE),ok=1e4,En,ks,Zt,Gl,kl,sc,vo,tc;tc===void 0&&lO();Rh.exports={notify:fO,fatal:EO,error:nc,warn:gh,info:Vl,debug:Th,trace:Sh,setLogLevel:fk,log_level:Zt,loggerWithTag:ak,suppressLogging:ck,initLogSettings:lO,setupConsoleLogging:_O,logCustomLevel:_k,closeLogFile:ph,getLogFilePath:()=>sc,OUTPUTS:uO,AuthAuditLog:mk};sk("logger",Rh.exports);function lO(e=!1){try{if(tc===void 0||e){ph();let t=dk(),r=iO(["ROOTPATH"]);try{tc=cO(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!Ci.pathExistsSync(hn.join(r.ROOTPATH,Ot.HDB_CONFIG_FILE)))throw s}({level:Zt,config_log_path:kl,to_file:En,to_stream:ks}=Ek(r.ROOTPATH?hn.join(r.ROOTPATH,Ot.HDB_CONFIG_FILE):tc.get("settings_path"))),Gl=Ot.LOG_NAMES.HDB,sc=hn.join(kl,Gl)}}catch(t){if(tc=void 0,t.code===Ot.NODE_ERROR_CODES.ENOENT){let r=iO(Object.keys(Ot.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Ot.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Ot.CONFIG_PARAMS.LOGGING_LEVEL){Zt=u;continue}if(c===Ot.CONFIG_PARAMS.LOGGING_STDSTREAMS){ks=u;continue}c===Ot.CONFIG_PARAMS.LOGGING_FILE&&(En=c)}let{default_level:s,default_to_file:n,default_to_stream:i}=hk();En=En===void 0?n:En,En=oO(En),ks=ks===void 0?i:ks,ks=oO(ks),Zt=Zt===void 0?s:Zt,kl=nk,Gl=Ot.LOG_NAMES.INSTALL,sc=hn.join(kl,Gl);return}throw nc("Error initializing log settings"),nc(t),t}process.env.DEV_MODE&&(ks=!0),_O()}a(lO,"initLogSettings");var hh=!0;function _O(){Po("error",nc),Po("warn",gh),Po("log",Vl),Po("info",Vl),Po("debug",Th),Po("trace",Sh)}a(_O,"setupConsoleLogging");function Po(e,t){console[e]=function(...r){if(hh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return rc[e](...r)}}a(Po,"logConsole");function ak(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(fO),fatal:r(EO),error:r(nc),warn:r(gh),info:r(Vl),debug:r(Th),trace:r(Sh)};function r(s){return function(...n){return s(t,...n)}}}a(ak,"loggerWithTag");function ck(e){try{hh=!1,e()}finally{hh=!0}}a(ck,"suppressLogging");var uk=ek?.name?.replace(/ /g,"-")||"main";function mn(e,t){let r=new Date(Date.now()).toISOString(),s="",n=t.length,i=n-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||uk+"/"+tk);c<n;c++){let _=t[c];_ instanceof Error&&_.stack?s+=_.stack:typeof _=="object"?s+=JSON.stringify(_):s+=_,c<i&&(s+=" ")}return`${r} [${o.join("] [")}]: ${s}
|
|
3
|
+
`}a(mn,"createLogRecord");function ic(e){En&&dO(e),ks&&process.stdout.write(e)}a(ic,"logStdOut");function $l(e){En&&dO(e),ks&&process.stderr.write(e)}a($l,"logStdErr");function dO(e){lk(),vo?Ci.appendFileSync(vo,e):rc.log(e)}a(dO,"logToFile");function ph(){try{Ci.closeSync(vo)}catch{}vo=null}a(ph,"closeLogFile");function lk(){if(!vo){try{if(!sc)debugger;vo=Ci.openSync(sc,"a")}catch(e){rc.error(e)}setTimeout(()=>{ph()},ok).unref()}}a(lk,"openLogFile");function Vl(...e){er[Zt]<=er.info&&ic(mn("info",e))}a(Vl,"info");function Sh(...e){er[Zt]<=er.trace&&ic(mn("trace",e))}a(Sh,"trace");function nc(...e){er[Zt]<=er.error&&$l(mn("error",e))}a(nc,"error");function Th(...e){er[Zt]<=er.debug&&ic(mn("debug",e))}a(Th,"debug");function fO(...e){er[Zt]<=er.notify&&ic(mn("notify",e))}a(fO,"notify");function EO(...e){er[Zt]<=er.fatal&&$l(mn("fatal",e))}a(EO,"fatal");function gh(...e){er[Zt]<=er.warn&&$l(mn("warn",e))}a(gh,"warn");function _k(e,t,...r){t===uO.STDERR?$l(mn(e,r)):ic(mn(e,r))}a(_k,"logCustomLevel");function dk(){let e;try{e=rk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=hn.join(e,Ot.HDB_HOME_DIR_NAME,Ot.BOOT_PROPS_FILE_NAME);return Ci.existsSync(t)||(t=hn.join(mh,"utility/hdb_boot_properties.file")),t}a(dk,"getPropsFilePath");function fk(e){Zt=e}a(fk,"setLogLevel");function oO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(oO,"autoCastBoolean");function Ek(e){try{if(e.includes("config/settings.js")){let o=cO(e);return{level:o.get(Ot.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:hn.dirname(o.get(Ot.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Ot.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Ot.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=aO.parseDocument(Ci.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),s=t.getIn(["logging","root"]),n=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:s,to_file:n,to_stream:i}}catch(t){if(t.code===Ot.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Ek,"getLogConfig");function hk(){try{let e=aO.parseDocument(Ci.readFileSync(ik,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),s=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:s}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(hk,"getDefaultConfig");function mk(e,t,r,s,n,i){this.username=e,this.status=t,this.type=r,this.originating_ip=s,this.request_method=n,this.path=i}a(mk,"AuthAuditLog")});var mO=T((Oae,hO)=>{"use strict";var pk=require("util"),Sk=require("path"),Tk=require("child_process"),gk=pk.promisify(Tk.execFile),Rk=1e3*1e3*10;hO.exports={findPs:Ak};async function Ak(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await gk("ps",["wwxo",`pid,${r}`],{maxBuffer:Rk});for(let n of s.trim().split(`
|
|
4
|
+
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,s])=>({pid:Number.parseInt(r,10),name:Sk.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(Ak,"findPs")});var ht=T((Nae,SO)=>{"use strict";var Ok="__dbis__",bk="__txns__",Nk="__environment_name__",yk="__dbi_defintion__",wk={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"},Ik=["__createdtime__","__updatedtime__"],Ck="\uFFFF",pO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},Dk=Object.values(pO);SO.exports={AUDIT_STORE_NAME:bk,INTERNAL_DBIS_NAME:Ok,DBI_DEFINITION_NAME:yk,SEARCH_TYPES:wk,TIMESTAMP_NAMES:Ik,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Nk,TRANSACTIONS_DBI_NAMES_ENUM:pO,TRANSACTIONS_DBIS:Dk,OVERFLOW_MARKER:Ck}});var Ir=T((yae,wO)=>{"use strict";var TO=L(),gO=ht(),RO={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},AO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),OO={500:AO("There was an error processing your request."),400:"Invalid request"},Lk=OO[RO.INTERNAL_SERVER_ERROR],Mk={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.`},Uk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},Pk={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"},vk={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 ${gO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${gO.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"},Bk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${TO.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 ${TO.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"},bO={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"},Hk={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."},xk={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`},qk={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"},Fk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Gk={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`},NO={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.`},yO={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}`},kk={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."},Vk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},$k={...bO,...Pk,...Mk,...Hk,...xk,...qk,...Fk,...Gk,...Bk,...NO,...yO,...kk,...Vk,...Uk};wO.exports={CHECK_LOGS_WRAPPER:AO,HDB_ERROR_MSGS:$k,DEFAULT_ERROR_MSGS:OO,DEFAULT_ERROR_RESP:Lk,HTTP_STATUS_CODES:RO,LMDB_ERRORS_ENUM:vk,AUTHENTICATION_ERROR_MSGS:bO,VALIDATION_ERROR_MSGS:NO,ITC_ERRORS:yO}});var Z=T((Iae,DO)=>{"use strict";var Bo=Ir(),Yk=V(),Kk=L(),Yl=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,IO),this.statusCode=s||Bo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Bo.DEFAULT_ERROR_MSGS[s]?Bo.DEFAULT_ERROR_MSGS[s]:Bo.DEFAULT_ERROR_MSGS[Bo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&Yk[n](i)}},Ah=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}},Oh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function IO(e,t,r,s=Kk.LOG_LEVELS.ERROR,n=null,i=!1){if(CO(e))return e;let o=new Yl(e,t,r,s,n);return i&&delete o.stack,o}a(IO,"handleHDBError");function CO(e){return e.__proto__.constructor.name===Yl.name}a(CO,"isHDBError");DO.exports={isHDBError:CO,handleHDBError:IO,ClientError:Ah,ServerError:Oh,hdb_errors:Bo}});var Xe=T((Dae,HO)=>{"use strict";var lc=L(),Wk=J(),tr=X(),_c=require("path"),Qk=require("minimist"),LO=require("fs-extra"),MO=require("lodash");tr.initSync();var{CONFIG_PARAMS:zn,DATABASES_PARAM_CONFIG:oc,SYSTEM_SCHEMA_NAME:Kl}=lc,ac,cc,uc;function UO(){if(ac!==void 0)return ac;if(tr.getHdbBasePath()!==void 0)return ac=tr.get(zn.STORAGE_PATH)||_c.join(tr.getHdbBasePath(),lc.DATABASES_DIR_NAME),ac}a(UO,"getBaseSchemaPath");function PO(){if(cc!==void 0)return cc;if(tr.getHdbBasePath()!==void 0)return cc=BO(Kl),cc}a(PO,"getSystemSchemaPath");function vO(){if(uc!==void 0)return uc;if(tr.getHdbBasePath()!==void 0)return uc=tr.get(lc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||_c.join(tr.getHdbBasePath(),lc.TRANSACTIONS_DIR_NAME),uc}a(vO,"getTransactionAuditStoreBasePath");function zk(e,t){let r=tr.get(zn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||_c.join(vO(),e.toString())}a(zk,"getTransactionAuditStorePath");function BO(e,t){e=e.toString(),t=t&&t.toString();let r=tr.get(lc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||_c.join(UO(),e)}a(BO,"getSchemaPath");function Jk(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,Qk(process.argv));let s=r[zn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!Wk.isObject(s))throw o;i=s}for(let o of i){let c=o[Kl];if(!c)continue;let u=tr.get(zn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[oc.PATH];if(_)return MO.set(u,[Kl,oc.TABLES,t,oc.PATH],_),tr.setProperty(zn.DATABASES,u),_;let l=c?.[oc.PATH];if(l)return MO.set(u,[Kl,oc.PATH],l),tr.setProperty(zn.DATABASES,u),l}}let n=r[zn.STORAGE_PATH.toUpperCase()];if(n){if(!LO.pathExistsSync(n))throw new Error(n+" does not exist");let i=_c.join(n,e);return LO.mkdirsSync(i),tr.setProperty(zn.STORAGE_PATH,n),i}return PO()}a(Jk,"initSystemSchemaPaths");function jk(){ac=void 0,cc=void 0,uc=void 0}a(jk,"resetPaths");HO.exports={getBaseSchemaPath:UO,getSystemSchemaPath:PO,getTransactionAuditStorePath:zk,getTransactionAuditStoreBasePath:vO,getSchemaPath:BO,initSystemSchemaPaths:Jk,resetPaths:jk}});var Cr=T((Pae,kO)=>{"use strict";var Xk=Ir().LMDB_ERRORS_ENUM,Mae=require("lmdb"),Zk=ht(),Uae=require("buffer").Buffer,{OVERFLOW_MARKER:xO,MAX_SEARCH_KEY_LENGTH:Wl}=Zk,qO=["number","string","symbol","boolean","bigint"];function eV(e){if(e=e?.primaryStore||e,!e)throw new Error(Xk.ENV_REQUIRED)}a(eV,"validateEnv");function tV(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(tV,"stringifyData");function rV(e){return e instanceof Date?e.valueOf():e}a(rV,"convertKeyValueToWrite");function sV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(qO.includes(typeof e))return e.length>Wl?[e.slice(0,Wl)+xO]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if(qO.includes(typeof i))i.length>Wl?r.push(i.slice(0,Wl)+xO):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(sV,"getIndexedValues");var Ql=0,FO=0;function GO(){FO=Date.now()-performance.now()}a(GO,"adjustStartTime");GO();var nV=6e4;setInterval(GO,nV).unref();function iV(){let e=performance.now()+FO;return e>Ql?(Ql=e,e):(Ql+=488e-6,Ql)}a(iV,"getNextMonotonicTime");kO.exports={validateEnv:eV,stringifyData:tV,convertKeyValueToWrite:rV,getNextMonotonicTime:iV,getIndexedValues:sV}});var VO,Os,bh,dc=Re(()=>{VO=require("events"),Os=class extends VO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new bh;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)}},bh=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 Di={};We(Di,{server:()=>lt});var $O,lt,rr=Re(()=>{$O=require("../index"),lt={};(0,$O._assignPackageExport)("server",lt)});var yh={};We(yh,{loadGQLSchema:()=>cV,start:()=>Nh,startOnMainThread:()=>aV});function Nh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),n)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let 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=S.name.value,A=[],b={table:null,database:null,properties:A};f.set(g,b);for(let H of S.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 S.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 p(S){let g=f.get(S.type);g?(Object.defineProperty(S,"properties",{value:g.properties}),Object.defineProperty(S,"definition",{value:g})):S.type==="array"?p(S.elements):oV.includes(S.type)||(0,YO.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${n}`)}a(p,"connectPropertyType");for(let S of f.values())for(let g of S.properties)p(g);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,zl.dirname)(s),S.tableClass):i.set((0,zl.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass));if(h)for(let S of h.properties){let g=f.get(S.type);if(!g)throw new Error(`${S.type} was not found as a Query export`);i.set((0,zl.dirname)(s)+"/"+S.name,g.tableClass)}}}var zl,YO,oV,aV,cV,KO=Re(()=>{zl=require("path");Ae();YO=B(Qe()),oV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Nh,"start");aV=Nh,cV=Nh({ensureTable:_t}).handleFile});async function Jl(e){return uV?(fc||(fc=lV(dV)),(await(await fc).import(e)).namespace):import(e)}async function lV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),fc=new Compartment({console,Math,Date,fetch:_V,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,QO.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:qt,tables:Dr,databases:nt})}};let s=await(0,WO.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),fc}function _V(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function dV(){return{Resource:qt,tables:Dr}}var WO,QO,uV,fc,wh=Re(()=>{bs();Ae();WO=require("fs/promises"),QO=require("path"),uV=!1;a(Jl,"secureImport");a(lV,"getCompartment");a(_V,"secureOnlyFetch");a(dV,"getGlobalVars")});var Ch={};We(Ch,{handleFile:()=>fV});async function fV(e,t,r,s){let n=new Map,i=(0,zO.pathToFileURL)(r).toString(),o=await Jl(i);u(o.default)&&s.set((0,Ih.dirname)(t),o.default),c(o,(0,Ih.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?s.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),n}var zO,Ih,JO=Re(()=>{zO=require("url");wh();Ih=require("path");a(fV,"handleFile")});var Lh={};We(Lh,{start:()=>EV});function EV({resources:e}){e.set("login",Dh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Dh,jO=Re(()=>{bs();a(EV,"start");Dh=class extends qt{static{a(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:o}=r;return{data:await s.login(n,i)}}}});var nb={};We(nb,{parse:()=>Uh,streamAsJSON:()=>Ec,stringify:()=>Li});function Ec(e){return new Mh({value:e})}function XO(e){return console.error(e),JSON.stringify(e.toString())}function ZO(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Li(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===rb)return sb(e);if(t.resolution)return t.resolution.then(()=>Li(e));throw t}}function sb(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let s=0;s<e.length;s++)s>0&&(r+=","),r+=sb(e[s]);return r+"]"}else{r="{";let s=!0;for(let n in e)s?s=!1:r+=",",r+=JSON.stringify(n)+":"+Li(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Uh(e){return pV.test(e)?hV.parse(e):JSON.parse(e)}var eb,tb,hV,mV,rb,Mh,pV,Ph=Re(()=>{eb=require("stream"),tb=B(require("json-bigint-fixes")),hV=(0,tb.default)({useNativeBigInt:!0}),mV=1e4,rb={};BigInt.prototype.toJSON=function(){throw rb};a(Ec,"streamAsJSON");Mh=class extends eb.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else n?n=!1:yield",",yield*this.serialize(o.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),XO)}catch(n){yield XO(n)}else yield Li(t)}else yield Li(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);ZO(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>mV?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 ZO(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let s of this.activeIterators)t?s.throw(t):s.return();r()}};a(XO,"handleError");a(ZO,"when");a(Li,"stringify");a(sb,"jsStringify");pV=/-?\d{16,}/;a(Uh,"parse")});var pb=T((Jae,mb)=>{"use strict";var vh=require("recursive-iterator"),SV=require("alasql"),Bh=require("clone"),ib=J(),{handleHDBError:ob,hdb_errors:TV}=Z(),{HDB_ERROR_MSGS:ab,HTTP_STATUS_CODES:cb}=TV,{getDatabases:gV}=(Ae(),ee(Fe)),RV=["DISTINCT_ARRAY"],ub=Symbol("validateTables"),Hh=Symbol("validateTable"),zae=Symbol("getAllColumns"),lb=Symbol("validateAllColumns"),jl=Symbol("findColumn"),_b=Symbol("validateOrderBy"),hc=Symbol("validateSegment"),xh=Symbol("validateColumn"),db=Symbol("setColumnsForTable"),fb=Symbol("checkColumnsForAsterisk"),Eb=Symbol("validateGroupBy"),hb=Symbol("hasColumns"),qh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[ub](),this[fb](),this[lb]()}[ub](){if(this[hb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Hh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Hh](t.table)})}}[hb](){let t=!1,r=new vh(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Hh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=gV();if(!r[t.databaseid])throw ob(new Error,ab.SCHEMA_NOT_FOUND(t.databaseid),cb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw ob(new Error,ab.TABLE_NOT_FOUND(t.databaseid,t.tableid),cb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=Bh(n);i.table=Bh(t),this.attributes.push(i)})}[jl](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)}[fb](){let t=new vh(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[db](r.tableid)}[db](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new SV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[lb](){this[hc](this.statement.columns,!1),this[hc](this.statement.joins,!1),this[hc](this.statement.where,!1),this[Eb](this.statement.group,!1),this[hc](this.statement.order,!0)}[hc](t,r){if(!t)return;let s=new vh(t),n=[];for(let{node:i,path:o}of s)!ib.isEmpty(i)&&!ib.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[_b](i):n.push(this[xh](i)));return n}[Eb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&RV.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=Bh(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[jl](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[jl](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[_b](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[xh](t)}[xh](t){let r=this[jl](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};mb.exports=qh});var Tb=T((Xae,Sb)=>{"use strict";var Fh=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")}};Sb.exports=Fh});var Rb=T((ece,gb)=>{"use strict";var Gh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};gb.exports=Gh});var Nb={};We(Nb,{HAS_EXPIRATION:()=>zh,LAST_TIMESTAMP_PLACEHOLDER:()=>Sc,LOCAL_TIMESTAMP:()=>AV,METADATA:()=>mc,NO_TIMESTAMP:()=>Vh,PENDING_LOCAL_TIME:()=>Jh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>Qh,RecordEncoder:()=>Kh,TIMESTAMP_ASSIGN_LAST:()=>bV,TIMESTAMP_ASSIGN_NEW:()=>Ob,TIMESTAMP_ASSIGN_PREVIOUS:()=>bb,TIMESTAMP_PLACEHOLDER:()=>Xl,TIMESTAMP_RECORD_PREVIOUS:()=>$h,fromResource:()=>r_,getUpdateRecord:()=>jh,handleLocalTimeForGets:()=>s_});function yV(){return pc[0]=pc[0]^64,OV.getFloat64(0)}function r_(e){Wh=!0;try{return e()}finally{Wh=!1}}function s_(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?.[mc];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?.[mc]>=0?c.value:c};let s=e.getRange;e.getRange=function(i){let o=s.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[mc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let n=e.useReadTransaction();if(n.done(),!n.done.isTracked){let i=n.constructor,o=n.use,c=n.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,Mi.push(new WeakRef(this))),!Wh)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<Mi.length;u++){let _=Mi[u].deref();(!_||_.isDone||_.isCommitted)&&Mi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function jh(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Ho=i?.localTime?$h|bb:Vh:Ho=u?i?.localTime?$h|16384:Ob|16384:Vh,l>0&&(c|=zh),e_=c,Yh=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Ho>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(s,n,h);if(u){let g=_?.user?.username;if(E&&(Zl=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,t_(o,t,s,v,g,d,Zl),{ifVersion:p}),S}}r.put(Sc,t_(o,t,s,i?.localTime?1:0,g,d,Zl),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+s+" options: "+h,S}}}var Ab,kh,Xl,Sc,Qh,AV,mc,pc,OV,Vh,Ob,bV,bb,$h,zh,Jh,NV,Zl,Ho,e_,Yh,Kh,sce,Wh,Mi,xo=Re(()=>{Ab=require("msgpackr");Ui();kh=B(V()),Xl=new Uint8Array([1,1,1,1,4,64,0,0]),Sc=new Uint8Array([1,1,1,1,1,0,0,0]),Qh=new Uint8Array([1,1,1,1,3,64,0,0]),AV=Symbol("local-timestamp"),mc=Symbol("metadata"),pc=new Uint8Array(8),OV=new DataView(pc.buffer,0,8),Vh=0,Ob=0,bV=1,bb=3,$h=4,zh=16,Jh=1,Ho=0,e_=-1,Yh=0,Kh=class extends Ab.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,n){if(Ho||e_>=0){let i=0,o=Ho;o&&(i+=8,Ho=0);let c=e_,u=Yh;c>=0&&(i+=2,e_=-1,u&&(i+=8,Yh=0));let _=NV=r.call(this,s,n|2048|i);Zl=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(Xl[4]=o,Xl[5]=o>>8,_.set(Xl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,s,n)}}decode(t,r){let s=r?.start||0,n=r>-1?r:r?.end||t.length,i=t[s],o=0;try{if(i<32&&n>2){let c=s,u;if(i===2){if(t.copy)t.copy(pc,0,c),c+=8;else for(let d=0;d<8;d++)pc[d]=t[c++];u=yV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&zh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,n),n-c);return{localTime:u,value:l,[mc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(yV,"getTimestamp");sce=Map.prototype.get;a(r_,"fromResource");a(s_,"handleLocalTimeForGets");Mi=[];setInterval(()=>{for(let e=0;e<Mi.length;e++){let t=Mi[e].deref();!t||t.isDone||t.isCommitted?Mi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(kh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):kh.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(jh,"getUpdateRecord")});var n_=T((ice,yb)=>{"use strict";var Zh=X(),em=L(),{RecordEncoder:wV}=(xo(),ee(Nb));Zh.initSync();var IV=Zh.get(em.CONFIG_PARAMS.STORAGE_COMPRESSION),CV=Zh.get(em.CONFIG_PARAMS.STORAGE_CACHING)!==!1,DV=em.UPDATES_PROPERTY,Xh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=IV&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=CV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:wV},this.alwaysLazyProperty=s=>s===DV)}};yb.exports=Xh});var o_=T((ace,Ib)=>{"use strict";var qo=X(),Tc=L();qo.initSync();var LV=qo.get(Tc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||qo.get(Tc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||qo.get(Tc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",wb=qo.get(Tc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),MV=qo.get(Tc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),i_=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=LV,this.noFSAccess=!0,wb!==void 0&&(this.overlappingSync=wb),this.noReadAhead=MV}};Ib.exports=i_;i_.MAX_DBS=1e4});var ze=T((uce,xb)=>{"use strict";var rm=require("lmdb"),Ns=require("fs-extra"),Lr=require("path"),a_=Cr(),Lb=V(),sr=Ir().LMDB_ERRORS_ENUM,c_=Rb(),sm=n_(),Mb=o_(),Jn=ht(),Cb=L(),{table:UV,resetDatabases:PV}=(Ae(),ee(Fe)),Db=X(),ys=Jn.INTERNAL_DBIS_NAME,Ub=Jn.DBI_DEFINITION_NAME,vV="data.mdb",BV="lock.mdb",gc=".mdb",HV="-lock",tm=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=ts(t,r),this.key_type=this.dbi[Jn.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Jn.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new rm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function u_(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(u_,"pathEnvNameValidation");async function nm(e,t,r=!0){try{await Ns.access(e)}catch(s){throw s.code==="ENOENT"?new Error(sr.INVALID_BASE_PATH):s}try{let s=Lr.join(e,t+gc);return await Ns.access(s,Ns.constants.R_OK|Ns.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Ns.access(Lr.join(e,t,vV),Ns.constants.R_OK|Ns.constants.F_OK),Lr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(sr.INVALID_ENVIRONMENT)}else throw new Error(sr.INVALID_ENVIRONMENT);throw s}}a(nm,"validateEnvironmentPath");function l_(e,t){if(a_.validateEnv(e),t===void 0)throw new Error(sr.DBI_NAME_REQUIRED)}a(l_,"validateEnvDBIName");async function xV(e,t,r=!1,s=!1){u_(e,t);let n=Lr.basename(e);t=t.toString();let i=Db.get(Cb.CONFIG_PARAMS.DATABASES);i||Db.setProperty(Cb.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await nm(e,t,s),Pb(e,t,r)}catch(o){if(o.message===sr.INVALID_ENVIRONMENT){let c=Lr.join(e,t);await Ns.mkdirp(s?c:e);let u=new Mb(s?c:c+gc,!1),_=rm.open(u);_.dbis=Object.create(null);let l=new sm(!1);_.openDB(ys,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=im(e,t,r);return _[Jn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(xV,"createEnvironment");async function qV(e,t,r,s=!0){u_(e,t),t=t.toString();let n=Lr.join(e,t);return UV({table:t,database:Lr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(qV,"copyEnvironment");async function Pb(e,t,r=!1){u_(e,t),t=t.toString();let s=im(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await nm(e,t),i=Lr.join(e,t+gc),o=n!=i,c=new Mb(n,o),u=rm.open(c);u.dbis=Object.create(null);let _=Bb(u);for(let l=0;l<_.length;l++)ts(u,_[l]);return u[Jn.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(Pb,"openEnvironment");async function FV(e,t,r=!1){u_(e,t),t=t.toString();let s=Lr.join(e,t+gc),n=await nm(e,t);if(global.lmdb_map!==void 0){let i=im(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await vb(o),delete global.lmdb_map[i]}}await Ns.remove(n),await Ns.remove(n===s?n+HV:Lr.join(Lr.dirname(n),BV))}a(FV,"deleteEnvironment");async function vb(e){a_.validateEnv(e);let t=e[Jn.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(vb,"closeEnvironment");function im(e,t,r=!1){let n=`${Lr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(im,"getCachedEnvironmentName");function GV(e){a_.validateEnv(e);let t=Object.create(null),r=ts(e,ys);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==ys)try{t[s]=Object.assign(new c_,n)}catch{Lb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(GV,"listDBIDefinitions");function Bb(e){a_.validateEnv(e);let t=[],r=ts(e,ys);for(let{key:s}of r.getRange({start:!1}))s!==ys&&t.push(s);return t}a(Bb,"listDBIs");function kV(e,t){let s=ts(e,ys).getEntry(t),n=new c_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Lb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(kV,"getDBIDefinition");function Hb(e,t,r,s=!r){if(l_(e,t),t=t.toString(),t===ys)throw new Error(sr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return ts(e,t)}catch(n){if(n.message===sr.DBI_DOES_NOT_EXIST){let i=new sm(r,s===!0),o=e.openDB(t,i),c=new c_(r===!0,s);return o[Ub]=c,ts(e,ys).putSync(t,c),e.dbis[t]=o,o}throw n}}a(Hb,"createDBI");function ts(e,t){if(l_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==ys?r=kV(e,t):r=new c_,r===void 0)throw new Error(sr.DBI_DOES_NOT_EXIST);let s;try{let n=new sm(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(sr.DBI_DOES_NOT_EXIST):n}return s[Ub]=r,e.dbis[t]=s,s}a(ts,"openDBI");function VV(e,t){l_(e,t),t=t.toString();let r=ts(e,t),s=r.getStats();return r[Jn.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(VV,"statDBI");async function $V(e,t){try{let r=Lr.join(e,t+gc);return(await Ns.stat(r)).size}catch{throw new Error(sr.INVALID_ENVIRONMENT)}}a($V,"environmentDataSize");function YV(e,t){if(l_(e,t),t=t.toString(),t===ys)throw new Error(sr.CANNOT_DROP_INTERNAL_DBIS_NAME);ts(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],ts(e,ys).removeSync(t)}a(YV,"dropDBI");function KV(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{ts(e,i)}catch(o){if(o.message===sr.DBI_DOES_NOT_EXIST)Hb(e,i,i!==t,i===t),s=!0;else throw o}}s&&PV()}a(KV,"initializeDBIs");xb.exports={openDBI:ts,openEnvironment:Pb,createEnvironment:xV,listDBIs:Bb,listDBIDefinitions:GV,createDBI:Hb,dropDBI:YV,statDBI:VV,deleteEnvironment:FV,initializeDBIs:KV,TransactionCursor:tm,environmentDataSize:$V,copyEnvironment:qV,closeEnvironment:vb}});var Fb=T((_ce,qb)=>{"use strict";var om=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};qb.exports=om});var kb=T((fce,Gb)=>{"use strict";var am=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};Gb.exports=am});var $b=T((hce,Vb)=>{"use strict";var cm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};Vb.exports=cm});var Fo=T((gce,Wb)=>{"use strict";var WV=ze(),QV=Fb(),zV=kb(),JV=$b(),Vs=Cr(),Rc=Ir().LMDB_ERRORS_ENUM,jV=ht(),pn=L(),XV=J(),ZV=require("uuid"),pce=require("lmdb"),{handleHDBError:e$,hdb_errors:t$}=Z(),{OVERFLOW_MARKER:Sce,MAX_SEARCH_KEY_LENGTH:Tce}=jV,Yb=X();Yb.initSync();var __=Yb.get(pn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),um=pn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Pi=pn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function r$(e,t,r,s,n=Vs.getNextMonotonicTime()){fm(e,t,r,s),lm(e,t,r);let i=new QV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];Kb(_,!0,n);let l=s$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return _m(o,c,s,i,n)}a(r$,"insertRecords");function s$(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][pn.FUNC_VAL],s[o]=c)}let u=Vs.getIndexedValues(c),_=e.dbis[o];if(u){__&&_.prefetch(u.map(l=>({key:l,value:n})),d_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],n)}}__&&e.dbis[t].prefetch([n],d_),e.dbis[t].put(n,s,s[Pi])})}a(s$,"insertRecord");function n$(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(n$,"removeSkippedRecords");function Kb(e,t,r){let s=r>0;(s||!Number.isInteger(e[Pi]))&&(e[Pi]=r||(r=Vs.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[um]))&&(e[um]=r||Vs.getNextMonotonicTime()):delete e[um]}a(Kb,"setTimestamps");function lm(e,t,r){r.indexOf(pn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(pn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(pn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(pn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),WV.initializeDBIs(e,t,r)}a(lm,"initializeTransaction");async function i$(e,t,r,s,n=Vs.getNextMonotonicTime()){fm(e,t,r,s),lm(e,t,r);let i=new zV,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=dm(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return _m(c,u,s,i,n,o)}a(i$,"updateRecords");async function o$(e,t,r,s,n=Vs.getNextMonotonicTime()){try{fm(e,t,r,s)}catch(u){throw e$(u,u.message,t$.HTTP_STATUS_CODES.BAD_REQUEST)}lm(e,t,r);let i=new JV,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;XV.isEmpty(_[t])?(l=ZV.v4(),_[t]=l):l=_[t];let d=dm(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return _m(o,c,s,i,n)}a(o$,"upsertRecords");async function _m(e,t,r,s,n,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||Vs.getNextMonotonicTime(),n$(r,i),s}a(_m,"finalizeWrite");function dm(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Kb(r,!l,o),Number.isInteger(r[Pi])&&_[Pi]>r[Pi])return!1;l&&n.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let g=_[h];if(typeof p=="function"){let b=p([[_]]);Array.isArray(b)&&(p=b[0][pn.FUNC_VAL],r[h]=p)}if(p===g)continue;let A=Vs.getIndexedValues(g);if(A){__&&S.prefetch(A.map(b=>({key:b,value:s})),d_);for(let b=0,v=A.length;b<v;b++)S.remove(A[b],s)}if(A=Vs.getIndexedValues(p),A){__&&S.prefetch(A.map(b=>({key:b,value:s})),d_);for(let b=0,v=A.length;b<v;b++)S.put(A[b],s)}}let E=Object.assign({},_,r);c.put(s,E,E[Pi])},"do_put");return u?d=c.ifVersion(s,u.version,f):d=c.ifNoExists(s,f),d.then(E=>E?!0:dm(e,t,r,s,n,i,o))}a(dm,"updateUpsertRecord");function a$(e,t,r){if(Vs.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(a$,"validateBasic");function fm(e,t,r,s){if(a$(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Rc.RECORDS_REQUIRED):new Error(Rc.RECORDS_MUST_BE_ARRAY)}a(fm,"validateWrite");function d_(){}a(d_,"noop");Wb.exports={insertRecords:r$,updateRecords:i$,upsertRecords:o$}});var vi=T((Ace,c$)=>{c$.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 Ys=T((Oce,Jb)=>{"use strict";var zb=J(),Qb=L(),Go=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,$s=require("joi"),jn={schema_format:{pattern:Go,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},u$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(Go).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number(),$s.array()).required(),l$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(Go).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number()),_$=$s.alternatives($s.string().min(1).max(jn.schema_length.maximum).pattern(Go).messages({"string.pattern.base":"{:#label} "+jn.schema_format.message}),$s.number()).required();function d$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>jn.schema_length.maximum?`'${e}' maximum of 250 characters`:Go.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(d$,"checkValidTable");function f$(e,t){return zb.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(f$,"validateSchemaExists");function E$(e,t){let r=t.state.ancestors[0].schema;return zb.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(E$,"validateTableExists");function h$(e,t){return e.toLowerCase()===Qb.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Qb.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(h$,"validateSchemaName");Jb.exports={common_validators:jn,schema_regex:Go,hdb_schema_table:u$,validateSchemaExists:f$,validateTableExists:E$,validateSchemaName:h$,checkValidTable:d$,hdb_database:l$,hdb_table:_$}});var Ze=T((Nce,jb)=>{"use strict";var nr=require("validate.js");nr.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||nr.validators.type.checks[t](e)?null:` must be a '${t}' value`};nr.validators.type.checks={Object:function(e){return nr.isObject(e)&&!nr.isArray(e)},Array:nr.isArray,Integer:nr.isInteger,Number:nr.isNumber,String:nr.isString,Date:nr.isDate,Boolean:function(e){return typeof e=="boolean"}};nr.validators.hasValidFileExt=function(e,t){return nr.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};jb.exports={validateObject:m$,validateObjectAsync:p$,validateBySchema:S$};function m$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=nr(e,t,{format:"flat"});return r?new Error(r):null}a(m$,"validateObject");async function p$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await nr.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(p$,"validateObjectAsync");function S$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(S$,"validateBySchema")});var f_=T((wce,Xb)=>{var{common_validators:Ks}=Ys(),Oc=Ze(),Ac="is required",mt={database:{presence:!1,format:Ks.schema_format,length:Ks.schema_length},schema:{presence:!1,format:Ks.schema_format,length:Ks.schema_length},table:{presence:!0,format:Ks.schema_format,length:Ks.schema_length},attribute:{presence:!0,format:Ks.schema_format,length:Ks.schema_length},hash_attribute:{presence:!0,format:Ks.schema_format,length:Ks.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 T$(e){return e=bc(e),mt.table.presence=!1,mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Oc.validateObject(e,mt)}a(T$,"schema_object");function g$(e){return e=bc(e),mt.table.presence={message:Ac},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Oc.validateObject(e,mt)}a(g$,"table_object");function R$(e){return e=bc(e),mt.table.presence={message:Ac},mt.attribute.presence=!1,Oc.validateObject(e,mt)}a(R$,"create_table_object");function A$(e){return e=bc(e),mt.table.presence={message:Ac},mt.attribute.presence={message:Ac},mt.hash_attribute.presence=!1,Oc.validateObject(e,mt)}a(A$,"attribute_object");function O$(e){return e=bc(e),mt.table.presence={message:Ac},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Oc.validateObject(e,mt)}a(O$,"describe_table");function b$(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(b$,"validateTableResidence");Xb.exports={schema_object:T$,create_table_object:R$,table_object:g$,attribute_object:A$,describe_table:O$,validateTableResidence:b$}});var eN=T((Cce,Zb)=>{"use strict";var N$=require("uuid"),Em=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||N$.v4(),this.schema_table=`${this.schema}.${this.table}`}};Zb.exports=Em});var E_=T((Lce,tN)=>{"use strict";var y$=eN(),hm=class extends y${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};tN.exports=hm});var sN=T((Uce,rN)=>{"use strict";rN.exports=I$;var w$="inserted";function I$(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===w$?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(I$,"returnObject")});var h_=T((vce,cN)=>{"use strict";var C$=L(),mm=ze(),D$=Fo(),{getSystemSchemaPath:L$,getSchemaPath:M$}=Xe(),U$=vi(),P$=f_(),v$=E_(),B$=sN(),{handleHDBError:nN,hdb_errors:oN}=Z(),iN=J(),{HTTP_STATUS_CODES:H$}=oN,pm=U$.hdb_attribute,aN=[];for(let e=0;e<pm.attributes.length;e++)aN.push(pm.attributes[e].attribute);var x$="inserted";cN.exports=q$;async function q$(e){let t=P$.attribute_object(e);if(t)throw nN(new Error,t.message,oN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&iN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw nN(new Error,r,H$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=iN.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new v$(e.schema,e.table,e.attribute,e.id);try{let i=await mm.openEnvironment(M$(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(L$(),C$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await D$.insertRecords(o,pm.hash_attribute,aN,[n]);return B$(x$,c,{records:[n]},u)}catch(i){throw i}}a(q$,"lmdbCreateAttribute")});var Tm=T((Hce,lN)=>{var{hdb_table:F$,hdb_database:uN}=Ys(),G$=Ze(),Sm=require("joi"),k$={undefined:"undefined",null:"null"},V$=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||k$[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),$$=Sm.object({database:uN,schema:uN,table:F$,records:Sm.array().items(Sm.object().custom(V$)).required()});lN.exports=function(e){return G$.validateBySchema(e,$$)}});var Nc=T((Fce,dN)=>{"use strict";var Sn=J(),_N=V(),qce=Tm(),{getDatabases:Y$}=(Ae(),ee(Fe)),{ClientError:Bi}=Z();dN.exports=K$;function K$(e){if(Sn.isEmpty(e))throw new Bi("invalid update parameters defined.");if(Sn.isEmptyOrZeroLength(e.schema))throw new Bi("invalid schema specified.");if(Sn.isEmptyOrZeroLength(e.table))throw new Bi("invalid table specified.");if(!Array.isArray(e.records))throw new Bi("records must be an array");let t=Y$()[e.schema]?.[e.table];if(Sn.isEmpty(t))throw new Bi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Sn.isEmptyOrZeroLength(o[r]))throw _N.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(!Sn.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw _N.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`);!Sn.isEmpty(o[r])&&o[r]!==""&&s.has(Sn.autoCast(o[r]))&&(o.skip=!0),s.add(Sn.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(K$,"insertUpdateValidate")});var yc=T((kce,fN)=>{"use strict";var W$=L().OPERATIONS_ENUM,gm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=W$.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};fN.exports=gm});var Dc=T((Yce,EN)=>{"use strict";var $ce=yc(),m_=L(),Am=J(),Rm=V(),Q$=require("uuid"),{handleHDBError:wc,hdb_errors:z$}=Z(),{HDB_ERROR_MSGS:Ic,HTTP_STATUS_CODES:Cc}=z$;EN.exports=J$;function J$(e,t,r){for(let n=0;n<t.length;n++)j$(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];X$(i,r,e.operation)}}a(J$,"processRows");function j$(e){if(Buffer.byteLength(String(e))>m_.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(j$,"validateAttribute");function X$(e,t,r){if(!e.hasOwnProperty(t)||Am.isEmptyOrZeroLength(e[t])){if(r===m_.OPERATIONS_ENUM.INSERT||r===m_.OPERATIONS_ENUM.UPSERT){e[t]=Q$.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]))>m_.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(X$,"validateHash")});var mN=T((Wce,hN)=>{"use strict";var Om=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};hN.exports=Om});var TN=T((zce,SN)=>{"use strict";var bm=ze(),Z$=V(),pN=Ir().LMDB_ERRORS_ENUM;SN.exports=e1;async function e1(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 bm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==pN.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await bm.closeEnvironment(global.lmdb_map[s]),await bm.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==pN.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){Z$.error(t)}}a(e1,"cleanLMDBMap")});var Tn=T((jce,ON)=>{"use strict";var Lc=require("crypto"),t1=X(),{CONFIG_PARAMS:r1}=L(),RN="aes-256-cbc",s1=32,n1=16,Nm=64,AN=32,i1=Nm+AN,gN=new Map;ON.exports={encrypt:o1,decrypt:a1,createNatsTableStreamName:c1};function o1(e){let t=Lc.randomBytes(s1),r=Lc.randomBytes(n1),s=Lc.createCipheriv(RN,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(o1,"encrypt");function a1(e){let t=e.substr(0,Nm),r=e.substr(Nm,AN),s=e.substr(i1,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Lc.createDecipheriv(RN,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(a1,"decrypt");function c1(e,t){let r=t1.get(r1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=gN.get(r);return s||(s=Lc.createHash("md5").update(r).digest("hex"),gN.set(r,s)),s}a(c1,"createNatsTableStreamName")});var Xn=T((eue,NN)=>{"use strict";var Zce=rs(),p_=V(),bN=f_(),u1=Tn(),S_=J(),{handleHDBError:T_,hdb_errors:l1}=Z(),{HDB_ERROR_MSGS:g_,HTTP_STATUS_CODES:ym}=l1,_1=X();_1.initSync();var{getDatabases:wm}=(Ae(),ee(Fe));NN.exports={describeAll:d1,describeTable:R_,describeSchema:f1};async function d1(e){try{let t=S_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=wm(),i={},o={},c=[],u=e?.exact_count;for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let d=n[l];for(let f in d)try{let E;if(t||s)E=await R_({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 R_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){p_.error(E)}}let _={};for(let l in c)t||s?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return p_.error("Got an error in describeAll"),p_.error(t),T_(new Error,g_.DESCRIBE_ALL_ERR)}}a(d1,"describeAll");async function R_(e,t){S_.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=bN.describe_table(e);if(i)throw i;let c=wm()[r];if(!c)throw T_(new Error,g_.SCHEMA_NOT_FOUND(e.schema),ym.NOT_FOUND);let u=c[s];if(!u)throw T_(new Error,g_.TABLE_NOT_FOUND(e.schema,e.table),ym.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(n){let f={};n.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=u1.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){p_.warn(`unable to stat table dbi due to ${f}`)}return d}a(R_,"descTable");async function f1(e){S_.transformReq(e);let t=bN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=wm()[s];if(!i)throw T_(new Error,g_.SCHEMA_NOT_FOUND(e.schema),ym.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),S_.isEmpty(u)||u.describe){let _=await R_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(f1,"describeSchema")});var gn=T((nue,DN)=>{var E1=vi(),{callbackify:wN,promisify:h1}=require("util"),{getDatabases:IN}=(Ae(),ee(Fe));DN.exports={setSchemaDataToGlobal:yN,getTableSchema:m1,getSystemSchema:p1,setSchemaDataToGlobalAsync:h1(yN)};var CN=Xn(),rue=wN(CN.describeAll),sue=wN(CN.describeTable);function yN(e){global.hdb_schema=IN(),e&&e()}a(yN,"setSchemaDataToGlobal");function m1(e,t,r){let s=IN()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}a(m1,"getTableSchema");function p1(){return E1}a(p1,"getSystemSchema")});var Mr=T((oue,PN)=>{"use strict";var O_=Tm(),Ft=J(),S1=require("util"),b_=ws(),T1=gn(),LN=V(),{handleHDBError:Hi,hdb_errors:g1}=Z(),{HTTP_STATUS_CODES:xi}=g1,R1=S1.promisify(T1.getTableSchema),A1="updated",MN="inserted",UN="upserted";PN.exports={insert:b1,update:N1,upsert:y1,validation:O1,flush:w1};async function O1(e){if(Ft.isEmpty(e))throw new Error("invalid update parameters defined.");if(Ft.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Ft.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await R1(e.schema,e.table),r=O_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Ft.isEmptyOrZeroLength(c[s]))throw LN.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(!Ft.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw LN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!Ft.isEmpty(c[s])&&c[s]!==""&&n.has(Ft.autoCast(c[s]))&&(c.skip=!0),n.add(Ft.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(O1,"validation");async function b1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=O_(e);if(t)throw Hi(new Error,t.message,xi.BAD_REQUEST);Ft.transformReq(e);let r=Ft.checkSchemaTableExist(e.schema,e.table);if(r)throw Hi(new Error,r,xi.BAD_REQUEST);let s=await b_.createRecords(e);return A_(MN,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(b1,"insertData");async function N1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=O_(e);if(t)throw Hi(new Error,t.message,xi.BAD_REQUEST);Ft.transformReq(e);let r=Ft.checkSchemaTableExist(e.schema,e.table);if(r)throw Hi(new Error,r,xi.BAD_REQUEST);let s=await b_.updateRecords(e);return Ft.isEmpty(s.existing_rows)?A_(A1,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):A_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(N1,"updateData");async function y1(e){if(e.operation!=="upsert")throw Hi(new Error,"invalid operation, must be upsert",xi.INTERNAL_SERVER_ERROR);let t=O_(e);if(t)throw Hi(new Error,t.message,xi.BAD_REQUEST);Ft.transformReq(e);let r=Ft.checkSchemaTableExist(e.schema,e.table);if(r)throw Hi(new Error,r,xi.BAD_REQUEST);let s=await b_.upsertRecords(e);return A_(UN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(y1,"upsertData");function A_(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===MN?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===UN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(A_,"returnObject");function w1(e){return Ft.transformReq(e),b_.flush(e.schema,e.table)}a(w1,"flush")});var Cm=T((cue,HN)=>{var I1=Ze(),Im=require("joi"),{hdb_table:C1,hdb_database:vN}=Ys(),BN={schema:vN,database:vN,table:C1},D1={date:Im.date().iso().required()},L1={timestamp:Im.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};HN.exports=function(e,t){let r=t==="timestamp"?{...BN,...L1}:{...BN,...D1},s=Im.object(r);return I1.validateBySchema(e,s)}});var FN=T((uue,qN)=>{var M1=Ze(),Dm=require("joi"),{hdb_table:U1,hdb_database:xN}=Ys(),P1=Dm.object({schema:xN,database:xN,table:U1,hash_values:Dm.array().required(),ids:Dm.array()});qN.exports=function(e){return M1.validateBySchema(e,P1)}});var kN=T((lue,GN)=>{"use strict";var Lm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},Mm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}},Um=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};GN.exports={InsertObject:Lm,NoSQLSeachObject:Mm,DeleteResponseObject:Um}});var ti=T((due,WN)=>{"use strict";var $N=Cm(),v1=FN(),qi=J(),VN=require("moment"),YN=V(),{promisify:B1,callbackify:H1}=require("util"),Fi=L(),x1=gn(),Pm=B1(x1.getTableSchema),vm=ws(),{DeleteResponseObject:q1}=kN(),{handleHDBError:Zn,hdb_errors:F1}=Z(),{HDB_ERROR_MSGS:N_,HTTP_STATUS_CODES:ei}=F1,G1="records successfully deleted",k1=H1(KN);WN.exports={delete:k1,deleteRecord:KN,deleteFilesBefore:V1,deleteAuditLogsBefore:$1};async function V1(e){let t=$N(e,"date");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(qi.transformReq(e),!VN(e.date,VN.ISO_8601).isValid())throw Zn(new Error,N_.INVALID_DATE,ei.BAD_REQUEST,Fi.LOG_LEVELS.ERROR,N_.INVALID_DATE,!0);let s=qi.checkSchemaTableExist(e.schema,e.table);if(s)throw Zn(new Error,s,ei.NOT_FOUND,Fi.LOG_LEVELS.ERROR,s,!0);let n=await vm.deleteRecordsBefore(e);if(await Pm(e.schema,e.table),YN.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(V1,"deleteFilesBefore");async function $1(e){let t=$N(e,"timestamp");if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);if(qi.transformReq(e),isNaN(e.timestamp))throw Zn(new Error,N_.INVALID_VALUE("Timestamp"),ei.BAD_REQUEST,Fi.LOG_LEVELS.ERROR,N_.INVALID_VALUE("Timestamp"),!0);let r=qi.checkSchemaTableExist(e.schema,e.table);if(r)throw Zn(new Error,r,ei.NOT_FOUND,Fi.LOG_LEVELS.ERROR,r,!0);let s=await vm.deleteAuditLogsBefore(e);return await Pm(e.schema,e.table),YN.info(`Finished deleting audit logs before ${e.timestamp}`),s}a($1,"deleteAuditLogsBefore");async function KN(e){e.ids&&(e.hash_values=e.ids);let t=v1(e);if(t)throw Zn(t,t.message,ei.BAD_REQUEST,void 0,void 0,!0);qi.transformReq(e);let r=qi.checkSchemaTableExist(e.schema,e.table);if(r)throw Zn(new Error,r,ei.NOT_FOUND,Fi.LOG_LEVELS.ERROR,r,!0);try{await Pm(e.schema,e.table);let s=await vm.deleteRecords(e);return qi.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${G1}`),s}catch(s){if(s.message===Fi.SEARCH_NOT_FOUND_MESSAGE){let n=new q1;return n.message=Fi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(KN,"deleteRecord")});var y_=T((Eue,JN)=>{var Y1=require("crypto"),QN=9;function K1(e){let t=Q1(QN),r=zN(e+t);return t+r}a(K1,"createHash");function W1(e,t){let r=e?.substr(0,QN),s=r+zN(t+r);return e===s}a(W1,"validateHash");function Q1(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(Q1,"generateSalt");function zN(e){return Y1.createHash("md5").update(e).digest("hex")}a(zN,"md5");JN.exports={hash:K1,validate:W1}});var XN=T((mue,jN)=>{var Bm=Ze(),Wt={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 z1(e){return Wt.password.presence=!0,Wt.username.presence=!0,Wt.role.presence=!0,Wt.active.presence=!0,Bm.validateObject(e,Wt)}a(z1,"addUserValidation");function J1(e){return Wt.password.presence=!1,Wt.username.presence=!0,Wt.role.presence=!1,Wt.active.presence=!1,Bm.validateObject(e,Wt)}a(J1,"alterUserValidation");function j1(e){return Wt.password.presence=!1,Wt.username.presence=!0,Wt.role.presence=!1,Wt.active.presence=!1,Bm.validateObject(e,Wt)}a(j1,"dropUserValidation");jN.exports={addUserValidation:z1,alterUserValidation:J1,dropUserValidation:j1}});var Ge=T((Tue,ey)=>{"use strict";var{platform:Sue}=require("os"),X1="nats-server.zip",Hm="nats-server",Z1=process.platform==="win32"?`${Hm}.exe`:Hm,xm="HDB",eY=/^[^\s.,*>]+$/,ZN="__request__",tY=a(e=>`${e}.${ZN}`,"REQUEST_SUBJECT"),rY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},sY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},nY={HUB:"hub.pid",LEAF:"leaf.pid"},iY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},oY={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:xm,deliver_subject:"__HDB__.WORKQUEUE"},aY={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:xm,deliver_subject:"HDB.SCHEMAQUEUE"},cY={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:xm,deliver_subject:"HDB.USERQUEUE"},uY={SUCCESS:"success",ERROR:"error"},lY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},_Y={TXN:"txn",MSGID:"msgid"},ko={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},dY={[ko.ERR]:1,[ko.WRN]:2,[ko.INF]:3,[ko.DBG]:4,[ko.TRC]:5},fY={debug:"-D",trace:"-DVV"};ey.exports={NATS_SERVER_ZIP:X1,NATS_SERVER_NAME:Hm,NATS_BINARY_NAME:Z1,PID_FILES:nY,NATS_CONFIG_FILES:sY,SERVER_SUFFIX:iY,WORK_QUEUE_CONSUMER_NAMES:oY,SCHEMA_QUEUE_CONSUMER_NAMES:aY,USER_QUEUE_CONSUMER_NAMES:cY,NATS_TERM_CONSTRAINTS_RX:eY,REQUEST_SUFFIX:ZN,UPDATE_REMOTE_RESPONSE_STATUSES:uY,CLUSTER_STATUS_STATUSES:lY,REQUEST_SUBJECT:tY,SUBJECT_PREFIXES:_Y,MSG_HEADERS:rY,LOG_LEVELS:ko,LOG_LEVEL_FLAGS:fY,LOG_LEVEL_HIERARCHY:dY}});var ry=T((Rue,ty)=>{"use strict";var EY={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
|
-
`)},X1="certificate.pem",j1="privateKey.pem",Z1="ca.pem";WN.exports={CERTIFICATE_VALUES:J1,CERTIFICATE_PEM_NAME:X1,PRIVATEKEY_PEM_NAME:j1,CA_PEM_NAME:Z1}});var Pm=T((eue,ZN)=>{"use strict";var jN=require("fs-extra"),ce=require("joi"),eY=require("os"),{boolean:Be,string:ts,number:vt,array:Mm}=ce.types(),{totalmem:zN}=require("os"),ki=require("path"),tY=G(),I_=z(),Zce=QN(),JN=D(),rY=Je(),XN="log",sY="components",nY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",iY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",oY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",aY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",cY="rootPath config parameter is undefined",uY="clustering.enabled config parameter is undefined",Vi=vt.min(0).required(),w_=Mm.items({host:ts.required(),port:Vi}).empty(null),Qs;ZN.exports={configValidator:lY,routesValidator:mY,route_constraints:w_};function lY(e){if(Qs=e.rootPath,I_.isEmpty(Qs))throw cY;let t=Be.required(),r=vt.min(0).max(1e3).empty(null).default(hY),s=ts.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Mc),n=ts.optional().empty(null),i=ts.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ce.string().empty(null).default(Mc),c=ce.custom(dY).empty(null).default(Mc),u=e.clustering?.enabled;if(I_.isEmpty(u))throw uY;let _;return u===!0?_=ce.object({enabled:t,hubServer:ce.object({cluster:ce.object({name:ce.required().empty(null),network:ce.object({port:Vi,routes:w_}).required()}).required(),leafNodes:ce.object({network:ce.object({port:Vi}).required()}).required(),network:ce.object({port:Vi}).required()}).required(),leafServer:ce.object({network:ce.object({port:Vi,routes:w_}).required(),streams:ce.object({maxAge:vt.min(120).allow(null).optional(),maxBytes:vt.min(1).allow(null).optional(),maxMsgs:vt.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ce.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:Be.optional(),databaseLevel:Be.optional(),tls:ce.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Be.required(),verify:Be.optional()}),user:ts.optional().empty(null)}).required():_=ce.object({enabled:t,tls:ce.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Be.required()})}).required(),ce.object({authentication:ce.object({authorizeLocal:Be,cacheTTL:vt.required(),enableSessions:Be}),analytics:ce.object({aggregatePeriod:vt}),componentsRoot:s.optional(),clustering:_,localStudio:ce.object({enabled:t}).required(),logging:ce.object({auditAuthEvents:ce.object({logFailed:Be,logSuccessful:Be}),file:Be.required(),level:ce.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ce.object({enabled:Be.optional(),compress:Be.optional(),interval:ts.custom(EY).optional().empty(null),maxSize:ts.custom(fY).optional().empty(null),path:ts.optional().empty(null).default(Mc)}).required(),root:s,stdStreams:Be.required(),auditLog:Be.required()}).required(),operationsApi:ce.object({network:ce.object({cors:Be.optional(),corsAccessList:Mm.optional(),headersTimeout:vt.min(1).optional(),keepAliveTimeout:vt.min(1).optional(),port:vt.optional().empty(null),domainSocket:ce.optional().empty("hdb/operations-server").default(Mc),securePort:vt.optional().empty(null),timeout:vt.min(1).optional()}).optional(),tls:ce.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:ts.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ce.object({network:ce.object({port:Vi,securePort:Vi,mtls:ce.alternatives([Be.optional(),ce.object({user:ts.optional(),certificateAuthority:n})])}).required(),webSocket:Be.optional(),requireAuthentication:Be.optional()}),http:ce.object({compressionThreshold:vt.optional(),cors:Be.optional(),corsAccessList:Mm.optional(),headersTimeout:vt.min(1).optional(),port:vt.min(0).optional().empty(null),securePort:vt.min(0).optional().empty(null)}).required(),threads:r.optional(),maxHeapMemory:vt.min(0).optional(),storage:ce.object({writeAsync:Be.required(),overlappingSync:Be.optional(),caching:Be.optional(),compression:Be.optional(),noReadAhead:Be.optional(),path:c,prefetchWrites:Be.optional()}).required(),ignoreScripts:Be.optional(),tls:ce.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:ts.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(lY,"configValidator");function _Y(e){return jN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(_Y,"doesPathExist");function dY(e,t){ce.assert(e,ts.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=_Y(e);if(r)return t.message(r)}a(dY,"validatePath");function fY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(nY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(oY):e}a(fY,"validateRotationMaxSize");function EY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(iY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(aY):e}a(EY,"validateRotationInterval");function hY(e,t){let r=t.state.path.join("."),s=eY.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||zN();return i=Math.round(Math.min(i,zN())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),tY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(hY,"setDefaultThreads");function Mc(e,t){let r=t.state.path.join(".");if(!I_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(I_.isEmpty(Qs))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return ki.join(Qs,sY);case"logging.root":return ki.join(Qs,XN);case"clustering.leafServer.streams.path":return ki.join(Qs,"clustering","leaf");case"storage.path":let s=ki.join(Qs,JN.LEGACY_DATABASES_DIR_NAME);return jN.existsSync(s)?s:ki.join(Qs,JN.DATABASES_DIR_NAME);case"logging.rotation.path":return ki.join(Qs,XN);case"operationsApi.network.domainSocket":return r==null?null:ki.join(Qs,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Mc,"setDefaultRoot");function mY(e){let t=ce.object({routes:w_});return rY.validateBySchema({routes:e},t)}a(mY,"routesValidator")});var Pr=T((sue,cy)=>{"use strict";var Mr=D(),Bt=z(),yt=G(),{configValidator:pY,routesValidator:ey}=Pm(),or=require("fs-extra"),SY=require("yaml"),Cs=require("path"),TY=require("is-number"),ry=require("properties-reader"),gY=require("lodash"),{handleHDBError:RY}=Z(),{HTTP_STATUS_CODES:AY,HDB_ERROR_MSGS:C_}=Ir(),rue=require("minimist"),{server:OY}=(sr(),ee(Li)),{DATABASES_PARAM_CONFIG:Pc,CONFIG_PARAMS:Ur,CONFIG_PARAM_MAP:Ds}=Mr,bY="Unable to get config value because config is uninitialized",NY="Config successfully initialized",yY="Error backing up config file",IY="Empty parameter sent to getConfigValue",sy=Cs.join(Mr.PACKAGE_ROOT,"config","yaml",Mr.HDB_DEFAULT_CONFIG_FILE),wY="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",ty={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"},D_,It,L_;cy.exports={createConfigFile:CY,getDefaultConfig:DY,getConfigValue:iy,initConfig:Bm,flattenConfig:Vo,updateConfigValue:oy,updateConfigObject:UY,getConfiguration:vY,setConfiguration:BY,readConfigFile:xm,getClusteringRoutes:HY,initOldConfig:ay,getConfigFromFile:xY,getConfigFilePath:$i,addConfig:qY,deleteConfigFromFile:FY,getConfigObj:GY};function CY(e){let t=ri(sy);D_=Vo(t.toJSON());let r;for(let o in e){let c=Ds[o.toLowerCase()];if(c===Ur.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=vm(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){yt.error(l)}}}r&&ny(t,r),Hm(t);let s=t.toJSON();It=Vo(s);let n=t.getIn(["rootPath"]),i=Cs.join(n,Mr.HDB_CONFIG_FILE);or.createFileSync(i),or.writeFileSync(i,String(t)),yt.trace(`Config file written to ${i}`)}a(CY,"createConfigFile");function ny(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!Bt.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(Pc.TABLES))for(let i in s[n][Pc.TABLES])for(let o in s[n][Pc.TABLES][i]){let c=s[n][Pc.TABLES][i][o],u=[Ur.DATABASES,n,Pc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[Ur.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){yt.error("Error parsing schemas CLI/env config arguments",s)}}a(ny,"setSchemasConfig");function DY(e){if(D_===void 0){let r=ri(sy);D_=Vo(r.toJSON())}let t=Ds[e.toLowerCase()];if(t!==void 0)return D_[t.toLowerCase()]}a(DY,"getDefaultConfig");function iy(e){if(e==null){yt.error(IY);return}if(It===void 0){yt.trace(bY);return}let t=Ds[e.toLowerCase()];if(t!==void 0)return It[t.toLowerCase()]}a(iy,"getConfigValue");function $i(e=Bt.getPropsFilePath()){let t=Bt.getEnvCliRootPath();return t?Cs.join(t,Mr.HDB_CONFIG_FILE):ry(e).get(Mr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a($i,"getConfigFilePath");function Bm(e=!1){if(It===void 0||e){let t;if(!Bt.noBootFile()){t=Bt.getPropsFilePath();try{or.accessSync(t,or.constants.F_OK|or.constants.R_OK)}catch(i){throw yt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=$i(t),s;if(r.includes("config/settings.js"))try{ay(r);return}catch(i){if(i.code!==Mr.NODE_ERROR_CODES.ENOENT)throw i}try{s=ri(r)}catch(i){if(i.code===Mr.NODE_ERROR_CODES.ENOENT){yt.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 yt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}LY(s,r),Hm(s);let n=s.toJSON();if(OY.config=n,It=Vo(n),It.logging_rotation_rotate)for(let i in ty)It[i]&&yt.error(`Config ${ty[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);yt.trace(NY)}}a(Bm,"initConfig");function LY(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Cs.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Cs.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Cs.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(yt.trace("Updating config file with missing config params"),or.writeFileSync(t,String(e)))}a(LY,"checkForUpdatedConfig");function Hm(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=pY(t);if(r.error)throw C_.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(Hm,"validateConfig");function UY(e,t){It===void 0&&(It={});let r=Ds[e.toLowerCase()];if(r===void 0){yt.trace(`Unable to update config object because config param '${e}' does not exist`);return}It[r.toLowerCase()]=t}a(UY,"updateConfigObject");function oy(e,t,r=void 0,s=!1,n=!1,i=!1){It===void 0&&Bm();let o=iy(Ds.hdb_root),c=Cs.join(o,Mr.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=Ds[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=vm(f,t);u.setIn([...E],h)}else for(let f in r){let E=Ds[f.toLowerCase()];if(E===Ur.HTTP_SECUREPORT&&r[f]===It[Ur.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Ur.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===It[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=Mr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=vm(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(R){yt.error(R)}}}_&&ny(u,_),Hm(u);let l=u.getIn(["rootPath"]),d=Cs.join(l,Mr.HDB_CONFIG_FILE);s===!0&&MY(c,l),or.writeFileSync(d,String(u)),n&&(It=Vo(u.toJSON())),yt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(oy,"updateConfigValue");function MY(e,t){try{let r=Cs.join(t,"backup",`${Mr.HDB_CONFIG_FILE}.bak`);or.copySync(e,r),yt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){yt.error(yY),yt.error(r)}}a(MY,"backupConfigFile");var PY=["databases"];function Vo(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)),L_=e,r(e);function r(s){let n={};for(let i in s)if(s.hasOwnProperty(i))if(typeof s[i]=="object"&&s[i]!==null&&!Array.isArray(s[i])&&!PY.includes(i)){let o=r(s[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Ur[u.toUpperCase()]&&Ds[u]&&(n[Ds[u].toLowerCase()]=o[c]),n[u]=o[c]}}else n[i.toLowerCase()]=s[i];return n}a(r,"squashObj")}a(Vo,"flattenConfig");function vm(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(TY(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Bt.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 Bt.autoCast(t)}a(vm,"castConfigValue");function vY(){let e=Bt.getPropsFilePath(),t=$i(e);return ri(t).toJSON()}a(vY,"getConfiguration");async function BY(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return oy(void 0,void 0,n,!0),wY}catch(i){throw typeof i=="string"||i instanceof String?RY(i,i,AY.BAD_REQUEST,void 0,void 0,!0):i}}a(BY,"setConfiguration");function xm(){let e=Bt.getPropsFilePath();try{or.accessSync(e,or.constants.F_OK|or.constants.R_OK)}catch(s){if(!Bt.noBootFile())throw yt.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=$i(e);return ri(t).toJSON()}a(xm,"readConfigFile");function ri(e){return SY.parseDocument(or.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ri,"parseYamlDoc");function HY(){let e=xm(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Bt.isEmptyOrZeroLength(t)?[]:t;let r=ey(t);if(r)throw C_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=Bt.isEmptyOrZeroLength(s)?[]:s;let n=ey(s);if(n)throw C_.CONFIG_VALIDATION(n.message);if(!Bt.isEmptyOrZeroLength(s)&&!Bt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!Bt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw C_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(HY,"getClusteringRoutes");function ay(e){let t=ry(e);It={};for(let r in Ds){let s=t.get(r.toUpperCase());if(Bt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=Ds[r].toLowerCase();n===Ur.LOGGING_ROOT?It[n]=Cs.dirname(s):It[n]=s}return It}a(ay,"initOldConfig");function xY(e){let t=xm();return gY.get(t,e.replaceAll("_","."))}a(xY,"getConfigFromFile");async function qY(e,t){let r=ri($i());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await or.writeFile($i(),String(r))}a(qY,"addConfig");function FY(e){let t=$i(Bt.getPropsFilePath()),r=ri(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Cs.join(s,Mr.HDB_CONFIG_FILE);or.writeFileSync(n,String(r))}a(FY,"deleteConfigFromFile");function GY(){return L_||(Bm(),L_)}a(GY,"getConfigObj")});var ly=T((iue,uy)=>{"use strict";var U_=D(),M_=class{static{a(this,"BaseLicense")}constructor(t=0,r=U_.RAM_ALLOCATION_ENUM.DEFAULT,s=U_.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},qm=class extends M_{static{a(this,"ExtendedLicense")}constructor(t=0,r=U_.RAM_ALLOCATION_ENUM.DEFAULT,s=U_.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};uy.exports={BaseLicense:M_,ExtendedLicense:qm}});var Yi=T((aue,my)=>{"use strict";var Yo=require("fs-extra"),dy=y_(),fy=require("crypto"),kY=require("moment"),VY=require("uuid").v4,zt=G(),Gm=require("path"),$Y=z(),si=D(),{totalmem:_y}=require("os"),YY=ly().ExtendedLicense,$o="invalid license key format",KY="061183",WY="mofi25",QY="aes-256-cbc",zY=16,JY=32,Ey=j();Ey.initSync();var Fm;my.exports={validateLicense:hy,generateFingerPrint:jY,licenseSearch:$m,getLicense:tK,checkMemoryLimit:rK};function km(){return Gm.join(Ey.getHdbBasePath(),si.LICENSE_KEY_DIR_NAME,si.LICENSE_FILE_NAME)}a(km,"getLicenseDirPath");function XY(){let e=km();return Gm.join(e,si.LICENSE_FILE_NAME)}a(XY,"getLicenseFilePath");function Vm(){let e=km();return Gm.join(e,si.REG_KEY_FILE_NAME)}a(Vm,"getFingerPrintFilePath");async function jY(){let e=Vm();try{return await Yo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await ZY();throw zt.error(`Error writing fingerprint file to ${e}`),zt.error(t),new Error("There was an error generating the fingerprint")}}a(jY,"generateFingerPrint");async function ZY(){let e=VY(),t=dy.hash(e),r=Vm();try{await Yo.mkdirp(km()),await Yo.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw zt.error(`Error writing fingerprint file to ${r}`),zt.error(s),new Error("There was an error generating the fingerprint")}return t}a(ZY,"writeFingerprint");function hy(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:si.RAM_ALLOCATION_ENUM.DEFAULT,version:si.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return zt.error("empty license key passed to validate."),r;let s=Vm(),n=!1;try{n=Yo.statSync(s)}catch(i){zt.error(i)}if(n){let i;try{i=Yo.readFileSync(s,"utf8")}catch{zt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(WY),c=o[1];c=Buffer.concat([Buffer.from(c)],zY);let u=Buffer.concat([Buffer.from(i)],JY),_=fy.createDecipheriv(QY,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=eK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error($o),zt.error($o),new Error($o)}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($o),zt.error($o),new Error($o)}else r.exp_date=l;r.exp_date<kY().valueOf()&&(r.valid_date=!1),dy.validate(o[1],`${KY}${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(hy,"validateLicense");function eK(e,t){try{let r=fy.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{zt.warn("Check old license failed")}}a(eK,"checkOldLicense");function $m(){let e=new YY,t=[];try{t=Yo.readFileSync(XY(),"utf-8").split(si.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 s=t[r];try{if($Y.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=hy(n.license_key,n.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(n){zt.error("There was an error parsing the license string."),zt.error(n),e.ram_allocation=si.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Fm=e,e}a($m,"licenseSearch");async function tK(){return Fm||await $m(),Fm}a(tK,"getLicense");function rK(){let e=$m().ram_allocation,t=process.constrainedMemory?.()||_y();if(t=Math.round(Math.min(t,_y())/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(rK,"checkMemoryLimit")});var rs=T((due,Uy)=>{"use strict";var gy="username is required",Ry="nothing to update, must supply active, role or password to update",Ay="password cannot be an empty string",Oy="If role is specified, it cannot be empty.",by="active must be true or false";Uy.exports={addUser:_K,alterUser:dK,dropUser:EK,getSuperUser:SK,userInfo:hK,listUsers:v_,listUsersExternal:mK,setUsersToGlobal:Wo,findAndValidateUser:Dy,getClusterUser:TK,USERNAME_REQUIRED:gy,ALTERUSER_NOTHING_TO_UPDATE:Ry,EMPTY_PASSWORD:Ay,EMPTY_ROLE:Oy,ACTIVE_BOOLEAN:by};var Ny=Lr(),sK=ti(),Wm=y_(),yy=$N(),Iy=es(),Qm=An(),vr=z(),wy=require("validate.js"),Te=G(),{promisify:nK}=require("util"),zm=gn(),py=D(),Sy=qe(),iK=Pr(),uue=j(),lue=Yi(),oK=Bi(),{table:_ue}=(ge(),ee(xe)),{handleHDBError:zs,hdb_errors:aK}=Z(),{HTTP_STATUS_CODES:Js,AUTHENTICATION_ERROR_MSGS:Ym,HDB_ERROR_MSGS:Ko}=aK,{UserEventMsg:Jm}=Ls(),Km=require("lodash"),{server:Xm}=(sr(),ee(Li)),cK=G();Xm.getUser=(e,t)=>Dy(e,t,t!=null);var Cy={username:!0,active:!0,role:!0,password:!0},Ty=new Map,P_=Iy.searchByValue,uK=Iy.searchByHash,lK=nK(sK.delete);async function _K(e){let t=wy.cleanAttributes(e,Cy),r=yy.addUserValidation(t);if(r)throw zs(new Error,r.message,Js.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await P_(s),n=n&&Array.from(n)}catch(u){throw Te.error("There was an error searching for a role in add user"),Te.error(u),u}if(!n||n.length<1)throw zs(new Error,Ko.ROLE_NAME_NOT_FOUND(t.role),Js.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw zs(new Error,Ko.DUP_ROLES_FOUND(t.role),Js.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=zm.encrypt(t.password)),t.password=Wm.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await Ny.insert(i)}catch(u){throw Te.error("There was an error searching for a user."),Te.error(u),u}Te.debug(o);try{await Wo()}catch(u){throw Te.error("Got an error setting users to global"),Te.error(u),u}if(o.skipped_hashes.length===1)throw zs(new Error,Ko.USER_ALREADY_EXISTS(t.username),Js.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],Qm.signalUserChange(new Jm(process.pid)),`${c.username} successfully added`}a(_K,"addUser");async function dK(e){let t=wy.cleanAttributes(e,Cy);if(vr.isEmptyOrZeroLength(t.username))throw new Error(gy);if(vr.isEmptyOrZeroLength(t.password)&&vr.isEmptyOrZeroLength(t.role)&&vr.isEmptyOrZeroLength(t.active))throw new Error(Ry);if(!vr.isEmpty(t.password)&&vr.isEmptyOrZeroLength(t.password.trim()))throw new Error(Ay);if(!vr.isEmpty(t.active)&&!vr.isBoolean(t.active))throw new Error(by);let r=fK(t.username);if(!vr.isEmpty(t.password)&&!vr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=zm.encrypt(t.password)),t.password=Wm.hash(t.password)),t.role==="")throw new Error(Oy);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 P_(i)||[])}catch(c){throw Te.error("Got an error searching for a role."),Te.error(c),c}if(!o||o.length===0){let c=Ko.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Te.error(c),zs(new Error,c,Js.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Ko.ALTER_USER_DUP_ROLES(t.role);throw Te.error(c),zs(new Error,c,Js.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await Ny.update(s)}catch(i){throw Te.error("Error during update."),Te.error(i),i}try{await Wo()}catch(i){throw Te.error("Got an error setting users to global"),Te.error(i),i}return Qm.signalUserChange(new Jm(process.pid)),n}a(dK,"alterUser");function fK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(fK,"isClusterUser");async function EK(e){try{let t=yy.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(vr.isEmpty(global.hdb_users.get(e.username)))throw zs(new Error,Ko.USER_NOT_EXIST(e.username),Js.NOT_FOUND,void 0,void 0,!0);let s;try{s=await lK(r)}catch(n){throw Te.error("Got an error deleting a user."),Te.error(n),n}Te.debug(s);try{await Wo()}catch(n){throw Te.error("Got an error setting users to global."),Te.error(n),n}return Qm.signalUserChange(new Jm(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(EK,"dropUser");async function hK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Km.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await uK(r)}catch(n){throw Te.error("Got an error searching for a role."),Te.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Te.error(r),r}return t}a(hK,"userInfo");async function mK(){let e;try{e=await v_()}catch(t){throw Te.error("Got an error listing users."),Te.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(mK,"listUsersExternal");async function v_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await P_(e)}catch(o){throw Te.error("Got an error searching for roles."),Te.error(o),o}let r={};for(let o of t)r[o.id]=Km.cloneDeep(o);if(Object.keys(r).length===0)return null;let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await P_(s)}catch(o){throw Te.error("Got an error searching for users."),Te.error(o),o}let i=new Map;for(let o of n)o=Km.cloneDeep(o),o.role=r[o.role],pK(o.role),i.set(o.username,o);return i}catch(e){throw Te.error("got an error listing users"),Te.error(e),vr.errorizeMessage(e)}return null}a(v_,"listUsers");function pK(e){try{if(!e){Te.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(oK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Te.error("Got an error trying to set system permissions."),Te.error(t)}}a(pK,"appendSystemTablesToRole");async function Wo(){try{let e=await v_();global.hdb_users=e}catch(e){throw Te.error(e),e}}a(Wo,"setUsersToGlobal");async function Dy(e,t,r=!0){global.hdb_users||await Wo();let s=global.hdb_users.get(e);if(!s){if(!r)return{username:e};throw zs(new Error,Ym.GENERIC_AUTH_FAIL,Js.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw zs(new Error,Ym.USER_INACTIVE,Js.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(Ty.get(t)===s.password)return n;if(Wm.validate(s.password,t))Ty.set(t,s.password);else throw zs(new Error,Ym.GENERIC_AUTH_FAIL,Js.UNAUTHORIZED,void 0,void 0,!0)}return n}a(Dy,"findAndValidateUser");async function SK(){global.hdb_users||await Wo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(SK,"getSuperUser");async function TK(){let e=await v_(),t=iK.getConfigFromFile(py.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!vr.isEmpty(r)&&r?.role?.role===py.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=zm.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+Sy.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+Sy.SERVER_SUFFIX.ADMIN,r}a(TK,"getClusterUser");var Ly=[];Xm.invalidateUser=function(e){for(let t of Ly)try{t(e)}catch(r){cK.error("Error invalidating user",r)}};Xm.onInvalidatedUser=function(e){Ly.push(e)}});var Bc=T((mue,By)=>{"use strict";var Ki=G(),Br=D(),gK=_N(),Eue=Rn(),hue=jn(),RK=rs(),{validateEvent:My}=Ls(),vc=ws(),AK=require("process"),{resetDatabases:OK}=(ge(),ee(xe)),bK={[Br.ITC_EVENT_TYPES.SCHEMA]:NK,[Br.ITC_EVENT_TYPES.USER]:vy};async function NK(e){let t=My(e);if(t){Ki.error(t);return}Ki.trace("ITC schemaHandler received schema event:",e),await gK(e.message),await yK(e.message)}a(NK,"schemaHandler");async function yK(e){try{vc.resetReadTxn(Br.SYSTEM_SCHEMA_NAME,Br.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),vc.resetReadTxn(Br.SYSTEM_SCHEMA_NAME,Br.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),vc.resetReadTxn(Br.SYSTEM_SCHEMA_NAME,Br.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=OK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Ki.error(t)}}a(yK,"syncSchemaMetadata");var Py=[];async function vy(e){try{try{vc.resetReadTxn(Br.SYSTEM_SCHEMA_NAME,Br.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),vc.resetReadTxn(Br.SYSTEM_SCHEMA_NAME,Br.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Ki.warn(r)}let t=My(e);if(t){Ki.error(t);return}Ki.trace(`ITC userHandler ${Br.HDB_ITC_CLIENT_PREFIX}${AK.pid} received user event:`,e),await RK.setUsersToGlobal();for(let r of Py)r()}catch(t){Ki.error(t)}}a(vy,"userHandler");vy.addListener=function(e){Py.push(e)};By.exports=bK});var Ls=T((Aue,xy)=>{"use strict";var Sue=G(),jm=z(),IK=D(),{ITC_ERRORS:Hc}=Ir(),{parentPort:Tue,threadId:wK,isMainThread:CK,workerData:gue}=require("worker_threads"),{onMessageFromWorkers:DK,broadcast:Rue,broadcastWithAcknowledgement:LK}=Ye();xy.exports={sendItcEvent:UK,validateEvent:Hy,SchemaEventMsg:MK,UserEventMsg:PK};var B_;DK(async(e,t)=>{B_=B_||Bc(),Hy(e),B_[e.type]&&await B_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function UK(e){return!CK&&e.message&&(e.message.originator=wK),LK(e)}a(UK,"sendItcEvent");function Hy(e){if(typeof e!="object")return Hc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||jm.isEmpty(e.type))return Hc.MISSING_TYPE;if(!e.hasOwnProperty("message")||jm.isEmpty(e.message))return Hc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||jm.isEmpty(e.message.originator))return Hc.MISSING_ORIGIN;if(IK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Hc.INVALID_EVENT(e.type)}a(Hy,"validateEvent");function MK(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(MK,"SchemaEventMsg");function PK(e){this.originator=e}a(PK,"UserEventMsg")});var An=T((Nue,ky)=>{"use strict";var qy=D(),bue=z(),H_=G(),Fy=cN(),Qo,{sendItcEvent:Gy}=Ls();function vK(e){try{H_.trace("signalSchemaChange called with message:",e),Qo=Qo||Bc();let t=new Fy(qy.ITC_EVENT_TYPES.SCHEMA,e);return Qo.schema(t),Gy(t)}catch(t){H_.error(t)}}a(vK,"signalSchemaChange");function BK(e){try{H_.trace("signalUserChange called with message:",e),Qo=Qo||Bc();let t=new Fy(qy.ITC_EVENT_TYPES.USER,e);return Qo.user(t),Gy(t)}catch(t){H_.error(t)}}a(BK,"signalUserChange");ky.exports={signalSchemaChange:vK,signalUserChange:BK}});var x_=T((Iue,$y)=>{"use strict";var Vy=z(),HK=D(),xK=G(),qK=h_(),FK=E_(),GK=An(),{SchemaEventMsg:kK}=Ls(),VK="already exists in";$y.exports=$K;async function $K(e,t,r){if(Vy.isEmptyOrZeroLength(r))return r;let s=[];Vy.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await YK(e,t.schema,t.name,i)})),n}a($K,"lmdbCheckForNewAttributes");async function YK(e,t,r,s){let n=new FK(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await KK(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(VK))xK.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(YK,"createNewAttribute");async function KK(e){let t;return t=await qK(e),GK.signalSchemaChange(new kK(process.pid,HK.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(KK,"createAttribute")});var zo=T((Cue,Yy)=>{"use strict";var Zm=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};Yy.exports=Zm});var Wy=T((Lue,Ky)=>{"use strict";var WK=zo(),QK=D().OPERATIONS_ENUM,ep=class extends WK{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(QK.INSERT,r,s,n,i),this.records=t}};Ky.exports=ep});var zy=T((Mue,Qy)=>{"use strict";var zK=zo(),JK=D().OPERATIONS_ENUM,tp=class extends zK{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(JK.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};Qy.exports=tp});var Xy=T((vue,Jy)=>{"use strict";var XK=zo(),jK=D().OPERATIONS_ENUM,rp=class extends XK{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(jK.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};Jy.exports=rp});var Zy=T((Hue,jy)=>{"use strict";var ZK=zo(),eW=D().OPERATIONS_ENUM,sp=class extends ZK{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(eW.DELETE,s,n,t,i),this.original_records=r}};jy.exports=sp});var xc=T((Fue,sI)=>{"use strict";var que=require("path"),eI=Ke(),tW=Wy(),rW=zy(),sW=Xy(),nW=Zy(),Jo=mt(),tI=z(),{CONFIG_PARAMS:iW}=D(),rI=j();rI.initSync();var q_=D().OPERATIONS_ENUM,{getTransactionAuditStorePath:oW}=ze();sI.exports=aW;async function aW(e,t){if(rI.get(iW.LOGGING_AUDITLOG)===!1)return;let r=oW(e.schema,e.table),s=await eI.openEnvironment(r,e.table,!0),n=cW(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){eI.initializeDBIs(s,Jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Jo.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[Jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[Jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),tI.isEmpty(n.user_name)||s.dbis[Jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[Jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(aW,"writeTransaction");function cW(e,t){let r=tI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===q_.INSERT)return new tW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.UPDATE)return new rW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.UPSERT)return new sW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.DELETE)return new nW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(cW,"createTransactionObject")});var np=T((Vue,nI)=>{"use strict";var uW=yc(),kue=Ic(),qc=D(),lW=Lc(),_W=Fo().insertRecords,dW=Ke(),fW=G(),EW=x_(),{getSchemaPath:hW}=ze(),mW=xc();nI.exports=pW;async function pW(e){try{let{schema_table:t,attributes:r}=uW(e);lW(e,r,t.hash_attribute),e.schema!==qc.SYSTEM_SCHEMA_NAME&&(r.includes(qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(qc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(qc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await EW(e.hdb_auth_header,t,r),n=hW(e.schema,e.table),i=await dW.openEnvironment(n,e.table),o=await _W(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await mW(e,o)}catch(c){fW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(pW,"lmdbCreateRecords")});var aI=T((Yue,oI)=>{"use strict";var iI=D(),SW=np(),TW=Ic(),gW=require("fs-extra"),{getSchemaPath:RW}=ze();oI.exports=AW;async function AW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new TW(iI.SYSTEM_SCHEMA_NAME,iI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await SW(r),await gW.mkdirp(RW(e.schema))}a(AW,"lmdbCreateSchema")});var uI=T((Wue,cI)=>{"use strict";var ip=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};cI.exports=ip});var fI=T((jue,dI)=>{"use strict";var lI=Ke(),op=wr(),ap=Ir().LMDB_ERRORS_ENUM,OW=mt(),_I=G(),zue=z(),bW=require("lmdb"),NW=uI(),yW=D(),{OVERFLOW_MARKER:Jue,MAX_SEARCH_KEY_LENGTH:Xue}=OW,IW=yW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function wW(e,t,r,s){if(op.validateEnv(e),t===void 0)throw new Error(ap.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(ap.IDS_REQUIRED):new Error(ap.IDS_MUST_BE_ITERABLE);try{let n=lI.listDBIs(e);lI.initializeDBIs(e,t,n);let i=new NW,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||s&&h[IW]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,bW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let R=n[S];if(!h.hasOwnProperty(R)||R===t)continue;let I=e.dbis[R],w=h[R];if(w!=null)try{let B=op.getIndexedValues(w);if(B)for(let K=0,q=B.length;K<q;K++)I.remove(B[K],o)}catch{_I.warn(`cannot delete from attribute: ${R}, ${w}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){_I.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=op.getNextMonotonicTime(),i}catch(n){throw n}}a(wW,"deleteRecords");dI.exports={deleteRecords:wW}});var Fc=T((ele,hI)=>{"use strict";var Xo=z(),CW=fI(),DW=Ke(),{getSchemaPath:LW}=ze(),UW=xc(),MW=G();hI.exports=PW;async function PW(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Xo.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Xo.isEmptyOrZeroLength(e.hash_values)&&!Xo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];Xo.isEmpty(u)||e.hash_values.push(u)}}if(Xo.isEmptyOrZeroLength(e.hash_values))return EI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Xo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[s]:e.hash_values[c]}}let n=LW(e.schema,e.table),i=await DW.openEnvironment(n,e.table),o=await CW.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await UW(e,o)}catch(c){MW.error(`unable to write transaction due to ${c.message}`)}return EI(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(PW,"lmdbDeleteRecords");function EI(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(EI,"createDeleteResponse")});var up=T((sle,mI)=>{"use strict";var vW=D(),rle=wr();function cp(e,t){let r=Object.create(null);if(t.length===1&&vW.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a(cp,"parseRow");function BW(e,t,r,s){let n=cp(r,e);s.push(n)}a(BW,"searchAll");function HW(e,t,r,s){let n=cp(r,e);s[t]=n}a(HW,"searchAllToMap");function xW(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(xW,"iterateDBI");function Wi(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(Wi,"pushResults");function qW(e,t,r,s,n,i){t.toString().endsWith(e)&&Wi(t,r,s,n,i)}a(qW,"endsWith");function FW(e,t,r,s,n,i){t.toString().includes(e)&&Wi(t,r,s,n,i)}a(FW,"contains");function GW(e,t,r,s,n,i){t>e&&Wi(t,r,s,n,i)}a(GW,"greaterThanCompare");function kW(e,t,r,s,n,i){t>=e&&Wi(t,r,s,n,i)}a(kW,"greaterThanEqualCompare");function VW(e,t,r,s,n,i){t<e&&Wi(t,r,s,n,i)}a(VW,"lessThanCompare");function $W(e,t,r,s,n,i){t<=e&&Wi(t,r,s,n,i)}a($W,"lessThanEqualCompare");mI.exports={parseRow:cp,searchAll:BW,searchAllToMap:HW,iterateDBI:xW,endsWith:qW,contains:FW,greaterThanCompare:GW,greaterThanEqualCompare:kW,lessThanCompare:VW,lessThanEqualCompare:$W,pushResults:Wi}});var jo=T((cle,OI)=>{"use strict";var ni=Ke(),ile=G(),Hr=wr(),F_=mt(),ft=Ir().LMDB_ERRORS_ENUM,ole=z(),YW=D(),G_=up(),{parseRow:KW}=G_,ale=require("lmdb"),{OVERFLOW_MARKER:pI,MAX_SEARCH_KEY_LENGTH:WW}=F_;function SI(e,t,r,s=!1,n=void 0,i=void 0){return Qi(e,t,r,(o,c)=>c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}a(SI,"iterateFullIndex");function Gc(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Qi(e,t,r,(l,d,f,E)=>{let I={transaction:l,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(I.values=!1,d.getRange(I).map(w=>({value:w}))):d.getRange(I)})}a(Gc,"iterateRangeBetween");function Qi(e,t,r,s){let n=e.database||e,i=ni.openDBI(n,r);i[F_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ni.openDBI(n,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=s(o,i,n,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Qi,"setupTransaction");function TI(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(pI)){if(!n)if(r)n=ni.openDBI(e,r);else{let u=ni.listDBIs(e);for(let _=0,l=u.length;_<l&&(n=ni.openDBI(e,u[_]),!n[F_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(TI,"getOverflowCheck");function QW(e,t,r,s=!1,n=void 0,i=void 0){if(Hr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);return Qi(e,t,t,(o,c,u)=>(k_(r),r=kc(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(_=>KW(_.value,r))))}a(QW,"searchAll");function zW(e,t,r,s=!1,n=void 0,i=void 0){if(Hr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);k_(r),r=kc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of SI(e,t,t,s,n,i))o.set(c,G_.parseRow(u,r));return o}a(zW,"searchAllToMap");function JW(e,t,r=!1,s=void 0,n=void 0){if(Hr.validateEnv(e),t===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=SI(e,void 0,t,r,s,n),c=o.transaction,u=TI(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(JW,"iterateDBI");function XW(e,t){if(Hr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);return ni.statDBI(e,t).entryCount}a(XW,"countAll");function jW(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Qi(e,t,r,(c,u,_,l)=>(s=Hr.convertKeyValueToWrite(s),l===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(jW,"equals");function ZW(e,t,r){return ii(e,t,r),ni.openDBI(e,t).getValuesCount(r)}a(ZW,"count");function eQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Qi(e,null,r,(c,u)=>{s=Hr.convertKeyValueToWrite(s);let _=!0;typeof s=="number"&&(_=!1);let l;if(n===!0){let d;for(let f of u.getKeys({transaction:c,start:s}))if(!f.startsWith(s)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(s))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(eQ,"startsWith");function tQ(e,t,r,s,n=!1,i=void 0,o=void 0){return gI(e,t,r,s,n,i,o,!0)}a(tQ,"endsWith");function gI(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return ii(e,r,s),Qi(e,null,r,(u,_,l,d)=>{let f=TI(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(E=>{let h=E.toString();return h.endsWith(pI)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(s):S.includes(s))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(s):h.includes(s))?_[F_.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(gI,"contains");function rQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Gc(e,t,r,s,u,n,i,o,!0,!1)}a(rQ,"greaterThan");function sQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Gc(e,t,r,s,u,n,i,o,!1,!1)}a(sQ,"greaterThanEqual");function nQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Gc(e,t,r,u,s,n,i,o,!1,!0)}a(nQ,"lessThan");function iQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Gc(e,t,r,u,s,n,i,o,!1,!1)}a(iQ,"lessThanEqual");function oQ(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(Hr.validateEnv(e),r===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ft.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ft.END_VALUE_REQUIRED);if(s=Hr.convertKeyValueToWrite(s),n=Hr.convertKeyValueToWrite(n),s>n)throw new Error(ft.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Gc(e,t,r,s,n,i,o,c)}a(oQ,"between");function aQ(e,t,r,s){Hr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(k_(r),r=kc(n,r),s===void 0)throw new Error(ft.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=G_.parseRow(c,r)),o}a(aQ,"searchByHash");function cQ(e,t,r){Hr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ft.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(cQ,"checkHashExists");function uQ(e,t,r,s,n=[]){return AI(e,t,r,s,n),RI(e,t,r,s,n).map(i=>i[1])}a(uQ,"batchSearchByHash");function lQ(e,t,r,s,n=[]){AI(e,t,r,s,n);let i=new Map;for(let[o,c]of RI(e,t,r,s,n))i.set(o,c);return i}a(lQ,"batchSearchByHashToMap");function RI(e,t,r,s,n=[]){return Qi(e,t,t,(i,o,c)=>{r=kc(c,r);let u=r.length<3;return s.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,G_.parseRow(l,r)];n.push(_)}).filter(_=>_)})}a(RI,"batchHashSearch");function AI(e,t,r,s,n){if(Hr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(k_(r),s==null)throw new Error(ft.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(ft.IDS_MUST_BE_ITERABLE)}a(AI,"initializeBatchSearchByHash");function k_(e){if(!Array.isArray(e))throw e===void 0?new Error(ft.FETCH_ATTRIBUTES_REQUIRED):new Error(ft.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(k_,"validateFetchAttributes");function ii(e,t,r){if(Hr.validateEnv(e),t===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ft.SEARCH_VALUE_REQUIRED);if(r?.length>WW)throw new Error(ft.SEARCH_VALUE_TOO_LARGE)}a(ii,"validateComparisonFunctions");function kc(e,t){return t.length===1&&YW.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ni.listDBIs(e)),t}a(kc,"setGetWholeRowAttributes");OI.exports={searchAll:QW,searchAllToMap:zW,count:ZW,countAll:XW,equals:jW,startsWith:eQ,endsWith:tQ,contains:gI,searchByHash:aQ,setGetWholeRowAttributes:kc,batchSearchByHash:uQ,batchSearchByHashToMap:lQ,checkHashExists:cQ,iterateDBI:JW,greaterThan:rQ,greaterThanEqual:sQ,lessThan:nQ,lessThanEqual:iQ,between:oQ}});var Zo=T((lle,wI)=>{var bI=require("lodash"),NI=Je(),fe=require("joi"),_Q=z(),{hdb_schema_table:Vc,checkValidTable:yI,hdb_table:II,hdb_database:V_}=Ks(),{handleHDBError:dQ,hdb_errors:fQ}=Z(),{getDatabases:EQ}=(ge(),ee(xe)),{HTTP_STATUS_CODES:hQ}=fQ,mQ=fe.object({database:V_,schema:V_,table:II,search_attribute:Vc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(Vc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),pQ=fe.object({database:V_,schema:V_,table:II,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives(Vc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(Vc,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives(Vc,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});wI.exports=function(e,t){let r=null;switch(t){case"value":r=NI.validateBySchema(e,mQ);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(yI("database",e.schema)),i(yI("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),n&&(r=new Error(n.trim()));break;case"conditions":r=NI.validateBySchema(e,pQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=_Q.checkGlobalSchemaTable(e.schema,e.table);if(n)return dQ(new Error,n,hQ.NOT_FOUND);let o=EQ()[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 _=bI.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!bI.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var lp=T((dle,CI)=>{"use strict";var SQ=Ke(),TQ=Zo(),{getSchemaPath:gQ}=ze();CI.exports=RQ;function RQ(e){let t=TQ(e,"hashes");if(t)throw t;let r=gQ(e.schema,e.table);return SQ.openEnvironment(r,e.table)}a(RQ,"initialize")});var _p=T((Ele,DI)=>{"use strict";var AQ=jo(),OQ=lp();DI.exports=bQ;async function bQ(e){let t=await OQ(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return AQ.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(bQ,"lmdbGetDataByHash")});var ea=T((mle,LI)=>{"use strict";var dp=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};LI.exports=dp});var MI=T((Tle,UI)=>{"use strict";var Sle=ea(),NQ=jo(),yQ=lp();UI.exports=IQ;async function IQ(e){let t=await yQ(e),r=global.hdb_schema[e.schema][e.table];return NQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(IQ,"lmdbSearchByHash")});var Xs=T((Rle,PI)=>{"use strict";var fp=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};PI.exports=fp});var $_=T((Ole,FI)=>{"use strict";var Jt=jo(),wQ=Ke(),CQ=z(),Ee=mt(),zi=D(),DQ=Bi(),vI=Ir().LMDB_ERRORS_ENUM,{getSchemaPath:LQ}=ze(),On=zi.SEARCH_WILDCARDS;async function UQ(e,t,r){let s;e.schema===zi.SYSTEM_SCHEMA_NAME?s=DQ[e.table]:s=global.hdb_schema[e.schema][e.table];let n=qI(e,s.hash_attribute,r,t);return HI(e,n,s.hash_attribute,r)}a(UQ,"prepSearch");async function HI(e,t,r,s){let n=LQ(e.schema,e.table),i=await wQ.openEnvironment(n,e.table),o=xI(i,e,t,r),c=o.transaction||i;if([Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Ee.SEARCH_TYPES.SEARCH_ALL,Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(MQ(e,r)===!1){let l=e.search_attribute;if(l===r)return s?BI(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?BI(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?Jt.batchSearchByHashToMap(c,r,e.get_attributes,_):Jt.batchSearchByHash(c,r,e.get_attributes,_)}a(HI,"executeSearch");function xI(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:n=Jt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:n=Jt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:n=Jt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:n=Jt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Jt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Jt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return Jt.searchAll(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Jt.searchAllToMap(e,s,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:n=Jt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:n=Jt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Jt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:n=Jt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:n=Jt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(xI,"searchByType");function BI(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(BI,"createMapFromIterable");function MQ(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(MQ,"checkToFetchMore");function qI(e,t,r,s){if(CQ.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),On.indexOf(n)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(On[0])<0&&n.indexOf(On[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(On.indexOf(i)>=0&&On.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(On.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(On.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(n.includes(On[0])||n.includes(On[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(vI.UNKNOWN_SEARCH_TYPE)}else switch(s){case zi.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case zi.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case zi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case zi.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case zi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(vI.UNKNOWN_SEARCH_TYPE)}}a(qI,"createSearchTypeFromSearchObject");FI.exports={executeSearch:HI,createSearchTypeFromSearchObject:qI,prepSearch:UQ,searchByType:xI}});var kI=T((yle,GI)=>{"use strict";var Nle=Xs(),PQ=Zo(),vQ=z(),BQ=D(),HQ=$_();GI.exports=xQ;function xQ(e,t){if(!vQ.isEmpty(t)&&BQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=PQ(e,"value");if(s)throw s;return HQ.prepSearch(e,t,!0)}a(xQ,"lmdbGetDataByValue")});var $c=T((Cle,VI)=>{"use strict";var wle=Xs(),qQ=Zo(),FQ=z(),GQ=D(),kQ=$_();VI.exports=VQ;async function VQ(e,t){if(!FQ.isEmpty(t)&&GQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=qQ(e,"value");if(s)throw s;return kQ.prepSearch(e,t,!1)}a(VQ,"lmdbSearchByValue")});var YI=T((Ule,$I)=>{"use strict";var Lle=mt(),Ep=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}},hp=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},mp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};$I.exports={SearchByConditionsObject:Ep,SearchCondition:hp,SortAttribute:mp}});var JI=T((Ble,zI)=>{"use strict";var Ple=YI().SearchByConditionsObject,$Q=Xs(),YQ=Zo(),pp=jo(),Y_=mt(),{Resource:vle}=(Ns(),ee(Sp)),QI=$_(),KQ=up(),WQ=require("lodash"),{getSchemaPath:QQ}=ze(),KI=Ke(),{handleHDBError:zQ,hdb_errors:JQ}=Z(),{HTTP_STATUS_CODES:XQ}=JQ,jQ=1e8;zI.exports=ZQ;async function ZQ(e){let t=YQ(e,"conditions");if(t)throw zQ(t,t.message,XQ.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=QQ(e.schema,e.table),s=await KI.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)KI.openDBI(s,_.search_attribute);let i=WQ.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===Y_.SEARCH_TYPES.EQUALS?_.estimated_count=pp.count(s,_.search_attribute,_.search_value):l===Y_.SEARCH_TYPES.CONTAINS||l===Y_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=jQ}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await WI(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=s.dbis[n.hash_attribute],l=i.slice(1).map(QI.filterByType),d=l.length,f=pp.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>KQ.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await WI(o,e,f,n.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=pp.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(ZQ,"lmdbSearchByConditions");async function WI(e,t,r,s){let n=new $Q(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===Y_.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,QI.searchByType(e,n,i,s).map(o=>o.value)}a(WI,"executeConditionSearch")});var ta=T((xle,XI)=>{"use strict";var ez=D().OPERATIONS_ENUM,Tp=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=ez.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};XI.exports=Tp});var gp=T((Fle,iw)=>{"use strict";var tw=Xs(),rw=ta(),sw=$c(),nw=Fc(),ar=D(),jI=z(),ZI=Ke(),{getTransactionAuditStorePath:tz,getSchemaPath:rz}=ze(),ew=G();iw.exports=sz;async function sz(e){try{if(jI.isEmpty(global.hdb_schema[e.schema])||jI.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await nz(e),await iz(e);let t=rz(e.schema,e.table);try{await ZI.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")ew.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=tz(e.schema,e.table);await ZI.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")ew.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(sz,"lmdbDropTable");async function nz(e){let t=new tw(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await sw(t)),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new rw(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await nw(n)}a(nz,"deleteAttributesFromSystem");async function iz(e){let t=new tw(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await sw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new rw(ar.SYSTEM_SCHEMA_NAME,ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await nw(n)}catch(i){throw i}}a(iz,"dropTableFromSystem")});var aw=T((kle,ow)=>{"use strict";var oz=require("fs-extra"),az=Xs(),cz=ea(),uz=ta(),lz=gp(),_z=Fc(),dz=_p(),fz=$c(),bn=D(),{getSchemaPath:Ez}=ze(),{handleHDBError:hz,hdb_errors:mz}=Z(),{HDB_ERROR_MSGS:pz,HTTP_STATUS_CODES:Sz}=mz;ow.exports=Tz;async function Tz(e){let t;try{t=await gz(e.schema);let r=new az(bn.SYSTEM_SCHEMA_NAME,bn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,bn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[bn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await fz(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await lz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new uz(bn.SYSTEM_SCHEMA_NAME,bn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await _z(n);let i=Ez(t);await oz.remove(i)}catch(r){throw r}}a(Tz,"lmdbDropSchema");async function gz(e){let t=new cz(bn.SYSTEM_SCHEMA_NAME,bn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[bn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await dz(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw hz(new Error,pz.SCHEMA_NOT_FOUND(e),Sz.NOT_FOUND,void 0,void 0,!0);return s}a(gz,"validateDropSchema")});var K_=T(($le,cw)=>{"use strict";var Rp=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};cw.exports=Rp});var lw=T((Wle,uw)=>{"use strict";var Rz=require("fs-extra"),W_=Ke(),{getTransactionAuditStorePath:Az}=ze(),Ap=mt(),Kle=K_();uw.exports=Oz;async function Oz(e){let t;try{let r=Az(e.schema,e.table);await Rz.mkdirp(r),t=await W_.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{W_.createDBI(t,Ap.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),W_.createDBI(t,Ap.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),W_.createDBI(t,Ap.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(Oz,"createTransactionsAuditEnvironment")});var Ew=T((zle,fw)=>{"use strict";var Op=D(),_w=Ke(),bz=Fo(),{getSystemSchemaPath:Nz,getSchemaPath:yz}=ze(),Iz=Bi(),wz=h_(),bp=E_(),Cz=G(),Dz=lw(),yp=Iz.hdb_table,dw=[];for(let e=0;e<yp.attributes.length;e++)dw.push(yp.attributes[e].attribute);fw.exports=Lz;async function Lz(e,t){let r=yz(t.schema,t.table),s=new bp(t.schema,t.table,Op.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new bp(t.schema,t.table,Op.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new bp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await _w.createEnvironment(r,t.table),e!==void 0){let o=await _w.openEnvironment(Nz(),Op.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await bz.insertRecords(o,yp.hash_attribute,dw,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Np(s),await Np(n),await Np(i)}await Dz(t)}catch(o){throw o}}a(Lz,"lmdbCreateTable");async function Np(e){try{await wz(e)}catch(t){Cz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Np,"createAttribute")});var mw=T((Xle,hw)=>{"use strict";var Uz=yc(),Mz=Lc(),Pz=x_(),Yc=D(),vz=Fo().updateRecords,Bz=Ke(),{getSchemaPath:Hz}=ze(),xz=xc(),qz=G();hw.exports=Fz;async function Fz(e){try{let{schema_table:t,attributes:r}=Uz(e);Mz(e,r,t.hash_attribute),e.schema!==Yc.SYSTEM_SCHEMA_NAME&&(r.includes(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await Pz(e.hdb_auth_header,t,r),n=Hz(e.schema,e.table),i=await Bz.openEnvironment(n,e.table),o=await vz(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await xz(e,o)}catch(c){qz.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(Fz,"lmdbUpdateRecords")});var Sw=T((Zle,pw)=>{"use strict";var Gz=D().OPERATIONS_ENUM,Ip=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=Gz.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};pw.exports=Ip});var gw=T((r_e,Tw)=>{"use strict";var t_e=Sw(),kz=yc(),Vz=Lc(),$z=x_(),Kc=D(),Yz=Fo().upsertRecords,Kz=Ke(),{getSchemaPath:Wz}=ze(),Qz=xc(),zz=G(),{handleHDBError:Jz,hdb_errors:Xz}=Z();Tw.exports=jz;async function jz(e){let t;try{t=kz(e)}catch(u){throw Jz(u,u.message,Xz.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;Vz(e,s,r.hash_attribute),e.schema!==Kc.SYSTEM_SCHEMA_NAME&&(s.includes(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await $z(e.hdb_auth_header,r,s),i=Wz(e.schema,e.table),o=await Kz.openEnvironment(i,e.table),c=await Yz(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await Qz(e,c)}catch(u){zz.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(jz,"lmdbUpsertRecords")});var Aw=T((n_e,Rw)=>{"use strict";var wp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};Rw.exports=wp});var bw=T((o_e,Ow)=>{"use strict";var Cp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};Ow.exports=Cp});var Iw=T((u_e,yw)=>{"use strict";var Dp=Ke(),{getTransactionAuditStorePath:Zz}=ze(),c_e=Aw(),Wc=mt(),eJ=z(),Nw=bw(),tJ=require("util").promisify,rJ=tJ(setTimeout),sJ=1e4,nJ=100;yw.exports=iJ;async function iJ(e){let t=Zz(e.schema,e.table),r=await Dp.openEnvironment(t,e.table,!0),s=Dp.listDBIs(r);Dp.initializeDBIs(r,Wc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new Nw;do n=await oJ(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await rJ(nJ);while(n.transactions_deleted>0);return i}a(iJ,"deleteAuditLogsBefore");async function oJ(e,t){let r=new Nw;try{let s=e.dbis[Wc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[Wc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];eJ.isEmpty(c)||(n=e.dbis[Wc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Wc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>sJ)break}return await n,r}catch(s){throw s}}a(oJ,"deleteTransactions")});var Cw=T((__e,ww)=>{"use strict";var Lp=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};ww.exports=Lp});var Lw=T((E_e,Dw)=>{"use strict";var aJ=Xs(),cJ=ta(),f_e=Cw(),js=D(),uJ=z(),Up=Ke(),lJ=Bi(),_J=$c(),dJ=Fc(),{getSchemaPath:fJ}=ze();Dw.exports=EJ;async function EJ(e,t=!0){let r;e.schema===js.SYSTEM_SCHEMA_NAME?r=lJ[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await mJ(e),n=fJ(e.schema,e.table),i=await Up.openEnvironment(n,e.table);return t===!0&&await hJ(e,i,r.hash_attribute),Up.dropDBI(i,e.attribute),s}a(EJ,"lmdbDropAttribute");async function hJ(e,t,r){let s=Up.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);n=t.dbis[r].put(o,_,u)}await n}a(hJ,"removeAttributeFromAllObjects");async function mJ(e){let t=new aJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await _J(t)).filter(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(uJ.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new cJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return dJ(i)}a(mJ,"dropAttributeFromSystem")});var Hw=T((p_e,Bw)=>{"use strict";var Mp=Ke(),ra=mt(),m_e=wr(),Pp=D(),Uw=z(),{getTransactionAuditStorePath:pJ}=ze(),SJ=jo(),Q_=zo(),TJ=G();Bw.exports=gJ;async function gJ(e){let t=pJ(e.schema,e.table),r=await Mp.openEnvironment(t,e.table,!0),s=Mp.listDBIs(r);Mp.initializeDBIs(r,ra.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Pp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return Mw(r,e.search_values);case Pp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,AJ(r,e.search_values,n);case Pp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return RJ(r,e.search_values);default:return Mw(r)}}a(gJ,"readAuditLog");function Mw(e,t=[0,Date.now()]){Uw.isEmpty(t[0])&&(t[0]=0),Uw.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[ra.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new Q_,n))}a(Mw,"searchTransactionsByTimestamp");function RJ(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[ra.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,vw(e,i))}return Object.fromEntries(r)}a(RJ,"searchTransactionsByUsername");function AJ(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=SJ.equals(e,ra.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ra.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);s.has(f)?s.get(f).push(_.toString()):s.set(f,[_.toString()])}}let n=Array.from(s.keys()),i=vw(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);Pw(u,"records",r,l,o),Pw(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(AJ,"searchTransactionsByHashValues");function Pw(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let _=n.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new 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],n.set(u,[_])}}}a(Pw,"loopRecords");function vw(e,t){let r=[];try{let s=e.dbis[ra.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new Q_,i);r.push(o)}}catch(i){TJ.warn(i)}return r}catch(s){throw s}}a(vw,"batchSearchTransactions")});var qw=T((R_e,xw)=>{"use strict";var{getSchemaPath:T_e}=ze(),g_e=Ke(),{database:OJ}=(ge(),ee(xe));xw.exports={writeTransaction:bJ};async function bJ(e,t,r){return OJ({database:e,table:t}).transaction(r)}a(bJ,"writeTransaction")});var Vw=T((O_e,kw)=>{"use strict";var{getSchemaPath:Fw}=ze(),Gw=Ke();kw.exports={flush:NJ,resetReadTxn:yJ};async function NJ(e,t){return(await Gw.openEnvironment(Fw(e,t),t.toString())).flushed}a(NJ,"flush");async function yJ(e,t){try{(await Gw.openEnvironment(Fw(e,t),t.toString())).resetReadTxn()}catch{}}a(yJ,"resetReadTxn")});var Ww=T((N_e,Kw)=>{"use strict";var{Readable:IJ}=require("stream"),{getDatabases:wJ}=(ge(),ee(xe)),{readSync:CJ,openSync:DJ,createReadStream:$w}=require("fs"),{open:LJ}=require("lmdb"),Yw=n_(),UJ=o_(),{AUDIT_STORE_OPTIONS:MJ}=(Pi(),ee(Qw)),{INTERNAL_DBIS_NAME:PJ,AUDIT_STORE_NAME:vJ}=mt();Kw.exports=HJ;var vp=32768,BJ=100;async function HJ(e){let t=e.database||e.schema||"data",r=wJ()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let _=r[n[0]];if(!_)throw new Error(`Can not find table ${n[0]}`);let l=_.dbisDB,d=LJ({noSync:!0,maxDbs:UJ.MAX_DBS}),f,E=d.openDB(PJ,new Yw(!1)),h=l.useReadTransaction(),p=0,S=a(async function(I,w){w.encoding="binary",w.encoder=void 0;let B=d.openDB(I,w),K=l.openDB(I,w);for(let{key:q,version:P,value:Q}of K.getRange({transaction:h,versions:K.useVersions}))f=B.put(q,Q,P),p++%BJ===0&&(await new Promise(Y=>setTimeout(Y,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:I,value:w}of l.getRange({transaction:h,start:!1}))if(n.some(B=>I.startsWith?.(B+"/"))){E.put(I,w);let[,B]=I.split("/"),K=!B,q=new Yw(!K,K);await S(I,q)}e.include_audit&&await S(vJ,Object.assign({},MJ)),await f;let R=$w(d.path);return R.headers=u(),R.on("close",()=>{h.done(),d.close()}),R}let o=r[Object.keys(r)[0]].primaryStore,c=DJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(vp);CJ(c,_,0,vp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=$w(null,{fd:c,start:vp}),f=new IJ.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",s),_}}a(HJ,"getBackup")});var Xw=T((I_e,Jw)=>{"use strict";var xJ=G(),{handleHDBError:qJ}=Z(),FJ=lb(),GJ=h_(),kJ=np(),VJ=aI(),$J=Fc(),YJ=_p(),KJ=MI(),WJ=kI(),QJ=$c(),zJ=JI(),JJ=aw(),XJ=Ew(),jJ=mw(),ZJ=gw(),e2=Iw(),t2=gp(),r2=Lw(),s2=Hw(),n2=qw(),zw=Vw(),i2=Ww(),Bp=class extends FJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return zJ(t)}async getDataByHash(t){return await YJ(t)}async searchByHash(t){return await KJ(t)}async getDataByValue(t,r){return await WJ(t,r)}async searchByValue(t){return await QJ(t)}async createSchema(t){return await VJ(t)}async dropSchema(t){return await JJ(t)}async createTable(t,r){return await XJ(t,r)}async dropTable(t){return await t2(t)}async createAttribute(t){return await GJ(t)}async createRecords(t){return await kJ(t)}async updateRecords(t){return await jJ(t)}async upsertRecords(t){try{return await ZJ(t)}catch(r){throw qJ(r,null,null,xJ.ERR,r)}}async deleteRecords(t){return await $J(t)}async dropAttribute(t){return await r2(t)}async deleteAuditLogsBefore(t){return await e2(t)}async readAuditLog(t){return await s2(t)}writeTransaction(t,r,s){return n2.writeTransaction(t,r,s)}flush(t,r){return zw.flush(t,r)}resetReadTxn(t,r){return zw.resetReadTxn(t,r)}getBackup(t){return i2(t)}};Jw.exports=Bp});function u2(){c2=setInterval(function(){for(let e of Hp)if(e.stale){let t=e[Re]?.url;jw.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},a2).unref()}var xp,jw,o2,Hp,Ji,z_,a2,c2,qp=Ae(()=>{xp=v(wr()),jw=v(G());Ns();o2=100,Hp=new Set,Ji=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;if(!this.open)throw new Error("Can not start a read on a transaction that is no longer open");return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),Hp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Hp.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,xp.getNextMonotonicTime)());let s=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let R=S();E?E.push?E.push(R):E=[E,R]:E=R}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}s||this.doneReadTxn(),t?.prepared?.(),this.open=!1;let n,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,s)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){s>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);n=n||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<o2>>s?u():n=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),n)return n.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=s+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=!1,this.writes=[]}},z_=class extends Ji{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,xp.getNextMonotonicTime)())}getReadTxn(){}},a2=3e4;a(u2,"startMonitoringTxns");u2()});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 s=e.transaction=new Ji;e.timestamp&&(s.timestamp=e.timestamp),s[Re]=e,e.resourceCache||(e.resourceCache=[]);let n;try{if(n=t(s),n?.then)return n.then(i,o)}catch(c){o(c)}return i(n);function i(c){let u=s.commit(r?.resetTransaction?{prepared(){s.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw s.abort({}),c}}var Zw,Xi=Ae(()=>{Zw=require("../index");Ns();qp();a(Xe,"transaction");(0,Zw._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Re]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Re]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var cC={};$e(cC,{ResourceBridge:()=>kp});function Vp({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 tC(e,t){let r=Zs(e),s=Vp(e,r);if(!r)throw new Us.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user},o;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:n,select:s},i);return l=l&&X_(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 Zs(e){let t=e.database||e.schema||_2,r=Ms()[t];if(!r)throw(0,Us.handleHDBError)(new Error,l2.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function rC(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*sC(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(o),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[o],records:[u]})}s&&(yield s)}var nC,J_,Us,iC,oC,Ps,Fp,Gp,aC,l2,_2,d2,f2,eC,kp,uC=Ae(()=>{"use strict";nC=v(Xw()),J_=v(Zo()),Us=v(Z());ge();iC=v(yc()),oC=v(Lc()),Ps=v(D()),Fp=v(An()),Gp=v(Ls()),aC=v(z());Xi();j_();({HDB_ERROR_MSGS:l2}=Us.hdb_errors),_2="data",d2=1e4,f2=10,kp=class extends nC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),eC=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,J_.default)(t,"conditions");if(r)throw(0,Us.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=Zs(t);if(!s)throw new Us.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Vp(t,s),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let o of s)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Us.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}dt({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await Zs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Zs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=a((o,c,u)=>(c=Object.assign({},c),delete c[s],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))n=i(o,c,u),await new Promise(_=>setImmediate(_));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Zs(t).dropTable()}createSchema(t){return Qc({database:t.schema,table:null}),Fp.signalSchemaChange(new Gp.SchemaEventMsg(process.pid,Ps.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await $p(t.schema),Fp.signalSchemaChange(new Gp.SchemaEventMsg(process.pid,Ps.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,eC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,iC.default)(t);(0,oC.default)(t,s,r.primaryKey);let n,i=Ms()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Xe(o,async c=>{if(!i.schemaDefined){n=[];for(let l of s)i.attributes.find(f=>f.name==l)||n.push(l);n.length>0&&await i.addAttributes(n.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=X_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:_}})}async deleteRecords(t){let r=Ms()[t.schema][t.table],s={user:t.hdb_user};return Xe(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,s)?o.push(u):c.push(u);return rC(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Ms()[t.schema][t.table];if(!r.createdTimeProperty)throw new Us.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Ps.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,aC.async_set_timeout)(f2),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%d2===0&&await _();return u.length>0&&await _(),n?rC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,J_.default)(t,"hashes");if(r)throw r;return tC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of tC(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&Ps.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let s=(0,J_.default)(t,"value");if(s)throw s;let n=Zs(t);if(!n)throw new Us.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Ps.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Vp(t,n)})}async getDataByValue(t,r){let s=new Map,n=Zs(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){Zs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Zs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Zs(t),s={};switch(t.search_type){case Ps.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case Ps.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of sC(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return sC(r,t.search_values?.[0],t.search_values?.[1])}}};a(Vp,"getSelect");a(tC,"getRecords");a(Zs,"getTable");a(rC,"createDeleteResponse");a(sC,"groupRecordsInHistory")});var ws=T((G_e,lC)=>{"use strict";var{ResourceBridge:E2}=(uC(),ee(cC)),h2=j();h2.initSync();var Z_;function m2(){return Z_||(Z_=new E2,Z_)}a(m2,"getBridge");lC.exports=m2()});var EC=T((V_e,fC)=>{"use strict";var _C=require("lodash"),zc=require("mathjs"),p2=require("jsonata"),dC=z();fC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?_C.uniqWith(e,_C.isEqual):e,searchJSON:S2,mad:Jc.bind(null,zc.mad),mean:Jc.bind(null,zc.mean),mode:Jc.bind(null,zc.mode),prod:Jc.bind(null,zc.prod),median:Jc.bind(null,zc.median)};function Jc(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(Jc,"aggregateFunction");function S2(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(dC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),dC.isEmpty(this.__ala__.res[r])){let s=p2(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(S2,"searchJSON")});var mC=T((Y_e,hC)=>{"use strict";var St=require("moment"),Yp="YYYY-MM-DDTHH:mm:ss.SSSZZ";St.suppressDeprecationWarnings=!0;hC.exports={current_date:()=>St().utc().format("YYYY-MM-DD"),current_time:()=>St().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return St(e).utc().format("YYYY");case"month":return St(e).utc().format("MM");case"day":return St(e).utc().format("DD");case"hour":return St(e).utc().format("HH");case"minute":return St(e).utc().format("mm");case"second":return St(e).utc().format("ss");case"millisecond":return St(e).utc().format("SSS");default:break}},date:e=>St(e).utc().format(Yp),date_format:(e,t)=>St(e).utc().format(t),date_add:(e,t,r)=>St(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>St(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=St(e).utc(),n=St(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>St().utc().valueOf(),get_server_time:()=>St().format(Yp),offset_utc:(e,t)=>St(e).utc().utcOffset(t).format(Yp)}});var gC=T((K_e,TC)=>{"use strict";var T2=require("@turf/area"),g2=require("@turf/length"),R2=require("@turf/circle"),A2=require("@turf/difference"),O2=require("@turf/distance"),b2=require("@turf/boolean-contains"),N2=require("@turf/boolean-equal"),y2=require("@turf/boolean-disjoint"),I2=require("@turf/helpers"),pC=D(),me=z(),Nn=G();TC.exports={geoArea:w2,geoLength:C2,geoCircle:D2,geoDifference:L2,geoDistance:SC,geoNear:U2,geoContains:M2,geoEqual:P2,geoCrosses:v2,geoConvert:B2};function w2(e){if(me.isEmpty(e))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e));try{return T2.default(e)}catch(t){return Nn.trace(t,e),NaN}}a(w2,"geoArea");function C2(e,t){if(me.isEmpty(e))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e));try{return g2.default(e,{units:t||"kilometers"})}catch(r){return Nn.trace(r,e),NaN}}a(C2,"geoLength");function D2(e,t,r){if(me.isEmpty(e))return NaN;if(me.isEmpty(t))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e));try{return R2.default(e,t,{units:r||"kilometers"})}catch(s){return Nn.trace(s,e,t),NaN}}a(D2,"geoCircle");function L2(e,t){if(me.isEmpty(e))return NaN;if(me.isEmpty(t))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return A2(e,t)}catch(r){return Nn.trace(r,e,t),NaN}}a(L2,"geoDifference");function SC(e,t,r){if(me.isEmpty(e))return NaN;if(me.isEmpty(t))return NaN;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return O2.default(e,t,{units:r||"kilometers"})}catch(s){return Nn.trace(s,e,t),NaN}}a(SC,"geoDistance");function U2(e,t,r,s){if(me.isEmpty(e)||me.isEmpty(t))return!1;if(me.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return SC(e,t,s)<=r}catch(n){return Nn.trace(n,e,t),!1}}a(U2,"geoNear");function M2(e,t){if(me.isEmpty(e)||me.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return b2.default(e,t)}catch(r){return Nn.trace(r,e,t),!1}}a(M2,"geoContains");function P2(e,t){if(me.isEmpty(e)||me.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return N2.default(e,t)}catch(r){return Nn.trace(r,e,t),!1}}a(P2,"geoEqual");function v2(e,t){if(me.isEmpty(e)||me.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=me.autoCastJSON(e)),typeof t=="string"&&(t=me.autoCastJSON(t));try{return!y2.default(e,t)}catch(r){return Nn.trace(r,e,t),!1}}a(v2,"geoCrosses");function B2(e,t,r){if(me.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(me.isEmpty(t))throw new Error("geo_type is required");if(me.isEmpty(pC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(pC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=me.autoCastJSON(e)),I2[t](e,r)}a(B2,"geoConvert")});var ed=T((Q_e,RC)=>{var ji=EC(),xr=mC(),en=gC();RC.exports=e=>{e.aggr.mad=e.aggr.MAD=ji.mad,e.aggr.mean=e.aggr.MEAN=ji.mean,e.aggr.mode=e.aggr.MODE=ji.mode,e.aggr.prod=e.aggr.PROD=ji.prod,e.aggr.median=e.aggr.MEDIAN=ji.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ji.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ji.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=xr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=xr.current_time,e.fn.extract=e.fn.EXTRACT=xr.extract,e.fn.date=e.fn.DATE=xr.date,e.fn.date_format=e.fn.DATE_FORMAT=xr.date_format,e.fn.date_add=e.fn.DATE_ADD=xr.date_add,e.fn.date_sub=e.fn.DATE_SUB=xr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=xr.date_diff,e.fn.now=e.fn.NOW=xr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=xr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=xr.get_server_time,e.fn.getdate=e.fn.GETDATE=xr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=xr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=en.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=en.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=en.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=en.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=en.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=en.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=en.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=en.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=en.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=en.geoNear}});var NC=T((z_e,bC)=>{"use strict";var Xc=require("lodash"),cr=require("alasql");cr.options.cache=!1;var H2=ed(),AC=require("clone"),td=require("recursive-iterator"),ue=G(),we=z(),sa=ws(),x2=D(),{hdb_errors:q2}=Z(),{getDatabases:OC}=(ge(),ee(xe)),F2="IS NULL",vs="There was a problem performing this search. Please check the logs and try again.";H2(cr);var Kp=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 s=await this._checkEmptySQL();if(!we.isEmptyOrZeroLength(s))return ue.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw ue.error("Error thrown from checkEmptySQL in SQLSearch class method search."),ue.error(s),new Error(vs)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw ue.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),ue.error(s),new Error(vs)}if(Object.keys(this.data).length===0)return ue.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw ue.error("Error thrown from processJoins in SQLSearch class method search."),ue.error(s),new Error(vs)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw ue.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),ue.error(s),new Error(vs)}try{return t=await this._finalSQL(),t}catch(s){throw ue.error("Error thrown from finalSQL in SQLSearch class method search."),ue.error(s),new Error(vs)}}_getColumns(){let t=new td(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(AC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Xc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=OC()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__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 td(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!we.isEmpty(r)&&r.right)if(we.isNotEmptyAndHasValue(r.right.value)){let s=we.autoCast(r.right.value);[!0,!1].indexOf(s)>=0&&(r.right=new cr.yy.LogicValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=we.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new cr.yy.LogicValue({value:i}):s instanceof cr.yy.StringValue&&we.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new cr.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 td(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!we.isEmpty(x2.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)?s.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)s.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(we.isEmptyOrZeroLength(this.all_table_attributes)&&we.isEmptyOrZeroLength(this.statement.from)&&we.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Xc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(we.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);we.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(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 cr.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 s=this._findColumn(r);s&&this.fetch_attributes.push(AC(s))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(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(F2)>-1&&this.tables.forEach(n=>{let i={columnid:OC()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Xc.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,_=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!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 sa.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(l){throw ue.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),ue.error(l),new Error(vs)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await sa.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),ue.error(l),new Error(vs)}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 sa.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...s[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]):(this.data[i].__merged_data[p]=[...s[i]],this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),ue.error(l),new Error(vs)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await sa.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw ue.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),ue.error(l),new Error(vs)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof cr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new cr.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new cr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let n=t.is_func?new cr.yy.FuncValue:new cr.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,n);f=await cr.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 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=Xc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,R=p.length;S<R;S++){let I=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[I]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new td(this.columns);for(let{node:i}of n)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&s.push(o)}}s=Xc.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw ue.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),ue.error(i),new Error(vs)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await sa.getDataByHash(c),_=n.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=n.columns[h],S=E[p]===void 0?null:E[p];this.data[s].__merged_data[f].push(S)}}}}catch(r){throw 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(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let s;try{let n=this._buildSQL();ue.trace(`Final SQL: ${n}`),s=await cr.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),ue.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw ue.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),ue.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return ue.error(q2.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(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=n[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;s=s.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;s=s.replace(u,_)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await sa.getDataByValue(i);for(let[c,u]of o)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(o){throw ue.error("There was an error when processing this SQL operation. Check your logs"),ue.error(o),new Error(vs)}}return Object.values(Object.values(this.data)[0].__merged_data)}};bC.exports=Kp});var es=T((X_e,yC)=>{"use strict";var G2=cb();yC.exports={searchByConditions:V2,searchByHash:$2,searchByValue:Y2,search:K2};var Wp=ws(),{transformReq:Qp}=z(),k2=NC();async function V2(e){return Qp(e),Wp.searchByConditions(e)}a(V2,"searchByConditions");async function $2(e){Qp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Wp.searchByHash(e))r&&t.push(r);return t}a($2,"searchByHash");async function Y2(e){Qp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Wp.searchByValue(e))t.push(r);return t}a(Y2,"searchByValue");function K2(e,t){try{let r=new G2(e);r.validate(),new k2(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(K2,"search")});var rd=T((Z_e,IC)=>{"use strict";var W2=ws();IC.exports={writeTransaction:Q2};function Q2(e,t,r){return W2.writeTransaction(e,t,r)}a(Q2,"writeTransaction")});var LC=T((rde,DC)=>{"use strict";var z2=es(),J2=Rn(),wC=G(),X2=Lr(),tde=rd(),j2=require("clone"),Jp=require("alasql"),Z2=ed(),CC=require("util"),e4=CC.promisify(J2.getTableSchema),t4=CC.promisify(z2.search),r4=D(),zp=z();Z2(Jp);DC.exports={update:n4};var s4="There was a problem performing this update. Please check the logs and try again.";async function n4({statement:e,hdb_user:t}){let r=await e4(e.table.databaseid,e.table.tableid),s=i4(e.columns);zp.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=j2(n),c=zp.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=Jp.parse(u).statements[0],l=await t4(_),d=o4(s,l);return a4(o,d,t)}a(n4,"update");function i4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=Jp.compile(`SELECT ${r.expression.toString()} AS [${r4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw wC.error(t),new Error(s4)}}a(i4,"createUpdateRecord");function o4(e,t){return zp.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(o4,"buildUpdateRecords");async function a4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await X2.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){wC.error(`Error delete new_attributes from update response: ${i}`)}return n}a(a4,"updateRecords")});var MC=T((ode,UC)=>{var c4=require("alasql"),u4=es(),l4=G(),_4=ws(),jp=require("util"),Xp=z(),d4=D(),f4=Rn(),nde=rd(),ide=Lr(),E4="record",h4="successfully deleted",m4=jp.callbackify(g4),p4=jp.promisify(u4.search),S4=jp.promisify(f4.getTableSchema);UC.exports={convertDelete:m4};function T4(e){return`${e.deleted_hashes.length} ${E4}${e.deleted_hashes.length===1?"":"s"} ${h4}`}a(T4,"generateReturnMessage");async function g4({statement:e,hdb_user:t}){let r=await S4(e.table.databaseid,e.table.tableid);Xp.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=Xp.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=c4.parse(o).statements[0],u={operation:d4.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await p4(c);let _=await _4.deleteRecords(u);return Xp.isEmptyOrZeroLength(_.message)&&(_.message=T4(_)),delete _.txn_time,_}catch(_){throw l4.error(_),_.hdb_code?_.message:_}}a(g4,"convertDelete")});var xC=T((cde,HC)=>{"use strict";var R4=jn(),{hdb_errors:PC}=Z(),{getDatabases:vC}=(ge(),ee(xe));HC.exports={checkSchemaExists:BC,checkSchemaTableExists:A4,schema_describe:R4};async function BC(e){if(!vC()[e])return PC.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(BC,"checkSchemaExists");async function A4(e,t){let r=await BC(e);if(r)return r;if(!vC()[e][t])return PC.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(A4,"checkSchemaTableExists")});var jc=T((lde,O4)=>{O4.exports={name:"harperdb",version:"4.3.0-alpha.2",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.2",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 ru={};$e(ru,{addAnalyticsListener:()=>tu,recordAction:()=>qr,recordActionBinary:()=>ss,setAnalyticsEnabled:()=>b4});function b4(e){QC=e}function qr(e,t,r,s,n){if(!QC)return;let i=t+(r?"-"+r:"");s!==void 0&&(i+="-"+s),n!==void 0&&(i+="-"+n);let o=id.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:s,type:n},id.set(i,o)}sd||N4()}function ss(e,t,r,s,n){qr(!!e,t,r,s,n)}function tu(e){XC.push(e)}function N4(){sd=performance.now(),setTimeout(async()=>{let e=performance.now()-sd;sd=0;let t=[],r={time:Date.now(),period:e,threadId:Zi.threadId,metrics:t};for(let[n,i]of id){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 ZC()}let s=process.memoryUsage();t.push({metric:"memory",threadId:Zi.threadId,byThread:!0,...s});for(let n of XC)n(t);id=new Map,Zi.parentPort?Zi.parentPort.postMessage({type:JC,report:r}):rD({report:r})},zC).unref()}async function y4(e,t=6e4){let r=tS(),s=eD(),n;for(let h of s.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){n=h.value.time;break}if(Date.now()-t<n)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:p}of r.primaryStore.getRange({start:n||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:S,threadId:R}=p;for(let I of S||[]){let{path:w,method:B,type:K,metric:q,count:P,total:Q,distribution:Y,threads:J,...re}=I;P||(P=1);let Ie=q+(w?"-"+w:"");B!==void 0&&(Ie+="-"+B),K!==void 0&&(Ie+="-"+K);let se=o.get(Ie);if(se){if(se.threads){let de=se.threads[R];if(de)se=de;else{se.threads[R]=Object.assign({},re);continue}}se.count||(se.count=1);let ut=se.count;for(let de in re){let lt=re[de];typeof lt=="number"&&(se[de]=(se[de]*ut+lt*P)/(ut+P))}se.count+=P,Q>=0&&(se.total+=Q,se.ratio=se.total/se.count)}else se=Object.assign({period:t},I),delete se.distribution,o.set(Ie,se),se.byThread&&(se.threads=[],se.threads[R]=Object.assign({},re),u.push(se));if(Y){Y=Y.map(de=>typeof de=="number"?{value:de,count:1}:de);let ut=c.get(Ie);ut?ut.push(...Y):c.set(Ie,Y)}}await ZC()}for(let h of u){let{path:p,method:S,type:R,metric:I,count:w,total:B,distribution:K,threads:q,...P}=h;q=q.filter(Q=>Q);for(let Q in P){if(typeof h[Q]!="number")continue;let Y=0;for(let J of q){let re=J[Q];typeof re=="number"&&(Y+=re)}h[Q]=Y}h.count=q.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((de,lt)=>de.value>lt.value?1:-1);let R=S.count-1,I=[],w=0,B=0,K;for(let de of jC){let lt=R*de;for(;w<lt;)K=p[B++],w+=K.count,B===1&&w--;let gs=p[B>1?B-2:0];K||(K=p[0]),I.push(K.value-(K.value-gs.value)*(w-lt)/K.count)}let[q,P,Q,Y,J,re,Ie,se,ut]=I;Object.assign(S,{p1:q,p10:P,p25:Q,median:Y,p75:J,p90:re,p95:Ie,p99:se,p999:ut})}let l;for(let[h,p]of o)p.id=(0,nd.getNextMonotonicTime)(),p.time=_,s.primaryStore.put(p.id,p,{append:!0}).then(S=>{S||s.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,nd.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-qC,active:E-FC,time:d,...process.memoryUsage()};s.primaryStore.put(h,p,{append:!0}).then(S=>{S||s.primaryStore.put(h,p)})}qC=f,FC=E}async function GC(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function tS(){return kC||(kC=dt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function eD(){return VC||(VC=dt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function C4(){tD=!0;let e=(0,eu.get)(eS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await y4(zC,e),await GC(tS(),I4),await GC(eD(),w4)},Math.min(e/2,2147483647)).unref()}function rD(e,t){let r=e.report;r.threadId=t?.threadId||Zi.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&($C+=s.mean*s.count);r.totalBytesProcessed=$C,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(YC.get(t))}),YC.set(t,t.performance.eventLoopUtilization())),r.id=(0,nd.getNextMonotonicTime)(),tS().primaryStore.put(r.id,r),tD||C4(),D4&&(sD=U4(r))}async function U4(e){if(await sD,!oi){let r=(0,Zc.dirname)((0,WC.getLogFilePath)());try{oi=await(0,Zp.open)((0,Zc.join)(r,"analytics.log"),"r+")}catch{oi=await(0,Zp.open)((0,Zc.join)(r,"analytics.log"),"w+")}}let t=(await oi.stat()).size;if(t>L4){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
|
|
6
|
+
`)},hY="certificate.pem",mY="privateKey.pem",pY="ca.pem";ty.exports={CERTIFICATE_VALUES:EY,CERTIFICATE_PEM_NAME:hY,PRIVATEKEY_PEM_NAME:mY,CA_PEM_NAME:pY}});var Fm=T((Oue,ay)=>{"use strict";var oy=require("fs-extra"),ue=require("joi"),SY=require("os"),{boolean:ve,string:ss,number:Pt,array:qm}=ue.types(),{totalmem:sy}=require("os"),Gi=require("path"),TY=V(),w_=J(),Aue=ry(),ny=L(),gY=Ze(),iy="log",RY="components",AY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",OY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",bY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",NY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",yY="rootPath config parameter is undefined",wY="clustering.enabled config parameter is undefined",ki=Pt.min(0).required(),I_=qm.items({host:ss.required(),port:ki}).empty(null),Ws;ay.exports={configValidator:IY,routesValidator:PY,route_constraints:I_};function IY(e){if(Ws=e.rootPath,w_.isEmpty(Ws))throw yY;let t=ve.required(),r=Pt.min(0).max(1e3).empty(null).default(UY),s=ss.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Mc),n=ss.optional().empty(null),i=ss.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ue.string().empty(null).default(Mc),c=ue.custom(DY).empty(null).default(Mc),u=e.clustering?.enabled;if(w_.isEmpty(u))throw wY;let _;return u===!0?_=ue.object({enabled:t,hubServer:ue.object({cluster:ue.object({name:ue.required().empty(null),network:ue.object({port:ki,routes:I_}).required()}).required(),leafNodes:ue.object({network:ue.object({port:ki}).required()}).required(),network:ue.object({port:ki}).required()}).required(),leafServer:ue.object({network:ue.object({port:ki,routes:I_}).required(),streams:ue.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:ue.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:ve.optional(),databaseLevel:ve.optional(),tls:ue.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:ve.required(),verify:ve.optional()}),user:ss.optional().empty(null)}).required():_=ue.object({enabled:t,tls:ue.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:ve.required()})}).required(),ue.object({authentication:ue.object({authorizeLocal:ve,cacheTTL:Pt.required(),enableSessions:ve}),analytics:ue.object({aggregatePeriod:Pt}),componentsRoot:s.optional(),clustering:_,localStudio:ue.object({enabled:t}).required(),logging:ue.object({auditAuthEvents:ue.object({logFailed:ve,logSuccessful:ve}),file:ve.required(),level:ue.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ue.object({enabled:ve.optional(),compress:ve.optional(),interval:ss.custom(MY).optional().empty(null),maxSize:ss.custom(LY).optional().empty(null),path:ss.optional().empty(null).default(Mc)}).required(),root:s,stdStreams:ve.required(),auditLog:ve.required()}).required(),operationsApi:ue.object({network:ue.object({cors:ve.optional(),corsAccessList:qm.optional(),headersTimeout:Pt.min(1).optional(),keepAliveTimeout:Pt.min(1).optional(),port:Pt.optional().empty(null),domainSocket:ue.optional().empty("hdb/operations-server").default(Mc),securePort:Pt.optional().empty(null),timeout:Pt.min(1).optional()}).optional(),tls:ue.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:ss.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ue.object({network:ue.object({port:ki,securePort:ki,mtls:ue.alternatives([ve.optional(),ue.object({user:ss.optional(),certificateAuthority:n,required:ve.optional()})])}).required(),webSocket:ve.optional(),requireAuthentication:ve.optional()}),http:ue.object({compressionThreshold:Pt.optional(),cors:ve.optional(),corsAccessList:qm.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:ue.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:ue.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:ss.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(IY,"configValidator");function CY(e){return oy.existsSync(e)?null:`Specified path ${e} does not exist.`}a(CY,"doesPathExist");function DY(e,t){ue.assert(e,ss.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=CY(e);if(r)return t.message(r)}a(DY,"validatePath");function LY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(AY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(bY):e}a(LY,"validateRotationMaxSize");function MY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(OY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(NY):e}a(MY,"validateRotationInterval");function UY(e,t){let r=t.state.path.join("."),s=SY.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||sy();return i=Math.round(Math.min(i,sy())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),TY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(UY,"setDefaultThreads");function Mc(e,t){let r=t.state.path.join(".");if(!w_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(w_.isEmpty(Ws))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Gi.join(Ws,RY);case"logging.root":return Gi.join(Ws,iy);case"clustering.leafServer.streams.path":return Gi.join(Ws,"clustering","leaf");case"storage.path":let s=Gi.join(Ws,ny.LEGACY_DATABASES_DIR_NAME);return oy.existsSync(s)?s:Gi.join(Ws,ny.DATABASES_DIR_NAME);case"logging.rotation.path":return Gi.join(Ws,iy);case"operationsApi.network.domainSocket":return r==null?null:Gi.join(Ws,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Mc,"setDefaultRoot");function PY(e){let t=ue.object({routes:I_});return gY.validateBySchema({routes:e},t)}a(PY,"routesValidator")});var vr=T((yue,my)=>{"use strict";var Pr=L(),vt=J(),bt=V(),{configValidator:vY,routesValidator:cy}=Fm(),ir=require("fs-extra"),BY=require("yaml"),Is=require("path"),HY=require("is-number"),ly=require("properties-reader"),xY=require("lodash"),{handleHDBError:qY}=Z(),{HTTP_STATUS_CODES:FY,HDB_ERROR_MSGS:C_}=Ir(),Nue=require("minimist"),{server:GY}=(rr(),ee(Di)),{DATABASES_PARAM_CONFIG:Uc,CONFIG_PARAMS:Ur,CONFIG_PARAM_MAP:Cs}=Pr,kY="Unable to get config value because config is uninitialized",VY="Config successfully initialized",$Y="Error backing up config file",YY="Empty parameter sent to getConfigValue",_y=Is.join(Pr.PACKAGE_ROOT,"config","yaml",Pr.HDB_DEFAULT_CONFIG_FILE),KY="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",uy={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"},D_,Nt,L_;my.exports={createConfigFile:WY,getDefaultConfig:QY,getConfigValue:fy,initConfig:km,flattenConfig:Vo,updateConfigValue:Ey,updateConfigObject:JY,getConfiguration:ZY,setConfiguration:eK,readConfigFile:$m,getClusteringRoutes:tK,initOldConfig:hy,getConfigFromFile:rK,getConfigFilePath:Vi,addConfig:sK,deleteConfigFromFile:nK,getConfigObj:iK};function WY(e){let t=ri(_y);D_=Vo(t.toJSON());let r;for(let o in e){let c=Cs[o.toLowerCase()];if(c===Ur.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=Gm(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){bt.error(l)}}}r&&dy(t,r),Vm(t);let s=t.toJSON();Nt=Vo(s);let n=t.getIn(["rootPath"]),i=Is.join(n,Pr.HDB_CONFIG_FILE);ir.createFileSync(i),ir.writeFileSync(i,String(t)),bt.trace(`Config file written to ${i}`)}a(WY,"createConfigFile");function dy(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!vt.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(Uc.TABLES))for(let i in s[n][Uc.TABLES])for(let o in s[n][Uc.TABLES][i]){let c=s[n][Uc.TABLES][i][o],u=[Ur.DATABASES,n,Uc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[Ur.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){bt.error("Error parsing schemas CLI/env config arguments",s)}}a(dy,"setSchemasConfig");function QY(e){if(D_===void 0){let r=ri(_y);D_=Vo(r.toJSON())}let t=Cs[e.toLowerCase()];if(t!==void 0)return D_[t.toLowerCase()]}a(QY,"getDefaultConfig");function fy(e){if(e==null){bt.error(YY);return}if(Nt===void 0){bt.trace(kY);return}let t=Cs[e.toLowerCase()];if(t!==void 0)return Nt[t.toLowerCase()]}a(fy,"getConfigValue");function Vi(e=vt.getPropsFilePath()){let t=vt.getEnvCliRootPath();return t?Is.join(t,Pr.HDB_CONFIG_FILE):ly(e).get(Pr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Vi,"getConfigFilePath");function km(e=!1){if(Nt===void 0||e){let t;if(!vt.noBootFile()){t=vt.getPropsFilePath();try{ir.accessSync(t,ir.constants.F_OK|ir.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Vi(t),s;if(r.includes("config/settings.js"))try{hy(r);return}catch(i){if(i.code!==Pr.NODE_ERROR_CODES.ENOENT)throw i}try{s=ri(r)}catch(i){if(i.code===Pr.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}`)}zY(s,r),Vm(s);let n=s.toJSON();if(GY.config=n,Nt=Vo(n),Nt.logging_rotation_rotate)for(let i in uy)Nt[i]&&bt.error(`Config ${uy[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(VY)}}a(km,"initConfig");function zY(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Is.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Is.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Is.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(bt.trace("Updating config file with missing config params"),ir.writeFileSync(t,String(e)))}a(zY,"checkForUpdatedConfig");function Vm(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=vY(t);if(r.error)throw C_.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(Vm,"validateConfig");function JY(e,t){Nt===void 0&&(Nt={});let r=Cs[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(JY,"updateConfigObject");function Ey(e,t,r=void 0,s=!1,n=!1,i=!1){Nt===void 0&&km();let o=fy(Cs.hdb_root),c=Is.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=Cs[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Gm(f,t);u.setIn([...E],h)}else for(let f in r){let E=Cs[f.toLowerCase()];if(E===Ur.HTTP_SECUREPORT&&r[f]===Nt[Ur.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Ur.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===Nt[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=Gm(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(g){bt.error(g)}}}_&&dy(u,_),Vm(u);let l=u.getIn(["rootPath"]),d=Is.join(l,Pr.HDB_CONFIG_FILE);s===!0&&jY(c,l),ir.writeFileSync(d,String(u)),n&&(Nt=Vo(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(Ey,"updateConfigValue");function jY(e,t){try{let r=Is.join(t,"backup",`${Pr.HDB_CONFIG_FILE}.bak`);ir.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error($Y),bt.error(r)}}a(jY,"backupConfigFile");var XY=["databases"];function Vo(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)),L_=e,r(e);function r(s){let n={};for(let i in s)if(s.hasOwnProperty(i))if(typeof s[i]=="object"&&s[i]!==null&&!Array.isArray(s[i])&&!XY.includes(i)){let o=r(s[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Ur[u.toUpperCase()]&&Cs[u]&&(n[Cs[u].toLowerCase()]=o[c]),n[u]=o[c]}}else n[i.toLowerCase()]=s[i];return n}a(r,"squashObj")}a(Vo,"flattenConfig");function Gm(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(HY(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(Gm,"castConfigValue");function ZY(){let e=vt.getPropsFilePath(),t=Vi(e);return ri(t).toJSON()}a(ZY,"getConfiguration");async function eK(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return Ey(void 0,void 0,n,!0),KY}catch(i){throw typeof i=="string"||i instanceof String?qY(i,i,FY.BAD_REQUEST,void 0,void 0,!0):i}}a(eK,"setConfiguration");function $m(){let e=vt.getPropsFilePath();try{ir.accessSync(e,ir.constants.F_OK|ir.constants.R_OK)}catch(s){if(!vt.noBootFile())throw bt.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Vi(e);return ri(t).toJSON()}a($m,"readConfigFile");function ri(e){return BY.parseDocument(ir.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ri,"parseYamlDoc");function tK(){let e=$m(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=vt.isEmptyOrZeroLength(t)?[]:t;let r=cy(t);if(r)throw C_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=vt.isEmptyOrZeroLength(s)?[]:s;let n=cy(s);if(n)throw C_.CONFIG_VALIDATION(n.message);if(!vt.isEmptyOrZeroLength(s)&&!vt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.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 C_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(tK,"getClusteringRoutes");function hy(e){let t=ly(e);Nt={};for(let r in Cs){let s=t.get(r.toUpperCase());if(vt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=Cs[r].toLowerCase();n===Ur.LOGGING_ROOT?Nt[n]=Is.dirname(s):Nt[n]=s}return Nt}a(hy,"initOldConfig");function rK(e){let t=$m();return xY.get(t,e.replaceAll("_","."))}a(rK,"getConfigFromFile");async function sK(e,t){let r=ri(Vi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await ir.writeFile(Vi(),String(r))}a(sK,"addConfig");function nK(e){let t=Vi(vt.getPropsFilePath()),r=ri(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Is.join(s,Pr.HDB_CONFIG_FILE);ir.writeFileSync(n,String(r))}a(nK,"deleteConfigFromFile");function iK(){return L_||(km(),L_)}a(iK,"getConfigObj")});var Sy=T((Iue,py)=>{"use strict";var M_=L(),U_=class{static{a(this,"BaseLicense")}constructor(t=0,r=M_.RAM_ALLOCATION_ENUM.DEFAULT,s=M_.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},Ym=class extends U_{static{a(this,"ExtendedLicense")}constructor(t=0,r=M_.RAM_ALLOCATION_ENUM.DEFAULT,s=M_.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};py.exports={BaseLicense:U_,ExtendedLicense:Ym}});var $i=T((Due,by)=>{"use strict";var Yo=require("fs-extra"),gy=y_(),Ry=require("crypto"),oK=require("moment"),aK=require("uuid").v4,Qt=V(),Wm=require("path"),cK=J(),si=L(),{totalmem:Ty}=require("os"),uK=Sy().ExtendedLicense,$o="invalid license key format",lK="061183",_K="mofi25",dK="aes-256-cbc",fK=16,EK=32,Ay=X();Ay.initSync();var Km;by.exports={validateLicense:Oy,generateFingerPrint:mK,licenseSearch:Jm,getLicense:TK,checkMemoryLimit:gK};function Qm(){return Wm.join(Ay.getHdbBasePath(),si.LICENSE_KEY_DIR_NAME,si.LICENSE_FILE_NAME)}a(Qm,"getLicenseDirPath");function hK(){let e=Qm();return Wm.join(e,si.LICENSE_FILE_NAME)}a(hK,"getLicenseFilePath");function zm(){let e=Qm();return Wm.join(e,si.REG_KEY_FILE_NAME)}a(zm,"getFingerPrintFilePath");async function mK(){let e=zm();try{return await Yo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await pK();throw Qt.error(`Error writing fingerprint file to ${e}`),Qt.error(t),new Error("There was an error generating the fingerprint")}}a(mK,"generateFingerPrint");async function pK(){let e=aK(),t=gy.hash(e),r=zm();try{await Yo.mkdirp(Qm()),await Yo.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Qt.error(`Error writing fingerprint file to ${r}`),Qt.error(s),new Error("There was an error generating the fingerprint")}return t}a(pK,"writeFingerprint");function Oy(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:si.RAM_ALLOCATION_ENUM.DEFAULT,version:si.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Qt.error("empty license key passed to validate."),r;let s=zm(),n=!1;try{n=Yo.statSync(s)}catch(i){Qt.error(i)}if(n){let i;try{i=Yo.readFileSync(s,"utf8")}catch{Qt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(_K),c=o[1];c=Buffer.concat([Buffer.from(c)],fK);let u=Buffer.concat([Buffer.from(i)],EK),_=Ry.createDecipheriv(dK,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=SK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error($o),Qt.error($o),new Error($o)}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($o),Qt.error($o),new Error($o)}else r.exp_date=l;r.exp_date<oK().valueOf()&&(r.valid_date=!1),gy.validate(o[1],`${lK}${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||Qt.error("Invalid licence"),r}a(Oy,"validateLicense");function SK(e,t){try{let r=Ry.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Qt.warn("Check old license failed")}}a(SK,"checkOldLicense");function Jm(){let e=new uK,t=[];try{t=Yo.readFileSync(hK(),"utf-8").split(si.NEW_LINE)}catch(r){r.code==="ENOENT"?Qt.info("no license file found"):Qt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(cK.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=Oy(n.license_key,n.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(n){Qt.error("There was an error parsing the license string."),Qt.error(n),e.ram_allocation=si.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Km=e,e}a(Jm,"licenseSearch");async function TK(){return Km||await Jm(),Km}a(TK,"getLicense");function gK(){let e=Jm().ram_allocation,t=process.constrainedMemory?.()||Ty();if(t=Math.round(Math.min(t,Ty())/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(gK,"checkMemoryLimit")});var ns=T((vue,Fy)=>{"use strict";var Iy="username is required",Cy="nothing to update, must supply active, role or password to update",Dy="password cannot be an empty string",Ly="If role is specified, it cannot be empty.",My="active must be true or false";Fy.exports={addUser:CK,alterUser:DK,dropUser:MK,getSuperUser:BK,userInfo:UK,listUsers:v_,listUsersExternal:PK,setUsersToGlobal:Wo,findAndValidateUser:xy,getClusterUser:HK,USERNAME_REQUIRED:Iy,ALTERUSER_NOTHING_TO_UPDATE:Cy,EMPTY_PASSWORD:Dy,EMPTY_ROLE:Ly,ACTIVE_BOOLEAN:My};var Uy=Mr(),RK=ti(),Zm=y_(),Py=XN(),vy=rs(),ep=Rn(),Br=J(),By=require("validate.js"),ge=V(),{promisify:AK}=require("util"),tp=Tn(),Ny=L(),yy=Ge(),OK=vr(),Mue=X(),Uue=$i(),bK=vi(),{table:Pue}=(Ae(),ee(Fe)),{handleHDBError:Qs,hdb_errors:NK}=Z(),{HTTP_STATUS_CODES:zs,AUTHENTICATION_ERROR_MSGS:jm,HDB_ERROR_MSGS:Ko}=NK,{UserEventMsg:rp}=Ds(),Xm=require("lodash"),{server:sp}=(rr(),ee(Di)),yK=V();sp.getUser=(e,t)=>xy(e,t,t!=null);var Hy={username:!0,active:!0,role:!0,password:!0},wy=new Map,P_=vy.searchByValue,wK=vy.searchByHash,IK=AK(RK.delete);async function CK(e){let t=By.cleanAttributes(e,Hy),r=Py.addUserValidation(t);if(r)throw Qs(new Error,r.message,zs.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await P_(s),n=n&&Array.from(n)}catch(u){throw ge.error("There was an error searching for a role in add user"),ge.error(u),u}if(!n||n.length<1)throw Qs(new Error,Ko.ROLE_NAME_NOT_FOUND(t.role),zs.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw Qs(new Error,Ko.DUP_ROLES_FOUND(t.role),zs.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=tp.encrypt(t.password)),t.password=Zm.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await Uy.insert(i)}catch(u){throw ge.error("There was an error searching for a user."),ge.error(u),u}ge.debug(o);try{await Wo()}catch(u){throw ge.error("Got an error setting users to global"),ge.error(u),u}if(o.skipped_hashes.length===1)throw Qs(new Error,Ko.USER_ALREADY_EXISTS(t.username),zs.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],ep.signalUserChange(new rp(process.pid)),`${c.username} successfully added`}a(CK,"addUser");async function DK(e){let t=By.cleanAttributes(e,Hy);if(Br.isEmptyOrZeroLength(t.username))throw new Error(Iy);if(Br.isEmptyOrZeroLength(t.password)&&Br.isEmptyOrZeroLength(t.role)&&Br.isEmptyOrZeroLength(t.active))throw new Error(Cy);if(!Br.isEmpty(t.password)&&Br.isEmptyOrZeroLength(t.password.trim()))throw new Error(Dy);if(!Br.isEmpty(t.active)&&!Br.isBoolean(t.active))throw new Error(My);let r=LK(t.username);if(!Br.isEmpty(t.password)&&!Br.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=tp.encrypt(t.password)),t.password=Zm.hash(t.password)),t.role==="")throw new Error(Ly);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 P_(i)||[])}catch(c){throw ge.error("Got an error searching for a role."),ge.error(c),c}if(!o||o.length===0){let c=Ko.ALTER_USER_ROLE_NOT_FOUND(t.role);throw ge.error(c),Qs(new Error,c,zs.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Ko.ALTER_USER_DUP_ROLES(t.role);throw ge.error(c),Qs(new Error,c,zs.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await Uy.update(s)}catch(i){throw ge.error("Error during update."),ge.error(i),i}try{await Wo()}catch(i){throw ge.error("Got an error setting users to global"),ge.error(i),i}return ep.signalUserChange(new rp(process.pid)),n}a(DK,"alterUser");function LK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(LK,"isClusterUser");async function MK(e){try{let t=Py.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 Qs(new Error,Ko.USER_NOT_EXIST(e.username),zs.NOT_FOUND,void 0,void 0,!0);let s;try{s=await IK(r)}catch(n){throw ge.error("Got an error deleting a user."),ge.error(n),n}ge.debug(s);try{await Wo()}catch(n){throw ge.error("Got an error setting users to global."),ge.error(n),n}return ep.signalUserChange(new rp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(MK,"dropUser");async function UK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Xm.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await wK(r)}catch(n){throw ge.error("Got an error searching for a role."),ge.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw ge.error(r),r}return t}a(UK,"userInfo");async function PK(){let e;try{e=await v_()}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(PK,"listUsersExternal");async function v_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await P_(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]=Xm.cloneDeep(o);if(Object.keys(r).length===0)return null;let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await P_(s)}catch(o){throw ge.error("Got an error searching for users."),ge.error(o),o}let i=new Map;for(let o of n)o=Xm.cloneDeep(o),o.role=r[o.role],vK(o.role),i.set(o.username,o);return i}catch(e){throw ge.error("got an error listing users"),ge.error(e),Br.errorizeMessage(e)}return null}a(v_,"listUsers");function vK(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(bK)){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(vK,"appendSystemTablesToRole");async function Wo(){try{let e=await v_();global.hdb_users=e}catch(e){throw ge.error(e),e}}a(Wo,"setUsersToGlobal");async function xy(e,t,r=!0){global.hdb_users||await Wo();let s=global.hdb_users.get(e);if(!s){if(!r)return{username:e};throw Qs(new Error,jm.GENERIC_AUTH_FAIL,zs.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw Qs(new Error,jm.USER_INACTIVE,zs.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(wy.get(t)===s.password)return n;if(Zm.validate(s.password,t))wy.set(t,s.password);else throw Qs(new Error,jm.GENERIC_AUTH_FAIL,zs.UNAUTHORIZED,void 0,void 0,!0)}return n}a(xy,"findAndValidateUser");async function BK(){global.hdb_users||await Wo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(BK,"getSuperUser");async function HK(){let e=await v_(),t=OK.getConfigFromFile(Ny.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Br.isEmpty(r)&&r?.role?.role===Ny.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=tp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+yy.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+yy.SERVER_SUFFIX.ADMIN,r}a(HK,"getClusterUser");var qy=[];sp.invalidateUser=function(e){for(let t of qy)try{t(e)}catch(r){yK.error("Error invalidating user",r)}};sp.onInvalidatedUser=function(e){qy.push(e)}});var vc=T((que,$y)=>{"use strict";var Yi=V(),Hr=L(),xK=TN(),Hue=gn(),xue=Xn(),qK=ns(),{validateEvent:Gy}=Ds(),Pc=ws(),FK=require("process"),{resetDatabases:GK}=(Ae(),ee(Fe)),kK={[Hr.ITC_EVENT_TYPES.SCHEMA]:VK,[Hr.ITC_EVENT_TYPES.USER]:Vy};async function VK(e){let t=Gy(e);if(t){Yi.error(t);return}Yi.trace("ITC schemaHandler received schema event:",e),await xK(e.message),await $K(e.message)}a(VK,"schemaHandler");async function $K(e){try{Pc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Pc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Pc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=GK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Yi.error(t)}}a($K,"syncSchemaMetadata");var ky=[];async function Vy(e){try{try{Pc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Pc.resetReadTxn(Hr.SYSTEM_SCHEMA_NAME,Hr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Yi.warn(r)}let t=Gy(e);if(t){Yi.error(t);return}Yi.trace(`ITC userHandler ${Hr.HDB_ITC_CLIENT_PREFIX}${FK.pid} received user event:`,e),await qK.setUsersToGlobal();for(let r of ky)r()}catch(t){Yi.error(t)}}a(Vy,"userHandler");Vy.addListener=function(e){ky.push(e)};$y.exports=kK});var Ds=T((Yue,Ky)=>{"use strict";var Gue=V(),np=J(),YK=L(),{ITC_ERRORS:Bc}=Ir(),{parentPort:kue,threadId:KK,isMainThread:WK,workerData:Vue}=require("worker_threads"),{onMessageFromWorkers:QK,broadcast:$ue,broadcastWithAcknowledgement:zK}=Qe();Ky.exports={sendItcEvent:JK,validateEvent:Yy,SchemaEventMsg:jK,UserEventMsg:XK};var B_;QK(async(e,t)=>{B_=B_||vc(),Yy(e),B_[e.type]&&await B_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function JK(e){return!WK&&e.message&&(e.message.originator=KK),zK(e)}a(JK,"sendItcEvent");function Yy(e){if(typeof e!="object")return Bc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||np.isEmpty(e.type))return Bc.MISSING_TYPE;if(!e.hasOwnProperty("message")||np.isEmpty(e.message))return Bc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||np.isEmpty(e.message.originator))return Bc.MISSING_ORIGIN;if(YK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Bc.INVALID_EVENT(e.type)}a(Yy,"validateEvent");function jK(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(jK,"SchemaEventMsg");function XK(e){this.originator=e}a(XK,"UserEventMsg")});var Rn=T((Que,Jy)=>{"use strict";var Wy=L(),Wue=J(),H_=V(),Qy=mN(),Qo,{sendItcEvent:zy}=Ds();function ZK(e){try{H_.trace("signalSchemaChange called with message:",e),Qo=Qo||vc();let t=new Qy(Wy.ITC_EVENT_TYPES.SCHEMA,e);return Qo.schema(t),zy(t)}catch(t){H_.error(t)}}a(ZK,"signalSchemaChange");function eW(e){try{H_.trace("signalUserChange called with message:",e),Qo=Qo||vc();let t=new Qy(Wy.ITC_EVENT_TYPES.USER,e);return Qo.user(t),zy(t)}catch(t){H_.error(t)}}a(eW,"signalUserChange");Jy.exports={signalSchemaChange:ZK,signalUserChange:eW}});var x_=T((Jue,Xy)=>{"use strict";var jy=J(),tW=L(),rW=V(),sW=h_(),nW=E_(),iW=Rn(),{SchemaEventMsg:oW}=Ds(),aW="already exists in";Xy.exports=cW;async function cW(e,t,r){if(jy.isEmptyOrZeroLength(r))return r;let s=[];jy.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await uW(e,t.schema,t.name,i)})),n}a(cW,"lmdbCheckForNewAttributes");async function uW(e,t,r,s){let n=new nW(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await lW(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(aW))rW.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(uW,"createNewAttribute");async function lW(e){let t;return t=await sW(e),iW.signalSchemaChange(new oW(process.pid,tW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(lW,"createAttribute")});var zo=T((Xue,Zy)=>{"use strict";var ip=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};Zy.exports=ip});var tw=T((ele,ew)=>{"use strict";var _W=zo(),dW=L().OPERATIONS_ENUM,op=class extends _W{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(dW.INSERT,r,s,n,i),this.records=t}};ew.exports=op});var sw=T((rle,rw)=>{"use strict";var fW=zo(),EW=L().OPERATIONS_ENUM,ap=class extends fW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(EW.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};rw.exports=ap});var iw=T((nle,nw)=>{"use strict";var hW=zo(),mW=L().OPERATIONS_ENUM,cp=class extends hW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(mW.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};nw.exports=cp});var aw=T((ole,ow)=>{"use strict";var pW=zo(),SW=L().OPERATIONS_ENUM,up=class extends pW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(SW.DELETE,s,n,t,i),this.original_records=r}};ow.exports=up});var Hc=T((ule,_w)=>{"use strict";var cle=require("path"),cw=ze(),TW=tw(),gW=sw(),RW=iw(),AW=aw(),Jo=ht(),uw=J(),{CONFIG_PARAMS:OW}=L(),lw=X();lw.initSync();var q_=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:bW}=Xe();_w.exports=NW;async function NW(e,t){if(lw.get(OW.LOGGING_AUDITLOG)===!1)return;let r=bW(e.schema,e.table),s=await cw.openEnvironment(r,e.table,!0),n=yW(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){cw.initializeDBIs(s,Jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Jo.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[Jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[Jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),uw.isEmpty(n.user_name)||s.dbis[Jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[Jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(NW,"writeTransaction");function yW(e,t){let r=uw.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===q_.INSERT)return new TW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.UPDATE)return new gW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.UPSERT)return new RW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===q_.DELETE)return new AW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(yW,"createTransactionObject")});var lp=T((dle,dw)=>{"use strict";var wW=Nc(),_le=yc(),xc=L(),IW=Dc(),CW=Fo().insertRecords,DW=ze(),LW=V(),MW=x_(),{getSchemaPath:UW}=Xe(),PW=Hc();dw.exports=vW;async function vW(e){try{let{schema_table:t,attributes:r}=wW(e);IW(e,r,t.hash_attribute),e.schema!==xc.SYSTEM_SCHEMA_NAME&&(r.includes(xc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(xc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(xc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(xc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await MW(e.hdb_auth_header,t,r),n=UW(e.schema,e.table),i=await DW.openEnvironment(n,e.table),o=await CW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await PW(e,o)}catch(c){LW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(vW,"lmdbCreateRecords")});var hw=T((Ele,Ew)=>{"use strict";var fw=L(),BW=lp(),HW=yc(),xW=require("fs-extra"),{getSchemaPath:qW}=Xe();Ew.exports=FW;async function FW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new HW(fw.SYSTEM_SCHEMA_NAME,fw.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await BW(r),await xW.mkdirp(qW(e.schema))}a(FW,"lmdbCreateSchema")});var pw=T((mle,mw)=>{"use strict";var _p=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};mw.exports=_p});var Rw=T((Rle,gw)=>{"use strict";var Sw=ze(),dp=Cr(),fp=Ir().LMDB_ERRORS_ENUM,GW=ht(),Tw=V(),Sle=J(),kW=require("lmdb"),VW=pw(),$W=L(),{OVERFLOW_MARKER:Tle,MAX_SEARCH_KEY_LENGTH:gle}=GW,YW=$W.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function KW(e,t,r,s){if(dp.validateEnv(e),t===void 0)throw new Error(fp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(fp.IDS_REQUIRED):new Error(fp.IDS_MUST_BE_ITERABLE);try{let n=Sw.listDBIs(e);Sw.initializeDBIs(e,t,n);let i=new VW,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||s&&h[YW]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,kW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let g=n[S];if(!h.hasOwnProperty(g)||g===t)continue;let A=e.dbis[g],b=h[g];if(b!=null)try{let v=dp.getIndexedValues(b);if(v)for(let G=0,H=v.length;G<H;G++)A.remove(v[G],o)}catch{Tw.warn(`cannot delete from attribute: ${g}, ${b}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){Tw.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=dp.getNextMonotonicTime(),i}catch(n){throw n}}a(KW,"deleteRecords");gw.exports={deleteRecords:KW}});var qc=T((Ole,Ow)=>{"use strict";var jo=J(),WW=Rw(),QW=ze(),{getSchemaPath:zW}=Xe(),JW=Hc(),jW=V();Ow.exports=XW;async function XW(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(jo.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(jo.isEmptyOrZeroLength(e.hash_values)&&!jo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];jo.isEmpty(u)||e.hash_values.push(u)}}if(jo.isEmptyOrZeroLength(e.hash_values))return Aw([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(jo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[s]:e.hash_values[c]}}let n=zW(e.schema,e.table),i=await QW.openEnvironment(n,e.table),o=await WW.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await JW(e,o)}catch(c){jW.error(`unable to write transaction due to ${c.message}`)}return Aw(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(XW,"lmdbDeleteRecords");function Aw(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(Aw,"createDeleteResponse")});var hp=T((yle,bw)=>{"use strict";var ZW=L(),Nle=Cr();function Ep(e,t){let r=Object.create(null);if(t.length===1&&ZW.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a(Ep,"parseRow");function eQ(e,t,r,s){let n=Ep(r,e);s.push(n)}a(eQ,"searchAll");function tQ(e,t,r,s){let n=Ep(r,e);s[t]=n}a(tQ,"searchAllToMap");function rQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(rQ,"iterateDBI");function Ki(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(Ki,"pushResults");function sQ(e,t,r,s,n,i){t.toString().endsWith(e)&&Ki(t,r,s,n,i)}a(sQ,"endsWith");function nQ(e,t,r,s,n,i){t.toString().includes(e)&&Ki(t,r,s,n,i)}a(nQ,"contains");function iQ(e,t,r,s,n,i){t>e&&Ki(t,r,s,n,i)}a(iQ,"greaterThanCompare");function oQ(e,t,r,s,n,i){t>=e&&Ki(t,r,s,n,i)}a(oQ,"greaterThanEqualCompare");function aQ(e,t,r,s,n,i){t<e&&Ki(t,r,s,n,i)}a(aQ,"lessThanCompare");function cQ(e,t,r,s,n,i){t<=e&&Ki(t,r,s,n,i)}a(cQ,"lessThanEqualCompare");bw.exports={parseRow:Ep,searchAll:eQ,searchAllToMap:tQ,iterateDBI:rQ,endsWith:sQ,contains:nQ,greaterThanCompare:iQ,greaterThanEqualCompare:oQ,lessThanCompare:aQ,lessThanEqualCompare:cQ,pushResults:Ki}});var Xo=T((Lle,Lw)=>{"use strict";var ni=ze(),Ile=V(),xr=Cr(),F_=ht(),dt=Ir().LMDB_ERRORS_ENUM,Cle=J(),uQ=L(),G_=hp(),{parseRow:lQ}=G_,Dle=require("lmdb"),{OVERFLOW_MARKER:Nw,MAX_SEARCH_KEY_LENGTH:_Q}=F_;function yw(e,t,r,s=!1,n=void 0,i=void 0){return Wi(e,t,r,(o,c)=>c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}a(yw,"iterateFullIndex");function Fc(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Wi(e,t,r,(l,d,f,E)=>{let A={transaction:l,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(A.values=!1,d.getRange(A).map(b=>({value:b}))):d.getRange(A)})}a(Fc,"iterateRangeBetween");function Wi(e,t,r,s){let n=e.database||e,i=ni.openDBI(n,r);i[F_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ni.openDBI(n,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=s(o,i,n,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Wi,"setupTransaction");function ww(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(Nw)){if(!n)if(r)n=ni.openDBI(e,r);else{let u=ni.listDBIs(e);for(let _=0,l=u.length;_<l&&(n=ni.openDBI(e,u[_]),!n[F_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(ww,"getOverflowCheck");function dQ(e,t,r,s=!1,n=void 0,i=void 0){if(xr.validateEnv(e),t===void 0)throw new Error(dt.HASH_ATTRIBUTE_REQUIRED);return Wi(e,t,t,(o,c,u)=>(k_(r),r=Gc(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(_=>lQ(_.value,r))))}a(dQ,"searchAll");function fQ(e,t,r,s=!1,n=void 0,i=void 0){if(xr.validateEnv(e),t===void 0)throw new Error(dt.HASH_ATTRIBUTE_REQUIRED);k_(r),r=Gc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of yw(e,t,t,s,n,i))o.set(c,G_.parseRow(u,r));return o}a(fQ,"searchAllToMap");function EQ(e,t,r=!1,s=void 0,n=void 0){if(xr.validateEnv(e),t===void 0)throw new Error(dt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=yw(e,void 0,t,r,s,n),c=o.transaction,u=ww(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(EQ,"iterateDBI");function hQ(e,t){if(xr.validateEnv(e),t===void 0)throw new Error(dt.HASH_ATTRIBUTE_REQUIRED);return ni.statDBI(e,t).entryCount}a(hQ,"countAll");function mQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Wi(e,t,r,(c,u,_,l)=>(s=xr.convertKeyValueToWrite(s),l===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(mQ,"equals");function pQ(e,t,r){return ii(e,t,r),ni.openDBI(e,t).getValuesCount(r)}a(pQ,"count");function SQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ii(e,r,s),Wi(e,null,r,(c,u)=>{s=xr.convertKeyValueToWrite(s);let _=!0;typeof s=="number"&&(_=!1);let l;if(n===!0){let d;for(let f of u.getKeys({transaction:c,start:s}))if(!f.startsWith(s)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(s))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(SQ,"startsWith");function TQ(e,t,r,s,n=!1,i=void 0,o=void 0){return Iw(e,t,r,s,n,i,o,!0)}a(TQ,"endsWith");function Iw(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return ii(e,r,s),Wi(e,null,r,(u,_,l,d)=>{let f=ww(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(E=>{let h=E.toString();return h.endsWith(Nw)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(s):S.includes(s))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(s):h.includes(s))?_[F_.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(Iw,"contains");function gQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Fc(e,t,r,s,u,n,i,o,!0,!1)}a(gQ,"greaterThan");function RQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Fc(e,t,r,s,u,n,i,o,!1,!1)}a(RQ,"greaterThanEqual");function AQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Fc(e,t,r,u,s,n,i,o,!1,!0)}a(AQ,"lessThan");function OQ(e,t,r,s,n=!1,i=void 0,o=void 0){ii(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Fc(e,t,r,u,s,n,i,o,!1,!1)}a(OQ,"lessThanEqual");function bQ(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(xr.validateEnv(e),r===void 0)throw new Error(dt.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(dt.START_VALUE_REQUIRED);if(n===void 0)throw new Error(dt.END_VALUE_REQUIRED);if(s=xr.convertKeyValueToWrite(s),n=xr.convertKeyValueToWrite(n),s>n)throw new Error(dt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Fc(e,t,r,s,n,i,o,c)}a(bQ,"between");function NQ(e,t,r,s){xr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(dt.HASH_ATTRIBUTE_REQUIRED);if(k_(r),r=Gc(n,r),s===void 0)throw new Error(dt.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=G_.parseRow(c,r)),o}a(NQ,"searchByHash");function yQ(e,t,r){xr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(dt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(dt.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(yQ,"checkHashExists");function wQ(e,t,r,s,n=[]){return Dw(e,t,r,s,n),Cw(e,t,r,s,n).map(i=>i[1])}a(wQ,"batchSearchByHash");function IQ(e,t,r,s,n=[]){Dw(e,t,r,s,n);let i=new Map;for(let[o,c]of Cw(e,t,r,s,n))i.set(o,c);return i}a(IQ,"batchSearchByHashToMap");function Cw(e,t,r,s,n=[]){return Wi(e,t,t,(i,o,c)=>{r=Gc(c,r);let u=r.length<3;return s.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,G_.parseRow(l,r)];n.push(_)}).filter(_=>_)})}a(Cw,"batchHashSearch");function Dw(e,t,r,s,n){if(xr.validateEnv(e),t===void 0)throw new Error(dt.HASH_ATTRIBUTE_REQUIRED);if(k_(r),s==null)throw new Error(dt.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(dt.IDS_MUST_BE_ITERABLE)}a(Dw,"initializeBatchSearchByHash");function k_(e){if(!Array.isArray(e))throw e===void 0?new Error(dt.FETCH_ATTRIBUTES_REQUIRED):new Error(dt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(k_,"validateFetchAttributes");function ii(e,t,r){if(xr.validateEnv(e),t===void 0)throw new Error(dt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(dt.SEARCH_VALUE_REQUIRED);if(r?.length>_Q)throw new Error(dt.SEARCH_VALUE_TOO_LARGE)}a(ii,"validateComparisonFunctions");function Gc(e,t){return t.length===1&&uQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ni.listDBIs(e)),t}a(Gc,"setGetWholeRowAttributes");Lw.exports={searchAll:dQ,searchAllToMap:fQ,count:pQ,countAll:hQ,equals:mQ,startsWith:SQ,endsWith:TQ,contains:Iw,searchByHash:NQ,setGetWholeRowAttributes:Gc,batchSearchByHash:wQ,batchSearchByHashToMap:IQ,checkHashExists:yQ,iterateDBI:EQ,greaterThan:gQ,greaterThanEqual:RQ,lessThan:AQ,lessThanEqual:OQ,between:bQ}});var Zo=T((Ule,Bw)=>{var Mw=require("lodash"),Uw=Ze(),Ee=require("joi"),CQ=J(),{hdb_schema_table:kc,checkValidTable:Pw,hdb_table:vw,hdb_database:V_}=Ys(),{handleHDBError:DQ,hdb_errors:LQ}=Z(),{getDatabases:MQ}=(Ae(),ee(Fe)),{HTTP_STATUS_CODES:UQ}=LQ,PQ=Ee.object({database:V_,schema:V_,table:vw,search_attribute:kc,search_value:Ee.any().required(),get_attributes:Ee.array().min(1).items(Ee.alternatives(kc,Ee.object())).optional(),desc:Ee.bool(),limit:Ee.number().integer().min(1),offset:Ee.number().integer().min(0)}),vQ=Ee.object({database:V_,schema:V_,table:vw,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(kc,Ee.object())).optional(),sort:Ee.object({attribute:Ee.alternatives(kc,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(kc,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()});Bw.exports=function(e,t){let r=null;switch(t){case"value":r=Uw.validateBySchema(e,PQ);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(Pw("database",e.schema)),i(Pw("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),n&&(r=new Error(n.trim()));break;case"conditions":r=Uw.validateBySchema(e,vQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=CQ.checkGlobalSchemaTable(e.schema,e.table);if(n)return DQ(new Error,n,UQ.NOT_FOUND);let o=MQ()[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 _=Mw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!Mw.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 mp=T((vle,Hw)=>{"use strict";var BQ=ze(),HQ=Zo(),{getSchemaPath:xQ}=Xe();Hw.exports=qQ;function qQ(e){let t=HQ(e,"hashes");if(t)throw t;let r=xQ(e.schema,e.table);return BQ.openEnvironment(r,e.table)}a(qQ,"initialize")});var pp=T((Hle,xw)=>{"use strict";var FQ=Xo(),GQ=mp();xw.exports=kQ;async function kQ(e){let t=await GQ(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return FQ.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(kQ,"lmdbGetDataByHash")});var ea=T((qle,qw)=>{"use strict";var Sp=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};qw.exports=Sp});var Gw=T((kle,Fw)=>{"use strict";var Gle=ea(),VQ=Xo(),$Q=mp();Fw.exports=YQ;async function YQ(e){let t=await $Q(e),r=global.hdb_schema[e.schema][e.table];return VQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(YQ,"lmdbSearchByHash")});var Js=T(($le,kw)=>{"use strict";var Tp=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};kw.exports=Tp});var $_=T((Kle,Qw)=>{"use strict";var zt=Xo(),KQ=ze(),WQ=J(),he=ht(),Qi=L(),QQ=vi(),Vw=Ir().LMDB_ERRORS_ENUM,{getSchemaPath:zQ}=Xe(),An=Qi.SEARCH_WILDCARDS;async function JQ(e,t,r){let s;e.schema===Qi.SYSTEM_SCHEMA_NAME?s=QQ[e.table]:s=global.hdb_schema[e.schema][e.table];let n=Ww(e,s.hash_attribute,r,t);return Yw(e,n,s.hash_attribute,r)}a(JQ,"prepSearch");async function Yw(e,t,r,s){let n=zQ(e.schema,e.table),i=await KQ.openEnvironment(n,e.table),o=Kw(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(jQ(e,r)===!1){let l=e.search_attribute;if(l===r)return s?$w(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?$w(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?zt.batchSearchByHashToMap(c,r,e.get_attributes,_):zt.batchSearchByHash(c,r,e.get_attributes,_)}a(Yw,"executeSearch");function Kw(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case he.SEARCH_TYPES.EQUALS:n=zt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.CONTAINS:n=zt.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:n=zt.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:n=zt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return zt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return zt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.SEARCH_ALL:return zt.searchAll(e,s,t.get_attributes,o,c,u);case he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return zt.searchAllToMap(e,s,t.get_attributes,o,c,u);case he.SEARCH_TYPES.BETWEEN:n=zt.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:n=zt.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:n=zt.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:n=zt.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:n=zt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(Kw,"searchByType");function $w(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a($w,"createMapFromIterable");function jQ(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(jQ,"checkToFetchMore");function Ww(e,t,r,s){if(WQ.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),An.indexOf(n)>-1)return r===!0?he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:he.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(An[0])<0&&n.indexOf(An[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(An.indexOf(i)>=0&&An.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),he.SEARCH_TYPES.CONTAINS;if(An.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),he.SEARCH_TYPES.ENDS_WITH;if(An.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),he.SEARCH_TYPES.STARTS_WITH;if(n.includes(An[0])||n.includes(An[1]))return he.SEARCH_TYPES.EQUALS;throw new Error(Vw.UNKNOWN_SEARCH_TYPE)}else switch(s){case Qi.VALUE_SEARCH_COMPARATORS.BETWEEN:return he.SEARCH_TYPES.BETWEEN;case Qi.VALUE_SEARCH_COMPARATORS.GREATER:return he.SEARCH_TYPES.GREATER_THAN;case Qi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return he.SEARCH_TYPES.GREATER_THAN_EQUAL;case Qi.VALUE_SEARCH_COMPARATORS.LESS:return he.SEARCH_TYPES.LESS_THAN;case Qi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return he.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Vw.UNKNOWN_SEARCH_TYPE)}}a(Ww,"createSearchTypeFromSearchObject");Qw.exports={executeSearch:Yw,createSearchTypeFromSearchObject:Ww,prepSearch:JQ,searchByType:Kw}});var Jw=T((zle,zw)=>{"use strict";var Qle=Js(),XQ=Zo(),ZQ=J(),ez=L(),tz=$_();zw.exports=rz;function rz(e,t){if(!ZQ.isEmpty(t)&&ez.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=XQ(e,"value");if(s)throw s;return tz.prepSearch(e,t,!0)}a(rz,"lmdbGetDataByValue")});var Vc=T((Xle,jw)=>{"use strict";var jle=Js(),sz=Zo(),nz=J(),iz=L(),oz=$_();jw.exports=az;async function az(e,t){if(!nz.isEmpty(t)&&iz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=sz(e,"value");if(s)throw s;return oz.prepSearch(e,t,!1)}a(az,"lmdbSearchByValue")});var Zw=T((t_e,Xw)=>{"use strict";var e_e=ht(),gp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}},Rp=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Ap=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Xw.exports={SearchByConditionsObject:gp,SearchCondition:Rp,SortAttribute:Ap}});var nI=T((i_e,sI)=>{"use strict";var s_e=Zw().SearchByConditionsObject,cz=Js(),uz=Zo(),Op=Xo(),Y_=ht(),{Resource:n_e}=(bs(),ee(bp)),rI=$_(),lz=hp(),_z=require("lodash"),{getSchemaPath:dz}=Xe(),eI=ze(),{handleHDBError:fz,hdb_errors:Ez}=Z(),{HTTP_STATUS_CODES:hz}=Ez,mz=1e8;sI.exports=pz;async function pz(e){let t=uz(e,"conditions");if(t)throw fz(t,t.message,hz.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=dz(e.schema,e.table),s=await eI.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)eI.openDBI(s,_.search_attribute);let i=_z.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===Y_.SEARCH_TYPES.EQUALS?_.estimated_count=Op.count(s,_.search_attribute,_.search_value):l===Y_.SEARCH_TYPES.CONTAINS||l===Y_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=mz}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await tI(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=s.dbis[n.hash_attribute],l=i.slice(1).map(rI.filterByType),d=l.length,f=Op.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>lz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await tI(o,e,f,n.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Op.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(pz,"lmdbSearchByConditions");async function tI(e,t,r,s){let n=new cz(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===Y_.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,rI.searchByType(e,n,i,s).map(o=>o.value)}a(tI,"executeConditionSearch")});var ta=T((a_e,iI)=>{"use strict";var Sz=L().OPERATIONS_ENUM,Np=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=Sz.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};iI.exports=Np});var yp=T((u_e,fI)=>{"use strict";var uI=Js(),lI=ta(),_I=Vc(),dI=qc(),or=L(),oI=J(),aI=ze(),{getTransactionAuditStorePath:Tz,getSchemaPath:gz}=Xe(),cI=V();fI.exports=Rz;async function Rz(e){try{if(oI.isEmpty(global.hdb_schema[e.schema])||oI.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await Az(e),await Oz(e);let t=gz(e.schema,e.table);try{await aI.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")cI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Tz(e.schema,e.table);await aI.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")cI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(Rz,"lmdbDropTable");async function Az(e){let t=new uI(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 _I(t)),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new lI(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await dI(n)}a(Az,"deleteAttributesFromSystem");async function Oz(e){let t=new uI(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,s;try{r=Array.from(await _I(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new lI(or.SYSTEM_SCHEMA_NAME,or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await dI(n)}catch(i){throw i}}a(Oz,"dropTableFromSystem")});var hI=T((__e,EI)=>{"use strict";var bz=require("fs-extra"),Nz=Js(),yz=ea(),wz=ta(),Iz=yp(),Cz=qc(),Dz=pp(),Lz=Vc(),On=L(),{getSchemaPath:Mz}=Xe(),{handleHDBError:Uz,hdb_errors:Pz}=Z(),{HDB_ERROR_MSGS:vz,HTTP_STATUS_CODES:Bz}=Pz;EI.exports=Hz;async function Hz(e){let t;try{t=await xz(e.schema);let r=new Nz(On.SYSTEM_SCHEMA_NAME,On.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,On.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[On.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await Lz(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await Iz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new wz(On.SYSTEM_SCHEMA_NAME,On.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await Cz(n);let i=Mz(t);await bz.remove(i)}catch(r){throw r}}a(Hz,"lmdbDropSchema");async function xz(e){let t=new yz(On.SYSTEM_SCHEMA_NAME,On.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[On.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await Dz(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw Uz(new Error,vz.SCHEMA_NOT_FOUND(e),Bz.NOT_FOUND,void 0,void 0,!0);return s}a(xz,"validateDropSchema")});var K_=T((f_e,mI)=>{"use strict";var wp=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};mI.exports=wp});var SI=T((m_e,pI)=>{"use strict";var qz=require("fs-extra"),W_=ze(),{getTransactionAuditStorePath:Fz}=Xe(),Ip=ht(),h_e=K_();pI.exports=Gz;async function Gz(e){let t;try{let r=Fz(e.schema,e.table);await qz.mkdirp(r),t=await W_.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{W_.createDBI(t,Ip.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),W_.createDBI(t,Ip.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),W_.createDBI(t,Ip.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(Gz,"createTransactionsAuditEnvironment")});var AI=T((S_e,RI)=>{"use strict";var Cp=L(),TI=ze(),kz=Fo(),{getSystemSchemaPath:Vz,getSchemaPath:$z}=Xe(),Yz=vi(),Kz=h_(),Dp=E_(),Wz=V(),Qz=SI(),Mp=Yz.hdb_table,gI=[];for(let e=0;e<Mp.attributes.length;e++)gI.push(Mp.attributes[e].attribute);RI.exports=zz;async function zz(e,t){let r=$z(t.schema,t.table),s=new Dp(t.schema,t.table,Cp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Dp(t.schema,t.table,Cp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Dp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await TI.createEnvironment(r,t.table),e!==void 0){let o=await TI.openEnvironment(Vz(),Cp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await kz.insertRecords(o,Mp.hash_attribute,gI,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Lp(s),await Lp(n),await Lp(i)}await Qz(t)}catch(o){throw o}}a(zz,"lmdbCreateTable");async function Lp(e){try{await Kz(e)}catch(t){Wz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Lp,"createAttribute")});var bI=T((g_e,OI)=>{"use strict";var Jz=Nc(),jz=Dc(),Xz=x_(),$c=L(),Zz=Fo().updateRecords,eJ=ze(),{getSchemaPath:tJ}=Xe(),rJ=Hc(),sJ=V();OI.exports=nJ;async function nJ(e){try{let{schema_table:t,attributes:r}=Jz(e);jz(e,r,t.hash_attribute),e.schema!==$c.SYSTEM_SCHEMA_NAME&&(r.includes($c.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push($c.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes($c.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push($c.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await Xz(e.hdb_auth_header,t,r),n=tJ(e.schema,e.table),i=await eJ.openEnvironment(n,e.table),o=await Zz(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await rJ(e,o)}catch(c){sJ.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(nJ,"lmdbUpdateRecords")});var yI=T((A_e,NI)=>{"use strict";var iJ=L().OPERATIONS_ENUM,Up=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=iJ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};NI.exports=Up});var II=T((N_e,wI)=>{"use strict";var b_e=yI(),oJ=Nc(),aJ=Dc(),cJ=x_(),Yc=L(),uJ=Fo().upsertRecords,lJ=ze(),{getSchemaPath:_J}=Xe(),dJ=Hc(),fJ=V(),{handleHDBError:EJ,hdb_errors:hJ}=Z();wI.exports=mJ;async function mJ(e){let t;try{t=oJ(e)}catch(u){throw EJ(u,u.message,hJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;aJ(e,s,r.hash_attribute),e.schema!==Yc.SYSTEM_SCHEMA_NAME&&(s.includes(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await cJ(e.hdb_auth_header,r,s),i=_J(e.schema,e.table),o=await lJ.openEnvironment(i,e.table),c=await uJ(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await dJ(e,c)}catch(u){fJ.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(mJ,"lmdbUpsertRecords")});var DI=T((w_e,CI)=>{"use strict";var Pp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};CI.exports=Pp});var MI=T((C_e,LI)=>{"use strict";var vp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};LI.exports=vp});var vI=T((M_e,PI)=>{"use strict";var Bp=ze(),{getTransactionAuditStorePath:pJ}=Xe(),L_e=DI(),Kc=ht(),SJ=J(),UI=MI(),TJ=require("util").promisify,gJ=TJ(setTimeout),RJ=1e4,AJ=100;PI.exports=OJ;async function OJ(e){let t=pJ(e.schema,e.table),r=await Bp.openEnvironment(t,e.table,!0),s=Bp.listDBIs(r);Bp.initializeDBIs(r,Kc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new UI;do n=await bJ(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await gJ(AJ);while(n.transactions_deleted>0);return i}a(OJ,"deleteAuditLogsBefore");async function bJ(e,t){let r=new UI;try{let s=e.dbis[Kc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[Kc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];SJ.isEmpty(c)||(n=e.dbis[Kc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Kc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>RJ)break}return await n,r}catch(s){throw s}}a(bJ,"deleteTransactions")});var HI=T((P_e,BI)=>{"use strict";var Hp=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};BI.exports=Hp});var qI=T((H_e,xI)=>{"use strict";var NJ=Js(),yJ=ta(),B_e=HI(),js=L(),wJ=J(),xp=ze(),IJ=vi(),CJ=Vc(),DJ=qc(),{getSchemaPath:LJ}=Xe();xI.exports=MJ;async function MJ(e,t=!0){let r;e.schema===js.SYSTEM_SCHEMA_NAME?r=IJ[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await PJ(e),n=LJ(e.schema,e.table),i=await xp.openEnvironment(n,e.table);return t===!0&&await UJ(e,i,r.hash_attribute),xp.dropDBI(i,e.attribute),s}a(MJ,"lmdbDropAttribute");async function UJ(e,t,r){let s=xp.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);n=t.dbis[r].put(o,_,u)}await n}a(UJ,"removeAttributeFromAllObjects");async function PJ(e){let t=new NJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await CJ(t)).filter(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(wJ.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[js.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new yJ(js.SYSTEM_SCHEMA_NAME,js.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return DJ(i)}a(PJ,"dropAttributeFromSystem")});var YI=T((F_e,$I)=>{"use strict";var qp=ze(),ra=ht(),q_e=Cr(),Fp=L(),FI=J(),{getTransactionAuditStorePath:vJ}=Xe(),BJ=Xo(),Q_=zo(),HJ=V();$I.exports=xJ;async function xJ(e){let t=vJ(e.schema,e.table),r=await qp.openEnvironment(t,e.table,!0),s=qp.listDBIs(r);qp.initializeDBIs(r,ra.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Fp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return GI(r,e.search_values);case Fp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,FJ(r,e.search_values,n);case Fp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return qJ(r,e.search_values);default:return GI(r)}}a(xJ,"readAuditLog");function GI(e,t=[0,Date.now()]){FI.isEmpty(t[0])&&(t[0]=0),FI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[ra.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new Q_,n))}a(GI,"searchTransactionsByTimestamp");function qJ(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[ra.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,VI(e,i))}return Object.fromEntries(r)}a(qJ,"searchTransactionsByUsername");function FJ(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=BJ.equals(e,ra.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ra.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);s.has(f)?s.get(f).push(_.toString()):s.set(f,[_.toString()])}}let n=Array.from(s.keys()),i=VI(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);kI(u,"records",r,l,o),kI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(FJ,"searchTransactionsByHashValues");function kI(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let _=n.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new 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],n.set(u,[_])}}}a(kI,"loopRecords");function VI(e,t){let r=[];try{let s=e.dbis[ra.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new Q_,i);r.push(o)}}catch(i){HJ.warn(i)}return r}catch(s){throw s}}a(VI,"batchSearchTransactions")});var WI=T(($_e,KI)=>{"use strict";var{getSchemaPath:k_e}=Xe(),V_e=ze(),{database:GJ}=(Ae(),ee(Fe));KI.exports={writeTransaction:kJ};async function kJ(e,t,r){return GJ({database:e,table:t}).transaction(r)}a(kJ,"writeTransaction")});var jI=T((K_e,JI)=>{"use strict";var{getSchemaPath:QI}=Xe(),zI=ze();JI.exports={flush:VJ,resetReadTxn:$J};async function VJ(e,t){return(await zI.openEnvironment(QI(e,t),t.toString())).flushed}a(VJ,"flush");async function $J(e,t){try{(await zI.openEnvironment(QI(e,t),t.toString())).resetReadTxn()}catch{}}a($J,"resetReadTxn")});var tC=T((Q_e,eC)=>{"use strict";var{Readable:YJ}=require("stream"),{getDatabases:KJ}=(Ae(),ee(Fe)),{readSync:WJ,openSync:QJ,createReadStream:XI}=require("fs"),{open:zJ}=require("lmdb"),ZI=n_(),JJ=o_(),{AUDIT_STORE_OPTIONS:jJ}=(Ui(),ee(rC)),{INTERNAL_DBIS_NAME:XJ,AUDIT_STORE_NAME:ZJ}=ht();eC.exports=t2;var Gp=32768,e2=100;async function t2(e){let t=e.database||e.schema||"data",r=KJ()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let _=r[n[0]];if(!_)throw new Error(`Can not find table ${n[0]}`);let l=_.dbisDB,d=zJ({noSync:!0,maxDbs:JJ.MAX_DBS}),f,E=d.openDB(XJ,new ZI(!1)),h=l.useReadTransaction(),p=0,S=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),p++%e2===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(n.some(v=>A.startsWith?.(v+"/"))){E.put(A,b);let[,v]=A.split("/"),G=!v,H=new ZI(!G,G);await S(A,H)}e.include_audit&&await S(ZJ,Object.assign({},jJ)),await f;let g=XI(d.path);return g.headers=u(),g.on("close",()=>{h.done(),d.close()}),g}let o=r[Object.keys(r)[0]].primaryStore,c=QJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(Gp);WJ(c,_,0,Gp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=XI(null,{fd:c,start:Gp}),f=new YJ.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",s),_}}a(t2,"getBackup")});var iC=T((J_e,nC)=>{"use strict";var r2=V(),{handleHDBError:s2}=Z(),n2=Tb(),i2=h_(),o2=lp(),a2=hw(),c2=qc(),u2=pp(),l2=Gw(),_2=Jw(),d2=Vc(),f2=nI(),E2=hI(),h2=AI(),m2=bI(),p2=II(),S2=vI(),T2=yp(),g2=qI(),R2=YI(),A2=WI(),sC=jI(),O2=tC(),kp=class extends n2{static{a(this,"LMDBBridge")}async searchByConditions(t){return f2(t)}async getDataByHash(t){return await u2(t)}async searchByHash(t){return await l2(t)}async getDataByValue(t,r){return await _2(t,r)}async searchByValue(t){return await d2(t)}async createSchema(t){return await a2(t)}async dropSchema(t){return await E2(t)}async createTable(t,r){return await h2(t,r)}async dropTable(t){return await T2(t)}async createAttribute(t){return await i2(t)}async createRecords(t){return await o2(t)}async updateRecords(t){return await m2(t)}async upsertRecords(t){try{return await p2(t)}catch(r){throw s2(r,null,null,r2.ERR,r)}}async deleteRecords(t){return await c2(t)}async dropAttribute(t){return await g2(t)}async deleteAuditLogsBefore(t){return await S2(t)}async readAuditLog(t){return await R2(t)}writeTransaction(t,r,s){return A2.writeTransaction(t,r,s)}flush(t,r){return sC.flush(t,r)}resetReadTxn(t,r){return sC.resetReadTxn(t,r)}getBackup(t){return O2(t)}};nC.exports=kp});function w2(){y2=setInterval(function(){for(let e of Vp)if(e.stale){let t=e[Oe]?.url;oC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},N2).unref()}var $p,oC,b2,Vp,zi,z_,N2,y2,Yp=Re(()=>{$p=B(Cr()),oC=B(V());bs();xo();b2=100,Vp=new Set,zi=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,r_(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),Vp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),r_(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Vp.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,$p.getNextMonotonicTime)());let s=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let g=S();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}s||this.doneReadTxn(),t?.prepared?.(),this.open=!1;let n,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,s)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){s>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);n=n||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<b2>>s?u():n=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),n)return n.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=s+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=!1,this.writes=[]}},z_=class extends zi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,$p.getNextMonotonicTime)())}getReadTxn(){}},N2=3e4;a(w2,"startMonitoringTxns");w2()});function et(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 s=e.transaction=new zi;e.timestamp&&(s.timestamp=e.timestamp),s[Oe]=e,e.resourceCache||(e.resourceCache=[]);let n;try{if(n=t(s),n?.then)return n.then(i,o)}catch(c){o(c)}return i(n);function i(c){let u=s.commit(r?.resetTransaction?{prepared(){s.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw s.abort({}),c}}var aC,Ji=Re(()=>{aC=require("../index");bs();Yp();a(et,"transaction");(0,aC._assignPackageExport)("transaction",et);et.commit=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};et.abort=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var mC={};We(mC,{ResourceBridge:()=>Qp});function zp({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 uC(e,t){let r=Xs(e),s=zp(e,r);if(!r)throw new Ls.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user},o;et(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:n,select:s},i);return l=l&&j_(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 Xs(e){let t=e.database||e.schema||C2,r=Ms()[t];if(!r)throw(0,Ls.handleHDBError)(new Error,I2.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function lC(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*_C(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(o),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[o],records:[u]})}s&&(yield s)}var dC,J_,Ls,fC,EC,Us,Kp,Wp,hC,I2,C2,D2,L2,cC,Qp,pC=Re(()=>{"use strict";dC=B(iC()),J_=B(Zo()),Ls=B(Z());Ae();fC=B(Nc()),EC=B(Dc()),Us=B(L()),Kp=B(Rn()),Wp=B(Ds()),hC=B(J());Ji();X_();({HDB_ERROR_MSGS:I2}=Ls.hdb_errors),C2="data",D2=1e4,L2=10,Qp=class extends dC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),cC=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,J_.default)(t,"conditions");if(r)throw(0,Ls.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=Xs(t);if(!s)throw new Ls.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:zp(t,s),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let o of s)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Ls.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}_t({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await Xs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Xs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=a((o,c,u)=>(c=Object.assign({},c),delete c[s],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))n=i(o,c,u),await new Promise(_=>setImmediate(_));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Xs(t).dropTable()}createSchema(t){return Wc({database:t.schema,table:null}),Kp.signalSchemaChange(new Wp.SchemaEventMsg(process.pid,Us.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Jp(t.schema),Kp.signalSchemaChange(new Wp.SchemaEventMsg(process.pid,Us.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,cC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,fC.default)(t);(0,EC.default)(t,s,r.primaryKey);let n,i=Ms()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return et(o,async c=>{if(!i.schemaDefined){n=[];for(let l of s)i.attributes.find(f=>f.name==l)||n.push(l);n.length>0&&await i.addAttributes(n.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=j_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:_}})}async deleteRecords(t){let r=Ms()[t.schema][t.table],s={user:t.hdb_user};return et(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,s)?o.push(u):c.push(u);return lC(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Ms()[t.schema][t.table];if(!r.createdTimeProperty)throw new Ls.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Us.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,hC.async_set_timeout)(L2),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%D2===0&&await _();return u.length>0&&await _(),n?lC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,J_.default)(t,"hashes");if(r)throw r;return uC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of uC(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&Us.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let s=(0,J_.default)(t,"value");if(s)throw s;let n=Xs(t);if(!n)throw new Ls.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===Us.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:zp(t,n)})}async getDataByValue(t,r){let s=new Map,n=Xs(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){Xs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Xs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Xs(t),s={};switch(t.search_type){case Us.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case Us.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of _C(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return _C(r,t.search_values?.[0],t.search_values?.[1])}}};a(zp,"getSelect");a(uC,"getRecords");a(Xs,"getTable");a(lC,"createDeleteResponse");a(_C,"groupRecordsInHistory")});var ws=T((_de,SC)=>{"use strict";var{ResourceBridge:M2}=(pC(),ee(mC)),U2=X();U2.initSync();var Z_;function P2(){return Z_||(Z_=new M2,Z_)}a(P2,"getBridge");SC.exports=P2()});var AC=T((fde,RC)=>{"use strict";var TC=require("lodash"),Qc=require("mathjs"),v2=require("jsonata"),gC=J();RC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?TC.uniqWith(e,TC.isEqual):e,searchJSON:B2,mad:zc.bind(null,Qc.mad),mean:zc.bind(null,Qc.mean),mode:zc.bind(null,Qc.mode),prod:zc.bind(null,Qc.prod),median:zc.bind(null,Qc.median)};function zc(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(zc,"aggregateFunction");function B2(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(gC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),gC.isEmpty(this.__ala__.res[r])){let s=v2(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(B2,"searchJSON")});var bC=T((hde,OC)=>{"use strict";var pt=require("moment"),jp="YYYY-MM-DDTHH:mm:ss.SSSZZ";pt.suppressDeprecationWarnings=!0;OC.exports={current_date:()=>pt().utc().format("YYYY-MM-DD"),current_time:()=>pt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return pt(e).utc().format("YYYY");case"month":return pt(e).utc().format("MM");case"day":return pt(e).utc().format("DD");case"hour":return pt(e).utc().format("HH");case"minute":return pt(e).utc().format("mm");case"second":return pt(e).utc().format("ss");case"millisecond":return pt(e).utc().format("SSS");default:break}},date:e=>pt(e).utc().format(jp),date_format:(e,t)=>pt(e).utc().format(t),date_add:(e,t,r)=>pt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>pt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=pt(e).utc(),n=pt(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>pt().utc().valueOf(),get_server_time:()=>pt().format(jp),offset_utc:(e,t)=>pt(e).utc().utcOffset(t).format(jp)}});var IC=T((mde,wC)=>{"use strict";var H2=require("@turf/area"),x2=require("@turf/length"),q2=require("@turf/circle"),F2=require("@turf/difference"),G2=require("@turf/distance"),k2=require("@turf/boolean-contains"),V2=require("@turf/boolean-equal"),$2=require("@turf/boolean-disjoint"),Y2=require("@turf/helpers"),NC=L(),Se=J(),bn=V();wC.exports={geoArea:K2,geoLength:W2,geoCircle:Q2,geoDifference:z2,geoDistance:yC,geoNear:J2,geoContains:j2,geoEqual:X2,geoCrosses:Z2,geoConvert:e4};function K2(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return H2.default(e)}catch(t){return bn.trace(t,e),NaN}}a(K2,"geoArea");function W2(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return x2.default(e,{units:t||"kilometers"})}catch(r){return bn.trace(r,e),NaN}}a(W2,"geoLength");function Q2(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return q2.default(e,t,{units:r||"kilometers"})}catch(s){return bn.trace(s,e,t),NaN}}a(Q2,"geoCircle");function z2(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 F2(e,t)}catch(r){return bn.trace(r,e,t),NaN}}a(z2,"geoDifference");function yC(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 G2.default(e,t,{units:r||"kilometers"})}catch(s){return bn.trace(s,e,t),NaN}}a(yC,"geoDistance");function J2(e,t,r,s){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return yC(e,t,s)<=r}catch(n){return bn.trace(n,e,t),!1}}a(J2,"geoNear");function j2(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 k2.default(e,t)}catch(r){return bn.trace(r,e,t),!1}}a(j2,"geoContains");function X2(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 V2.default(e,t)}catch(r){return bn.trace(r,e,t),!1}}a(X2,"geoEqual");function Z2(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!$2.default(e,t)}catch(r){return bn.trace(r,e,t),!1}}a(Z2,"geoCrosses");function e4(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(NC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(NC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),Y2[t](e,r)}a(e4,"geoConvert")});var ed=T((Sde,CC)=>{var ji=AC(),qr=bC(),Zs=IC();CC.exports=e=>{e.aggr.mad=e.aggr.MAD=ji.mad,e.aggr.mean=e.aggr.MEAN=ji.mean,e.aggr.mode=e.aggr.MODE=ji.mode,e.aggr.prod=e.aggr.PROD=ji.prod,e.aggr.median=e.aggr.MEDIAN=ji.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ji.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ji.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=qr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=qr.current_time,e.fn.extract=e.fn.EXTRACT=qr.extract,e.fn.date=e.fn.DATE=qr.date,e.fn.date_format=e.fn.DATE_FORMAT=qr.date_format,e.fn.date_add=e.fn.DATE_ADD=qr.date_add,e.fn.date_sub=e.fn.DATE_SUB=qr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=qr.date_diff,e.fn.now=e.fn.NOW=qr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=qr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=qr.get_server_time,e.fn.getdate=e.fn.GETDATE=qr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=qr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=Zs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=Zs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=Zs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=Zs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=Zs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=Zs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=Zs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=Zs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=Zs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=Zs.geoNear}});var UC=T((Tde,MC)=>{"use strict";var Jc=require("lodash"),ar=require("alasql");ar.options.cache=!1;var t4=ed(),DC=require("clone"),td=require("recursive-iterator"),le=V(),Ie=J(),sa=ws(),r4=L(),{hdb_errors:s4}=Z(),{getDatabases:LC}=(Ae(),ee(Fe)),n4="IS NULL",Ps="There was a problem performing this search. Please check the logs and try again.";t4(ar);var Xp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ie.isEmpty(t))throw le.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),Ie.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!Ie.isEmptyOrZeroLength(s))return le.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw le.error("Error thrown from checkEmptySQL in SQLSearch class method search."),le.error(s),new Error(Ps)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw le.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),le.error(s),new Error(Ps)}if(Object.keys(this.data).length===0)return le.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw le.error("Error thrown from processJoins in SQLSearch class method search."),le.error(s),new Error(Ps)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw le.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),le.error(s),new Error(Ps)}try{return t=await this._finalSQL(),t}catch(s){throw le.error("Error thrown from finalSQL in SQLSearch class method search."),le.error(s),new Error(Ps)}}_getColumns(){let t=new td(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(DC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Jc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=LC()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ie.isEmpty(this.statement.where)){le.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new td(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ie.isEmpty(r)&&r.right)if(Ie.isNotEmptyAndHasValue(r.right.value)){let s=Ie.autoCast(r.right.value);[!0,!1].indexOf(s)>=0&&(r.right=new ar.yy.LogicValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=Ie.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new ar.yy.LogicValue({value:i}):s instanceof ar.yy.StringValue&&Ie.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new ar.yy.NumValue({value:i}))});if(t){le.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new td(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ie.isEmpty(r4.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ie.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ie.isEmptyOrZeroLength(r.left.columnid)||Ie.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(Ie.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"=":!Ie.isEmpty(r.right.value)||!Ie.isEmpty(r.left.value)?s.add(Ie.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)s.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(Ie.isEmptyOrZeroLength(this.all_table_attributes)&&Ie.isEmptyOrZeroLength(this.statement.from)&&Ie.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Jc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(Ie.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);Ie.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(Ie.isEmptyOrZeroLength(this.all_table_attributes)&&!Ie.isEmptyOrZeroLength(this.columns.columns))return t;if(Ie.isEmptyOrZeroLength(this.all_table_attributes)&&Ie.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await ar.promise(r)}catch(r){throw le.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),le.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let s=this._findColumn(r);s&&this.fetch_attributes.push(DC(s))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(Ie.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(n4)>-1&&this.tables.forEach(n=>{let i={columnid:LC()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Jc.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,_=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!Ie.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ie.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await sa.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Ps)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await sa.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(Ps)}else if(!Ie.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ie.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 sa.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...s[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]):(this.data[i].__merged_data[p]=[...s[i]],this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),le.error(l),new Error(Ps)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await sa.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),le.error(l),new Error(Ps)}}}_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(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new ar.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}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 n=t.is_func?new ar.yy.FuncValue:new ar.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,n);f=await ar.promise(h,t),t=null}catch(E){throw le.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),le.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let p=f[E];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),p=Jc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,g=p.length;S<g;S++){let A=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[A]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new td(this.columns);for(let{node:i}of n)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&s.push(o)}}s=Jc.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw le.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),le.error(i),new Error(Ps)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await sa.getDataByHash(c),_=n.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=n.columns[h],S=E[p]===void 0?null:E[p];this.data[s].__merged_data[f].push(S)}}}}catch(r){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getData."),le.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let s;try{let n=this._buildSQL();le.trace(`Final SQL: ${n}`),s=await ar.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),le.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw le.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),le.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return le.error(s4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),le.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=n[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;s=s.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;s=s.replace(u,_)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await sa.getDataByValue(i);for(let[c,u]of o)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(o){throw le.error("There was an error when processing this SQL operation. Check your logs"),le.error(o),new Error(Ps)}}return Object.values(Object.values(this.data)[0].__merged_data)}};MC.exports=Xp});var rs=T((Rde,PC)=>{"use strict";var i4=pb();PC.exports={searchByConditions:a4,searchByHash:c4,searchByValue:u4,search:l4};var Zp=ws(),{transformReq:eS}=J(),o4=UC();async function a4(e){return eS(e),Zp.searchByConditions(e)}a(a4,"searchByConditions");async function c4(e){eS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of Zp.searchByHash(e))r&&t.push(r);return t}a(c4,"searchByHash");async function u4(e){eS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of Zp.searchByValue(e))t.push(r);return t}a(u4,"searchByValue");function l4(e,t){try{let r=new i4(e);r.validate(),new o4(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(l4,"search")});var rd=T((Ode,vC)=>{"use strict";var _4=ws();vC.exports={writeTransaction:d4};function d4(e,t,r){return _4.writeTransaction(e,t,r)}a(d4,"writeTransaction")});var qC=T((yde,xC)=>{"use strict";var f4=rs(),E4=gn(),BC=V(),h4=Mr(),Nde=rd(),m4=require("clone"),rS=require("alasql"),p4=ed(),HC=require("util"),S4=HC.promisify(E4.getTableSchema),T4=HC.promisify(f4.search),g4=L(),tS=J();p4(rS);xC.exports={update:A4};var R4="There was a problem performing this update. Please check the logs and try again.";async function A4({statement:e,hdb_user:t}){let r=await S4(e.table.databaseid,e.table.tableid),s=O4(e.columns);tS.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=m4(n),c=tS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=rS.parse(u).statements[0],l=await T4(_),d=b4(s,l);return N4(o,d,t)}a(A4,"update");function O4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=rS.compile(`SELECT ${r.expression.toString()} AS [${g4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw BC.error(t),new Error(R4)}}a(O4,"createUpdateRecord");function b4(e,t){return tS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(b4,"buildUpdateRecords");async function N4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await h4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){BC.error(`Error delete new_attributes from update response: ${i}`)}return n}a(N4,"updateRecords")});var GC=T((Dde,FC)=>{var y4=require("alasql"),w4=rs(),I4=V(),C4=ws(),nS=require("util"),sS=J(),D4=L(),L4=gn(),Ide=rd(),Cde=Mr(),M4="record",U4="successfully deleted",P4=nS.callbackify(x4),v4=nS.promisify(w4.search),B4=nS.promisify(L4.getTableSchema);FC.exports={convertDelete:P4};function H4(e){return`${e.deleted_hashes.length} ${M4}${e.deleted_hashes.length===1?"":"s"} ${U4}`}a(H4,"generateReturnMessage");async function x4({statement:e,hdb_user:t}){let r=await B4(e.table.databaseid,e.table.tableid);sS.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=sS.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=y4.parse(o).statements[0],u={operation:D4.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await v4(c);let _=await C4.deleteRecords(u);return sS.isEmptyOrZeroLength(_.message)&&(_.message=H4(_)),delete _.txn_time,_}catch(_){throw I4.error(_),_.hdb_code?_.message:_}}a(x4,"convertDelete")});var KC=T((Mde,YC)=>{"use strict";var q4=Xn(),{hdb_errors:kC}=Z(),{getDatabases:VC}=(Ae(),ee(Fe));YC.exports={checkSchemaExists:$C,checkSchemaTableExists:F4,schema_describe:q4};async function $C(e){if(!VC()[e])return kC.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a($C,"checkSchemaExists");async function F4(e,t){let r=await $C(e);if(r)return r;if(!VC()[e][t])return kC.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(F4,"checkSchemaTableExists")});var jc=T((Pde,G4)=>{G4.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 tu={};We(tu,{addAnalyticsListener:()=>eu,recordAction:()=>Fr,recordActionBinary:()=>is,setAnalyticsEnabled:()=>k4});function k4(e){rD=e}function Fr(e,t,r,s,n){if(!rD)return;let i=t+(r?"-"+r:"");s!==void 0&&(i+="-"+s),n!==void 0&&(i+="-"+n);let o=id.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:s,type:n},id.set(i,o)}sd||V4()}function is(e,t,r,s,n){Fr(!!e,t,r,s,n)}function eu(e){iD.push(e)}function V4(){sd=performance.now(),setTimeout(async()=>{let e=performance.now()-sd;sd=0;let t=[],r={time:Date.now(),period:e,threadId:Xi.threadId,metrics:t};for(let[n,i]of id){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 oD){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 aD()}let s=process.memoryUsage();t.push({metric:"memory",threadId:Xi.threadId,byThread:!0,...s});for(let n of iD)n(t);id=new Map,Xi.parentPort?Xi.parentPort.postMessage({type:nD,report:r}):lD({report:r})},sD).unref()}async function $4(e,t=6e4){let r=aS(),s=cD(),n;for(let h of s.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){n=h.value.time;break}if(Date.now()-t<n)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:p}of r.primaryStore.getRange({start:n||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:S,threadId:g}=p;for(let A of S||[]){let{path:b,method:v,type:G,metric:H,count:P,total:z,distribution:W,threads:Q,...ne}=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({},ne);continue}}oe.count||(oe.count=1);let qe=oe.count;for(let ce in ne){let Lt=ne[ce];typeof Lt=="number"&&(oe[ce]=(oe[ce]*qe+Lt*P)/(qe+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({},ne),u.push(oe));if(W){W=W.map(ce=>typeof ce=="number"?{value:ce,count:1}:ce);let qe=c.get(pe);qe?qe.push(...W):c.set(pe,W)}}await aD()}for(let h of u){let{path:p,method:S,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 ne=Q[z];typeof ne=="number"&&(W+=ne)}h[z]=W}h.count=H.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((ce,Lt)=>ce.value>Lt.value?1:-1);let g=S.count-1,A=[],b=0,v=0,G;for(let ce of oD){let Lt=g*ce;for(;b<Lt;)G=p[v++],b+=G.count,v===1&&b--;let Ul=p[v>1?v-2:0];G||(G=p[0]),A.push(G.value-(G.value-Ul.value)*(b-Lt)/G.count)}let[H,P,z,W,Q,ne,pe,oe,qe]=A;Object.assign(S,{p1:H,p10:P,p25:z,median:W,p75:Q,p90:ne,p95:pe,p99:oe,p999:qe})}let l;for(let[h,p]of o)p.id=(0,nd.getNextMonotonicTime)(),p.time=_,s.primaryStore.put(p.id,p,{append:!0}).then(S=>{S||s.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,nd.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-WC,active:E-QC,time:d,...process.memoryUsage()};s.primaryStore.put(h,p,{append:!0}).then(S=>{S||s.primaryStore.put(h,p)})}WC=f,QC=E}async function zC(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function aS(){return JC||(JC=_t({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function cD(){return jC||(jC=_t({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function W4(){uD=!0;let e=(0,Zc.get)(oS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await $4(sD,e),await zC(aS(),Y4),await zC(cD(),K4)},Math.min(e/2,2147483647)).unref()}function lD(e,t){let r=e.report;r.threadId=t?.threadId||Xi.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(XC+=s.mean*s.count);r.totalBytesProcessed=XC,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(ZC.get(t))}),ZC.set(t,t.performance.eventLoopUtilization())),r.id=(0,nd.getNextMonotonicTime)(),aS().primaryStore.put(r.id,r),uD||W4(),Q4&&(_D=J4(r))}async function J4(e){if(await _D,!oi){let r=(0,Xc.dirname)((0,tD.getLogFilePath)());try{oi=await(0,iS.open)((0,Xc.join)(r,"analytics.log"),"r+")}catch{oi=await(0,iS.open)((0,Xc.join)(r,"analytics.log"),"w+")}}let t=(await oi.stat()).size;if(t>z4){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 Xi,eD,tD,Xc,iS,nd,Zc,oS,id,rD,sd,sD,nD,iD,oD,WC,QC,aD,Y4,K4,JC,jC,uD,XC,ZC,Q4,_D,oi,z4,Nn=Re(()=>{Xi=require("worker_threads"),eD=B(Qe());Ae();tD=B(V()),Xc=require("path"),iS=require("fs/promises"),nd=B(Cr()),Zc=B(X()),oS=B(L());rr();(0,Zc.initSync)();id=new Map,rD=(0,Zc.get)(oS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(k4,"setAnalyticsEnabled");a(Fr,"recordAction");lt.recordAnalytics=Fr;a(is,"recordActionBinary");sd=0,sD=1e3,nD="analytics-report",iD=[];a(eu,"addAnalyticsListener");oD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(V4,"sendAnalytics");a($4,"aggregation");WC=0,QC=0,aD=a(()=>new Promise(setImmediate),"rest");a(zC,"cleanup");Y4=36e5,K4=31536e6;a(aS,"getRawAnalyticsTable");a(cD,"getAnalyticsTable");(0,eD.setChildListenerByType)(nD,lD);a(W4,"startScheduledTasks");XC=0,ZC=new Map,Q4=!1;a(lD,"recordAnalytics");z4=1e6;a(J4,"logAnalytics")});var it=T((Qde,LD)=>{"use strict";var Gt=X();Gt.initSync();var j4=require("fs-extra"),X4=require("semver"),nu=require("path"),{monotonicFactory:Z4}=require("ulidx"),fD=Z4(),e3=require("util"),ED=require("child_process"),t3=e3.promisify(ED.exec),r3=ED.spawn,be=Ge(),Pe=L(),_S=J(),Gr=V(),od=Tn(),s3=rd(),ru=vr(),{onMessageByType:n3}=Qe(),{isMainThread:i3}=require("worker_threads"),{Encoder:o3,decode:dS}=require("msgpackr"),hD=new o3,{isEmpty:ro}=_S,mD=ns(),a3=48*36e11,c3=5e9;i3&&n3(Pe.ITC_EVENT_TYPES.RESTART,()=>{os=void 0,to=void 0});var{connect:u3,StorageType:pD,RetentionPolicy:SD,AckPolicy:ad,DeliverPolicy:cd,DiscardPolicy:l3,NatsConnection:$de,JetStreamManager:Yde,JetStreamClient:Kde,StringCodec:Wde,JSONCodec:_3,createInbox:fS,headers:d3,ErrorCode:dD}=require("nats"),{PACKAGE_ROOT:f3}=L(),E3=jc(),{recordAction:h3}=(Nn(),ee(tu)),TD=_3(),m3="clustering",p3=E3.engines[be.NATS_SERVER_NAME],S3=nu.join(f3,"dependencies"),lS=nu.join(S3,`${process.platform}-${process.arch}`,be.NATS_BINARY_NAME),cS,uS,su,Zi,eo;LD.exports={runCommand:gD,checkNATSServerInstalled:T3,createConnection:ES,getConnection:ud,getJetStreamManager:iu,getJetStream:AD,getNATSReferences:cr,getServerList:R3,createLocalStream:hS,listStreams:OD,deleteLocalStream:A3,getServerConfig:ou,listRemoteStreams:O3,viewStream:b3,viewStreamIterator:N3,publishToStream:y3,createWorkQueueStream:w3,addSourceToWorkStream:ND,request:C3,removeSourceFromWorkStream:wD,reloadNATS:mS,reloadNATSHub:D3,reloadNATSLeaf:L3,extractServerName:yD,requestErrorHandler:M3,updateWorkStream:U3,createLocalTableStream:CD,createTableStreams:P3,purgeTableStream:DD,purgeSchemaTableStreams:v3,getStreamInfo:B3,updateLocalStreams:x3,closeConnection:g3,getJsmServerName:au,addNatsMsgHeader:bD,updateIngestStreamConsumer:I3,clearClientCache:RD};async function gD(e,t=void 0){let{stdout:r,stderr:s}=await t3(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(dD,"runCommand");async function t3(){try{await M4.access(nS)}catch{return!1}let e=await dD(`${nS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return P4.eq(t,Z4)}a(t3,"checkNATSServerInstalled");async function cS(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await cD.getClusterUser();if(so(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Fr.trace("create nats connection called");let i=await Y4({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:2e5,tls:{keyFile:Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Fr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Fr.error("Error with Nats client connection, connection closed",o),fD()}),i}a(cS,"createConnection");function fD(){ns=void 0,eo=void 0,to=void 0,ro=void 0}a(fD,"clearClientCache");async function r3(){ns&&(await ns.drain(),ns=void 0,eo=void 0,to=void 0,ro=void 0)}a(r3,"closeConnection");var ns,ro;async function ud(){return ro||(ro=cS(Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),ns=await ro),ns||ro}a(ud,"getConnection");async function ou(){if(eo)return eo;so(ns)&&await ud();let{domain:e}=au(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(so(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return eo=await ns.jetstreamManager({domain:e,timeout:6e4}),eo}a(ou,"getJetStreamManager");async function ED(){if(to)return to;so(ns)&&await ud();let{domain:e}=au(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(so(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return to=ns.jetstream({domain:e,timeout:6e4}),to}a(ED,"getJetStream");async function ur(){let e=ns||await ud(),t=eo||await ou(),r=to||await ED();return{connection:e,jsm:t,js:r}}a(ur,"getNATSReferences");async function s3(e){let t=Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await cD.getClusterUser(),n=await cS(t,r,s),i=aS(),o=n.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=_D.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await n.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await n.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await n.flush(),await iS.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(s3,"getServerList");async function uS(e,t){let{jsm:r}=await ur(),s=Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:uD.File,retention:lD.Limits,subjects:t,discard:K4.Old,max_msgs:n,max_bytes:i,max_age:s})}a(uS,"createLocalStream");async function hD(){let{jsm:e}=await ur(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(hD,"listStreams");async function n3(e){let{jsm:t}=await ur();await t.streams.delete(e)}a(n3,"deleteLocalStream");async function i3(e){let{connection:t}=await ur(),r=[],s=aS(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(_D.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(i3,"listRemoteStreams");async function o3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await ur(),i=iD(),o={durable_name:i,ack_policy:ad.Explicit};t&&(o.deliver_policy=cd.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=oS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Oe.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(o3,"viewStream");async function*a3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await ur(),i=iD(),o={durable_name:i,ack_policy:ad.Explicit};t&&(o.deliver_policy=cd.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=oS(_.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(Oe.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(a3,"viewStreamIterator");async function c3(e,t,r,s){Fr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=mD(s,r);let{js:n}=await ur(),i=await cu(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:aD.encode(s);try{Fr.trace(`publishToStream publishing to subject: ${o}`),X4(c.length,"bytes-sent",e,s.operation,"replication"),await n.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return gD(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Fr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await uS(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(c3,"publishToStream");function mD(e,t){t===void 0&&(t=Q4());let r=Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Oe.MSG_HEADERS.ORIGIN)&&r&&t.append(Oe.MSG_HEADERS.ORIGIN,r),t}a(mD,"addNatsMsgHeader");function au(e){e=e.toLowerCase();let t=iu.join(Gt.get(Ue.CONFIG_PARAMS.ROOTPATH),j4);if(e===Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return so(sS)&&(sS={port:su.getConfigFromFile(Ue.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:su.getConfigFromFile(Ue.CONFIG_PARAMS.CLUSTERING_NODENAME)+Oe.SERVER_SUFFIX.HUB,config_file:Oe.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:iu.join(t,Oe.PID_FILES.HUB),hdb_nats_path:t}),sS;if(e===Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return so(rS)&&(rS={port:su.getConfigFromFile(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:su.getConfigFromFile(Ue.CONFIG_PARAMS.CLUSTERING_NODENAME)+Oe.SERVER_SUFFIX.LEAF,config_file:Oe.NATS_CONFIG_FILES.LEAF_SERVER,domain:su.getConfigFromFile(Ue.CONFIG_PARAMS.CLUSTERING_NODENAME)+Oe.SERVER_SUFFIX.LEAF,pid_file_path:iu.join(t,Oe.PID_FILES.LEAF),hdb_nats_path:t}),rS;Fr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(au,"getServerConfig");async function u3(e){let{jsm:t}=await ur(),r=await cu();try{await t.streams.add({name:e.stream_name,storage:uD.File,retention:lD.Limits,max_age:V4,max_bytes:$4,subjects:[`${Oe.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:ad.Explicit,durable_name:e.durable_name,deliver_policy:cd.All,max_ack_pending:1e4});else throw s}}a(u3,"createWorkQueueStream");async function l3(){let{jsm:e}=await ur();(await e.consumers.info(Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name,Oe.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Fr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name,Oe.WORK_QUEUE_CONSUMER_NAMES.durable_name),Fr.info("Adding pull consumer to ingest stream"),await e.consumers.add(Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:ad.Explicit,durable_name:Oe.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:cd.All,max_ack_pending:1e4}))}a(l3,"updateIngestStreamConsumer");async function pD(e,t,r){let{jsm:s}=await ur(),n=await s.streams.info(t),i=SD(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=od.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let p=0,S=n.config.sources.length;p<S;p++)if(d=n.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 s.streams.purge(t,{filter:p}),n.config.sources.splice(f,1),await s.streams.update(t,n.config)}let h={name:_,opt_start_time:o,filter_subject:`${Oe.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(pD,"addSourceToWorkStream");function SD(e){return e.split(".")[1]}a(SD,"extractServerName");async function TD(e,t,r){let{jsm:s}=await ur(),{schema:n,table:i}=r,o=`txn.${n}.${i}.${e}`;await s.streams.purge(t,{filter:o});let c=od.createNatsTableStreamName(n,i),u=await s.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 s.streams.update(t,u.config)}a(TD,"removeSourceFromWorkStream");async function _3(e,t,r=6e4,s=aS()){if(!iS.isObject(t))throw new Error("data param must be an object");let n=aD.encode(t),{connection:i}=await ur(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return oS(c.data)}a(_3,"request");function lS(e){return new Promise(async(t,r)=>{let s=x4(nS,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(lS,"reloadNATS");async function d3(){let{pid_file_path:e}=au(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await lS(e)}a(d3,"reloadNATSHub");async function f3(){let{pid_file_path:e}=au(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await lS(e)}a(f3,"reloadNATSLeaf");function E3(e,t,r){let s;switch(e.code){case nD.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case nD.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(E3,"requestErrorHandler");async function h3(e,t){let r=t+Oe.SERVER_SUFFIX.LEAF;await gD(async()=>{e.subscribe===!0?await pD(r,Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await TD(r,Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(h3,"updateWorkStream");function gD(e){return q4.writeTransaction(Ue.SYSTEM_SCHEMA_NAME,Ue.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(gD,"exclusiveLock");async function RD(e,t){let r=od.createNatsTableStreamName(e,t),s=await cu(),n=T3(e,t,s);await uS(r,[n])}a(RD,"createLocalTableStream");async function m3(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await RD(s,n)}}a(m3,"createTableStreams");async function AD(e,t,r=!1){if(Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let s=od.createNatsTableStreamName(e,t),{jsm:n}=await ur();r?await n.streams.purge(Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name):await n.streams.purge(s)}catch(s){if(s.message==="stream not found")Fr.warn(s);else throw s}}a(AD,"purgeTableStream");async function p3(e,t){if(Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await AD(e,t[r])}a(p3,"purgeSchemaTableStreams");async function S3(e){return(await ou()).streams.info(e)}a(S3,"getStreamInfo");function T3(e,t,r){return`${Oe.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(T3,"createSubjectName");async function cu(){if(nu)return nu;if(nu=(await ou())?.nc?.info?.server_name,nu===void 0)throw new Error("Unable to get jetstream manager server name");return nu}a(cu,"getJsmServerName");async function g3(){let e=await ou(),t=await cu(),r=await hD();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=R3(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===Oe.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Oe.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Fr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Fr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Fr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}await e.streams.update(n.name,n)}}}a(g3,"updateLocalStreams");function R3(e){let{config:t}=e,r=!1;if(t.name===Oe.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===Oe.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Gt.get(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(R3,"updateStreamLimits")});var uu=T((Ide,ID)=>{"use strict";var na=f_(),ia=xC(),A3=G(),O3=require("uuid").v4,yde=require("clone"),_d=An(),oa=D(),b3=require("util"),ai=ws(),{handleHDBError:lr,hdb_errors:N3}=Z(),{HDB_ERROR_MSGS:ld,HTTP_STATUS_CODES:_r}=N3,{SchemaEventMsg:dd}=Ls(),bD=nt(),{getDatabases:y3}=(ge(),ee(xe)),{transformReq:aa}=z();ID.exports={createSchema:I3,createSchemaStructure:ND,createTable:w3,createTableStructure:yD,createAttribute:M3,dropSchema:C3,dropTable:D3,dropAttribute:L3,getBackup:P3};async function I3(e){let t=await ND(e);return _d.signalSchemaChange(new dd(process.pid,e.operation,e.schema)),t}a(I3,"createSchema");async function ND(e){let t=na.schema_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);if(aa(e),!await ia.checkSchemaExists(e.schema))throw lr(new Error,ld.SCHEMA_EXISTS_ERR(e.schema),_r.BAD_REQUEST,oa.LOG_LEVELS.ERROR,ld.SCHEMA_EXISTS_ERR(e.schema),!0);return await ai.createSchema(e),`database '${e.schema}' successfully created`}a(ND,"createSchemaStructure");async function w3(e){return aa(e),e.hash_attribute=e.primary_key??e.hash_attribute,await yD(e)}a(w3,"createTable");async function yD(e){let t=na.create_table_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);if(na.validateTableResidence(e.residence),!await ia.checkSchemaTableExists(e.schema,e.table))throw lr(new Error,ld.TABLE_EXISTS_ERR(e.schema,e.table),_r.BAD_REQUEST,oa.LOG_LEVELS.ERROR,ld.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:O3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await ai.createTable(s,e);else throw lr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",_r.BAD_REQUEST);else await ai.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(yD,"createTableStructure");async function C3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=na.schema_object(e),s=t??r;if(s)throw lr(s,s.message,_r.BAD_REQUEST,void 0,void 0,!0);aa(e);let n=await ia.checkSchemaExists(e.schema);if(n)throw lr(new Error,n,_r.NOT_FOUND,oa.LOG_LEVELS.ERROR,n,!0);let i=await ia.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ai.dropSchema(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema)),await bD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(C3,"dropSchema");async function D3(e){let t=na.table_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);aa(e);let r=await ia.checkSchemaTableExists(e.schema,e.table);if(r)throw lr(new Error,r,_r.NOT_FOUND,oa.LOG_LEVELS.ERROR,r,!0);return await ai.dropTable(e),await bD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(D3,"dropTable");async function L3(e){let t=na.attribute_object(e);if(t)throw lr(t,t.message,_r.BAD_REQUEST,void 0,void 0,!0);aa(e);let r=await ia.checkSchemaTableExists(e.schema,e.table);if(r)throw lr(new Error,r,_r.NOT_FOUND,oa.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw lr(new Error,"You cannot drop a hash attribute",_r.BAD_REQUEST,void 0,void 0,!0);if(oa.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw lr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,_r.BAD_REQUEST,void 0,void 0,!0);try{return await ai.dropAttribute(e),U3(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw A3.error(`Got an error deleting attribute ${b3.inspect(e)}.`),s}}a(L3,"dropAttribute");function U3(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(U3,"dropAttributeFromGlobal");async function M3(e){aa(e);let t=y3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw lr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,_r.BAD_REQUEST,void 0,void 0,!0);return await ai.createAttribute(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(M3,"createAttribute");function P3(e){return ai.getBackup(e)}a(P3,"getBackup")});var CD=T((Cde,wD)=>{"use strict";var{OPERATIONS_ENUM:v3}=D(),_S=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=v3.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};wD.exports=_S});var dS=T((Ude,PD)=>{"use strict";var B3=ws(),Lde=CD(),fd=z(),Ed=D(),H3=j(),{handleHDBError:DD,hdb_errors:x3}=Z(),{HDB_ERROR_MSGS:LD,HTTP_STATUS_CODES:UD}=x3,q3=Object.values(Ed.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),MD="To use this operation audit log must be enabled in harperdb-config.yaml";PD.exports=F3;async function F3(e){if(fd.isEmpty(e.schema))throw new Error(LD.SCHEMA_REQUIRED_ERR);if(fd.isEmpty(e.table))throw new Error(LD.TABLE_REQUIRED_ERR);if(!H3.get(Ed.CONFIG_PARAMS.LOGGING_AUDITLOG))throw DD(new Error,MD,UD.BAD_REQUEST,Ed.LOG_LEVELS.ERROR,MD,!0);let t=fd.checkSchemaTableExist(e.schema,e.table);if(t)throw DD(new Error,t,UD.NOT_FOUND,Ed.LOG_LEVELS.ERROR,t,!0);if(!fd.isEmpty(e.search_type)&&q3.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await B3.readAuditLog(e)}a(F3,"readAuditLog")});var BD=T((Pde,vD)=>{"use strict";var{OPERATIONS_ENUM:G3}=D(),fS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=G3.GET_BACKUP,this.schema=t,this.table=r}};vD.exports=fS});var qD=T((xde,xD)=>{"use strict";var k3=ws(),Bde=BD(),ES=z(),V3=D(),Hde=j(),{handleHDBError:$3,hdb_errors:Y3}=Z(),{HDB_ERROR_MSGS:HD,HTTP_STATUS_CODES:K3}=Y3;xD.exports=W3;async function W3(e){if(ES.isEmpty(e.schema))throw new Error(HD.SCHEMA_REQUIRED_ERR);if(ES.isEmpty(e.table))throw new Error(HD.TABLE_REQUIRED_ERR);let t=ES.checkSchemaTableExist(e.schema,e.table);if(t)throw $3(new Error,t,K3.NOT_FOUND,V3.LOG_LEVELS.ERROR,t,!0);return await k3.getBackup(read_audit_log_object)}a(W3,"getBackup")});var YD=T((Fde,$D)=>{var ci=require("validate.js"),GD=Je(),ca=D(),{handleHDBError:Q3,hdb_errors:z3}=Z(),{HDB_ERROR_MSGS:Et,HTTP_STATUS_CODES:J3}=z3,hS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),X3={STRUCTURE_USER:"structure_user"},FD=Object.values(ca.ROLE_TYPES_ENUM),j3="attribute_permissions",Z3="attribute_name",{PERMS_CRUD_ENUM:ua}=ca,eX=[j3,...Object.values(ua)],kD=[ua.READ,ua.INSERT,ua.UPDATE],tX=[Z3,...kD];function rX(e){let t=hS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,VD(e,t)}a(rX,"addRoleValidation");function sX(e){let t=hS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,VD(e,t)}a(sX,"alterRoleValidation");function nX(e){let t=hS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,GD.validateObject(e,t)}a(nX,"dropRoleValidation");var iX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function VD(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)iX.includes(s[o])||n.push(s[o]);n.length>0&&Tt(Et.INVALID_ROLE_JSON_KEYS(n),r);let i=GD.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Tt(o,r)}),e.permission){let o=oX(e);o&&Tt(o,r),FD.forEach(c=>{e.permission[c]&&!ci.isBoolean(e.permission[c])&&Tt(Et.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(FD.indexOf(o)<0){if(o===X3.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||Tt(Et.SCHEMA_NOT_FOUND(d),r)}continue}Tt(Et.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Tt(Et.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){Tt(Et.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{eX.includes(l)||Tt(Et.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ua).forEach(l=>{ci.isDefined(_[l])?ci.isBoolean(_[l])||Tt(Et.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):Tt(Et.TABLE_PERM_MISSING(l),r,o,u)}),ci.isDefined(_.attribute_permissions)){if(!ci.isArray(_.attribute_permissions)){Tt(Et.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Tt(Et.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=>{!tX.includes(p)&&p!==ua.DELETE&&Tt(Et.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!ci.isDefined(E.attribute_name)){Tt(Et.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){Tt(Et.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}kD.forEach(p=>{ci.isDefined(E[p])?ci.isBoolean(E[p])||Tt(Et.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):Tt(Et.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;Tt(Et.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return aX(r)}a(VD,"customValidate");$D.exports={addRoleValidation:rX,alterRoleValidation:sX,dropRoleValidation:nX};function oX(e){let{operation:t,permission:r}=e;if(t===ca.OPERATIONS_ENUM.ADD_ROLE||t===ca.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return Et.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ca.ROLE_TYPES_ENUM.SUPER_USER:ca.ROLE_TYPES_ENUM.CLUSTER_USER;return Et.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(oX,"validateNoSUPerms");function aX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:Et.ROLE_PERMS_ERROR,...e};return Q3(new Error,s,J3.BAD_REQUEST)}else return null}a(aX,"generateRolePermResponse");function Tt(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(Tt,"addPermError")});var RS=T((kde,zD)=>{"use strict";var KD=Lr(),WD=es(),cX=ti(),pS=YD(),SS=An(),uX=require("uuid").v4,lX=require("util"),hd=D(),_X=z(),TS=WD.searchByValue,dX=WD.searchByHash,fX=lX.promisify(cX.delete),EX=Xs(),hX=ea(),{hdb_errors:mX,handleHDBError:no}=Z(),{HDB_ERROR_MSGS:QD,HTTP_STATUS_CODES:lu}=mX,{UserEventMsg:gS}=Ls();zD.exports={addRole:pX,alterRole:SX,dropRole:TX,listRoles:gX};function mS(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(mS,"scrubRoleDetails");async function pX(e){let t=pS.addRoleValidation(e);if(t)throw t;e=mS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},s;try{s=Array.from(await TS(r)||[])}catch(i){throw no(i)}if(s&&s.length>0)throw no(new Error,QD.ROLE_ALREADY_EXISTS(e.role),lu.CONFLICT,void 0,void 0,!0);e.id||(e.id=uX());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await KD.insert(n),SS.signalUserChange(new gS(process.pid)),e=mS(e),e}a(pX,"addRole");async function SX(e){let t=pS.alterRoleValidation(e);if(t)throw t;e=mS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await KD.update(r)}catch(n){throw no(n)}if(s&&s?.message==="updated 0 of 1 records")throw no(new Error,"Invalid role id",lu.BAD_REQUEST,void 0,void 0,!0);return await SS.signalUserChange(new gS(process.pid)),e}a(SX,"alterRole");async function TX(e){let t=pS.dropRoleValidation(e);if(t)throw no(new Error,t,lu.BAD_REQUEST,void 0,void 0,!0);let r=new hX(hd.SYSTEM_SCHEMA_NAME,hd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await dX(r));if(s.length===0)throw no(new Error,QD.ROLE_NOT_FOUND,lu.NOT_FOUND,void 0,void 0,!0);let n=new EX(hd.SYSTEM_SCHEMA_NAME,hd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await TS(n)),o=!1;if(_X.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw no(new Error,`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`,lu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await fX(c),SS.signalUserChange(new gS(process.pid)),`${s[0].role} successfully deleted`}a(TX,"dropRole");async function gX(){return TS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(gX,"listRoles")});var ZD=T(($de,jD)=>{"use strict";var RX=j(),ui=require("joi"),AX=Je(),JD=require("moment"),OX=require("fs-extra"),AS=require("path"),bX=require("lodash"),_u=D(),{LOG_LEVELS:io}=D(),NX="YYYY-MM-DD hh:mm:ss",yX=AS.resolve(__dirname,"../logs");jD.exports=function(e){return AX.validateBySchema(e,IX)};var IX=ui.object({from:ui.custom(XD),until:ui.custom(XD),level:ui.valid(io.NOTIFY,io.FATAL,io.ERROR,io.WARN,io.INFO,io.DEBUG,io.TRACE),order:ui.valid("asc","desc"),limit:ui.number().min(1),start:ui.number().min(0),log_name:ui.custom(wX)});function XD(e,t){if(JD(e,JD.ISO_8601).format(NX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(XD,"validateDatetime");function wX(e,t){if(bX.invert(_u.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=RX.get(_u.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?_u.LOG_NAMES.HDB:e,i=n===_u.LOG_NAMES.INSTALL?AS.join(yX,_u.LOG_NAMES.INSTALL):AS.join(s,n);return OX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(wX,"validateReadLogPath")});var bS=T((Kde,tL)=>{"use strict";var md=D(),CX=G(),DX=j(),LX=ZD(),OS=require("path"),eL=require("fs-extra"),{once:UX}=require("events"),{handleHDBError:MX,hdb_errors:PX}=Z(),{PACKAGE_ROOT:vX}=D(),BX=OS.join(vX,"logs"),HX=1e3,xX=200;tL.exports=qX;async function qX(e){let t=LX(e);if(t)throw MX(t,t.message,PX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=DX.get(md.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?md.LOG_NAMES.HDB:e.log_name,n=s===md.LOG_NAMES.INSTALL?OS.join(BX,md.LOG_NAMES.INSTALL):OS.join(r,s),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?HX: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(eL.statSync(n).size-(h+5)*xX,0));let S=eL.createReadStream(n,{start:p});S.on("error",q=>{CX.error(q)});let R=0,I=[],w="",B;S.on("data",q=>{let P=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;q=w+q;let Q=0,Y;for(;(Y=P.exec(q))&&!S.destroyed;){B&&(B.message=q.slice(Q,Y.index),K(B));let[J,re,Ie]=Y,se=Ie.split("] ["),ut=se[0],de=se[1];se.splice(0,2),B={timestamp:re,thread:ut,level:de,tags:se,message:""},Q=Y.index+J.length}w=q.slice(Q)}),S.on("end",q=>{S.destroyed||B&&(B.message=w.trim(),K(B))}),S.resume();function K(q){let P,Q,Y;switch(!0){case(i&&c&&_):P=new Date(q.timestamp),Q=new Date(u),Y=new Date(l),q.level===o&&P>=Q&&P<=Y&&R<E?R++:q.level===o&&P>=Q&&P<=Y&&(li(q,f,I),R++,R===h&&S.destroy());break;case(i&&c):P=new Date(q.timestamp),Q=new Date(u),q.level===o&&P>=Q&&R<E?R++:q.level===o&&P>=Q&&(li(q,f,I),R++,R===h&&S.destroy());break;case(i&&_):P=new Date(q.timestamp),Y=new Date(l),q.level===o&&P<=Y&&R<E?R++:q.level===o&&P<=Y&&(li(q,f,I),R++,R===h&&S.destroy());break;case(c&&_):P=new Date(q.timestamp),Q=new Date(u),Y=new Date(l),P>=Q&&P<=Y&&R<E?R++:P>=Q&&P<=Y&&(li(q,f,I),R++,R===h&&S.destroy());break;case i:q.level===o&&R<E?R++:q.level===o&&(li(q,f,I),R++,R===h&&S.destroy());break;case c:P=new Date(q.timestamp),Q=new Date(u),P>=Q&&R<E?R++:P>=Q&&R>=E&&(li(q,f,I),R++,R===h&&S.destroy());break;case _:P=new Date(q.timestamp),Y=new Date(l),P<=Y&&R<E?R++:P<=Y&&R>=E&&(li(q,f,I),R++,R===h&&S.destroy());break;default:R<E?R++:(li(q,f,I),R++,R===h&&S.destroy())}}return a(K,"onLogMessage"),await UX(S,"close"),I}a(qX,"readLog");function li(e,t,r){t==="desc"?FX(e,r):t==="asc"?GX(e,r):r.push(e)}a(li,"pushLineToResult");function FX(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(FX,"insertDescending");function GX(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(GX,"insertAscending")});var pd=T((Xde,iL)=>{"use strict";var NS=require("joi"),{string:du,boolean:rL,date:kX}=NS.types(),VX=Je(),{validateSchemaExists:Qde,validateTableExists:zde,validateSchemaName:Jde}=Ks(),$X=D(),YX=qe(),sL=j();sL.initSync();var KX=du.invalid(sL.get($X.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(YX.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(),nL={operation:du.valid("add_node","update_node","set_node_replication"),node_name:KX,subscriptions:NS.array().items({table:du.optional(),schema:du.optional(),database:du.optional(),subscribe:rL.required(),publish:rL.required().custom(QX),start_time:kX.iso()}).min(1).required()};function WX(e){return VX.validateBySchema(e,NS.object(nL))}a(WX,"addUpdateNodeValidator");function QX(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(QX,"checkForFalsy");iL.exports={addUpdateNodeValidator:WX,validation_schema:nL}});var aL=T((Zde,oL)=>{var zX=Je(),JX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};oL.exports=function(e){return zX.validateObject(e,JX)}});var Sd=T((efe,cL)=>{"use strict";var XX=D().OPERATIONS_ENUM,yS=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=XX.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};cL.exports=yS});var lL=T((rfe,uL)=>{"use strict";var jX={OPERATION:"operation",REFRESH:"refresh"},IS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},wS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};uL.exports={JWTTokens:IS,TOKEN_TYPE_ENUM:jX,JWTRSAKeys:wS}});var hu=T((nfe,EL)=>{"use strict";var Eu=require("jsonwebtoken"),CS=require("fs-extra"),DS=z(),is=D(),{handleHDBError:dr,hdb_errors:ZX}=Z(),{HTTP_STATUS_CODES:fr,AUTHENTICATION_ERROR_MSGS:Er}=ZX,fu=G(),_L=y_(),MS=rs(),ej=Lr().update,tj=Sd(),rj=An(),{UserEventMsg:sj}=Ls(),_i=j();_i.initSync();var LS=require("path"),{JWTTokens:nj,JWTRSAKeys:ij,TOKEN_TYPE_ENUM:Td}=lL(),oj=_i.get(is.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?_i.get(is.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",aj=_i.get(is.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?_i.get(is.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",gd="RS256",US;EL.exports={createTokens:cj,validateOperationToken:lj,refreshOperationToken:uj,validateRefreshToken:fL};async function cj(e){if(DS.isEmpty(e)||typeof e!="object")throw dr(new Error,Er.INVALID_AUTH_OBJECT,fr.BAD_REQUEST,void 0,void 0,!0);if(DS.isEmpty(e.username))throw dr(new Error,Er.USERNAME_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);if(DS.isEmpty(e.password))throw dr(new Error,Er.PASSWORD_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await MS.findAndValidateUser(e.username,e.password),!t)throw dr(new Error,Er.INVALID_CREDENTIALS,fr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw fu.error(f),dr(new Error,Er.INVALID_CREDENTIALS,fr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Rd(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await dL(i,r.private_key,r.passphrase),c=await Eu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:aj,algorithm:gd,subject:Td.REFRESH}),u=_L.hash(c),_=new tj(is.SYSTEM_SCHEMA_NAME,is.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await ej(_)}catch(f){fu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw dr(new Error,Er.REFRESH_TOKEN_SAVE_FAILED,fr.INTERNAL_SERVER_ERROR);return rj.signalUserChange(new sj(process.pid)),new nj(o,c)}a(cj,"createTokens");async function dL(e,t,r){return await Eu.sign(e,{key:t,passphrase:r},{expiresIn:oj,algorithm:gd,subject:Td.OPERATION})}a(dL,"signOperationToken");async function Rd(){if(US===void 0)try{let e=LS.join(_i.getHdbBasePath(),is.LICENSE_KEY_DIR_NAME,is.JWT_ENUM.JWT_PASSPHRASE_NAME),t=LS.join(_i.getHdbBasePath(),is.LICENSE_KEY_DIR_NAME,is.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=LS.join(_i.getHdbBasePath(),is.LICENSE_KEY_DIR_NAME,is.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await CS.readFile(e)).toString(),n=(await CS.readFile(t)).toString(),i=(await CS.readFile(r)).toString();US=new ij(i,n,s)}catch(e){throw fu.error(e),dr(new Error,Er.NO_ENCRYPTION_KEYS,fr.INTERNAL_SERVER_ERROR)}return US}a(Rd,"getJWTRSAKeys");async function uj(e){if(!e)throw dr(new Error,Er.INVALID_BODY,fr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw dr(new Error,Er.REFRESH_TOKEN_REQUIRED,fr.BAD_REQUEST,void 0,void 0,!0);await fL(e.refresh_token);let t=await Rd(),r=await Eu.decode(e.refresh_token);return{operation_token:await dL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(uj,"refreshOperationToken");async function lj(e){try{let t=await Rd(),r=await Eu.verify(e,t.public_key,{algorithms:gd,subject:Td.OPERATION});return await MS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw fu.warn(t),t.name&&t.name==="TokenExpiredError"?dr(new Error,Er.TOKEN_EXPIRED,fr.FORBIDDEN):dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED)}}a(lj,"validateOperationToken");async function fL(e){let t;try{let r=await Rd(),s=await Eu.verify(e,r.public_key,{algorithms:gd,subject:Td.REFRESH});t=await MS.findAndValidateUser(s.username,void 0,!1)}catch(r){throw fu.warn(r),r.name&&r.name==="TokenExpiredError"?dr(new Error,Er.TOKEN_EXPIRED,fr.FORBIDDEN):dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED)}if(!_L.validate(t.refresh_token,e))throw dr(new Error,Er.INVALID_TOKEN,fr.UNAUTHORIZED);return t}a(fL,"validateRefreshToken")});var PS=T((afe,pL)=>{"use strict";var _j=aL(),la=require("passport"),dj=require("passport-local").Strategy,fj=require("passport-http").BasicStrategy,Ej=require("util"),hj=rs(),mL=Ej.callbackify(hj.findAndValidateUser),ofe=Ir(),mj=D(),hL=hu();la.use(new dj(function(e,t,r){mL(e,t,r)}));la.use(new fj(function(e,t,r){mL(e,t,r)}));la.serializeUser(function(e,t){t(null,e)});la.deserializeUser(function(e,t){t(null,e)});function pj(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let s,n;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),s){case"Basic":la.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===mj.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?hL.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):hL.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:la.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(pj,"authorize");function Sj(e,t){let r=_j(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n?.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(Sj,"checkPermissions");pL.exports={authorize:pj,checkPermissions:Sj}});var di=T((ufe,SL)=>{"use strict";var vS=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},BS=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};SL.exports={Node:vS,NodeSubscription:BS}});var gL=T((_fe,TL)=>{"use strict";var Tj=D().OPERATIONS_ENUM,HS=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=Tj.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};TL.exports=HS});var mu=T((ffe,RL)=>{"use strict";var xS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},qS=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,s,n,i,o,c){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};RL.exports={RemotePayloadObject:xS,RemotePayloadSubscription:qS}});var OL=T((hfe,AL)=>{"use strict";var FS=class{static{a(this,"TableSizeObject")}constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};AL.exports=FS});var yL=T((gfe,NL)=>{"use strict";var gj=OL(),pfe=mt(),bL=Ke(),Rj=G(),{getSchemaPath:Sfe,getTransactionAuditStorePath:Tfe}=ze(),{getDatabases:Aj}=(ge(),ee(xe));NL.exports=Oj;async function Oj(e){let t=new gj;try{let r=Aj()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await bL.environmentDataSize(schema_path,e.name),o=await bL.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=s.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=n.entryCount}catch(r){Rj.warn(`unable to stat table dbi due to ${r}`)}return t}a(Oj,"lmdbGetTableSize")});var wL=T((Afe,IL)=>{"use strict";var GS=class{static{a(this,"SystemInformationObject")}constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};IL.exports=GS});var _a=T((yfe,UL)=>{"use strict";var bj=require("fs-extra"),Nj=require("path"),Xt=require("systeminformation"),fi=G(),yj=nt(),kS=qe(),Od=D(),Ij=yL(),LL=jn(),{getThreadInfo:CL}=Ye(),jS=j();jS.initSync();var wj=wL(),{openEnvironment:bfe}=Ke(),{getSchemaPath:Nfe}=ze(),{database:Cj}=(ge(),ee(xe)),Ad;UL.exports={getHDBProcessInfo:KS,getNetworkInfo:QS,getDiskInfo:WS,getMemoryInfo:YS,getCPUInfo:$S,getTimeInfo:VS,getSystemInformation:zS,systemInformation:Dj,getTableSize:JS,getMetrics:XS};function VS(){return Xt.time()}a(VS,"getTimeInfo");async function $S(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,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:p,raw_currentload_user:S,cpus:R,...I}=await Xt.currentLoad();return I.cpus=[],R.forEach(w=>{let{raw_load:B,raw_load_idle:K,raw_load_irq:q,raw_load_nice:P,raw_load_system:Q,raw_load_user:Y,...J}=w;I.cpus.push(J)}),l.current_load=I,l}catch(e){return fi.error(`error in getCPUInfo: ${e}`),{}}}a($S,"getCPUInfo");async function YS(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Xt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return fi.error(`error in getMemoryInfo: ${e}`),{}}}a(YS,"getMemoryInfo");async function KS(){let e={core:[],clustering:[]};try{let t=await Xt.processes(),r;try{r=Number.parseInt(await bj.readFile(Nj.join(jS.get(Od.CONFIG_PARAMS.ROOTPATH),Od.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===Od.NODE_ERROR_CODES.ENOENT)fi.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return fi.error(`error in getHDBProcessInfo: ${t}`),e}}a(KS,"getHDBProcessInfo");async function WS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...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 fi.error(`error in getDiskInfo: ${t}`),e}}a(WS,"getDiskInfo");async function QS(){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(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=s;e.interfaces.push(f)}),(await Xt.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return fi.error(`error in getNetworkInfo: ${t}`),e}}a(QS,"getNetworkInfo");async function zS(){if(Ad!==void 0)return Ad;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,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,Ad=e,Ad}catch(t){return fi.error(`error in getSystemInformation: ${t}`),e}}a(zS,"getSystemInformation");async function JS(){let e=[],t=await LL.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await Ij(s));return e}a(JS,"getTableSize");async function XS(){let e=await LL.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let i=Cj({database:r,table:n}),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}}),s[n]=o}catch(i){fi.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(XS,"getMetrics");async function DL(){if(jS.get(Od.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await yj.getNATSReferences(),r=await t.streams.info(kS.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(kS.WORK_QUEUE_CONSUMER_NAMES.stream_name,kS.WORK_QUEUE_CONSUMER_NAMES.durable_name),n={ingest:{stream:{...r.state},consumer:{num_ack_pending:s._info.num_ack_pending,num_redelivered:s._info.num_redelivered,num_waiting:s._info.num_waiting,num_pending:s._info.num_pending}}};return r.sources&&(n.ingest.stream.sources=r.sources),n}}a(DL,"getNatsStreamInfo");async function Dj(e){let t=new wj;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await zS(),t.time=VS(),t.cpu=await $S(),t.memory=await YS(),t.disk=await WS(),t.network=await QS(),t.harperdb_processes=await KS(),t.table_size=await JS(),t.metrics=await XS(),t.threads=await CL(),t.replication=await DL(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await zS();break;case"time":t.time=VS();break;case"cpu":t.cpu=await $S();break;case"memory":t.memory=await YS();break;case"disk":t.disk=await WS();break;case"network":t.network=await QS();break;case"harperdb_processes":t.harperdb_processes=await KS();break;case"table_size":t.table_size=await JS();break;case"database_metrics":case"metrics":t.metrics=await XS();break;case"threads":t.threads=await CL();break;case"replication":t.replication=await DL();break;default:break}return t}a(Dj,"systemInformation")});var ZS=T((wfe,ML)=>{"use strict";ML.exports={version:Lj,printVersion:Uj};var bd=jc();function Lj(){if(bd)return bd.version}a(Lj,"version");function Uj(){bd&&console.log(`HarperDB Version ${bd.version}`)}a(Uj,"printVersion")});var os=T((Ufe,HL)=>{"use strict";var Mj=Lr(),eT=z(),Pj=require("util"),oo=D(),PL=j();PL.initSync();var vj=PS(),vL=es(),{Node:Dfe,NodeSubscription:Lfe}=di(),Bj=ea(),Hj=gL(),{RemotePayloadObject:xj,RemotePayloadSubscription:qj}=mu(),{handleHDBError:Fj,hdb_errors:Gj}=Z(),{HTTP_STATUS_CODES:kj,HDB_ERROR_MSGS:Vj}=Gj,$j=Xs(),Yj=_a(),Kj=ZS(),{getDatabases:Wj}=(ge(),ee(xe)),Qj=Pj.promisify(vj.authorize),zj=vL.searchByHash,Jj=vL.searchByValue;HL.exports={authHeaderToUser:Xj,isEmpty:jj,getNodeRecord:Zj,upsertNodeRecord:eZ,buildNodePayloads:tZ,checkClusteringEnabled:rZ,getAllNodeRecords:sZ,getSystemInfo:nZ,reverseSubscription:BL};async function Xj(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await Qj(t,null),e}a(Xj,"authHeaderToUser");function jj(e){return e==null}a(jj,"isEmpty");async function Zj(e){let t=new Bj(oo.SYSTEM_SCHEMA_NAME,oo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return zj(t)}a(Zj,"getNodeRecord");async function eZ(e){let t=new Hj(oo.SYSTEM_SCHEMA_NAME,oo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return Mj.upsert(t)}a(eZ,"upsertNodeRecord");function BL(e){if(eT.isEmpty(e.subscribe)||eT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(BL,"reverseSubscription");function tZ(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=eT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=BL(c),E=Wj()[u]?.[_],h=new qj(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new xj(r,t,n,s)}a(tZ,"buildNodePayloads");function rZ(){if(!PL.get(oo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Fj(new Error,Vj.CLUSTERING_NOT_ENABLED,kj.BAD_REQUEST,void 0,void 0,!0)}a(rZ,"checkClusteringEnabled");async function sZ(){let e=new $j(oo.SYSTEM_SCHEMA_NAME,oo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await Jj(e))}a(sZ,"getAllNodeRecords");async function nZ(){let e=await Yj.getSystemInformation();return{hdb_version:Kj.version(),node_version:e.node_version,platform:e.platform}}a(nZ,"getSystemInfo")});var tT=T((Pfe,YL)=>{"use strict";var Nd=nt(),xL=z(),qL=qe(),FL=D(),yd=G(),GL=uu(),iZ=K_(),{RemotePayloadObject:oZ}=mu(),{handleHDBError:kL,hdb_errors:aZ}=Z(),{HTTP_STATUS_CODES:VL}=aZ,{NodeSubscription:$L}=di();YL.exports=cZ;async function cZ(e,t){let r;try{r=await Nd.request(`${t}.${qL.REQUEST_SUFFIX}`,new oZ(FL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),yd.trace("Response from remote describe all request:",r)}catch(o){yd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Nd.requestErrorHandler(o,"add_node",t);throw kL(new Error,c,VL.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===qL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw kL(new Error,o,VL.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===FL.SYSTEM_SCHEMA_NAME){await Nd.createLocalTableStream(u,c);let h=new $L(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=xL.doesSchemaExist(u),l=s[u]!==void 0,d=c?xL.doesTableExist(u,c):!0,f=c?s?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){n.push(o);continue}if(!_&&l&&(yd.trace(`addNode creating schema: ${u}`),await GL.createSchema({operation:"create_schema",schema:u})),!d&&f){yd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(s[u][c].attributes)}`);let h=new iZ(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await GL.createTable(h)}await Nd.createLocalTableStream(u,c);let E=new $L(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(cZ,"reviewSubscriptions")});var Cd=T((Bfe,QL)=>{"use strict";var{handleHDBError:Id,hdb_errors:uZ}=Z(),{HTTP_STATUS_CODES:wd}=uZ,{addUpdateNodeValidator:lZ}=pd(),pu=G(),WL=D(),KL=qe(),_Z=z(),rT=nt(),Su=os(),dZ=j(),fZ=tT(),{Node:EZ,NodeSubscription:hZ}=di(),{broadcast:mZ}=Ye(),pZ="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",SZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",TZ=dZ.get(WL.CONFIG_PARAMS.CLUSTERING_NODENAME);QL.exports=gZ;async function gZ(e,t=!1){pu.trace("addNode called with:",e),Su.checkClusteringEnabled();let r=lZ(e);if(r)throw Id(r,r.message,wd.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await Su.getNodeRecord(s);if(!_Z.isEmptyOrZeroLength(d))throw Id(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,wd.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await fZ(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=pZ,o;let c=Su.buildNodePayloads(n,TZ,WL.OPERATIONS_ENUM.ADD_NODE,await Su.getSystemInfo());pu.trace("addNode sending remote payload:",c);let u;try{u=await rT.request(`${s}.${KL.REQUEST_SUFFIX}`,c)}catch(d){pu.error(`addNode received error from request: ${d}`);let f=rT.requestErrorHandler(d,"add_node",s);throw Id(new Error,f,wd.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===KL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw Id(new Error,d,wd.INTERNAL_SERVER_ERROR,"error",d)}pu.trace(u);let _=[];for(let d=0,f=n.length;d<f;d++){let E=n[d];pu.trace("Add node updating work stream for node:",s,"subscriptions:",E),await rT.updateWorkStream(E,s),n[d].start_time===void 0&&delete n[d].start_time,_.push(new hZ(E.schema,E.table,E.publish,E.subscribe))}let l=new EZ(s,_,u.system_info);return await Su.upsertNodeRecord(l),mZ({type:"nats_update"}),i.length>0?o.message=SZ:o.message=`Successfully added '${s}' to manifest`,o}a(gZ,"addNode")});var oT=T((qfe,XL)=>{"use strict";var{handleHDBError:sT,hdb_errors:RZ}=Z(),{HTTP_STATUS_CODES:nT}=RZ,{addUpdateNodeValidator:AZ}=pd(),Tu=G(),JL=D(),zL=qe(),xfe=z(),iT=nt(),gu=os(),OZ=j(),{cloneDeep:bZ}=require("lodash"),NZ=tT(),{Node:yZ,NodeSubscription:IZ}=di(),{broadcast:wZ}=Ye(),CZ="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",DZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",LZ=OZ.get(JL.CONFIG_PARAMS.CLUSTERING_NODENAME);XL.exports=UZ;async function UZ(e){Tu.trace("updateNode called with:",e),gu.checkClusteringEnabled();let t=AZ(e);if(t)throw sT(t,t.message,nT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await gu.getNodeRecord(r);n.length>0&&(s=bZ(n));let{added:i,skipped:o}=await NZ(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=CZ,c;let u=gu.buildNodePayloads(i,LZ,JL.OPERATIONS_ENUM.UPDATE_NODE,await gu.getSystemInfo());Tu.trace("updateNode sending remote payload:",u);let _;try{_=await iT.request(`${r}.${zL.REQUEST_SUFFIX}`,u)}catch(l){Tu.error(`updateNode received error from request: ${l}`);let d=iT.requestErrorHandler(l,"update_node",r);throw sT(new Error,d,nT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===zL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw sT(new Error,l,nT.INTERNAL_SERVER_ERROR,"error",l)}Tu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];Tu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await iT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return s||(s=[new yZ(r,[],_.system_info)]),await MZ(s[0],i,_.system_info),o.length>0?c.message=DZ:c.message=`Successfully updated '${r}'`,c}a(UZ,"updateNode");async function MZ(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=s.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new IZ(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await gu.upsertNodeRecord(s),wZ({type:"nats_update"})}a(MZ,"updateNodeTable")});var rU=T((Gfe,tU)=>{"use strict";var eU=require("joi"),{string:jL}=eU.types(),PZ=Je(),ZL=D(),vZ=j(),BZ=qe();tU.exports=HZ;function HZ(e){let t=jL.invalid(vZ.get(ZL.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(BZ.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=eU.object({operation:jL.valid(ZL.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return PZ.validateBySchema(e,r)}a(HZ,"removeNodeValidator")});var Ld=T((Vfe,cU)=>{"use strict";var{handleHDBError:sU,hdb_errors:xZ}=Z(),{HTTP_STATUS_CODES:nU}=xZ,qZ=rU(),Ru=G(),iU=os(),FZ=z(),Dd=D(),oU=qe(),aU=nt(),GZ=j(),{RemotePayloadObject:kZ}=mu(),{NodeSubscription:VZ}=di(),$Z=ta(),YZ=ti(),{broadcast:KZ}=Ye(),WZ=GZ.get(Dd.CONFIG_PARAMS.CLUSTERING_NODENAME);cU.exports=QZ;async function QZ(e){Ru.trace("removeNode called with:",e),iU.checkClusteringEnabled();let t=qZ(e);if(t)throw sU(t,t.message,nU.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await iU.getNodeRecord(r);if(FZ.isEmptyOrZeroLength(s))throw sU(new Error,`Node '${r}' was not found.`,nU.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new kZ(Dd.OPERATIONS_ENUM.REMOVE_NODE,WZ,[]),i,o=!1;try{i=await aU.request(`${r}.${oU.REQUEST_SUFFIX}`,n),Ru.trace("Remove node reply from remote node:",r,i)}catch(u){Ru.error("removeNode received error from request:",u),o=!0}for(let u=0,_=s.subscriptions.length;u<_;u++){let l=s.subscriptions[u];Ru.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new VZ(l.schema,l.table,!1,!1);await aU.updateWorkStream(d,r)}let c=new $Z(Dd.SYSTEM_SCHEMA_NAME,Dd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await YZ.deleteRecord(c),KZ({type:"nats_update"}),i?.status===oU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Ru.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(QZ,"removeNode")});var _U=T((Yfe,lU)=>{"use strict";var uU=require("joi"),{string:zZ,array:JZ}=uU.types(),XZ=Je(),jZ=pd();lU.exports=ZZ;function ZZ(e){let t=uU.object({operation:zZ.valid("configure_cluster").required(),connections:JZ.items(jZ.validation_schema).required()});return XZ.validateBySchema(e,t)}a(ZZ,"configureClusterValidator")});var aT=T((Wfe,mU)=>{"use strict";var e5=D(),Ud=G(),t5=z(),r5=Ld(),s5=Cd(),dU=os(),n5=_U(),{handleHDBError:fU,hdb_errors:i5}=Z(),{HTTP_STATUS_CODES:EU}=i5,o5="Configure cluster complete.",a5="Failed to configure the cluster. Check the logs for more details.",c5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";mU.exports=u5;async function u5(e){Ud.trace("configure cluster called with:",e),dU.checkClusteringEnabled();let t=n5(e);if(t)throw fU(t,t.message,EU.BAD_REQUEST,void 0,void 0,!0);let r=await dU.getAllNodeRecords(),s=[];for(let f=0,E=r.length;f<E;f++)s.push(hU(r5,{operation:e5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let n=await Promise.allSettled(s);Ud.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(hU(s5,E,E.node_name))}let c=await Promise.allSettled(i);Ud.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=n.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(Ud.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(t5.isEmptyOrZeroLength(u))return{message:o5,connections:_};if(l)return{message:c5,failed_nodes:u,connections:_};throw fU(new Error,a5,EU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(u5,"configureCluster");async function hU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(hU,"functionWrapper")});var SU=T((zfe,pU)=>{"use strict";var Md=require("joi"),l5=Je(),{validateSchemaExists:_5,validateTableExists:d5,validateSchemaName:f5}=Ks(),E5=Md.object({operation:Md.string().valid("purge_stream"),schema:Md.string().custom(_5).custom(f5).required(),table:Md.string().custom(d5).required()});function h5(e){return l5.validateBySchema(e,E5)}a(h5,"purgeStreamValidator");pU.exports=h5});var cT=T((Xfe,TU)=>{"use strict";var{handleHDBError:m5,hdb_errors:p5}=Z(),{HTTP_STATUS_CODES:S5}=p5,T5=SU(),g5=nt(),R5=os();TU.exports=A5;async function A5(e){if(e.purge_ingest!==!0){let n=T5(e);if(n)throw m5(n,n.message,S5.BAD_REQUEST,void 0,void 0,!0)}R5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:s}=e;return await g5.purgeTableStream(t,r,s),s?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(A5,"purgeStream")});var _T=T((Zfe,NU)=>{"use strict";var lT=os(),O5=nt(),AU=j(),Pd=D(),ao=qe(),b5=z(),uT=G(),{RemotePayloadObject:N5}=mu(),{ErrorCode:gU}=require("nats"),RU=AU.get(Pd.CONFIG_PARAMS.CLUSTERING_ENABLED),OU=AU.get(Pd.CONFIG_PARAMS.CLUSTERING_NODENAME);NU.exports={clusterStatus:y5,buildNodeStatus:bU};async function y5(){let e={node_name:OU,is_enabled:RU,connections:[]};if(!RU)return e;let t=await lT.getAllNodeRecords();if(b5.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(bU(t[s],e.connections));return await Promise.allSettled(r),e}a(y5,"clusterStatus");async function bU(e,t){let r=e.name,s=new N5(Pd.OPERATIONS_ENUM.CLUSTER_STATUS,OU,void 0,await lT.getSystemInfo()),n,i,o=ao.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await O5.request(ao.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===ao.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=ao.CLUSTER_STATUS_STATUSES.CLOSED,uT.error(`Error getting node status from ${r} `,n))}catch(u){uT.warn(`Error getting node status from ${r}`,u),u.code===gU.NoResponders?o=ao.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===gU.Timeout?o=ao.CLUSTER_STATUS_STATUSES.TIMEOUT:o=ao.CLUSTER_STATUS_STATUSES.CLOSED}let c=new I5(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let u={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==Pd.PRE_4_0_0_VERSION&&await lT.upsertNodeRecord(u)}catch(u){uT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(bU,"buildNodeStatus");function I5(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(I5,"NodeStatusObject")});var fT=T((tEe,yU)=>{"use strict";var{handleHDBError:w5,hdb_errors:C5}=Z(),{HTTP_STATUS_CODES:D5}=C5,L5=nt(),U5=os(),dT=z(),vd=require("joi"),M5=Je(),P5=2e3,v5=vd.object({timeout:vd.number().min(1),connected_nodes:vd.boolean(),routes:vd.boolean()});yU.exports=B5;async function B5(e){U5.checkClusteringEnabled();let t=M5.validateBySchema(e,v5);if(t)throw w5(t,t.message,D5.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||dT.autoCastBoolean(s),o=n===void 0||dT.autoCastBoolean(n),c={nodes:[]},u=await L5.getServerList(r??P5),_={};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:dT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(B5,"clusterNetwork")});var DU=T((sEe,CU)=>{"use strict";var ET=require("joi"),IU=Je(),{route_constraints:wU}=Pm();CU.exports={setRoutesValidator:H5,deleteRoutesValidator:x5};function H5(e){let t=ET.object({server:ET.valid("hub","leaf").required(),routes:wU.required()});return IU.validateBySchema(e,t)}a(H5,"setRoutesValidator");function x5(e){let t=ET.object({routes:wU.required()});return IU.validateBySchema(e,t)}a(x5,"deleteRoutesValidator")});var mT=T((iEe,PU)=>{"use strict";var co=Pr(),hT=z(),Bd=D(),LU=DU(),{handleHDBError:UU,hdb_errors:q5}=Z(),{HTTP_STATUS_CODES:MU}=q5,F5="cluster routes successfully set",G5="cluster routes successfully deleted";PU.exports={setRoutes:k5,getRoutes:V5,deleteRoutes:$5};function k5(e){let t=LU.setRoutesValidator(e);if(t)throw UU(t,t.message,MU.BAD_REQUEST,void 0,void 0,!0);let r=co.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=hT.autoCast(_.port);let l=s.some(f=>f.host===_.host&&f.port===_.port),d=n.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(s.push(_),o.push(_))}return e.server==="hub"?co.updateConfigValue(Bd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):co.updateConfigValue(Bd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:F5,set:o,skipped:i}}a(k5,"setRoutes");function V5(){let e=co.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(V5,"getRoutes");function $5(e){let t=LU.deleteRoutesValidator(e);if(t)throw UU(t,t.message,MU.BAD_REQUEST,void 0,void 0,!0);let r=co.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=s.length;E<h;E++){let p=s[E];if(d.host===p.host&&d.port===p.port){s.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=n.length;h<p;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(s=hT.isEmptyOrZeroLength(s)?null:s,co.updateConfigValue(Bd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=hT.isEmptyOrZeroLength(n)?null:n,co.updateConfigValue(Bd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:G5,deleted:i,skipped:o}}a($5,"deleteRoutes")});var BU=T((aEe,vU)=>{"use strict";var Au=require("alasql"),uo=require("recursive-iterator"),Bs=G(),Y5=z(),Ou=D(),pT=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,W5(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(n=>Ou.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!Ou.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Ou.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=K5(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(_=>!Ou.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Au.yy.Column({columnid:_});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function K5(e){return e.filter(t=>t[Ou.PERMS_CRUD_ENUM.READ])}a(K5,"filterReadRestrictedAttrs");function W5(e,t,r,s,n){Q5(e,t,r,s,n)}a(W5,"interpretAST");function bu(e,t,r,s,n){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a(bu,"addSchemaTableToMap");function Q5(e,t,r,s,n){if(!e){Bs.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Au.yy.Insert?j5(e,t,r):e instanceof Au.yy.Select?z5(e,t,r,s,n):e instanceof Au.yy.Update?J5(e,t,r):e instanceof Au.yy.Delete?X5(e,t,r):Bs.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(Q5,"getRecordAttributesAST");function z5(e,t,r,s,n){if(!e){Bs.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(Y5.isEmptyOrZeroLength(i)){Bs.error("No schema specified");return}e.from.forEach(c=>{bu(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),bu(c.table,t,r,s,n)});let o=new uo(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Bs.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 uo(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{Bs.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 uo(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=n.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Bs.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 uo(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Bs.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(z5,"getSelectAttributes");function J5(e,t,r){if(!e){Bs.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new uo(e.columns),n=e.table.databaseid;bu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&ST(e.table.tableid,n,i.columnid,t,r)}a(J5,"getUpdateAttributes");function X5(e,t,r){if(!e){Bs.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new uo(e.where),n=e.table.databaseid;bu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&ST(e.table.tableid,n,i.columnid,t,r)}a(X5,"getDeleteAttributes");function j5(e,t,r){if(!e){Bs.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new uo(e.columns),n=e.into.databaseid;bu(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&ST(e.into.tableid,n,i.columnid,t,r)}a(j5,"getInsertAttributes");function ST(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(ST,"pushAttribute");vU.exports=pT});var RT=T((uEe,FU)=>{var Hd=Yi(),HU=require("chalk"),Gr=G(),xU=require("prompt"),{promisify:Z5}=require("util"),TT=D(),e8=require("fs-extra"),t8=require("path"),r8=z(),s8=ZS(),qU=j();qU.initSync();var n8=require("moment"),i8=Z5(xU.get),o8=t8.join(qU.getHdbBasePath(),TT.LICENSE_KEY_DIR_NAME,TT.LICENSE_FILE_NAME,TT.LICENSE_FILE_NAME);FU.exports={getFingerprint:c8,setLicense:a8,parseLicense:gT,register:u8,getRegistrationInfo:_8};async function a8(e){if(e&&e.key&&e.company){try{Gr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await gT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Gr.error(r),Gr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(a8,"setLicense");async function c8(){let e={};try{e=await Hd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Gr.error(r),Gr.error(t),new Error(r)}return e}a(c8,"getFingerprint");async function gT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Gr.info("Validating license input...");let r=Hd.validateLicense(e,t);if(Gr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Gr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Gr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Gr.info("writing license to disk"),await e8.writeFile(o8,JSON.stringify({license_key:e,company:t}))}catch(s){throw Gr.error("Failed to write License"),s}return"Registration successful."}a(gT,"parseLicense");async function u8(){let e=await l8();return gT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(u8,"register");async function l8(){let e=await Hd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:HU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:HU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{xU.start()}catch(s){Gr.error(s)}let r;try{r=await i8(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(l8,"promptForRegistration");async function _8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Hd.getLicense()}catch(r){throw Gr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(r8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=s8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=n8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(_8,"getRegistrationInfo")});var kU=T((_Ee,GU)=>{"use strict";var d8=qe(),AT=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+d8.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};GU.exports=AT});var YU=T((fEe,$U)=>{"use strict";var VU=qe(),OT=class{static{a(this,"LeafConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+VU.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+VU.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};$U.exports=OT});var WU=T((hEe,KU)=>{"use strict";var bT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};KU.exports=bT});var zU=T((pEe,QU)=>{"use strict";var f8=qe(),NT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+f8.SERVER_SUFFIX.ADMIN,this.password=r}};QU.exports=NT});var wT=T((TEe,jU)=>{"use strict";var da=require("path"),Fd=require("fs-extra"),E8=kU(),h8=YU(),m8=WU(),p8=zU(),yT=rs(),Ea=z(),hr=Pr(),qd=D(),Nu=qe(),{CONFIG_PARAMS:ht}=qd,yu=G(),Iu=j(),JU=gn(),IT=nt(),fa="clustering",S8=1e4,XU=5;jU.exports={generateNatsConfig:g8,removeNatsConfig:R8,getHubConfigPath:T8};function T8(){let e=Iu.get(ht.ROOTPATH);return da.join(e,fa,Nu.NATS_CONFIG_FILES.HUB_SERVER)}a(T8,"getHubConfigPath");async function g8(e=!1,t=void 0){Iu.initSync();let r=Iu.get(ht.ROOTPATH),s=da.join(r,fa,Nu.PID_FILES.HUB),n=da.join(r,fa,Nu.PID_FILES.LEAF),i=hr.getConfigFromFile(ht.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=da.join(r,fa,Nu.NATS_CONFIG_FILES.HUB_SERVER),c=da.join(r,fa,Nu.NATS_CONFIG_FILES.LEAF_SERVER),u=hr.getConfigFromFile(ht.CLUSTERING_TLS_CERTIFICATE),_=hr.getConfigFromFile(ht.CLUSTERING_TLS_PRIVATEKEY),l=hr.getConfigFromFile(ht.CLUSTERING_TLS_CERT_AUTH),d=hr.getConfigFromFile(ht.CLUSTERING_TLS_INSECURE),f=hr.getConfigFromFile(ht.CLUSTERING_TLS_VERIFY),E=hr.getConfigFromFile(ht.CLUSTERING_NODENAME),h=hr.getConfigFromFile(ht.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await IT.checkNATSServerInstalled()||Gd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await yT.listUsers(),S=hr.getConfigFromFile(ht.CLUSTERING_USER),R=await yT.getClusterUser();(Ea.isEmpty(R)||R.active!==!0)&&Gd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await xd(ht.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await xd(ht.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await xd(ht.CLUSTERING_HUBSERVER_NETWORK_PORT),await xd(ht.CLUSTERING_LEAFSERVER_NETWORK_PORT));let I=[],w=[];for(let[J,re]of p.entries())re.role.role===qd.ROLE_TYPES_ENUM.CLUSTER_USER&&re.active&&(I.push(new p8(re.username,JU.decrypt(re.hash))),w.push(new m8(re.username,JU.decrypt(re.hash))));let B=[],{hub_routes:K}=hr.getClusteringRoutes();if(!Ea.isEmptyOrZeroLength(K))for(let J of K)B.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${J.host}:${J.port}`);let q=new E8(hr.getConfigFromFile(ht.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,hr.getConfigFromFile(ht.CLUSTERING_HUBSERVER_CLUSTER_NAME),hr.getConfigFromFile(ht.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),B,I,w);l==null&&(delete q.tls.ca_file,delete q.leafnodes.tls.ca_file),t=Ea.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===qd.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Fd.writeJson(o,q),yu.trace(`Hub server config written to ${o}`));let P=`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,Q=`tls://${R.uri_encoded_name}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,Y=new h8(hr.getConfigFromFile(ht.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[P],[Q],I,w,u,_,l,d);l==null&&delete Y.tls.ca_file,(t===void 0||t===qd.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Fd.writeJson(c,Y),yu.trace(`Leaf server config written to ${c}`))}a(g8,"generateNatsConfig");async function xd(e){let t=Iu.get(e);return Ea.isEmpty(t)&&Gd(`port undefined for '${e}'`),await Ea.isPortTaken(t)&&Gd(`'${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(xd,"isPortAvailable");function Gd(e){let t=`Error generating clustering config: ${e}`;yu.error(t),console.error(t),process.exit(1)}a(Gd,"generateNatsConfigError");async function R8(e){let{port:t,config_file:r}=IT.getServerConfig(e),{username:s,decrypt_hash:n}=await yT.getClusterUser(),i=0,o=2e3;for(;i<XU;){try{let _=await IT.createConnection(t,s,n,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){yu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=XU)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 Ea.async_set_timeout(o*(i*2))}let c="0".repeat(S8),u=da.join(Iu.get(ht.ROOTPATH),fa,r);await Fd.writeFile(u,c),await Fd.remove(u),yu.notify(e,"started.")}a(R8,"removeNatsConfig")});var nM=T((REe,sM)=>{"use strict";var kr=j(),A8=Yi(),he=D(),wu=qe(),In=require("path"),{PACKAGE_ROOT:Vd}=D(),ZU=j(),kd=z(),ha="/dev/null",O8=In.join(Vd,"launchServiceScripts"),eM=In.join(Vd,"utility/scripts"),b8=In.join(eM,he.HDB_RESTART_SCRIPT),tM=In.resolve(Vd,"dependencies",`${process.platform}-${process.arch}`,wu.NATS_BINARY_NAME);function rM(){let t=A8.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,s={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return kd.noBootFile()&&(s[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=kd.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:Vd}}a(rM,"generateMainServerConfig");var N8=9930;function y8(){kr.initSync(!0);let e=kr.get(he.CONFIG_PARAMS.ROOTPATH),t=In.join(e,"clustering",wu.NATS_CONFIG_FILES.HUB_SERVER),r=In.join(kr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=ZU.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=wu.LOG_LEVEL_FLAGS[kr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==N8?"-"+s:""),script:tM,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return kr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ha,i.error_file=ha),i}a(y8,"generateNatsHubServerConfig");var I8=9940;function w8(){kr.initSync(!0);let e=kr.get(he.CONFIG_PARAMS.ROOTPATH),t=In.join(e,"clustering",wu.NATS_CONFIG_FILES.LEAF_SERVER),r=In.join(kr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),s=ZU.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=wu.LOG_LEVEL_FLAGS[kr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==I8?"-"+s:""),script:tM,args:n?`${n} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return kr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ha,i.error_file=ha),i}a(w8,"generateNatsLeafServerConfig");function C8(){kr.initSync();let e=In.join(kr.get(he.CONFIG_PARAMS.LOGGING_ROOT),he.LOG_NAMES.HDB),t={name:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:he.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:O8,autorestart:!1};return kr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ha,t.error_file=ha),t}a(C8,"generateClusteringUpgradeV4ServiceConfig");function D8(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return kd.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=kd.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:eM},script:b8}}a(D8,"generateRestart");function L8(){return{apps:[rM()]}}a(L8,"generateAllServiceConfigs");sM.exports={generateAllServiceConfigs:L8,generateMainServerConfig:rM,generateRestart:D8,generateNatsHubServerConfig:y8,generateNatsLeafServerConfig:w8,generateClusteringUpgradeV4ServiceConfig:C8}});var SM=T((bEe,pM)=>{"use strict";var Ce=D(),U8=z(),wn=wT(),Cu=nt(),tn=qe(),Ei=nM(),$d=j(),hi=G(),M8=os(),{startWorker:iM,onMessageFromWorkers:P8}=Ye(),v8=_a(),OEe=require("util"),B8=require("child_process"),H8=require("fs"),{execFile:x8}=B8,be;pM.exports={enterPM2Mode:q8,start:mi,stop:CT,reload:aM,restart:cM,list:DT,describe:lM,connect:Cn,kill:$8,startAllServices:Y8,startService:LT,getUniqueServicesList:_M,restartAllServices:K8,isServiceRegistered:dM,reloadStopStart:fM,restartHdb:uM,deleteProcess:k8,startClusteringProcesses:hM,startClusteringThreads:mM,isHdbRestartRunning:V8,isClusteringRunning:Q8,stopClustering:W8,reloadClustering:z8};var Du=!1;P8(e=>{e.type==="restart"&&$d.initSync(!0)});function q8(){Du=!0}a(q8,"enterPM2Mode");function Cn(){return be||(be=require("pm2")),new Promise((e,t)=>{be.connect((r,s)=>{hi.setupConsoleLogging(),r&&t(r),e(s)})})}a(Cn,"connect");var mr,F8=10,oM;function mi(e,t=!1){if(Du)return G8(e);let r=x8(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=mr.indexOf(r);o>-1&&mr.splice(o,1),!oM&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<F8&&(H8.existsSync(wn.getHubConfigPath())?mi(e):(await wn.generateNatsConfig(!0),mi(e),await new Promise(c=>setTimeout(c,3e3)),await wn.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await wn.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=$d.get(Ce.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&tn.LOG_LEVEL_HIERARCHY[o]>=tn.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===tn.LOG_LEVELS.ERR||l===tn.LOG_LEVELS.WRN?hi.OUTPUTS.STDERR:hi.OUTPUTS.STDOUT;hi.logCustomLevel(l||"info",E,s,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=tn.LOG_LEVELS[f]}if(tn.LOG_LEVEL_HIERARCHY[o]>=tn.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===tn.LOG_LEVELS.ERR||l===tn.LOG_LEVELS.WRN?hi.OUTPUTS.STDERR:hi.OUTPUTS.STDOUT;hi.logCustomLevel(l||"info",d,s,i.slice(_).trim())}}if(a(n,"extractMessages"),r.stdout.on("data",n),r.stderr.on("data",n),r.unref(),mr=[],!mr&&!t){let i=a(()=>{oM=!0,mr&&(mr.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)}mr.push(r)}a(mi,"start");function G8(e){return new Promise(async(t,r)=>{try{await Cn()}catch(s){r(s)}be.start(e,(s,n)=>{s&&(be.disconnect(),r(s)),be.disconnect(),t(n)})})}a(G8,"startWithPM2");function CT(e){if(!Du){for(let t of mr||[])t.name===e&&(mr.splice(mr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Cn()}catch(s){r(s)}be.stop(e,async(s,n)=>{s&&(be.disconnect(),r(s)),be.delete(e,(i,o)=>{i&&(be.disconnect(),r(s)),be.disconnect(),t(o)})})})}a(CT,"stop");function aM(e){return new Promise(async(t,r)=>{try{await Cn()}catch(s){r(s)}be.reload(e,(s,n)=>{s&&(be.disconnect(),r(s)),be.disconnect(),t(n)})})}a(aM,"reload");function cM(e){if(!Du)for(let t of mr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Cn()}catch(s){r(s)}be.restart(e,(s,n)=>{be.disconnect(),t(n)})})}a(cM,"restart");function k8(e){return new Promise(async(t,r)=>{try{await Cn()}catch(s){r(s)}be.delete(e,(s,n)=>{s&&(be.disconnect(),r(s)),be.disconnect(),t(n)})})}a(k8,"deleteProcess");async function uM(){await mi(Ei.generateRestart())}a(uM,"restartHdb");async function V8(){let e=await DT();for(let t in e)if(e[t].name===Ce.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(V8,"isHdbRestartRunning");function DT(){return new Promise(async(e,t)=>{try{await Cn()}catch(r){t(r)}be.list((r,s)=>{r&&(be.disconnect(),t(r)),be.disconnect(),e(s)})})}a(DT,"list");function lM(e){return new Promise(async(t,r)=>{try{await Cn()}catch(s){r(s)}be.describe(e,(s,n)=>{s&&(be.disconnect(),r(s)),be.disconnect(),t(n)})})}a(lM,"describe");function $8(){if(!Du){for(let e of mr||[])e.kill();mr=[];return}return new Promise(async(e,t)=>{try{await Cn()}catch(r){t(r)}be.killDaemon((r,s)=>{r&&(be.disconnect(),t(r)),be.disconnect(),e(s)})})}a($8,"kill");async function Y8(){try{await hM(),await mM(),await mi(Ei.generateAllServiceConfigs())}catch(e){throw be?.disconnect(),e}}a(Y8,"startAllServices");async function LT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ce.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ei.generateMainServerConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ei.generateNatsIngestServiceConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ei.generateNatsReplyServiceConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ei.generateNatsHubServerConfig(),await mi(r,t),await wn.removeNatsConfig(e);return;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ei.generateNatsLeafServerConfig(),await mi(r,t),await wn.removeNatsConfig(e);return;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ei.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await mi(r)}catch(r){throw be?.disconnect(),r}}a(LT,"startService");async function _M(){try{let e=await DT(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw be?.disconnect(),e}}a(_M,"getUniqueServicesList");async function K8(e=[]){try{let t=!1,r=await _M();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===Ce.PROCESS_DESCRIPTORS.HDB?t=!0:await cM(o))}t&&await fM(Ce.PROCESS_DESCRIPTORS.HDB)}catch(t){throw be?.disconnect(),t}}a(K8,"restartAllServices");async function dM(e){if(mr?.find(r=>r.name===e))return!0;let t=await v8.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(dM,"isServiceRegistered");async function fM(e){let t=e===Ce.PROCESS_DESCRIPTORS.HDB?$d.get(Ce.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):$d.get(Ce.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await lM(e),s=U8.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await CT(e),await LT(e)):e===Ce.PROCESS_DESCRIPTORS.HDB?await uM():await aM(e)}a(fM,"reloadStopStart");var EM;async function hM(e=!1){for(let t in Ce.CLUSTERING_PROCESSES){let r=Ce.CLUSTERING_PROCESSES[t];await LT(r,e)}}a(hM,"startClusteringProcesses");async function mM(){EM=iM(Ce.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ce.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Cu.createWorkQueueStream(tn.WORK_QUEUE_CONSUMER_NAMES),await Cu.updateIngestStreamConsumer(),await Cu.updateLocalStreams();let e=await M8.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ce.PRE_4_0_0_VERSION){hi.info("Starting clustering upgrade 4.0.0 process"),iM(Ce.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(mM,"startClusteringThreads");async function W8(){for(let e in Ce.CLUSTERING_PROCESSES)if(e!==Ce.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ce.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await EM.terminate();else{let t=Ce.CLUSTERING_PROCESSES[e];await CT(t)}}a(W8,"stopClustering");async function Q8(){for(let e in Ce.CLUSTERING_PROCESSES){let t=Ce.CLUSTERING_PROCESSES[e];if(await dM(t)===!1)return!1}return!0}a(Q8,"isClusteringRunning");async function z8(){await wn.generateNatsConfig(!0),await Cu.reloadNATSHub(),await Cu.reloadNATSLeaf(),await wn.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await wn.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(z8,"reloadClustering")});var Qd=T((yEe,NM)=>{"use strict";var J8=require("minimist"),{isMainThread:PT,parentPort:RM}=require("worker_threads"),it=D(),{PROCESS_DESCRIPTORS_VALIDATE:Lu}=it,rn=G(),vT=z(),Yd=wT(),ma=nt(),UT=qe(),AM=Pr(),sn=SM(),TM=_a(),X8=lh(),{restartWorkers:Kd,onMessageByType:j8}=Ye(),{handleHDBError:Z8,hdb_errors:e6}=Z(),{HTTP_STATUS_CODES:t6}=e6,Wd=j();Wd.initSync();var Uu=`Restarting HarperDB. This may take up to ${it.RESTART_TIMEOUT_MS/1e3} seconds.`,r6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",gM="Clustering is not enabled so cannot be restarted",s6="Invalid service",pa,as;NM.exports={restart:OM,restartService:BT};PT&&j8(it.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?BT({service:e.workerType}):OM({operation:"restart"})});async function OM(e){as=Object.keys(e).length===0,pa=await sn.isServiceRegistered(it.HDB_PROC_DESCRIPTOR);let t=J8(process.argv);if(t.service){await BT(t);return}if(as&&!pa){console.error(r6);return}if(as&&console.log(Uu),pa){sn.enterPM2Mode(),rn.notify(Uu);let r=X8(Object.keys(it.CONFIG_PARAM_MAP),!0);return vT.isEmptyOrZeroLength(Object.keys(r))||AM.updateConfigValue(void 0,void 0,r,!0,!0),i6(),Uu}return PT?(rn.notify(Uu),setTimeout(()=>{Kd()},50)):RM.postMessage({type:it.ITC_EVENT_TYPES.RESTART}),Uu}a(OM,"restart");async function BT(e){let{service:t}=e;if(it.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw Z8(new Error,s6,t6.BAD_REQUEST,void 0,void 0,!0);if(pa=await sn.isServiceRegistered(it.HDB_PROC_DESCRIPTOR),!PT)return RM.postMessage({type:it.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Lu.clustering:if(!Wd.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=gM;break}as&&console.log("Restarting clustering"),rn.notify("Restarting clustering"),await bM();break;case Lu.clustering_config:case Lu["clustering config"]:if(!Wd.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=gM;break}as&&console.log("Restarting clustering_config"),rn.notify("Restarting clustering_config"),await sn.reloadClustering();break;case"custom_functions":case"custom functions":case Lu.harperdb:case Lu.http_workers:if(as&&!pa){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}as&&console.log("Restarting http_workers"),rn.notify("Restarting http_workers"),as?await sn.restart(it.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Kd("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(rn.error(r),as&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(BT,"restartService");async function n6(){await ma.publishToStream(`${UT.SUBJECT_PREFIXES.TXN}.${UT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,UT.WORK_QUEUE_CONSUMER_NAMES.stream_name,ma.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(n6,"postDummyNatsMsg");async function i6(){await bM(),await sn.restart(it.HDB_PROC_DESCRIPTOR),await vT.async_set_timeout(2e3),Wd.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await MT(),as&&(await ma.closeConnection(),process.exit(0))}a(i6,"restartPM2Mode");async function bM(){if(!AM.getConfigFromFile(it.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await TM.getHDBProcessInfo()).clustering.length===0)rn.trace("Clustering not running, restart will start clustering services"),await Yd.generateNatsConfig(!0),await sn.startClusteringProcesses(),await sn.startClusteringThreads(),await MT(),as&&await ma.closeConnection();else{await n6(),await Yd.generateNatsConfig(!0),pa?(rn.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await sn.restart(it.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await sn.restart(it.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await TM.getHDBProcessInfo()).clustering.forEach(n=>{rn.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await vT.async_set_timeout(3e3),await MT(),await ma.updateLocalStreams(),as&&await ma.closeConnection(),rn.trace("Restart clustering restarting ingest and reply service threads");let t=Kd(it.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Kd(it.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(bM,"restartClustering");async function MT(){await Yd.removeNatsConfig(it.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Yd.removeNatsConfig(it.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(MT,"removeNatsConfig")});var BM=T((CEe,vM)=>{"use strict";var wEe=require("lodash"),pr=D(),{handleHDBError:yM,hdb_errors:o6}=Z(),{HDB_ERROR_MSGS:a6,HTTP_STATUS_CODES:c6}=o6,HT=G();vM.exports={getRolePermissions:l6};var lo=Object.create(null),u6=a(e=>({key:e,perms:{}}),"perms_template_obj"),DM=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),LM=a((e=!1,t=!1,r=!1,s=!1)=>({[pr.PERMS_CRUD_ENUM.READ]:e,[pr.PERMS_CRUD_ENUM.INSERT]:t,[pr.PERMS_CRUD_ENUM.UPDATE]:r,[pr.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),xT=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...LM(t,r,s,n)}),"table_perms_template"),IM=a((e,t=LM())=>({attribute_name:e,describe:PM(t),[Mu]:t[Mu],[qT]:t[qT],[FT]:t[FT]}),"attr_perms_template"),wM=a((e,t=!1)=>({attribute_name:e,describe:t,[Mu]:t}),"timestamp_attr_perms_template"),{READ:Mu,INSERT:qT,UPDATE:FT}=pr.PERMS_CRUD_ENUM,UM=Object.values(pr.PERMS_CRUD_ENUM),MM=[Mu,qT,FT];function l6(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[pr.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(lo[t]&&lo[t].key===s)return lo[t].perms;let n=_6(e,r);return lo[t]?lo[t].key=s:lo[t]=u6(s),lo[t].perms=n,n}catch(r){if(!e[pr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[pr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<pr.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw HT.error(s),HT.debug(r),yM(new Error,a6.OUTDATED_PERMS_TRANSLATION_ERROR,c6.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
-
${r.stack}`;throw HT.error(s),yM(new Error)}}}a(l6,"getRolePermissions");function _6(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[pr.SYSTEM_SCHEMA_NAME]=s[pr.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=d6(t[i]);return}r[i]=DM(),s[i]?(s[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],u=t[i][o],_=f6(c,u);r[i].describe||UM.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=xT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=xT()})}),r}a(_6,"translateRolePermissions");function d6(e){let t=DM(!0);return Object.keys(e).forEach(r=>{t.tables[r]=xT(!0,!0,!0,!0,!0)}),t}a(d6,"createStructureUserPermissions");function f6(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return pr.TIME_STAMP_NAMES.includes(d)&&(f=wM(d,l[Mu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=IM(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=PM(l),n.attribute_permissions.push(l),c||E6(l,u)}else if(_!==o){let l;pr.TIME_STAMP_NAMES.includes(_)?l=wM(_):l=IM(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=CM(n),n}else return e.describe=CM(e),e}a(f6,"getTableAttrPerms");function CM(e){return UM.filter(t=>e[t]).length>0}a(CM,"getSchemaTableDescribePerm");function PM(e){return MM.filter(t=>e[t]).length>0}a(PM,"getAttributeDescribePerm");function E6(e,t){MM.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(E6,"checkForHashPerms")});var HM={};$e(HM,{Resources:()=>zd,keyArrayToString:()=>Sa,resetResources:()=>h6,resources:()=>pi});function h6(){return pi=new zd}function Sa(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var zd,pi,Pu=Ae(()=>{Xi();zd=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,s,n){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:s,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!n)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let s=2,n;for(;(s=t.indexOf("/",s))>-1;){let c=t.slice(0,s),u=this.get(c);if(u){if(u.relativeURL=t.slice(s),!u.hasSubPaths)return u;n=u}s+=2}if(n)return n;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return n=this.get(o),n?n.relativeURL=i>-1?t.slice(i):"":n||(n=this.get(""),n&&(t[0]!=="/"&&(t="/"+t),n.relativeURL=t)),n}getResource(t,r){let s=this.getMatch(t);if(s)return t=s.relativeURL,s.Resource.getResource(this.pathToId(t,s.Resource),r)}call(t,r,s){return Xe(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(h6,"resetResources");a(Sa,"keyArrayToString")});var xM={};$e(xM,{Headers:()=>Si});var Si,Jd=Ae(()=>{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 s=t.toLowerCase();if(!super.has(s))return super.set(s,[t,r])}append(t,r,s){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase(),i=super.get(n);if(i){let o=i[1];s?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var vu={};$e(vu,{authentication:()=>KM,bypassAuth:()=>A6,login:()=>b6,logout:()=>N6,start:()=>O6});function A6(){YM=!0}async function KM(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?T6?S6:[]:p6?m6:[];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 Xd&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Xd&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Xd){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(E);if(h>=0){let p=n.indexOf(";",h),S=n.indexOf("=",h);u=n.slice(S+1,p===-1?n.length:p),_=await FM.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Zd.AuthAuditLog(E,h,kt.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===kt.AUTH_AUDIT_STATUS.SUCCESS?qM.notify(S):qM.error(S)},"authAuditLog"),d;if(s){if(d=_o.get(s),!d){let[E,h]=s.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await _t.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,jd.validateOperationToken)(h)}catch(R){if(R.message==="invalid token")try{return await(0,jd.validateRefreshToken)(h),c({status:-1})}catch{throw R}}break}}catch(R){return R6&&(_o.get(h)||(_o.set(h,h),l(p,kt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ti({error:R.message},e)})}_o.set(s,d),g6&&l(d.username,kt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await _t.getUser(_.user,null,e):(YM&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,kM.getSuperUser)());Xd&&(e.session.update=function(E){if(!u){u=(0,VM.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,FM.put(E)},e.login=async function(E,h){e.user=await _t.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")&&pi.loginPath?(f.status=302,f.headers.set("Location",pi.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 O6({server:e,port:t}){e.request(KM,{port:t||"all"}),GM||(GM=!0,setInterval(()=>{_o=new Map},cs.get(kt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),$M.user.addListener(()=>{_o=new Map}))}async function b6(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 N6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var kM,jd,VM,cs,kt,Zd,$M,qM,m6,p6,S6,T6,FM,Xd,YM,g6,R6,_o,GM,ef=Ae(()=>{kM=v(rs());sr();Pu();jd=v(hu());ge();VM=require("uuid"),cs=v(j()),kt=v(D()),Zd=v(G()),$M=v(Bc());Jd();Ta();qM=(0,Zd.loggerWithTag)("auth-event");cs.initSync();m6=cs.get(kt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),p6=cs.get(kt.CONFIG_PARAMS.HTTP_CORS),S6=cs.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),T6=cs.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),FM=dt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Xd=cs.get(kt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,YM=cs.get(kt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,g6=cs.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,R6=cs.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,_o=new Map;_t.onInvalidatedUser(()=>{_o=new Map});a(A6,"bypassAuth");a(KM,"authentication");a(O6,"start");a(b6,"login");a(N6,"logout")});var ZM=T((FEe,jM)=>{"use strict";var Ne=require("joi"),WM=require("fs-extra"),QM=require("path"),Ln=Je(),zM=j(),JM=D(),XM=G(),{hdb_errors:y6}=Z(),{HDB_ERROR_MSGS:jt}=y6,Dn=/^[a-zA-Z0-9-_]+$/;jM.exports={getDropCustomFunctionValidator:w6,setCustomFunctionValidator:C6,addComponentValidator:M6,dropCustomFunctionProjectValidator:P6,packageComponentValidator:v6,deployComponentValidator:B6,setComponentFileValidator:D6,getComponentFileValidator:U6,dropComponentFileValidator:L6};function tf(e,t,r){try{let s=zM.get(JM.CONFIG_PARAMS.COMPONENTSROOT),n=QM.join(s,t);return WM.existsSync(n)?e?t:r.message(jt.PROJECT_EXISTS):e?r.message(jt.NO_PROJECT):t}catch(s){return XM.error(s),r.message(jt.VALIDATION_ERR)}}a(tf,"checkProjectExists");function Bu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Bu,"checkFilePath");function I6(e,t,r,s){try{let n=zM.get(JM.CONFIG_PARAMS.COMPONENTSROOT),i=QM.join(n,e,t,r+".js");return WM.existsSync(i)?r:s.message(jt.NO_FILE)}catch(n){return XM.error(n),s.message(jt.VALIDATION_ERR)}}a(I6,"checkFileExists");function w6(e){let t=Ne.object({project:Ne.string().pattern(Dn).custom(tf.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),type:Ne.string().valid("helpers","routes").required(),file:Ne.string().pattern(Dn).custom(I6.bind(null,e.project,e.type)).custom(Bu).required().messages({"string.pattern.base":jt.BAD_FILE_NAME})});return Ln.validateBySchema(e,t)}a(w6,"getDropCustomFunctionValidator");function C6(e){let t=Ne.object({project:Ne.string().pattern(Dn).custom(tf.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),type:Ne.string().valid("helpers","routes").required(),file:Ne.string().custom(Bu).required(),function_content:Ne.string().required()});return Ln.validateBySchema(e,t)}a(C6,"setCustomFunctionValidator");function D6(e){let t=Ne.object({project:Ne.string().pattern(Dn).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),file:Ne.string().custom(Bu).required(),payload:Ne.string().allow("").optional(),encoding:Ne.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ln.validateBySchema(e,t)}a(D6,"setComponentFileValidator");function L6(e){let t=Ne.object({project:Ne.string().pattern(Dn).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),file:Ne.string().custom(Bu).optional()});return Ln.validateBySchema(e,t)}a(L6,"dropComponentFileValidator");function U6(e){let t=Ne.object({project:Ne.string().required(),file:Ne.string().custom(Bu).required(),encoding:Ne.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ln.validateBySchema(e,t)}a(U6,"getComponentFileValidator");function M6(e){let t=Ne.object({project:Ne.string().pattern(Dn).custom(tf.bind(null,!1)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME})});return Ln.validateBySchema(e,t)}a(M6,"addComponentValidator");function P6(e){let t=Ne.object({project:Ne.string().pattern(Dn).custom(tf.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME})});return Ln.validateBySchema(e,t)}a(P6,"dropCustomFunctionProjectValidator");function v6(e){let t=Ne.object({project:Ne.string().pattern(Dn).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),skip_node_modules:Ne.boolean()});return Ln.validateBySchema(e,t)}a(v6,"packageComponentValidator");function B6(e){let t=Ne.object({project:Ne.string().pattern(Dn).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),payload:Ne.string().optional().messages({"string.pattern.base":jt.BAD_PACKAGE}),package:Ne.string().optional()});return Ln.validateBySchema(e,t)}a(B6,"deployComponentValidator")});var of=T((kEe,oP)=>{"use strict";var rf=require("joi"),sf=require("path"),eP=require("fs-extra"),{exec:H6}=require("child_process"),x6=require("util"),tP=x6.promisify(H6),Hu=D(),{handleHDBError:ga,hdb_errors:q6}=Z(),{HTTP_STATUS_CODES:Ra}=q6,xu=j(),F6=Je(),Aa=G();xu.initSync();var GT=xu.get(Hu.CONFIG_PARAMS.COMPONENTSROOT),rP="npm install --omit=dev --json",G6=`${rP} --dry-run`;oP.exports={installModules:Y6,auditModules:K6,installAllRootModules:k6,uninstallRootModule:V6,linkHarperdb:$6};async function k6(e=!1){await nf(),await qu(e?"npm install --ignore-scripts":"npm install",xu.get(Hu.CONFIG_PARAMS.ROOTPATH))}a(k6,"installAllRootModules");async function V6(e){await qu(`npm uninstall ${e}`,xu.get(Hu.CONFIG_PARAMS.ROOTPATH))}a(V6,"uninstallRootModule");async function $6(){await nf(),await qu(`npm link ${Hu.PACKAGE_ROOT}`,xu.get(Hu.CONFIG_PARAMS.ROOTPATH))}a($6,"linkHarperdb");async function qu(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await tP(e,{cwd:t}))}catch(n){throw new Error(n.stderr.replace(`
|
|
10
|
+
`,"")}a(gD,"runCommand");async function T3(){try{await j4.access(lS)}catch{return!1}let e=await gD(`${lS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return X4.eq(t,p3)}a(T3,"checkNATSServerInstalled");async function ES(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await mD.getClusterUser();if(ro(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Gr.trace("create nats connection called");let i=await u3({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,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(),Gr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Gr.error("Error with Nats client connection, connection closed",o),RD()}),i}a(ES,"createConnection");function RD(){os=void 0,Zi=void 0,eo=void 0,to=void 0}a(RD,"clearClientCache");async function g3(){os&&(await os.drain(),os=void 0,Zi=void 0,eo=void 0,to=void 0)}a(g3,"closeConnection");var os,to;async function ud(){return to||(to=ES(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),os=await to),os||to}a(ud,"getConnection");async function iu(){if(Zi)return Zi;ro(os)&&await ud();let{domain:e}=ou(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ro(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Zi=await os.jetstreamManager({domain:e,timeout:6e4}),Zi}a(iu,"getJetStreamManager");async function AD(){if(eo)return eo;ro(os)&&await ud();let{domain:e}=ou(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ro(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return eo=os.jetstream({domain:e,timeout:6e4}),eo}a(AD,"getJetStream");async function cr(){let e=os||await ud(),t=Zi||await iu(),r=eo||await AD();return{connection:e,jsm:t,js:r}}a(cr,"getNATSReferences");async function R3(e){let t=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await mD.getClusterUser(),n=await ES(t,r,s),i=fS(),o=n.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=TD.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await n.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await n.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await n.flush(),await _S.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(R3,"getServerList");async function hS(e,t){let{jsm:r}=await cr(),s=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:pD.File,retention:SD.Limits,subjects:t,discard:l3.Old,max_msgs:n,max_bytes:i,max_age:s})}a(hS,"createLocalStream");async function OD(){let{jsm:e}=await cr(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(OD,"listStreams");async function A3(e){let{jsm:t}=await cr();await t.streams.delete(e)}a(A3,"deleteLocalStream");async function O3(e){let{connection:t}=await cr(),r=[],s=fS(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(TD.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(O3,"listRemoteStreams");async function b3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await cr(),i=fD(),o={durable_name:i,ack_policy:ad.Explicit};t&&(o.deliver_policy=cd.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=dS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(be.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(b3,"viewStream");async function*N3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await cr(),i=fD(),o={durable_name:i,ack_policy:ad.Explicit};t&&(o.deliver_policy=cd.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=dS(_.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(be.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(N3,"viewStreamIterator");async function y3(e,t,r,s){Gr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=bD(s,r);let{js:n}=await cr(),i=await au(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:hD.encode(s);try{Gr.trace(`publishToStream publishing to subject: ${o}`),h3(c.length,"bytes-sent",e,s.operation,"replication"),await n.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return ID(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Gr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await hS(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(y3,"publishToStream");function bD(e,t){t===void 0&&(t=d3());let r=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(be.MSG_HEADERS.ORIGIN)&&r&&t.append(be.MSG_HEADERS.ORIGIN,r),t}a(bD,"addNatsMsgHeader");function ou(e){e=e.toLowerCase();let t=nu.join(Gt.get(Pe.CONFIG_PARAMS.ROOTPATH),m3);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ro(uS)&&(uS={port:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+be.SERVER_SUFFIX.HUB,config_file:be.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:nu.join(t,be.PID_FILES.HUB),hdb_nats_path:t}),uS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ro(cS)&&(cS={port:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+be.SERVER_SUFFIX.LEAF,config_file:be.NATS_CONFIG_FILES.LEAF_SERVER,domain:ru.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+be.SERVER_SUFFIX.LEAF,pid_file_path:nu.join(t,be.PID_FILES.LEAF),hdb_nats_path:t}),cS;Gr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(ou,"getServerConfig");async function w3(e){let{jsm:t}=await cr(),r=await au();try{await t.streams.add({name:e.stream_name,storage:pD.File,retention:SD.Limits,max_age:a3,max_bytes:c3,subjects:[`${be.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:ad.Explicit,durable_name:e.durable_name,deliver_policy:cd.All,max_ack_pending:1e4});else throw s}}a(w3,"createWorkQueueStream");async function I3(){let{jsm:e}=await cr();(await e.consumers.info(be.WORK_QUEUE_CONSUMER_NAMES.stream_name,be.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Gr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(be.WORK_QUEUE_CONSUMER_NAMES.stream_name,be.WORK_QUEUE_CONSUMER_NAMES.durable_name),Gr.info("Adding pull consumer to ingest stream"),await e.consumers.add(be.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:ad.Explicit,durable_name:be.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:cd.All,max_ack_pending:1e4}))}a(I3,"updateIngestStreamConsumer");async function ND(e,t,r){let{jsm:s}=await cr(),n=await s.streams.info(t),i=yD(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=od.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let p=0,S=n.config.sources.length;p<S;p++)if(d=n.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 s.streams.purge(t,{filter:p}),n.config.sources.splice(f,1),await s.streams.update(t,n.config)}let h={name:_,opt_start_time:o,filter_subject:`${be.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(h),await s.streams.update(t,n.config)}a(ND,"addSourceToWorkStream");function yD(e){return e.split(".")[1]}a(yD,"extractServerName");async function wD(e,t,r){let{jsm:s}=await cr(),{schema:n,table:i}=r,o=`txn.${n}.${i}.${e}`;await s.streams.purge(t,{filter:o});let c=od.createNatsTableStreamName(n,i),u=await s.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 s.streams.update(t,u.config)}a(wD,"removeSourceFromWorkStream");async function C3(e,t,r=6e4,s=fS()){if(!_S.isObject(t))throw new Error("data param must be an object");let n=hD.encode(t),{connection:i}=await cr(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return dS(c.data)}a(C3,"request");function mS(e){return new Promise(async(t,r)=>{let s=r3(lS,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(mS,"reloadNATS");async function D3(){let{pid_file_path:e}=ou(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await mS(e)}a(D3,"reloadNATSHub");async function L3(){let{pid_file_path:e}=ou(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await mS(e)}a(L3,"reloadNATSLeaf");function M3(e,t,r){let s;switch(e.code){case dD.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case dD.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(M3,"requestErrorHandler");async function U3(e,t){let r=t+be.SERVER_SUFFIX.LEAF;await ID(async()=>{e.subscribe===!0?await ND(r,be.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await wD(r,be.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(U3,"updateWorkStream");function ID(e){return s3.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(ID,"exclusiveLock");async function CD(e,t){let r=od.createNatsTableStreamName(e,t),s=await au(),n=H3(e,t,s);await hS(r,[n])}a(CD,"createLocalTableStream");async function P3(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await CD(s,n)}}a(P3,"createTableStreams");async function DD(e,t,r=!1){if(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let s=od.createNatsTableStreamName(e,t),{jsm:n}=await cr();r?await n.streams.purge(be.WORK_QUEUE_CONSUMER_NAMES.stream_name):await n.streams.purge(s)}catch(s){if(s.message==="stream not found")Gr.warn(s);else throw s}}a(DD,"purgeTableStream");async function v3(e,t){if(Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await DD(e,t[r])}a(v3,"purgeSchemaTableStreams");async function B3(e){return(await iu()).streams.info(e)}a(B3,"getStreamInfo");function H3(e,t,r){return`${be.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(H3,"createSubjectName");async function au(){if(su)return su;if(su=(await iu())?.nc?.info?.server_name,su===void 0)throw new Error("Unable to get jetstream manager server name");return su}a(au,"getJsmServerName");async function x3(){let e=await iu(),t=await au(),r=await OD();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=q3(s),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(n.name===be.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${be.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Gr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===be.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${be.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Gr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Gr.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l}await e.streams.update(n.name,n)}}}a(x3,"updateLocalStreams");function q3(e){let{config:t}=e,r=!1;if(t.name===be.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===be.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let s=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Gt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(q3,"updateStreamLimits")});var cu=T((jde,vD)=>{"use strict";var na=f_(),ia=KC(),F3=V(),G3=require("uuid").v4,Jde=require("clone"),_d=Rn(),oa=L(),k3=require("util"),ai=ws(),{handleHDBError:ur,hdb_errors:V3}=Z(),{HDB_ERROR_MSGS:ld,HTTP_STATUS_CODES:lr}=V3,{SchemaEventMsg:dd}=Ds(),MD=it(),{getDatabases:$3}=(Ae(),ee(Fe)),{transformReq:aa}=J();vD.exports={createSchema:Y3,createSchemaStructure:UD,createTable:K3,createTableStructure:PD,createAttribute:j3,dropSchema:W3,dropTable:Q3,dropAttribute:z3,getBackup:X3};async function Y3(e){let t=await UD(e);return _d.signalSchemaChange(new dd(process.pid,e.operation,e.schema)),t}a(Y3,"createSchema");async function UD(e){let t=na.schema_object(e);if(t)throw ur(t,t.message,lr.BAD_REQUEST,void 0,void 0,!0);if(aa(e),!await ia.checkSchemaExists(e.schema))throw ur(new Error,ld.SCHEMA_EXISTS_ERR(e.schema),lr.BAD_REQUEST,oa.LOG_LEVELS.ERROR,ld.SCHEMA_EXISTS_ERR(e.schema),!0);return await ai.createSchema(e),`database '${e.schema}' successfully created`}a(UD,"createSchemaStructure");async function K3(e){return aa(e),e.hash_attribute=e.primary_key??e.hash_attribute,await PD(e)}a(K3,"createTable");async function PD(e){let t=na.create_table_object(e);if(t)throw ur(t,t.message,lr.BAD_REQUEST,void 0,void 0,!0);if(na.validateTableResidence(e.residence),!await ia.checkSchemaTableExists(e.schema,e.table))throw ur(new Error,ld.TABLE_EXISTS_ERR(e.schema,e.table),lr.BAD_REQUEST,oa.LOG_LEVELS.ERROR,ld.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:G3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await ai.createTable(s,e);else throw ur(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",lr.BAD_REQUEST);else await ai.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(PD,"createTableStructure");async function W3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=na.schema_object(e),s=t??r;if(s)throw ur(s,s.message,lr.BAD_REQUEST,void 0,void 0,!0);aa(e);let n=await ia.checkSchemaExists(e.schema);if(n)throw ur(new Error,n,lr.NOT_FOUND,oa.LOG_LEVELS.ERROR,n,!0);let i=await ia.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ai.dropSchema(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema)),await MD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(W3,"dropSchema");async function Q3(e){let t=na.table_object(e);if(t)throw ur(t,t.message,lr.BAD_REQUEST,void 0,void 0,!0);aa(e);let r=await ia.checkSchemaTableExists(e.schema,e.table);if(r)throw ur(new Error,r,lr.NOT_FOUND,oa.LOG_LEVELS.ERROR,r,!0);return await ai.dropTable(e),await MD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Q3,"dropTable");async function z3(e){let t=na.attribute_object(e);if(t)throw ur(t,t.message,lr.BAD_REQUEST,void 0,void 0,!0);aa(e);let r=await ia.checkSchemaTableExists(e.schema,e.table);if(r)throw ur(new Error,r,lr.NOT_FOUND,oa.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw ur(new Error,"You cannot drop a hash attribute",lr.BAD_REQUEST,void 0,void 0,!0);if(oa.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw ur(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,lr.BAD_REQUEST,void 0,void 0,!0);try{return await ai.dropAttribute(e),J3(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw F3.error(`Got an error deleting attribute ${k3.inspect(e)}.`),s}}a(z3,"dropAttribute");function J3(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(J3,"dropAttributeFromGlobal");async function j3(e){aa(e);let t=$3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw ur(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,lr.BAD_REQUEST,void 0,void 0,!0);return await ai.createAttribute(e),_d.signalSchemaChange(new dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(j3,"createAttribute");function X3(e){return ai.getBackup(e)}a(X3,"getBackup")});var HD=T((Zde,BD)=>{"use strict";var{OPERATIONS_ENUM:Z3}=L(),pS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=Z3.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};BD.exports=pS});var SS=T((rfe,kD)=>{"use strict";var ej=ws(),tfe=HD(),fd=J(),Ed=L(),tj=X(),{handleHDBError:xD,hdb_errors:rj}=Z(),{HDB_ERROR_MSGS:qD,HTTP_STATUS_CODES:FD}=rj,sj=Object.values(Ed.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),GD="To use this operation audit log must be enabled in harperdb-config.yaml";kD.exports=nj;async function nj(e){if(fd.isEmpty(e.schema))throw new Error(qD.SCHEMA_REQUIRED_ERR);if(fd.isEmpty(e.table))throw new Error(qD.TABLE_REQUIRED_ERR);if(!tj.get(Ed.CONFIG_PARAMS.LOGGING_AUDITLOG))throw xD(new Error,GD,FD.BAD_REQUEST,Ed.LOG_LEVELS.ERROR,GD,!0);let t=fd.checkSchemaTableExist(e.schema,e.table);if(t)throw xD(new Error,t,FD.NOT_FOUND,Ed.LOG_LEVELS.ERROR,t,!0);if(!fd.isEmpty(e.search_type)&&sj.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await ej.readAuditLog(e)}a(nj,"readAuditLog")});var $D=T((nfe,VD)=>{"use strict";var{OPERATIONS_ENUM:ij}=L(),TS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=ij.GET_BACKUP,this.schema=t,this.table=r}};VD.exports=TS});var WD=T((cfe,KD)=>{"use strict";var oj=ws(),ofe=$D(),gS=J(),aj=L(),afe=X(),{handleHDBError:cj,hdb_errors:uj}=Z(),{HDB_ERROR_MSGS:YD,HTTP_STATUS_CODES:lj}=uj;KD.exports=_j;async function _j(e){if(gS.isEmpty(e.schema))throw new Error(YD.SCHEMA_REQUIRED_ERR);if(gS.isEmpty(e.table))throw new Error(YD.TABLE_REQUIRED_ERR);let t=gS.checkSchemaTableExist(e.schema,e.table);if(t)throw cj(new Error,t,lj.NOT_FOUND,aj.LOG_LEVELS.ERROR,t,!0);return await oj.getBackup(read_audit_log_object)}a(_j,"getBackup")});var ZD=T((lfe,XD)=>{var ci=require("validate.js"),zD=Ze(),ca=L(),{handleHDBError:dj,hdb_errors:fj}=Z(),{HDB_ERROR_MSGS:ft,HTTP_STATUS_CODES:Ej}=fj,RS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),hj={STRUCTURE_USER:"structure_user"},QD=Object.values(ca.ROLE_TYPES_ENUM),mj="attribute_permissions",pj="attribute_name",{PERMS_CRUD_ENUM:ua}=ca,Sj=[mj,...Object.values(ua)],JD=[ua.READ,ua.INSERT,ua.UPDATE],Tj=[pj,...JD];function gj(e){let t=RS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,jD(e,t)}a(gj,"addRoleValidation");function Rj(e){let t=RS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,jD(e,t)}a(Rj,"alterRoleValidation");function Aj(e){let t=RS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,zD.validateObject(e,t)}a(Aj,"dropRoleValidation");var Oj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function jD(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)Oj.includes(s[o])||n.push(s[o]);n.length>0&&St(ft.INVALID_ROLE_JSON_KEYS(n),r);let i=zD.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{St(o,r)}),e.permission){let o=bj(e);o&&St(o,r),QD.forEach(c=>{e.permission[c]&&!ci.isBoolean(e.permission[c])&&St(ft.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(QD.indexOf(o)<0){if(o===hj.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||St(ft.SCHEMA_NOT_FOUND(d),r)}continue}St(ft.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){St(ft.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){St(ft.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{Sj.includes(l)||St(ft.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ua).forEach(l=>{ci.isDefined(_[l])?ci.isBoolean(_[l])||St(ft.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):St(ft.TABLE_PERM_MISSING(l),r,o,u)}),ci.isDefined(_.attribute_permissions)){if(!ci.isArray(_.attribute_permissions)){St(ft.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{St(ft.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=>{!Tj.includes(p)&&p!==ua.DELETE&&St(ft.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!ci.isDefined(E.attribute_name)){St(ft.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){St(ft.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}JD.forEach(p=>{ci.isDefined(E[p])?ci.isBoolean(E[p])||St(ft.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):St(ft.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;St(ft.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return Nj(r)}a(jD,"customValidate");XD.exports={addRoleValidation:gj,alterRoleValidation:Rj,dropRoleValidation:Aj};function bj(e){let{operation:t,permission:r}=e;if(t===ca.OPERATIONS_ENUM.ADD_ROLE||t===ca.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return ft.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ca.ROLE_TYPES_ENUM.SUPER_USER:ca.ROLE_TYPES_ENUM.CLUSTER_USER;return ft.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(bj,"validateNoSUPerms");function Nj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:ft.ROLE_PERMS_ERROR,...e};return dj(new Error,s,Ej.BAD_REQUEST)}else return null}a(Nj,"generateRolePermResponse");function St(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(St,"addPermError")});var wS=T((dfe,sL)=>{"use strict";var eL=Mr(),tL=rs(),yj=ti(),OS=ZD(),bS=Rn(),wj=require("uuid").v4,Ij=require("util"),hd=L(),Cj=J(),NS=tL.searchByValue,Dj=tL.searchByHash,Lj=Ij.promisify(yj.delete),Mj=Js(),Uj=ea(),{hdb_errors:Pj,handleHDBError:so}=Z(),{HDB_ERROR_MSGS:rL,HTTP_STATUS_CODES:uu}=Pj,{UserEventMsg:yS}=Ds();sL.exports={addRole:vj,alterRole:Bj,dropRole:Hj,listRoles:xj};function AS(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(AS,"scrubRoleDetails");async function vj(e){let t=OS.addRoleValidation(e);if(t)throw t;e=AS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},s;try{s=Array.from(await NS(r)||[])}catch(i){throw so(i)}if(s&&s.length>0)throw so(new Error,rL.ROLE_ALREADY_EXISTS(e.role),uu.CONFLICT,void 0,void 0,!0);e.id||(e.id=wj());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await eL.insert(n),bS.signalUserChange(new yS(process.pid)),e=AS(e),e}a(vj,"addRole");async function Bj(e){let t=OS.alterRoleValidation(e);if(t)throw t;e=AS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await eL.update(r)}catch(n){throw so(n)}if(s&&s?.message==="updated 0 of 1 records")throw so(new Error,"Invalid role id",uu.BAD_REQUEST,void 0,void 0,!0);return await bS.signalUserChange(new yS(process.pid)),e}a(Bj,"alterRole");async function Hj(e){let t=OS.dropRoleValidation(e);if(t)throw so(new Error,t,uu.BAD_REQUEST,void 0,void 0,!0);let r=new Uj(hd.SYSTEM_SCHEMA_NAME,hd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await Dj(r));if(s.length===0)throw so(new Error,rL.ROLE_NOT_FOUND,uu.NOT_FOUND,void 0,void 0,!0);let n=new Mj(hd.SYSTEM_SCHEMA_NAME,hd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await NS(n)),o=!1;if(Cj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw so(new Error,`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`,uu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Lj(c),bS.signalUserChange(new yS(process.pid)),`${s[0].role} successfully deleted`}a(Hj,"dropRole");async function xj(){return NS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(xj,"listRoles")});var aL=T((Efe,oL)=>{"use strict";var qj=X(),ui=require("joi"),Fj=Ze(),nL=require("moment"),Gj=require("fs-extra"),IS=require("path"),kj=require("lodash"),lu=L(),{LOG_LEVELS:no}=L(),Vj="YYYY-MM-DD hh:mm:ss",$j=IS.resolve(__dirname,"../logs");oL.exports=function(e){return Fj.validateBySchema(e,Yj)};var Yj=ui.object({from:ui.custom(iL),until:ui.custom(iL),level:ui.valid(no.NOTIFY,no.FATAL,no.ERROR,no.WARN,no.INFO,no.DEBUG,no.TRACE),order:ui.valid("asc","desc"),limit:ui.number().min(1),start:ui.number().min(0),log_name:ui.custom(Kj)});function iL(e,t){if(nL(e,nL.ISO_8601).format(Vj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(iL,"validateDatetime");function Kj(e,t){if(kj.invert(lu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=qj.get(lu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?lu.LOG_NAMES.HDB:e,i=n===lu.LOG_NAMES.INSTALL?IS.join($j,lu.LOG_NAMES.INSTALL):IS.join(s,n);return Gj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Kj,"validateReadLogPath")});var DS=T((mfe,uL)=>{"use strict";var md=L(),Wj=V(),Qj=X(),zj=aL(),CS=require("path"),cL=require("fs-extra"),{once:Jj}=require("events"),{handleHDBError:jj,hdb_errors:Xj}=Z(),{PACKAGE_ROOT:Zj}=L(),eX=CS.join(Zj,"logs"),tX=1e3,rX=200;uL.exports=sX;async function sX(e){let t=zj(e);if(t)throw jj(t,t.message,Xj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Qj.get(md.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?md.LOG_NAMES.HDB:e.log_name,n=s===md.LOG_NAMES.INSTALL?CS.join(eX,md.LOG_NAMES.INSTALL):CS.join(r,s),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?tX: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(cL.statSync(n).size-(h+5)*rX,0));let S=cL.createReadStream(n,{start:p});S.on("error",H=>{Wj.error(H)});let g=0,A=[],b="",v;S.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))&&!S.destroyed;){v&&(v.message=H.slice(z,W.index),G(v));let[Q,ne,pe]=W,oe=pe.split("] ["),qe=oe[0],ce=oe[1];oe.splice(0,2),v={timestamp:ne,thread:qe,level:ce,tags:oe,message:""},z=W.index+Q.length}b=H.slice(z)}),S.on("end",H=>{S.destroyed||v&&(v.message=b.trim(),G(v))}),S.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&&(li(H,f,A),g++,g===h&&S.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&&(li(H,f,A),g++,g===h&&S.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&&(li(H,f,A),g++,g===h&&S.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&&(li(H,f,A),g++,g===h&&S.destroy());break;case i:H.level===o&&g<E?g++:H.level===o&&(li(H,f,A),g++,g===h&&S.destroy());break;case c:P=new Date(H.timestamp),z=new Date(u),P>=z&&g<E?g++:P>=z&&g>=E&&(li(H,f,A),g++,g===h&&S.destroy());break;case _:P=new Date(H.timestamp),W=new Date(l),P<=W&&g<E?g++:P<=W&&g>=E&&(li(H,f,A),g++,g===h&&S.destroy());break;default:g<E?g++:(li(H,f,A),g++,g===h&&S.destroy())}}return a(G,"onLogMessage"),await Jj(S,"close"),A}a(sX,"readLog");function li(e,t,r){t==="desc"?nX(e,r):t==="asc"?iX(e,r):r.push(e)}a(li,"pushLineToResult");function nX(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(nX,"insertDescending");function iX(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(iX,"insertAscending")});var pd=T((Rfe,fL)=>{"use strict";var LS=require("joi"),{string:_u,boolean:lL,date:oX}=LS.types(),aX=Ze(),{validateSchemaExists:Sfe,validateTableExists:Tfe,validateSchemaName:gfe}=Ys(),cX=L(),uX=Ge(),_L=X();_L.initSync();var lX=_u.invalid(_L.get(cX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(uX.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(),dL={operation:_u.valid("add_node","update_node","set_node_replication"),node_name:lX,subscriptions:LS.array().items({table:_u.optional(),schema:_u.optional(),database:_u.optional(),subscribe:lL.required(),publish:lL.required().custom(dX),start_time:oX.iso()}).min(1).required()};function _X(e){return aX.validateBySchema(e,LS.object(dL))}a(_X,"addUpdateNodeValidator");function dX(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(dX,"checkForFalsy");fL.exports={addUpdateNodeValidator:_X,validation_schema:dL}});var hL=T((Ofe,EL)=>{var fX=Ze(),EX={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};EL.exports=function(e){return fX.validateObject(e,EX)}});var Sd=T((bfe,mL)=>{"use strict";var hX=L().OPERATIONS_ENUM,MS=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=hX.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};mL.exports=MS});var SL=T((yfe,pL)=>{"use strict";var mX={OPERATION:"operation",REFRESH:"refresh"},US=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},PS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};pL.exports={JWTTokens:US,TOKEN_TYPE_ENUM:mX,JWTRSAKeys:PS}});var Eu=T((Ife,AL)=>{"use strict";var fu=require("jsonwebtoken"),vS=require("fs-extra"),BS=J(),as=L(),{handleHDBError:_r,hdb_errors:pX}=Z(),{HTTP_STATUS_CODES:dr,AUTHENTICATION_ERROR_MSGS:fr}=pX,du=V(),TL=y_(),qS=ns(),SX=Mr().update,TX=Sd(),gX=Rn(),{UserEventMsg:RX}=Ds(),_i=X();_i.initSync();var HS=require("path"),{JWTTokens:AX,JWTRSAKeys:OX,TOKEN_TYPE_ENUM:Td}=SL(),bX=_i.get(as.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?_i.get(as.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",NX=_i.get(as.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?_i.get(as.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",gd="RS256",xS;AL.exports={createTokens:yX,validateOperationToken:IX,refreshOperationToken:wX,validateRefreshToken:RL};async function yX(e){if(BS.isEmpty(e)||typeof e!="object")throw _r(new Error,fr.INVALID_AUTH_OBJECT,dr.BAD_REQUEST,void 0,void 0,!0);if(BS.isEmpty(e.username))throw _r(new Error,fr.USERNAME_REQUIRED,dr.BAD_REQUEST,void 0,void 0,!0);if(BS.isEmpty(e.password))throw _r(new Error,fr.PASSWORD_REQUIRED,dr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await qS.findAndValidateUser(e.username,e.password),!t)throw _r(new Error,fr.INVALID_CREDENTIALS,dr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw du.error(f),_r(new Error,fr.INVALID_CREDENTIALS,dr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Rd(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await gL(i,r.private_key,r.passphrase),c=await fu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:NX,algorithm:gd,subject:Td.REFRESH}),u=TL.hash(c),_=new TX(as.SYSTEM_SCHEMA_NAME,as.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await SX(_)}catch(f){du.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw _r(new Error,fr.REFRESH_TOKEN_SAVE_FAILED,dr.INTERNAL_SERVER_ERROR);return gX.signalUserChange(new RX(process.pid)),new AX(o,c)}a(yX,"createTokens");async function gL(e,t,r){return await fu.sign(e,{key:t,passphrase:r},{expiresIn:bX,algorithm:gd,subject:Td.OPERATION})}a(gL,"signOperationToken");async function Rd(){if(xS===void 0)try{let e=HS.join(_i.getHdbBasePath(),as.LICENSE_KEY_DIR_NAME,as.JWT_ENUM.JWT_PASSPHRASE_NAME),t=HS.join(_i.getHdbBasePath(),as.LICENSE_KEY_DIR_NAME,as.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=HS.join(_i.getHdbBasePath(),as.LICENSE_KEY_DIR_NAME,as.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await vS.readFile(e)).toString(),n=(await vS.readFile(t)).toString(),i=(await vS.readFile(r)).toString();xS=new OX(i,n,s)}catch(e){throw du.error(e),_r(new Error,fr.NO_ENCRYPTION_KEYS,dr.INTERNAL_SERVER_ERROR)}return xS}a(Rd,"getJWTRSAKeys");async function wX(e){if(!e)throw _r(new Error,fr.INVALID_BODY,dr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw _r(new Error,fr.REFRESH_TOKEN_REQUIRED,dr.BAD_REQUEST,void 0,void 0,!0);await RL(e.refresh_token);let t=await Rd(),r=await fu.decode(e.refresh_token);return{operation_token:await gL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(wX,"refreshOperationToken");async function IX(e){try{let t=await Rd(),r=await fu.verify(e,t.public_key,{algorithms:gd,subject:Td.OPERATION});return await qS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw du.warn(t),t.name&&t.name==="TokenExpiredError"?_r(new Error,fr.TOKEN_EXPIRED,dr.FORBIDDEN):_r(new Error,fr.INVALID_TOKEN,dr.UNAUTHORIZED)}}a(IX,"validateOperationToken");async function RL(e){let t;try{let r=await Rd(),s=await fu.verify(e,r.public_key,{algorithms:gd,subject:Td.REFRESH});t=await qS.findAndValidateUser(s.username,void 0,!1)}catch(r){throw du.warn(r),r.name&&r.name==="TokenExpiredError"?_r(new Error,fr.TOKEN_EXPIRED,dr.FORBIDDEN):_r(new Error,fr.INVALID_TOKEN,dr.UNAUTHORIZED)}if(!TL.validate(t.refresh_token,e))throw _r(new Error,fr.INVALID_TOKEN,dr.UNAUTHORIZED);return t}a(RL,"validateRefreshToken")});var FS=T((Lfe,NL)=>{"use strict";var CX=hL(),la=require("passport"),DX=require("passport-local").Strategy,LX=require("passport-http").BasicStrategy,MX=require("util"),UX=ns(),bL=MX.callbackify(UX.findAndValidateUser),Dfe=Ir(),PX=L(),OL=Eu();la.use(new DX(function(e,t,r){bL(e,t,r)}));la.use(new LX(function(e,t,r){bL(e,t,r)}));la.serializeUser(function(e,t){t(null,e)});la.deserializeUser(function(e,t){t(null,e)});function vX(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let s,n;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),s){case"Basic":la.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===PX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?OL.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):OL.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:la.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(vX,"authorize");function BX(e,t){let r=CX(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n?.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(BX,"checkPermissions");NL.exports={authorize:vX,checkPermissions:BX}});var di=T((Ufe,yL)=>{"use strict";var GS=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},kS=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};yL.exports={Node:GS,NodeSubscription:kS}});var IL=T((vfe,wL)=>{"use strict";var HX=L().OPERATIONS_ENUM,VS=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=HX.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};wL.exports=VS});var hu=T((Hfe,CL)=>{"use strict";var $S=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},YS=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,s,n,i,o,c){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};CL.exports={RemotePayloadObject:$S,RemotePayloadSubscription:YS}});var LL=T((qfe,DL)=>{"use strict";var KS=class{static{a(this,"TableSizeObject")}constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};DL.exports=KS});var PL=T(($fe,UL)=>{"use strict";var xX=LL(),Gfe=ht(),ML=ze(),qX=V(),{getSchemaPath:kfe,getTransactionAuditStorePath:Vfe}=Xe(),{getDatabases:FX}=(Ae(),ee(Fe));UL.exports=GX;async function GX(e){let t=new xX;try{let r=FX()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await ML.environmentDataSize(schema_path,e.name),o=await ML.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=s.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=n.entryCount}catch(r){qX.warn(`unable to stat table dbi due to ${r}`)}return t}a(GX,"lmdbGetTableSize")});var BL=T((Kfe,vL)=>{"use strict";var WS=class{static{a(this,"SystemInformationObject")}constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};vL.exports=WS});var _a=T((Jfe,FL)=>{"use strict";var kX=require("fs-extra"),VX=require("path"),Jt=require("systeminformation"),fi=V(),$X=it(),QS=Ge(),Od=L(),YX=PL(),qL=Xn(),{getThreadInfo:HL}=Qe(),nT=X();nT.initSync();var KX=BL(),{openEnvironment:Qfe}=ze(),{getSchemaPath:zfe}=Xe(),{database:WX}=(Ae(),ee(Fe)),Ad;FL.exports={getHDBProcessInfo:XS,getNetworkInfo:eT,getDiskInfo:ZS,getMemoryInfo:jS,getCPUInfo:JS,getTimeInfo:zS,getSystemInformation:tT,systemInformation:QX,getTableSize:rT,getMetrics:sT};function zS(){return Jt.time()}a(zS,"getTimeInfo");async function JS(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Jt.cpu();l.cpu_speed=await Jt.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:g,...A}=await Jt.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 fi.error(`error in getCPUInfo: ${e}`),{}}}a(JS,"getCPUInfo");async function jS(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Jt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return fi.error(`error in getMemoryInfo: ${e}`),{}}}a(jS,"getMemoryInfo");async function XS(){let e={core:[],clustering:[]};try{let t=await Jt.processes(),r;try{r=Number.parseInt(await kX.readFile(VX.join(nT.get(Od.CONFIG_PARAMS.ROOTPATH),Od.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===Od.NODE_ERROR_CODES.ENOENT)fi.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return fi.error(`error in getHDBProcessInfo: ${t}`),e}}a(XS,"getHDBProcessInfo");async function ZS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Jt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Jt.fsStats();return e.read_write=_,e.size=await Jt.fsSize(),e}catch(t){return fi.error(`error in getDiskInfo: ${t}`),e}}a(ZS,"getDiskInfo");async function eT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Jt.networkInterfaceDefault(),e.latency=await Jt.inetChecksite("google.com"),(await Jt.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=s;e.interfaces.push(f)}),(await Jt.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return fi.error(`error in getNetworkInfo: ${t}`),e}}a(eT,"getNetworkInfo");async function tT(){if(Ad!==void 0)return Ad;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Jt.osInfo();e=c;let u=await Jt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Ad=e,Ad}catch(t){return fi.error(`error in getSystemInformation: ${t}`),e}}a(tT,"getSystemInformation");async function rT(){let e=[],t=await qL.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await YX(s));return e}a(rT,"getTableSize");async function sT(){let e=await qL.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let i=WX({database:r,table:n}),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}}),s[n]=o}catch(i){fi.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(sT,"getMetrics");async function xL(){if(nT.get(Od.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await $X.getNATSReferences(),r=await t.streams.info(QS.WORK_QUEUE_CONSUMER_NAMES.stream_name),s=await e.consumers.get(QS.WORK_QUEUE_CONSUMER_NAMES.stream_name,QS.WORK_QUEUE_CONSUMER_NAMES.durable_name),n={ingest:{stream:{...r.state},consumer:{num_ack_pending:s._info.num_ack_pending,num_redelivered:s._info.num_redelivered,num_waiting:s._info.num_waiting,num_pending:s._info.num_pending}}};return r.sources&&(n.ingest.stream.sources=r.sources),n}}a(xL,"getNatsStreamInfo");async function QX(e){let t=new KX;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await tT(),t.time=zS(),t.cpu=await JS(),t.memory=await jS(),t.disk=await ZS(),t.network=await eT(),t.harperdb_processes=await XS(),t.table_size=await rT(),t.metrics=await sT(),t.threads=await HL(),t.replication=await xL(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await tT();break;case"time":t.time=zS();break;case"cpu":t.cpu=await JS();break;case"memory":t.memory=await jS();break;case"disk":t.disk=await ZS();break;case"network":t.network=await eT();break;case"harperdb_processes":t.harperdb_processes=await XS();break;case"table_size":t.table_size=await rT();break;case"database_metrics":case"metrics":t.metrics=await sT();break;case"threads":t.threads=await HL();break;case"replication":t.replication=await xL();break;default:break}return t}a(QX,"systemInformation")});var Nd=T((Xfe,GL)=>{"use strict";GL.exports={version:zX,printVersion:JX};var bd=jc();function zX(){if(bd)return bd.version}a(zX,"version");function JX(){bd&&console.log(`HarperDB Version ${bd.version}`)}a(JX,"printVersion")});var cs=T((rEe,YL)=>{"use strict";var jX=Mr(),iT=J(),XX=require("util"),io=L(),kL=X();kL.initSync();var ZX=FS(),VL=rs(),{Node:eEe,NodeSubscription:tEe}=di(),eZ=ea(),tZ=IL(),{RemotePayloadObject:rZ,RemotePayloadSubscription:sZ}=hu(),{handleHDBError:nZ,hdb_errors:iZ}=Z(),{HTTP_STATUS_CODES:oZ,HDB_ERROR_MSGS:aZ}=iZ,cZ=Js(),uZ=_a(),lZ=Nd(),{getDatabases:_Z}=(Ae(),ee(Fe)),dZ=XX.promisify(ZX.authorize),fZ=VL.searchByHash,EZ=VL.searchByValue;YL.exports={authHeaderToUser:hZ,isEmpty:mZ,getNodeRecord:pZ,upsertNodeRecord:SZ,buildNodePayloads:TZ,checkClusteringEnabled:gZ,getAllNodeRecords:RZ,getSystemInfo:AZ,reverseSubscription:$L};async function hZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await dZ(t,null),e}a(hZ,"authHeaderToUser");function mZ(e){return e==null}a(mZ,"isEmpty");async function pZ(e){let t=new eZ(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return fZ(t)}a(pZ,"getNodeRecord");async function SZ(e){let t=new tZ(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return jX.upsert(t)}a(SZ,"upsertNodeRecord");function $L(e){if(iT.isEmpty(e.subscribe)||iT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a($L,"reverseSubscription");function TZ(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=iT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=$L(c),E=_Z()[u]?.[_],h=new sZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new rZ(r,t,n,s)}a(TZ,"buildNodePayloads");function gZ(){if(!kL.get(io.CONFIG_PARAMS.CLUSTERING_ENABLED))throw nZ(new Error,aZ.CLUSTERING_NOT_ENABLED,oZ.BAD_REQUEST,void 0,void 0,!0)}a(gZ,"checkClusteringEnabled");async function RZ(){let e=new cZ(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await EZ(e))}a(RZ,"getAllNodeRecords");async function AZ(){let e=await uZ.getSystemInformation();return{hdb_version:lZ.version(),node_version:e.node_version,platform:e.platform}}a(AZ,"getSystemInfo")});var oT=T((nEe,ZL)=>{"use strict";var yd=it(),KL=J(),WL=Ge(),QL=L(),wd=V(),zL=cu(),OZ=K_(),{RemotePayloadObject:bZ}=hu(),{handleHDBError:JL,hdb_errors:NZ}=Z(),{HTTP_STATUS_CODES:jL}=NZ,{NodeSubscription:XL}=di();ZL.exports=yZ;async function yZ(e,t){let r;try{r=await yd.request(`${t}.${WL.REQUEST_SUFFIX}`,new bZ(QL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),wd.trace("Response from remote describe all request:",r)}catch(o){wd.error(`addNode received error from describe all request to remote node: ${o}`);let c=yd.requestErrorHandler(o,"add_node",t);throw JL(new Error,c,jL.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===WL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw JL(new Error,o,jL.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===QL.SYSTEM_SCHEMA_NAME){await yd.createLocalTableStream(u,c);let h=new XL(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=KL.doesSchemaExist(u),l=s[u]!==void 0,d=c?KL.doesTableExist(u,c):!0,f=c?s?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){n.push(o);continue}if(!_&&l&&(wd.trace(`addNode creating schema: ${u}`),await zL.createSchema({operation:"create_schema",schema:u})),!d&&f){wd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(s[u][c].attributes)}`);let h=new OZ(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await zL.createTable(h)}await yd.createLocalTableStream(u,c);let E=new XL(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(yZ,"reviewSubscriptions")});var Dd=T((oEe,rM)=>{"use strict";var{handleHDBError:Id,hdb_errors:wZ}=Z(),{HTTP_STATUS_CODES:Cd}=wZ,{addUpdateNodeValidator:IZ}=pd(),mu=V(),tM=L(),eM=Ge(),CZ=J(),aT=it(),pu=cs(),DZ=X(),LZ=oT(),{Node:MZ,NodeSubscription:UZ}=di(),{broadcast:PZ}=Qe(),vZ="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",BZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",HZ=DZ.get(tM.CONFIG_PARAMS.CLUSTERING_NODENAME);rM.exports=xZ;async function xZ(e,t=!1){mu.trace("addNode called with:",e),pu.checkClusteringEnabled();let r=IZ(e);if(r)throw Id(r,r.message,Cd.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await pu.getNodeRecord(s);if(!CZ.isEmptyOrZeroLength(d))throw Id(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,Cd.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await LZ(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=vZ,o;let c=pu.buildNodePayloads(n,HZ,tM.OPERATIONS_ENUM.ADD_NODE,await pu.getSystemInfo());mu.trace("addNode sending remote payload:",c);let u;try{u=await aT.request(`${s}.${eM.REQUEST_SUFFIX}`,c)}catch(d){mu.error(`addNode received error from request: ${d}`);let f=aT.requestErrorHandler(d,"add_node",s);throw Id(new Error,f,Cd.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===eM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${u.message}`;throw Id(new Error,d,Cd.INTERNAL_SERVER_ERROR,"error",d)}mu.trace(u);let _=[];for(let d=0,f=n.length;d<f;d++){let E=n[d];mu.trace("Add node updating work stream for node:",s,"subscriptions:",E),await aT.updateWorkStream(E,s),n[d].start_time===void 0&&delete n[d].start_time,_.push(new UZ(E.schema,E.table,E.publish,E.subscribe))}let l=new MZ(s,_,u.system_info);return await pu.upsertNodeRecord(l),PZ({type:"nats_update"}),i.length>0?o.message=BZ:o.message=`Successfully added '${s}' to manifest`,o}a(xZ,"addNode")});var _T=T((uEe,iM)=>{"use strict";var{handleHDBError:cT,hdb_errors:qZ}=Z(),{HTTP_STATUS_CODES:uT}=qZ,{addUpdateNodeValidator:FZ}=pd(),Su=V(),nM=L(),sM=Ge(),cEe=J(),lT=it(),Tu=cs(),GZ=X(),{cloneDeep:kZ}=require("lodash"),VZ=oT(),{Node:$Z,NodeSubscription:YZ}=di(),{broadcast:KZ}=Qe(),WZ="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",QZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",zZ=GZ.get(nM.CONFIG_PARAMS.CLUSTERING_NODENAME);iM.exports=JZ;async function JZ(e){Su.trace("updateNode called with:",e),Tu.checkClusteringEnabled();let t=FZ(e);if(t)throw cT(t,t.message,uT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await Tu.getNodeRecord(r);n.length>0&&(s=kZ(n));let{added:i,skipped:o}=await VZ(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=WZ,c;let u=Tu.buildNodePayloads(i,zZ,nM.OPERATIONS_ENUM.UPDATE_NODE,await Tu.getSystemInfo());Su.trace("updateNode sending remote payload:",u);let _;try{_=await lT.request(`${r}.${sM.REQUEST_SUFFIX}`,u)}catch(l){Su.error(`updateNode received error from request: ${l}`);let d=lT.requestErrorHandler(l,"update_node",r);throw cT(new Error,d,uT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===sM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw cT(new Error,l,uT.INTERNAL_SERVER_ERROR,"error",l)}Su.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];Su.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await lT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return s||(s=[new $Z(r,[],_.system_info)]),await jZ(s[0],i,_.system_info),o.length>0?c.message=QZ:c.message=`Successfully updated '${r}'`,c}a(JZ,"updateNode");async function jZ(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=s.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new YZ(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Tu.upsertNodeRecord(s),KZ({type:"nats_update"})}a(jZ,"updateNodeTable")});var lM=T((_Ee,uM)=>{"use strict";var cM=require("joi"),{string:oM}=cM.types(),XZ=Ze(),aM=L(),ZZ=X(),e5=Ge();uM.exports=t5;function t5(e){let t=oM.invalid(ZZ.get(aM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(e5.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=cM.object({operation:oM.valid(aM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return XZ.validateBySchema(e,r)}a(t5,"removeNodeValidator")});var Md=T((fEe,mM)=>{"use strict";var{handleHDBError:_M,hdb_errors:r5}=Z(),{HTTP_STATUS_CODES:dM}=r5,s5=lM(),gu=V(),fM=cs(),n5=J(),Ld=L(),EM=Ge(),hM=it(),i5=X(),{RemotePayloadObject:o5}=hu(),{NodeSubscription:a5}=di(),c5=ta(),u5=ti(),{broadcast:l5}=Qe(),_5=i5.get(Ld.CONFIG_PARAMS.CLUSTERING_NODENAME);mM.exports=d5;async function d5(e){gu.trace("removeNode called with:",e),fM.checkClusteringEnabled();let t=s5(e);if(t)throw _M(t,t.message,dM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await fM.getNodeRecord(r);if(n5.isEmptyOrZeroLength(s))throw _M(new Error,`Node '${r}' was not found.`,dM.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new o5(Ld.OPERATIONS_ENUM.REMOVE_NODE,_5,[]),i,o=!1;try{i=await hM.request(`${r}.${EM.REQUEST_SUFFIX}`,n),gu.trace("Remove node reply from remote node:",r,i)}catch(u){gu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=s.subscriptions.length;u<_;u++){let l=s.subscriptions[u];gu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new a5(l.schema,l.table,!1,!1);await hM.updateWorkStream(d,r)}let c=new c5(Ld.SYSTEM_SCHEMA_NAME,Ld.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await u5.deleteRecord(c),l5({type:"nats_update"}),i?.status===EM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(gu.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(d5,"removeNode")});var TM=T((hEe,SM)=>{"use strict";var pM=require("joi"),{string:f5,array:E5}=pM.types(),h5=Ze(),m5=pd();SM.exports=p5;function p5(e){let t=pM.object({operation:f5.valid("configure_cluster").required(),connections:E5.items(m5.validation_schema).required()});return h5.validateBySchema(e,t)}a(p5,"configureClusterValidator")});var dT=T((pEe,bM)=>{"use strict";var S5=L(),Ud=V(),T5=J(),g5=Md(),R5=Dd(),gM=cs(),A5=TM(),{handleHDBError:RM,hdb_errors:O5}=Z(),{HTTP_STATUS_CODES:AM}=O5,b5="Configure cluster complete.",N5="Failed to configure the cluster. Check the logs for more details.",y5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";bM.exports=w5;async function w5(e){Ud.trace("configure cluster called with:",e),gM.checkClusteringEnabled();let t=A5(e);if(t)throw RM(t,t.message,AM.BAD_REQUEST,void 0,void 0,!0);let r=await gM.getAllNodeRecords(),s=[];for(let f=0,E=r.length;f<E;f++)s.push(OM(g5,{operation:S5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let n=await Promise.allSettled(s);Ud.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(OM(R5,E,E.node_name))}let c=await Promise.allSettled(i);Ud.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=n.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(Ud.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(T5.isEmptyOrZeroLength(u))return{message:b5,connections:_};if(l)return{message:y5,failed_nodes:u,connections:_};throw RM(new Error,N5,AM.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(w5,"configureCluster");async function OM(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(OM,"functionWrapper")});var yM=T((TEe,NM)=>{"use strict";var Pd=require("joi"),I5=Ze(),{validateSchemaExists:C5,validateTableExists:D5,validateSchemaName:L5}=Ys(),M5=Pd.object({operation:Pd.string().valid("purge_stream"),schema:Pd.string().custom(C5).custom(L5).required(),table:Pd.string().custom(D5).required()});function U5(e){return I5.validateBySchema(e,M5)}a(U5,"purgeStreamValidator");NM.exports=U5});var fT=T((REe,wM)=>{"use strict";var{handleHDBError:P5,hdb_errors:v5}=Z(),{HTTP_STATUS_CODES:B5}=v5,H5=yM(),x5=it(),q5=cs();wM.exports=F5;async function F5(e){if(e.purge_ingest!==!0){let n=H5(e);if(n)throw P5(n,n.message,B5.BAD_REQUEST,void 0,void 0,!0)}q5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:s}=e;return await x5.purgeTableStream(t,r,s),s?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(F5,"purgeStream")});var mT=T((OEe,UM)=>{"use strict";var hT=cs(),G5=it(),DM=X(),vd=L(),oo=Ge(),k5=J(),ET=V(),{RemotePayloadObject:V5}=hu(),{ErrorCode:IM}=require("nats"),CM=DM.get(vd.CONFIG_PARAMS.CLUSTERING_ENABLED),LM=DM.get(vd.CONFIG_PARAMS.CLUSTERING_NODENAME);UM.exports={clusterStatus:$5,buildNodeStatus:MM};async function $5(){let e={node_name:LM,is_enabled:CM,connections:[]};if(!CM)return e;let t=await hT.getAllNodeRecords();if(k5.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(MM(t[s],e.connections));return await Promise.allSettled(r),e}a($5,"clusterStatus");async function MM(e,t){let r=e.name,s=new V5(vd.OPERATIONS_ENUM.CLUSTER_STATUS,LM,void 0,await hT.getSystemInfo()),n,i,o=oo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await G5.request(oo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===oo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=oo.CLUSTER_STATUS_STATUSES.CLOSED,ET.error(`Error getting node status from ${r} `,n))}catch(u){ET.warn(`Error getting node status from ${r}`,u),u.code===IM.NoResponders?o=oo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===IM.Timeout?o=oo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=oo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new Y5(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let u={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==vd.PRE_4_0_0_VERSION&&await hT.upsertNodeRecord(u)}catch(u){ET.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(MM,"buildNodeStatus");function Y5(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(Y5,"NodeStatusObject")});var ST=T((NEe,PM)=>{"use strict";var{handleHDBError:K5,hdb_errors:W5}=Z(),{HTTP_STATUS_CODES:Q5}=W5,z5=it(),J5=cs(),pT=J(),Bd=require("joi"),j5=Ze(),X5=2e3,Z5=Bd.object({timeout:Bd.number().min(1),connected_nodes:Bd.boolean(),routes:Bd.boolean()});PM.exports=e8;async function e8(e){J5.checkClusteringEnabled();let t=j5.validateBySchema(e,Z5);if(t)throw K5(t,t.message,Q5.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||pT.autoCastBoolean(s),o=n===void 0||pT.autoCastBoolean(n),c={nodes:[]},u=await z5.getServerList(r??X5),_={};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:pT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(e8,"clusterNetwork")});var xM=T((wEe,HM)=>{"use strict";var TT=require("joi"),vM=Ze(),{route_constraints:BM}=Fm();HM.exports={setRoutesValidator:t8,deleteRoutesValidator:r8};function t8(e){let t=TT.object({server:TT.valid("hub","leaf").required(),routes:BM.required()});return vM.validateBySchema(e,t)}a(t8,"setRoutesValidator");function r8(e){let t=TT.object({routes:BM.required()});return vM.validateBySchema(e,t)}a(r8,"deleteRoutesValidator")});var RT=T((CEe,kM)=>{"use strict";var ao=vr(),gT=J(),Hd=L(),qM=xM(),{handleHDBError:FM,hdb_errors:s8}=Z(),{HTTP_STATUS_CODES:GM}=s8,n8="cluster routes successfully set",i8="cluster routes successfully deleted";kM.exports={setRoutes:o8,getRoutes:a8,deleteRoutes:c8};function o8(e){let t=qM.setRoutesValidator(e);if(t)throw FM(t,t.message,GM.BAD_REQUEST,void 0,void 0,!0);let r=ao.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=gT.autoCast(_.port);let l=s.some(f=>f.host===_.host&&f.port===_.port),d=n.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(s.push(_),o.push(_))}return e.server==="hub"?ao.updateConfigValue(Hd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):ao.updateConfigValue(Hd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:n8,set:o,skipped:i}}a(o8,"setRoutes");function a8(){let e=ao.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(a8,"getRoutes");function c8(e){let t=qM.deleteRoutesValidator(e);if(t)throw FM(t,t.message,GM.BAD_REQUEST,void 0,void 0,!0);let r=ao.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=s.length;E<h;E++){let p=s[E];if(d.host===p.host&&d.port===p.port){s.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=n.length;h<p;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(s=gT.isEmptyOrZeroLength(s)?null:s,ao.updateConfigValue(Hd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=gT.isEmptyOrZeroLength(n)?null:n,ao.updateConfigValue(Hd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:i8,deleted:i,skipped:o}}a(c8,"deleteRoutes")});var $M=T((LEe,VM)=>{"use strict";var Ru=require("alasql"),co=require("recursive-iterator"),vs=V(),u8=J(),Au=L(),AT=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,_8(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(n=>Au.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!Au.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Au.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=l8(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(_=>!Au.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Ru.yy.Column({columnid:_});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function l8(e){return e.filter(t=>t[Au.PERMS_CRUD_ENUM.READ])}a(l8,"filterReadRestrictedAttrs");function _8(e,t,r,s,n){d8(e,t,r,s,n)}a(_8,"interpretAST");function Ou(e,t,r,s,n){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a(Ou,"addSchemaTableToMap");function d8(e,t,r,s,n){if(!e){vs.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Ru.yy.Insert?m8(e,t,r):e instanceof Ru.yy.Select?f8(e,t,r,s,n):e instanceof Ru.yy.Update?E8(e,t,r):e instanceof Ru.yy.Delete?h8(e,t,r):vs.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(d8,"getRecordAttributesAST");function f8(e,t,r,s,n){if(!e){vs.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(u8.isEmptyOrZeroLength(i)){vs.error("No schema specified");return}e.from.forEach(c=>{Ou(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Ou(c.table,t,r,s,n)});let o=new co(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{vs.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 co(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{vs.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 co(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=n.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{vs.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 co(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{vs.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(f8,"getSelectAttributes");function E8(e,t,r){if(!e){vs.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new co(e.columns),n=e.table.databaseid;Ou(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&OT(e.table.tableid,n,i.columnid,t,r)}a(E8,"getUpdateAttributes");function h8(e,t,r){if(!e){vs.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new co(e.where),n=e.table.databaseid;Ou(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&OT(e.table.tableid,n,i.columnid,t,r)}a(h8,"getDeleteAttributes");function m8(e,t,r){if(!e){vs.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new co(e.columns),n=e.into.databaseid;Ou(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&OT(e.into.tableid,n,i.columnid,t,r)}a(m8,"getInsertAttributes");function OT(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(OT,"pushAttribute");VM.exports=AT});var yT=T((UEe,QM)=>{var xd=$i(),YM=require("chalk"),kr=V(),KM=require("prompt"),{promisify:p8}=require("util"),bT=L(),S8=require("fs-extra"),T8=require("path"),g8=J(),R8=Nd(),WM=X();WM.initSync();var A8=require("moment"),O8=p8(KM.get),b8=T8.join(WM.getHdbBasePath(),bT.LICENSE_KEY_DIR_NAME,bT.LICENSE_FILE_NAME,bT.LICENSE_FILE_NAME);QM.exports={getFingerprint:y8,setLicense:N8,parseLicense:NT,register:w8,getRegistrationInfo:C8};async function N8(e){if(e&&e.key&&e.company){try{kr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await NT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw kr.error(r),kr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(N8,"setLicense");async function y8(){let e={};try{e=await xd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw kr.error(r),kr.error(t),new Error(r)}return e}a(y8,"getFingerprint");async function NT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");kr.info("Validating license input...");let r=xd.validateLicense(e,t);if(kr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(kr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(kr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{kr.info("writing license to disk"),await S8.writeFile(b8,JSON.stringify({license_key:e,company:t}))}catch(s){throw kr.error("Failed to write License"),s}return"Registration successful."}a(NT,"parseLicense");async function w8(){let e=await I8();return NT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(w8,"register");async function I8(){let e=await xd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:YM.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:YM.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{KM.start()}catch(s){kr.error(s)}let r;try{r=await O8(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(I8,"promptForRegistration");async function C8(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await xd.getLicense()}catch(r){throw kr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(g8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=R8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=A8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(C8,"getRegistrationInfo")});var JM=T((vEe,zM)=>{"use strict";var D8=Ge(),wT=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+D8.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};zM.exports=wT});var ZM=T((HEe,XM)=>{"use strict";var jM=Ge(),IT=class{static{a(this,"LeafConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+jM.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+jM.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"}};XM.exports=IT});var tU=T((qEe,eU)=>{"use strict";var CT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};eU.exports=CT});var sU=T((GEe,rU)=>{"use strict";var L8=Ge(),DT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+L8.SERVER_SUFFIX.ADMIN,this.password=r}};rU.exports=DT});var UT=T((VEe,oU)=>{"use strict";var da=require("path"),Gd=require("fs-extra"),M8=JM(),U8=ZM(),P8=tU(),v8=sU(),LT=ns(),Ea=J(),Er=vr(),Fd=L(),bu=Ge(),{CONFIG_PARAMS:Et}=Fd,Nu=V(),yu=X(),nU=Tn(),MT=it(),fa="clustering",B8=1e4,iU=5;oU.exports={generateNatsConfig:x8,removeNatsConfig:q8,getHubConfigPath:H8};function H8(){let e=yu.get(Et.ROOTPATH);return da.join(e,fa,bu.NATS_CONFIG_FILES.HUB_SERVER)}a(H8,"getHubConfigPath");async function x8(e=!1,t=void 0){yu.initSync();let r=yu.get(Et.ROOTPATH),s=da.join(r,fa,bu.PID_FILES.HUB),n=da.join(r,fa,bu.PID_FILES.LEAF),i=Er.getConfigFromFile(Et.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=da.join(r,fa,bu.NATS_CONFIG_FILES.HUB_SERVER),c=da.join(r,fa,bu.NATS_CONFIG_FILES.LEAF_SERVER),u=Er.getConfigFromFile(Et.CLUSTERING_TLS_CERTIFICATE),_=Er.getConfigFromFile(Et.CLUSTERING_TLS_PRIVATEKEY),l=Er.getConfigFromFile(Et.CLUSTERING_TLS_CERT_AUTH),d=Er.getConfigFromFile(Et.CLUSTERING_TLS_INSECURE),f=Er.getConfigFromFile(Et.CLUSTERING_TLS_VERIFY),E=Er.getConfigFromFile(Et.CLUSTERING_NODENAME),h=Er.getConfigFromFile(Et.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await MT.checkNATSServerInstalled()||kd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await LT.listUsers(),S=Er.getConfigFromFile(Et.CLUSTERING_USER),g=await LT.getClusterUser();(Ea.isEmpty(g)||g.active!==!0)&&kd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await qd(Et.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await qd(Et.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await qd(Et.CLUSTERING_HUBSERVER_NETWORK_PORT),await qd(Et.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],b=[];for(let[Q,ne]of p.entries())ne.role.role===Fd.ROLE_TYPES_ENUM.CLUSTER_USER&&ne.active&&(A.push(new v8(ne.username,nU.decrypt(ne.hash))),b.push(new P8(ne.username,nU.decrypt(ne.hash))));let v=[],{hub_routes:G}=Er.getClusteringRoutes();if(!Ea.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 M8(Er.getConfigFromFile(Et.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,Er.getConfigFromFile(Et.CLUSTERING_HUBSERVER_CLUSTER_NAME),Er.getConfigFromFile(Et.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),v,A,b);l==null&&(delete H.tls.ca_file,delete H.leafnodes.tls.ca_file),t=Ea.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Fd.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Gd.writeJson(o,H),Nu.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 U8(Er.getConfigFromFile(Et.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[P],[z],A,b,u,_,l,d);l==null&&delete W.tls.ca_file,(t===void 0||t===Fd.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Gd.writeJson(c,W),Nu.trace(`Leaf server config written to ${c}`))}a(x8,"generateNatsConfig");async function qd(e){let t=yu.get(e);return Ea.isEmpty(t)&&kd(`port undefined for '${e}'`),await Ea.isPortTaken(t)&&kd(`'${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(qd,"isPortAvailable");function kd(e){let t=`Error generating clustering config: ${e}`;Nu.error(t),console.error(t),process.exit(1)}a(kd,"generateNatsConfigError");async function q8(e){let{port:t,config_file:r}=MT.getServerConfig(e),{username:s,decrypt_hash:n}=await LT.getClusterUser(),i=0,o=2e3;for(;i<iU;){try{let _=await MT.createConnection(t,s,n,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){Nu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=iU)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 Ea.async_set_timeout(o*(i*2))}let c="0".repeat(B8),u=da.join(yu.get(Et.ROOTPATH),fa,r);await Gd.writeFile(u,c),await Gd.remove(u),Nu.notify(e,"started.")}a(q8,"removeNatsConfig")});var dU=T((YEe,_U)=>{"use strict";var Vr=X(),F8=$i(),me=L(),wu=Ge(),yn=require("path"),{PACKAGE_ROOT:$d}=L(),aU=X(),Vd=J(),ha="/dev/null",G8=yn.join($d,"launchServiceScripts"),cU=yn.join($d,"utility/scripts"),k8=yn.join(cU,me.HDB_RESTART_SCRIPT),uU=yn.resolve($d,"dependencies",`${process.platform}-${process.arch}`,wu.NATS_BINARY_NAME);function lU(){let t=F8.licenseSearch().ram_allocation||me.RAM_ALLOCATION_ENUM.DEFAULT,r=me.MEM_SETTING_KEY+t,s={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Vd.noBootFile()&&(s[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Vd.getEnvCliRootPath()),{name:me.PROCESS_DESCRIPTORS.HDB,script:me.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:$d}}a(lU,"generateMainServerConfig");var V8=9930;function $8(){Vr.initSync(!0);let e=Vr.get(me.CONFIG_PARAMS.ROOTPATH),t=yn.join(e,"clustering",wu.NATS_CONFIG_FILES.HUB_SERVER),r=yn.join(Vr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),s=aU.get(me.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=wu.LOG_LEVEL_FLAGS[Vr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==V8?"-"+s:""),script:uU,args:n?`${n} -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 Vr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ha,i.error_file=ha),i}a($8,"generateNatsHubServerConfig");var Y8=9940;function K8(){Vr.initSync(!0);let e=Vr.get(me.CONFIG_PARAMS.ROOTPATH),t=yn.join(e,"clustering",wu.NATS_CONFIG_FILES.LEAF_SERVER),r=yn.join(Vr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),s=aU.get(me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=wu.LOG_LEVEL_FLAGS[Vr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==Y8?"-"+s:""),script:uU,args:n?`${n} -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 Vr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ha,i.error_file=ha),i}a(K8,"generateNatsLeafServerConfig");function W8(){Vr.initSync();let e=yn.join(Vr.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:G8,autorestart:!1};return Vr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ha,t.error_file=ha),t}a(W8,"generateClusteringUpgradeV4ServiceConfig");function Q8(){let e={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.RESTART_HDB};return Vd.noBootFile()&&(e[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Vd.getEnvCliRootPath()),{...{name:me.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:cU},script:k8}}a(Q8,"generateRestart");function z8(){return{apps:[lU()]}}a(z8,"generateAllServiceConfigs");_U.exports={generateAllServiceConfigs:z8,generateMainServerConfig:lU,generateRestart:Q8,generateNatsHubServerConfig:$8,generateNatsLeafServerConfig:K8,generateClusteringUpgradeV4ServiceConfig:W8}});var yU=T((QEe,NU)=>{"use strict";var Ce=L(),J8=J(),wn=UT(),Iu=it(),en=Ge(),Ei=dU(),Yd=X(),hi=V(),j8=cs(),{startWorker:fU,onMessageFromWorkers:X8}=Qe(),Z8=_a(),WEe=require("util"),e6=require("child_process"),t6=require("fs"),{execFile:r6}=e6,Ne;NU.exports={enterPM2Mode:s6,start:mi,stop:PT,reload:hU,restart:mU,list:vT,describe:SU,connect:In,kill:c6,startAllServices:u6,startService:BT,getUniqueServicesList:TU,restartAllServices:l6,isServiceRegistered:gU,reloadStopStart:RU,restartHdb:pU,deleteProcess:o6,startClusteringProcesses:OU,startClusteringThreads:bU,isHdbRestartRunning:a6,isClusteringRunning:d6,stopClustering:_6,reloadClustering:f6};var Cu=!1;X8(e=>{e.type==="restart"&&Yd.initSync(!0)});function s6(){Cu=!0}a(s6,"enterPM2Mode");function In(){return Ne||(Ne=require("pm2")),new Promise((e,t)=>{Ne.connect((r,s)=>{hi.setupConsoleLogging(),r&&t(r),e(s)})})}a(In,"connect");var hr,n6=10,EU;function mi(e,t=!1){if(Cu)return i6(e);let r=r6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=hr.indexOf(r);o>-1&&hr.splice(o,1),!EU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<n6&&(t6.existsSync(wn.getHubConfigPath())?mi(e):(await wn.generateNatsConfig(!0),mi(e),await new Promise(c=>setTimeout(c,3e3)),await wn.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await wn.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=Yd.get(Ce.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&en.LOG_LEVEL_HIERARCHY[o]>=en.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===en.LOG_LEVELS.ERR||l===en.LOG_LEVELS.WRN?hi.OUTPUTS.STDERR:hi.OUTPUTS.STDOUT;hi.logCustomLevel(l||"info",E,s,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=en.LOG_LEVELS[f]}if(en.LOG_LEVEL_HIERARCHY[o]>=en.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===en.LOG_LEVELS.ERR||l===en.LOG_LEVELS.WRN?hi.OUTPUTS.STDERR:hi.OUTPUTS.STDOUT;hi.logCustomLevel(l||"info",d,s,i.slice(_).trim())}}if(a(n,"extractMessages"),r.stdout.on("data",n),r.stderr.on("data",n),r.unref(),hr=[],!hr&&!t){let i=a(()=>{EU=!0,hr&&(hr.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)}hr.push(r)}a(mi,"start");function i6(e){return new Promise(async(t,r)=>{try{await In()}catch(s){r(s)}Ne.start(e,(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(n)})})}a(i6,"startWithPM2");function PT(e){if(!Cu){for(let t of hr||[])t.name===e&&(hr.splice(hr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await In()}catch(s){r(s)}Ne.stop(e,async(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.delete(e,(i,o)=>{i&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(o)})})})}a(PT,"stop");function hU(e){return new Promise(async(t,r)=>{try{await In()}catch(s){r(s)}Ne.reload(e,(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(n)})})}a(hU,"reload");function mU(e){if(!Cu)for(let t of hr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await In()}catch(s){r(s)}Ne.restart(e,(s,n)=>{Ne.disconnect(),t(n)})})}a(mU,"restart");function o6(e){return new Promise(async(t,r)=>{try{await In()}catch(s){r(s)}Ne.delete(e,(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(n)})})}a(o6,"deleteProcess");async function pU(){await mi(Ei.generateRestart())}a(pU,"restartHdb");async function a6(){let e=await vT();for(let t in e)if(e[t].name===Ce.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(a6,"isHdbRestartRunning");function vT(){return new Promise(async(e,t)=>{try{await In()}catch(r){t(r)}Ne.list((r,s)=>{r&&(Ne.disconnect(),t(r)),Ne.disconnect(),e(s)})})}a(vT,"list");function SU(e){return new Promise(async(t,r)=>{try{await In()}catch(s){r(s)}Ne.describe(e,(s,n)=>{s&&(Ne.disconnect(),r(s)),Ne.disconnect(),t(n)})})}a(SU,"describe");function c6(){if(!Cu){for(let e of hr||[])e.kill();hr=[];return}return new Promise(async(e,t)=>{try{await In()}catch(r){t(r)}Ne.killDaemon((r,s)=>{r&&(Ne.disconnect(),t(r)),Ne.disconnect(),e(s)})})}a(c6,"kill");async function u6(){try{await OU(),await bU(),await mi(Ei.generateAllServiceConfigs())}catch(e){throw Ne?.disconnect(),e}}a(u6,"startAllServices");async function BT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ce.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ei.generateMainServerConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ei.generateNatsIngestServiceConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ei.generateNatsReplyServiceConfig();break;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ei.generateNatsHubServerConfig(),await mi(r,t),await wn.removeNatsConfig(e);return;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ei.generateNatsLeafServerConfig(),await mi(r,t),await wn.removeNatsConfig(e);return;case Ce.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ei.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await mi(r)}catch(r){throw Ne?.disconnect(),r}}a(BT,"startService");async function TU(){try{let e=await vT(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw Ne?.disconnect(),e}}a(TU,"getUniqueServicesList");async function l6(e=[]){try{let t=!1,r=await TU();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===Ce.PROCESS_DESCRIPTORS.HDB?t=!0:await mU(o))}t&&await RU(Ce.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ne?.disconnect(),t}}a(l6,"restartAllServices");async function gU(e){if(hr?.find(r=>r.name===e))return!0;let t=await Z8.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(gU,"isServiceRegistered");async function RU(e){let t=e===Ce.PROCESS_DESCRIPTORS.HDB?Yd.get(Ce.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):Yd.get(Ce.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await SU(e),s=J8.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await PT(e),await BT(e)):e===Ce.PROCESS_DESCRIPTORS.HDB?await pU():await hU(e)}a(RU,"reloadStopStart");var AU;async function OU(e=!1){for(let t in Ce.CLUSTERING_PROCESSES){let r=Ce.CLUSTERING_PROCESSES[t];await BT(r,e)}}a(OU,"startClusteringProcesses");async function bU(){AU=fU(Ce.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ce.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Iu.createWorkQueueStream(en.WORK_QUEUE_CONSUMER_NAMES),await Iu.updateIngestStreamConsumer(),await Iu.updateLocalStreams();let e=await j8.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ce.PRE_4_0_0_VERSION){hi.info("Starting clustering upgrade 4.0.0 process"),fU(Ce.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(bU,"startClusteringThreads");async function _6(){for(let e in Ce.CLUSTERING_PROCESSES)if(e!==Ce.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ce.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await AU.terminate();else{let t=Ce.CLUSTERING_PROCESSES[e];await PT(t)}}a(_6,"stopClustering");async function d6(){for(let e in Ce.CLUSTERING_PROCESSES){let t=Ce.CLUSTERING_PROCESSES[e];if(await gU(t)===!1)return!1}return!0}a(d6,"isClusteringRunning");async function f6(){await wn.generateNatsConfig(!0),await Iu.reloadNATSHub(),await Iu.reloadNATSLeaf(),await wn.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await wn.removeNatsConfig(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(f6,"reloadClustering")});var zd=T((JEe,UU)=>{"use strict";var E6=require("minimist"),{isMainThread:qT,parentPort:CU}=require("worker_threads"),ot=L(),{PROCESS_DESCRIPTORS_VALIDATE:Du}=ot,tn=V(),FT=J(),Kd=UT(),ma=it(),HT=Ge(),DU=vr(),rn=yU(),wU=_a(),h6=Eh(),{restartWorkers:Wd,onMessageByType:m6}=Qe(),{handleHDBError:p6,hdb_errors:S6}=Z(),{HTTP_STATUS_CODES:T6}=S6,Qd=X();Qd.initSync();var Lu=`Restarting HarperDB. This may take up to ${ot.RESTART_TIMEOUT_MS/1e3} seconds.`,g6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",IU="Clustering is not enabled so cannot be restarted",R6="Invalid service",pa,us;UU.exports={restart:LU,restartService:GT};qT&&m6(ot.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?GT({service:e.workerType}):LU({operation:"restart"})});async function LU(e){us=Object.keys(e).length===0,pa=await rn.isServiceRegistered(ot.HDB_PROC_DESCRIPTOR);let t=E6(process.argv);if(t.service){await GT(t);return}if(us&&!pa){console.error(g6);return}if(us&&console.log(Lu),pa){rn.enterPM2Mode(),tn.notify(Lu);let r=h6(Object.keys(ot.CONFIG_PARAM_MAP),!0);return FT.isEmptyOrZeroLength(Object.keys(r))||DU.updateConfigValue(void 0,void 0,r,!0,!0),O6(),Lu}return qT?(tn.notify(Lu),setTimeout(()=>{Wd()},50)):CU.postMessage({type:ot.ITC_EVENT_TYPES.RESTART}),Lu}a(LU,"restart");async function GT(e){let{service:t}=e;if(ot.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw p6(new Error,R6,T6.BAD_REQUEST,void 0,void 0,!0);if(pa=await rn.isServiceRegistered(ot.HDB_PROC_DESCRIPTOR),!qT)return CU.postMessage({type:ot.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Du.clustering:if(!Qd.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=IU;break}us&&console.log("Restarting clustering"),tn.notify("Restarting clustering"),await MU();break;case Du.clustering_config:case Du["clustering config"]:if(!Qd.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=IU;break}us&&console.log("Restarting clustering_config"),tn.notify("Restarting clustering_config"),await rn.reloadClustering();break;case"custom_functions":case"custom functions":case Du.harperdb:case Du.http_workers:if(us&&!pa){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}us&&console.log("Restarting http_workers"),tn.notify("Restarting http_workers"),us?await rn.restart(ot.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Wd("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(tn.error(r),us&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(GT,"restartService");async function A6(){await ma.publishToStream(`${HT.SUBJECT_PREFIXES.TXN}.${HT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,HT.WORK_QUEUE_CONSUMER_NAMES.stream_name,ma.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(A6,"postDummyNatsMsg");async function O6(){await MU(),await rn.restart(ot.HDB_PROC_DESCRIPTOR),await FT.async_set_timeout(2e3),Qd.get(ot.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await xT(),us&&(await ma.closeConnection(),process.exit(0))}a(O6,"restartPM2Mode");async function MU(){if(!DU.getConfigFromFile(ot.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await wU.getHDBProcessInfo()).clustering.length===0)tn.trace("Clustering not running, restart will start clustering services"),await Kd.generateNatsConfig(!0),await rn.startClusteringProcesses(),await rn.startClusteringThreads(),await xT(),us&&await ma.closeConnection();else{await A6(),await Kd.generateNatsConfig(!0),pa?(tn.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await rn.restart(ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await rn.restart(ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await wU.getHDBProcessInfo()).clustering.forEach(n=>{tn.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await FT.async_set_timeout(3e3),await xT(),await ma.updateLocalStreams(),us&&await ma.closeConnection(),tn.trace("Restart clustering restarting ingest and reply service threads");let t=Wd(ot.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Wd(ot.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(MU,"restartClustering");async function xT(){await Kd.removeNatsConfig(ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Kd.removeNatsConfig(ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(xT,"removeNatsConfig")});var $U=T((ZEe,VU)=>{"use strict";var XEe=require("lodash"),mr=L(),{handleHDBError:PU,hdb_errors:b6}=Z(),{HDB_ERROR_MSGS:N6,HTTP_STATUS_CODES:y6}=b6,kT=V();VU.exports={getRolePermissions:I6};var uo=Object.create(null),w6=a(e=>({key:e,perms:{}}),"perms_template_obj"),xU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),qU=a((e=!1,t=!1,r=!1,s=!1)=>({[mr.PERMS_CRUD_ENUM.READ]:e,[mr.PERMS_CRUD_ENUM.INSERT]:t,[mr.PERMS_CRUD_ENUM.UPDATE]:r,[mr.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),VT=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...qU(t,r,s,n)}),"table_perms_template"),vU=a((e,t=qU())=>({attribute_name:e,describe:kU(t),[Mu]:t[Mu],[$T]:t[$T],[YT]:t[YT]}),"attr_perms_template"),BU=a((e,t=!1)=>({attribute_name:e,describe:t,[Mu]:t}),"timestamp_attr_perms_template"),{READ:Mu,INSERT:$T,UPDATE:YT}=mr.PERMS_CRUD_ENUM,FU=Object.values(mr.PERMS_CRUD_ENUM),GU=[Mu,$T,YT];function I6(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[mr.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(uo[t]&&uo[t].key===s)return uo[t].perms;let n=C6(e,r);return uo[t]?uo[t].key=s:uo[t]=w6(s),uo[t].perms=n,n}catch(r){if(!e[mr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[mr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<mr.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw kT.error(s),kT.debug(r),PU(new Error,N6.OUTDATED_PERMS_TRANSLATION_ERROR,y6.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
+
${r.stack}`;throw kT.error(s),PU(new Error)}}}a(I6,"getRolePermissions");function C6(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[mr.SYSTEM_SCHEMA_NAME]=s[mr.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=D6(t[i]);return}r[i]=xU(),s[i]?(s[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],u=t[i][o],_=L6(c,u);r[i].describe||FU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=VT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=VT()})}),r}a(C6,"translateRolePermissions");function D6(e){let t=xU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=VT(!0,!0,!0,!0,!0)}),t}a(D6,"createStructureUserPermissions");function L6(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return mr.TIME_STAMP_NAMES.includes(d)&&(f=BU(d,l[Mu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=vU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=kU(l),n.attribute_permissions.push(l),c||M6(l,u)}else if(_!==o){let l;mr.TIME_STAMP_NAMES.includes(_)?l=BU(_):l=vU(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=HU(n),n}else return e.describe=HU(e),e}a(L6,"getTableAttrPerms");function HU(e){return FU.filter(t=>e[t]).length>0}a(HU,"getSchemaTableDescribePerm");function kU(e){return GU.filter(t=>e[t]).length>0}a(kU,"getAttributeDescribePerm");function M6(e,t){GU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(M6,"checkForHashPerms")});var YU={};We(YU,{Resources:()=>Jd,keyArrayToString:()=>Sa,resetResources:()=>U6,resources:()=>pi});function U6(){return pi=new Jd}function Sa(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Jd,pi,Uu=Re(()=>{Ji();Jd=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,s,n){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:s,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!n)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let s=2,n;for(;(s=t.indexOf("/",s))>-1;){let c=t.slice(0,s),u=this.get(c);if(u){if(u.relativeURL=t.slice(s),!u.hasSubPaths)return u;n=u}s+=2}if(n)return n;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return n=this.get(o),n?n.relativeURL=i>-1?t.slice(i):"":n||(n=this.get(""),n&&(t[0]!=="/"&&(t="/"+t),n.relativeURL=t)),n}getResource(t,r){let s=this.getMatch(t);if(s)return t=s.relativeURL,s.Resource.getResource(this.pathToId(t,s.Resource),r)}call(t,r,s){return et(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(U6,"resetResources");a(Sa,"keyArrayToString")});var KU={};We(KU,{Headers:()=>Si});var Si,jd=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 s=t.toLowerCase();if(!super.has(s))return super.set(s,[t,r])}append(t,r,s){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase(),i=super.get(n);if(i){let o=i[1];s?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var Pu={};We(Pu,{authentication:()=>eP,bypassAuth:()=>F6,login:()=>k6,logout:()=>V6,start:()=>G6});function F6(){ZU=!0}async function eP(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?H6?B6:[]:v6?P6:[];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 Xd&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Xd&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Xd){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(E);if(h>=0){let p=n.indexOf(";",h),S=n.indexOf("=",h);u=n.slice(S+1,p===-1?n.length:p),_=await QU.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new ef.AuthAuditLog(E,h,kt.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===kt.AUTH_AUDIT_STATUS.SUCCESS?WU.notify(S):WU.error(S)},"authAuditLog"),d;if(s){if(d=lo.get(s),!d){let[E,h]=s.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await lt.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Zd.validateOperationToken)(h)}catch(g){if(g.message==="invalid token")try{return await(0,Zd.validateRefreshToken)(h),c({status:-1})}catch{throw g}}break}}catch(g){return q6&&(lo.get(h)||(lo.set(h,h),l(p,kt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ti({error:g.message},e)})}lo.set(s,d),x6&&l(d.username,kt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await lt.getUser(_.user,null,e):(ZU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,JU.getSuperUser)());Xd&&(e.session.update=function(E){if(!u){u=(0,jU.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,QU.put(E)},e.login=async function(E,h){e.user=await lt.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")&&pi.loginPath?(f.status=302,f.headers.set("Location",pi.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 G6({server:e,port:t}){e.request(eP,{port:t||"all"}),zU||(zU=!0,setInterval(()=>{lo=new Map},ls.get(kt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),XU.user.addListener(()=>{lo=new Map}))}async function k6(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 V6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var JU,Zd,jU,ls,kt,ef,XU,WU,P6,v6,B6,H6,QU,Xd,ZU,x6,q6,lo,zU,tf=Re(()=>{JU=B(ns());rr();Uu();Zd=B(Eu());Ae();jU=require("uuid"),ls=B(X()),kt=B(L()),ef=B(V()),XU=B(vc());jd();Ta();WU=(0,ef.loggerWithTag)("auth-event");ls.initSync();P6=ls.get(kt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),v6=ls.get(kt.CONFIG_PARAMS.HTTP_CORS),B6=ls.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),H6=ls.get(kt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),QU=_t({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Xd=ls.get(kt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,ZU=ls.get(kt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,x6=ls.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,q6=ls.get(kt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,lo=new Map;lt.onInvalidatedUser(()=>{lo=new Map});a(F6,"bypassAuth");a(eP,"authentication");a(G6,"start");a(k6,"login");a(V6,"logout")});var aP=T((lhe,oP)=>{"use strict";var ye=require("joi"),tP=require("fs-extra"),rP=require("path"),Dn=Ze(),sP=X(),nP=L(),iP=V(),{hdb_errors:$6}=Z(),{HDB_ERROR_MSGS:jt}=$6,Cn=/^[a-zA-Z0-9-_]+$/;oP.exports={getDropCustomFunctionValidator:K6,setCustomFunctionValidator:W6,addComponentValidator:j6,dropCustomFunctionProjectValidator:X6,packageComponentValidator:Z6,deployComponentValidator:e9,setComponentFileValidator:Q6,getComponentFileValidator:J6,dropComponentFileValidator:z6};function rf(e,t,r){try{let s=sP.get(nP.CONFIG_PARAMS.COMPONENTSROOT),n=rP.join(s,t);return tP.existsSync(n)?e?t:r.message(jt.PROJECT_EXISTS):e?r.message(jt.NO_PROJECT):t}catch(s){return iP.error(s),r.message(jt.VALIDATION_ERR)}}a(rf,"checkProjectExists");function vu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(vu,"checkFilePath");function Y6(e,t,r,s){try{let n=sP.get(nP.CONFIG_PARAMS.COMPONENTSROOT),i=rP.join(n,e,t,r+".js");return tP.existsSync(i)?r:s.message(jt.NO_FILE)}catch(n){return iP.error(n),s.message(jt.VALIDATION_ERR)}}a(Y6,"checkFileExists");function K6(e){let t=ye.object({project:ye.string().pattern(Cn).custom(rf.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),type:ye.string().valid("helpers","routes").required(),file:ye.string().pattern(Cn).custom(Y6.bind(null,e.project,e.type)).custom(vu).required().messages({"string.pattern.base":jt.BAD_FILE_NAME})});return Dn.validateBySchema(e,t)}a(K6,"getDropCustomFunctionValidator");function W6(e){let t=ye.object({project:ye.string().pattern(Cn).custom(rf.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),type:ye.string().valid("helpers","routes").required(),file:ye.string().custom(vu).required(),function_content:ye.string().required()});return Dn.validateBySchema(e,t)}a(W6,"setCustomFunctionValidator");function Q6(e){let t=ye.object({project:ye.string().pattern(Cn).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),file:ye.string().custom(vu).required(),payload:ye.string().allow("").optional(),encoding:ye.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Dn.validateBySchema(e,t)}a(Q6,"setComponentFileValidator");function z6(e){let t=ye.object({project:ye.string().pattern(Cn).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),file:ye.string().custom(vu).optional()});return Dn.validateBySchema(e,t)}a(z6,"dropComponentFileValidator");function J6(e){let t=ye.object({project:ye.string().required(),file:ye.string().custom(vu).required(),encoding:ye.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Dn.validateBySchema(e,t)}a(J6,"getComponentFileValidator");function j6(e){let t=ye.object({project:ye.string().pattern(Cn).custom(rf.bind(null,!1)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME})});return Dn.validateBySchema(e,t)}a(j6,"addComponentValidator");function X6(e){let t=ye.object({project:ye.string().pattern(Cn).custom(rf.bind(null,!0)).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME})});return Dn.validateBySchema(e,t)}a(X6,"dropCustomFunctionProjectValidator");function Z6(e){let t=ye.object({project:ye.string().pattern(Cn).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),skip_node_modules:ye.boolean()});return Dn.validateBySchema(e,t)}a(Z6,"packageComponentValidator");function e9(e){let t=ye.object({project:ye.string().pattern(Cn).required().messages({"string.pattern.base":jt.BAD_PROJECT_NAME}),payload:ye.string().optional().messages({"string.pattern.base":jt.BAD_PACKAGE}),package:ye.string().optional()});return Dn.validateBySchema(e,t)}a(e9,"deployComponentValidator")});var af=T((dhe,EP)=>{"use strict";var sf=require("joi"),nf=require("path"),cP=require("fs-extra"),{exec:t9}=require("child_process"),r9=require("util"),uP=r9.promisify(t9),Bu=L(),{handleHDBError:ga,hdb_errors:s9}=Z(),{HTTP_STATUS_CODES:Ra}=s9,Hu=X(),n9=Ze(),Aa=V();Hu.initSync();var KT=Hu.get(Bu.CONFIG_PARAMS.COMPONENTSROOT),lP="npm install --omit=dev --json",i9=`${lP} --dry-run`;EP.exports={installModules:u9,auditModules:l9,installAllRootModules:o9,uninstallRootModule:a9,linkHarperdb:c9};async function o9(e=!1){await of(),await xu(e?"npm install --ignore-scripts":"npm install",Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(o9,"installAllRootModules");async function a9(e){await xu(`npm uninstall ${e}`,Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(a9,"uninstallRootModule");async function c9(){await of(),await xu(`npm link ${Bu.PACKAGE_ROOT}`,Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(c9,"linkHarperdb");async function xu(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await uP(e,{cwd:t}))}catch(n){throw new Error(n.stderr.replace(`
|
|
12
12
|
`,""))}return s&&!s.includes("Debugger listening")&&Aa.error("Error running NPM command:",e,s),Aa.trace(r,s),r?.replace(`
|
|
13
|
-
`,"")}a(
|
|
13
|
+
`,"")}a(xu,"runCommand");async function u9(e){Aa.info(`starting installModules for request: ${e}`);let t=fP(e);if(t)throw ga(t,t.message,Ra.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?i9:lP;await of(),await dP(r);let i={};for(let o=0,c=r.length;o<c;o++){let u=r[o];i[u]={npm_output:null,npm_error:null};let _=nf.join(KT,u),l,d=null;try{let{stdout:f,stderr:E}=await uP(n,{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&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(sP,"parseNPMStdErr");async function K6(e){Aa.info(`starting auditModules for request: ${e}`);let t=iP(e);if(t)throw ga(t,t.message,Ra.BAD_REQUEST);let{projects:r}=e;await nf(),await nP(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=sf.join(GT,o);s[o]={npm_output:null,npm_error:null};try{let u=await qu("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=sP(u.stderr)}}return Aa.info(`finished auditModules with response ${s}`),s}a(K6,"auditModules");async function nf(){try{return await qu("npm -v"),!0}catch{throw ga(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ra.BAD_REQUEST,void 0,void 0,!0)}}a(nf,"checkNPMInstalled");async function nP(e){if(!Array.isArray(e)||e.length===0)throw ga(new Error,"projects argument must be an array with at least 1 element",Ra.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=sf.join(GT,i.toString());if(!await eP.pathExists(o)){t.push(i);continue}let u=sf.join(o,"package.json");await eP.pathExists(u)||r.push(i)}if(t.length>0)throw ga(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ra.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw ga(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ra.BAD_REQUEST,void 0,void 0,!0)}a(nP,"checkProjectPaths");function iP(e){let t=rf.object({projects:rf.array().min(1).items(rf.string()).required(),dry_run:rf.boolean().default(!1)});return F6.validateBySchema(e,t)}a(iP,"modulesValidator")});var VT=T(($Ee,_P)=>{"use strict";var Oa=require("fs-extra"),kT=require("path"),af=G(),aP=z(),cf=D(),lP=j(),W6=Pr();_P.exports=Q6;async function Q6(){let e=z6(),t=lP.get(cf.CONFIG_PARAMS.ROOTPATH),r=kT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+cf.PACKAGE_ROOT}},n=kT.join(t,"node_modules");await Oa.ensureDir(n);let i,o=!0,c=!1;try{i=await Oa.readJson(r)}catch(u){if(aP.isEmptyOrZeroLength(e))return;if(u.code!==cf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!aP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await cP(_);s.dependencies[u]=l+_}if(!o){af.notify("Installing components"),await uP(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await cP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(af.notify("Removing component",u),c=!0);c&&(af.notify("Updating components."),await uP(r,s,i))}a(Q6,"installComponents");function z6(){let e=W6.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(z6,"getComponentsConfig");async function cP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":kT.extname(e)||await Oa.pathExists(e)?"file:":"github:"}a(cP,"getPkgPrefix");async function uP(e,t,r){af.trace("npm installing components package.json",t),await Oa.writeFile(e,JSON.stringify(t,null," "));try{await of().installAllRootModules(lP.get(cf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(s){throw r?await Oa.writeFile(e,JSON.stringify(r,null," ")):await Oa.unlink(e),s}}a(uP,"installPackages")});var KT=T((WEe,hP)=>{"use strict";var Fe=require("fs-extra"),$T=require("fast-glob"),pe=require("path"),fP=require("tar-fs"),KEe=require("uuid").v4,YT=require("normalize-path"),nn=ZM(),wt=G(),We=D(),gt=j(),Fu=Pr(),J6=z(),{PACKAGE_ROOT:X6}=D(),{handleHDBError:Ht,hdb_errors:j6}=Z(),{basename:Z6}=require("path"),e9=VT(),EP=j(),t9=D(),{Readable:r9}=require("stream"),{isMainThread:s9}=require("worker_threads"),{HDB_ERROR_MSGS:fo,HTTP_STATUS_CODES:xt}=j6,n9=pe.join(X6,"application-template"),dP=pe.join(gt.get(We.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function i9(){wt.trace("getting custom api status");let e={};try{e={port:gt.get(We.CONFIG_PARAMS.HTTP_PORT),directory:gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Ht(new Error,fo.FUNCTION_STATUS,xt.INTERNAL_SERVER_ERROR,wt.ERR,t)}return e}a(i9,"customFunctionsStatus");function o9(){wt.trace("getting custom api endpoints");let e={},t=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT);try{$T.sync(YT(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:$T.sync(YT(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:$T.sync(YT(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Ht(new Error,fo.GET_FUNCTIONS,xt.INTERNAL_SERVER_ERROR,wt.ERR,r)}return e}a(o9,"getCustomFunctions");function a9(e){e.project&&(e.project=pe.parse(e.project).name),e.file&&(e.file=pe.parse(e.file).name);let t=nn.getDropCustomFunctionValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);wt.trace("getting custom api endpoint file content");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e,o=pe.join(r,s,n,i+".js");try{return Fe.readFileSync(o,{encoding:"utf8"})}catch(c){throw Ht(new Error,fo.GET_FUNCTION,xt.INTERNAL_SERVER_ERROR,wt.ERR,c)}}a(a9,"getCustomFunction");function c9(e){e.project&&(e.project=pe.parse(e.project).name),e.file&&(e.file=pe.parse(e.file).name);let t=nn.setCustomFunctionValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);wt.trace("setting custom function file content");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i,function_content:o}=e;try{return Fe.outputFileSync(pe.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Ht(new Error,fo.SET_FUNCTION,xt.INTERNAL_SERVER_ERROR,wt.ERR,c)}}a(c9,"setCustomFunction");function u9(e){e.project&&(e.project=pe.parse(e.project).name),e.file&&(e.file=pe.parse(e.file).name);let t=nn.getDropCustomFunctionValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);wt.trace("dropping custom function file");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e;try{return Fe.unlinkSync(pe.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Ht(new Error,fo.DROP_FUNCTION,xt.INTERNAL_SERVER_ERROR,wt.ERR,o)}}a(u9,"dropCustomFunction");function l9(e){e.project&&(e.project=pe.parse(e.project).name);let t=nn.addComponentValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);wt.trace("adding component");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;try{let n=pe.join(r,s);return Fe.mkdirSync(n,{recursive:!0}),Fe.copySync(n9,n),`Successfully added project: ${s}`}catch(n){throw Ht(new Error,fo.ADD_FUNCTION,xt.INTERNAL_SERVER_ERROR,wt.ERR,n)}}a(l9,"addComponent");function _9(e){e.project&&(e.project=pe.parse(e.project).name);let t=nn.dropCustomFunctionProjectValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);wt.trace("dropping custom function project");let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=gt.get(We.CONFIG_PARAMS.APPS);if(!J6.isEmptyOrZeroLength(n)){let i=!1;for(let[o,c]of n.entries())if(c.name===s){n.splice(o,1),i=!0;break}if(i)return Fu.updateConfigValue(We.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=pe.join(r,s);return Fe.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw Ht(new Error,fo.DROP_FUNCTION_PROJECT,xt.INTERNAL_SERVER_ERROR,wt.ERR,i)}}a(_9,"dropCustomFunctionProject");async function d9(e){e.project&&(e.project=pe.parse(e.project).name);let t=nn.packageComponentValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;wt.trace("packaging component",s);let n;try{n=await Fe.realpath(pe.join(r,s))}catch(u){if(u.code!==We.NODE_ERROR_CODES.ENOENT)throw u;try{n=await Fe.realpath(pe.join(gt.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(_){if(_.code===We.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await Fe.ensureDir(dP);let i=pe.join(dP,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(pe.join(n,"node_modules"))}),fP.pack(n,o).pipe(Fe.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Fe.readFileSync(i,{encoding:"base64"});return await Fe.remove(i),{project:s,payload:c}}a(d9,"packageComponent");async function f9(e){e.project&&(e.project=pe.parse(e.project).name);let t=nn.deployComponentValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let r=gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:s,payload:n,package:i}=e;if(wt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(n){o=pe.join(r,s),i="file:"+o,await Fe.ensureDir(o);let f=r9.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe(fP.extract(o,{finish:h})).on("error",p)});let E=await Fe.readdir(o);E.length===1&&E[0]==="package"&&(await Fe.copy(pe.join(o,"package"),o),await Fe.remove(pe.join(o,"package")))}if(await Fu.addConfig(s,{package:i}),!n){await e9();let f=EP.get(t9.CONFIG_PARAMS.ROOTPATH);o=pe.join(f,"node_modules",s)}if(s9)return;let c=new Map;c.isWorker=!0;let u=(lf(),ee(uf)),_;u.setErrorReporter(f=>_=f);let l=Z6(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return wt.info("Installed component"),`Successfully deployed: ${s}`}a(f9,"deployComponent");async function E9(){let e=Fu.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 Fe.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=pe.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await Fe.stat(d),E={name:pe.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return wt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),s=await r(gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{name:gt.get(We.CONFIG_PARAMS.COMPONENTSROOT).split(pe.sep).slice(-1).pop(),entries:t});for(let o of s.entries)if(o.package){let c=await r(pe.join(gt.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(lf(),ee(uf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return s}a(E9,"getComponents");async function h9(e){let t=nn.getComponentFileValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let s=Fu.getConfigObj()[e.project]||e.project==="harperdb"?pe.join(EP.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules"):gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),n=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Fe.stat(pe.join(s,e.project,e.file));return{message:await Fe.readFile(pe.join(s,e.project,e.file),n),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===We.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${pe.join(e.project,e.file)}'`):i}}a(h9,"getComponentFile");async function m9(e){let t=nn.setComponentFileValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=pe.join(gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Fe.ensureFile(s),await Fe.outputFile(s,e.payload,r)):await Fe.ensureDir(s),"Successfully set component: "+e.file}a(m9,"setComponentFile");async function p9(e){let t=nn.dropComponentFileValidator(e);if(t)throw Ht(t,t.message,xt.BAD_REQUEST);let r=e.file?pe.join(e.project,e.file):e.project,s=pe.join(gt.get(We.CONFIG_PARAMS.COMPONENTSROOT),r);return await Fe.pathExists(s)&&await Fe.remove(s),Fu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(p9,"dropComponent");hP.exports={customFunctionsStatus:i9,getCustomFunctions:o9,getCustomFunction:a9,setCustomFunction:c9,dropCustomFunction:u9,addComponent:l9,dropCustomFunctionProject:_9,packageComponent:d9,deployComponent:f9,getComponents:E9,getComponentFile:h9,setComponentFile:m9,dropComponent:p9}});var WT=T((zEe,pP)=>{"use strict";var on=require("joi"),mP=Je();pP.exports={readTransactionLogValidator:S9,deleteTransactionLogsBeforeValidator:T9};function S9(e){let t=on.object({schema:on.string().required(),table:on.string().required(),from:on.date().timestamp(),to:on.date().timestamp(),limit:on.number().min(1)});return mP.validateBySchema(e,t)}a(S9,"readTransactionLogValidator");function T9(e){let t=on.object({schema:on.string().required(),table:on.string().required(),timestamp:on.date().timestamp().required()});return mP.validateBySchema(e,t)}a(T9,"deleteTransactionLogsBeforeValidator")});var df=T((XEe,AP)=>{"use strict";var QT=D(),_f=nt(),SP=z(),TP=j(),gP=gn(),{handleHDBError:ba,hdb_errors:g9}=Z(),{HTTP_STATUS_CODES:Na}=g9,{readTransactionLogValidator:R9,deleteTransactionLogsBeforeValidator:A9}=WT(),RP="This operation relies on clustering and cannot run with it disable.",O9="Logs successfully deleted from transaction log.",b9="All logs successfully deleted from transaction log.";AP.exports={readTransactionLog:N9,deleteTransactionLogsBefore:y9};async function*N9(e){let t=R9(e);if(t)throw ba(t,t.message,Na.BAD_REQUEST,void 0,void 0,!0);if(!TP.get(QT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ba(new Error,RP,Na.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=SP.checkSchemaTableExist(r,s);if(n)throw ba(new Error,n,Na.NOT_FOUND,void 0,void 0,!0);let i=gP.createNatsTableStreamName(r,s),o=await _f.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===QT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(N9,"readTransactionLog");async function y9(e){let t=A9(e);if(t)throw ba(t,t.message,Na.BAD_REQUEST,void 0,void 0,!0);if(!TP.get(QT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ba(new Error,RP,Na.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=SP.checkSchemaTableExist(r,s);if(i)throw ba(new Error,i,Na.NOT_FOUND,void 0,void 0,!0);let o=gP.createNatsTableStreamName(r,s),{jsm:c}=await _f.getNATSReferences(),u=await _f.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(n<=_)return`No transactions exist before: ${n}`;let l=O9,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=b9):d=(await _f.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(y9,"deleteTransactionLogsBefore")});var bP=T((ZEe,OP)=>{"use strict";var zT=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};OP.exports=zT});var yP=T((the,NP)=>{"use strict";var JT=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};NP.exports=JT});var jT=T((she,wP)=>{"use strict";var IP=bP(),I9=yP(),{HDB_ERROR_MSGS:w9}=Ir(),XT=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=w9.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new IP(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new I9(c,n[c]);i.push(u)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new IP(r,s,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};wP.exports=XT});var mf=T((ihe,$P)=>{"use strict";var ZT=Lr(),ff=es(),ls=uu(),Vu=jn(),eg=ti(),C9=dS(),D9=qD(),$u=rs(),Ef=RS(),Ct=G(),L9=bS(),U9=Cd(),M9=oT(),P9=Ld(),v9=aT(),B9=cT(),H9=_T(),x9=fT(),tg=mT(),Un=z(),q9=BU(),rg=RT(),LP=Qd(),us=D(),UP=BM(),F9=_a(),MP=hu(),PP=(ef(),ee(vu)),vP=Pr(),Vr=KT(),G9=require("alasql"),BP=df(),HP=of(),xP=jT(),{handleHDBError:Sr,hdb_errors:qP}=Z(),{HDB_ERROR_MSGS:Vt,HTTP_STATUS_CODES:Gu}=qP,F=new Map,FP="delete",gi="insert",Mn="read",Eo="update",ku="describe",CP=Vu.describeSchema.name,DP=Vu.describeTable.name,GP={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},k9="catchup",V9="handleGetJob",$9="handleGetJobsByStartDate",hf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},Y9=[ls.createTable.name,ls.createAttribute.name,ls.dropTable.name,ls.dropAttribute.name],kP={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},$=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};F.set(ZT.insert.name,new $(!1,[gi]));F.set(ZT.update.name,new $(!1,[Eo]));F.set(ZT.upsert.name,new $(!1,[gi,Eo]));F.set(ff.searchByConditions.name,new $(!1,[Mn]));F.set(ff.searchByHash.name,new $(!1,[Mn]));F.set(ff.searchByValue.name,new $(!1,[Mn]));F.set(ff.search.name,new $(!1,[Mn]));F.set(ls.createSchema.name,new $(!0,[]));F.set(ls.createTable.name,new $(!0,[]));F.set(ls.createAttribute.name,new $(!1,[gi]));F.set(ls.dropSchema.name,new $(!0,[]));F.set(ls.dropTable.name,new $(!0,[]));F.set(ls.dropAttribute.name,new $(!0,[]));F.set(Vu.describeSchema.name,new $(!1,[Mn]));F.set(Vu.describeTable.name,new $(!1,[Mn]));F.set(eg.deleteRecord.name,new $(!1,[FP]));F.set($u.addUser.name,new $(!0,[]));F.set($u.alterUser.name,new $(!0,[]));F.set($u.dropUser.name,new $(!0,[]));F.set($u.listUsersExternal.name,new $(!0,[]));F.set(Ef.listRoles.name,new $(!0,[]));F.set(Ef.addRole.name,new $(!0,[]));F.set(Ef.alterRole.name,new $(!0,[]));F.set(Ef.dropRole.name,new $(!0,[]));F.set(L9.name,new $(!0,[]));F.set(U9.name,new $(!0,[]));F.set(M9.name,new $(!0,[]));F.set(P9.name,new $(!0,[]));F.set(v9.name,new $(!0,[]));F.set(B9.name,new $(!0,[]));F.set(tg.setRoutes.name,new $(!0,[]));F.set(tg.getRoutes.name,new $(!0,[]));F.set(tg.deleteRoutes.name,new $(!0,[]));F.set(vP.setConfiguration.name,new $(!0,[]));F.set(H9.clusterStatus.name,new $(!0,[]));F.set(x9.name,new $(!0,[]));F.set(rg.getFingerprint.name,new $(!0,[]));F.set(rg.setLicense.name,new $(!0,[]));F.set(eg.deleteFilesBefore.name,new $(!0,[]));F.set(eg.deleteAuditLogsBefore.name,new $(!0,[]));F.set(LP.restart.name,new $(!0,[]));F.set(LP.restartService.name,new $(!0,[]));F.set(C9.name,new $(!0,[]));F.set(D9.name,new $(!0,[Mn]));F.set(F9.systemInformation.name,new $(!0,[]));F.set(vP.getConfiguration.name,new $(!0,[]));F.set(BP.readTransactionLog.name,new $(!0,[]));F.set(BP.deleteTransactionLogsBefore.name,new $(!0,[]));F.set(HP.installModules.name,new $(!0,[]));F.set(HP.auditModules.name,new $(!0,[]));F.set(MP.createTokens.name,new $(!1,[]));F.set(MP.refreshOperationToken.name,new $(!1,[]));F.set(PP.login.name,new $(!1,[]));F.set(PP.logout.name,new $(!1,[]));F.set(Vr.customFunctionsStatus.name,new $(!0,[]));F.set(Vr.getCustomFunctions.name,new $(!0,[]));F.set(Vr.getComponents.name,new $(!0,[]));F.set(Vr.getComponentFile.name,new $(!0,[]));F.set(Vr.setComponentFile.name,new $(!0,[]));F.set(Vr.dropComponent.name,new $(!0,[]));F.set(Vr.getCustomFunction.name,new $(!0,[]));F.set(Vr.setCustomFunction.name,new $(!0,[]));F.set(Vr.dropCustomFunction.name,new $(!0,[]));F.set(Vr.addComponent.name,new $(!0,[]));F.set(Vr.dropCustomFunctionProject.name,new $(!0,[]));F.set(Vr.packageComponent.name,new $(!0,[]));F.set(Vr.deployComponent.name,new $(!0,[]));F.set(rg.getRegistrationInfo.name,new $(!1,[]));F.set($u.userInfo.name,new $(!1,[]));F.set(Vu.describeAll.name,new $(!1,[]));F.set(V9,new $(!1,[]));F.set($9,new $(!0,[]));F.set(k9,new $(!0,[]));F.set(hf.CSV_DATA_LOAD,new $(!1,[gi,Eo]));F.set(hf.CSV_URL_LOAD,new $(!1,[gi,Eo]));F.set(hf.CSV_FILE_LOAD,new $(!1,[gi,Eo]));F.set(hf.IMPORT_FROM_S3,new $(!1,[gi,Eo]));F.set(kP.EXPORT_TO_S3,new $(!0,[]));F.set(kP.EXPORT_LOCAL,new $(!0,[]));F.set(us.VALID_SQL_OPS_ENUM.DELETE,new $(!1,[FP]));F.set(us.VALID_SQL_OPS_ENUM.SELECT,new $(!1,[Mn]));F.set(us.VALID_SQL_OPS_ENUM.INSERT,new $(!1,[gi]));F.set(us.VALID_SQL_OPS_ENUM.UPDATE,new $(!1,[Eo]));$P.exports={verifyPerms:W9,verifyPermsAst:K9,verifyBulkLoadAttributePerms:z9};function K9(e,t,r){if(Un.isEmptyOrZeroLength(e))throw Ct.info("verify_perms_ast has an empty user parameter"),Sr(new Error);if(Un.isEmptyOrZeroLength(t))throw Ct.info("verify_perms_ast has an empty user parameter"),Sr(new Error);if(Un.isEmptyOrZeroLength(r))throw Ct.info("verify_perms_ast has a null operation parameter"),Sr(new Error);try{let s=new xP,n=new q9(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw Ct.info("No schemas defined in verifyPermsAst(), will not continue."),Sr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&GP[r])throw Sr(new Error,Vt.DROP_SYSTEM,Gu.FORBIDDEN);if(c&&!u)return null;let _=UP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof G9.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=n.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=VP(t,r,o,s);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=n.getAttributesBySchemaTableName(f,d[E]),p=ng(t.role.permission,f,d[E]);sg(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw Sr(s)}}a(K9,"verifyPermsAst");function W9(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Ct.info("null required parameter in verifyPerms"),Sr(new Error,Vt.DEFAULT_INVALID_REQUEST,Gu.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema??e.database,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new xP;if(Un.isEmptyOrZeroLength(e.hdb_user.role)||Un.isEmptyOrZeroLength(e.hdb_user.role.permission))return Ct.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(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(us.SYSTEM_SCHEMA_NAME)||n===us.SYSTEM_SCHEMA_NAME;if(l&&GP[r])throw Sr(new Error,Vt.DROP_SYSTEM,Gu.FORBIDDEN);if(u&&!l||_===!0&&(r===ls.createSchema.name||r===ls.dropSchema.name))return null;if(Y9.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=UP.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===CP||r===DP){if(n===us.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Vt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===CP&&(!d[n]||!d[n][ku]))return c.handleInvalidItem(Vt.SCHEMA_NOT_FOUND(n));if(r===DP&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][ku]))return c.handleInvalidItem(Vt.TABLE_NOT_FOUND(n,i))}}let f=VP(e.hdb_user,r,o,c,s);if(f)return f;if(F.get(r)&&F.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&us.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[n].tables[i];S[us.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(I=>I[us.PERMS_CRUD_ENUM.READ]).forEach(I=>{p.push(I.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(R=>R.attribute),e.get_attributes=p)}let E=Q9(e),h=ng(e.hdb_user.role.permission,n,i);return sg(E,h,r,i,n,c,s),c.getPermsResponse()}a(W9,"verifyPerms");function VP(e,t,r,s,n){if(Un.arrayHasEmptyValues([e,t,r]))throw Ct.info("hasPermissions has an invalid parameter"),Sr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||F.get(t).requires_su))return null;if(!F.get(t))throw Ct.info(`operation ${t} not found.`),Sr(new Error,Vt.OP_NOT_FOUND(t),Gu.BAD_REQUEST);if(F.get(t)&&F.get(t).requires_su)return Ct.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Vt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][ku]===!1){s.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[ku]===!1)s.addInvalidItem(Vt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=F.get(t).perms;!Un.isEmpty(n)&&E.includes(n)&&(E=[n]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(Ct.info(`Required ${p} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&s.addUnauthorizedTable(u,l,f)}catch(f){let E=Vt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Ct.error(E),Ct.error(f),Sr(qP.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(VP,"hasPermissions");function sg(e,t,r,s,n,i,o){if(!e||!t)throw Ct.info("no attributes specified in checkAttributePerms."),Sr(new Error);let c=F.get(r).perms;if(!c||c==="")throw Ct.info(`no permissions found for ${r} in checkAttributePerms().`),Sr(new Error);if(Un.isEmptyOrZeroLength(t))return Ct.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[ku]===!1){i.addInvalidItem(Vt.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let f of c){if(us.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Mn)throw Sr(new Error,Vt.SYSTEM_TIMESTAMP_PERMS_ERR,Gu.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(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(sg,"checkAttributePerms");function Q9(e){let t=new Set;try{if(e.action)return t;if(e.operation===us.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){Ct.info(r)}return t}a(Q9,"getRecordAttributes");function ng(e,t,r){let s=new Map;if(Un.isEmpty(e))return Ct.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{Ct.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(ng,"getAttributePermissions");function z9(e,t,r,s,n,i,o){let c=new Set(i),u=ng(e,s,n);sg(c,u,t,n,s,o,r)}a(z9,"verifyBulkLoadAttributePerms")});var Sf=T((ahe,zP)=>{"use strict";zP.exports={evaluateSQL:c7,processAST:QP,convertSQLToAST:WP,checkASTPermissions:KP};var J9=Lr(),YP=require("util"),X9=YP.callbackify(J9.insert),j9=es().search,Z9=LC().update,e7=YP.callbackify(Z9),t7=MC().convertDelete,Ri=require("alasql"),r7=mf(),pf=G(),s7=ed(),n7=z(),Yu=D(),{hdb_errors:i7,handleHDBError:ig}=Z(),{HTTP_STATUS_CODES:og}=i7;s7(Ri);var o7=403,a7="There was a problem performing this insert. Please check the logs and try again.",ag=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function c7(e,t){let r=e.parsed_sql_object;if(!r){r=WP(e.sql);let s,n=r.ast.statements[0];if(n instanceof Ri.yy.Insert?s=n.into.databaseid:n instanceof Ri.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Ri.yy.Update||n instanceof Ri.yy.Delete?s=n.table.databaseid:pf.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Ri.yy.Select)&&n7.isEmptyOrZeroLength(s))return t("No schema specified",null)}QP(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(c7,"evaluateSQL");function KP(e,t){let r;try{r=r7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(KP,"checkASTPermissions");function WP(e){let t=new ag;if(!e)throw ig(new Error,"The 'sql' parameter is missing from the request body",og.BAD_REQUEST);try{let r=e.trim(),s=Ri.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
17
|
-
`);throw s[1]?ig(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,og.BAD_REQUEST):ig(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",og.BAD_REQUEST)}return t}a(WP,"convertSQLToAST");function QP(e,t,r){try{let s=u7;if(!e.bypass_auth&&!t.permissions_checked){let i=KP(e,t);if(i&&i.length>0)return r(o7,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Yu.VALID_SQL_OPS_ENUM.SELECT:s=j9,n=t.ast.statements[0];break;case Yu.VALID_SQL_OPS_ENUM.INSERT:s=l7;break;case Yu.VALID_SQL_OPS_ENUM.UPDATE:s=e7;break;case Yu.VALID_SQL_OPS_ENUM.DELETE:s=t7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(QP,"processAST");function u7(e,t){pf.info(e),t("unknown sql statement")}a(u7,"nullFunction");function l7({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=_7(i,e.values)}catch(o){return r(o)}X9(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){pf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(l7,"convertInsert");function _7(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=Ri.compile(`SELECT ${n.toString()} AS [${Yu.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw pf.error(r),new Error(a7)}}a(_7,"createDataObjects")});var cg=T((uhe,XP)=>{"use strict";var{S3:d7,GetObjectCommand:f7}=require("@aws-sdk/client-s3");XP.exports={getFileStreamFromS3:E7,getS3AuthObj:JP};async function E7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await JP(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new f7(r))).Body}a(E7,"getFileStreamFromS3");function JP(e,t,r){return new d7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(JP,"getS3AuthObj")});var Tf=T((_he,ov)=>{"use strict";var lg=es(),h7=Sf(),m7=cg(),{AsyncParser:p7,Transform:S7}=require("json2csv"),Wu=require("stream"),$r=z(),ug=require("fs-extra"),T7=require("path"),_s=G(),{promisify:ev}=require("util"),Ku=z(),{handleHDBError:Rt,hdb_errors:g7}=Z(),{HDB_ERROR_MSGS:Tr,HTTP_STATUS_CODES:At}=g7,{streamAsJSON:R7}=(Dh(),ee(zO)),{Upload:A7}=require("@aws-sdk/lib-storage"),jP=["search_by_value","search_by_hash","sql","search_by_conditions"],ZP=["json","csv"],tv="json",rv="csv",O7="Successfully exported JSON locally.",b7="Successfully exported CSV locally.",N7=1e3,y7=lg.searchByHash,I7=lg.searchByValue,w7=ev(h7.evaluateSQL),C7=ev(Wu.finished);ov.exports={export_to_s3:M7,export_local:D7,toCsvStream:sv};async function D7(e){_s.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=nv(e);if(!$r.isEmpty(t))throw _s.error(t),Rt(new Error,t,At.BAD_REQUEST,void 0,void 0,!0);if($r.isEmpty(e.path))throw _s.error(Tr.MISSING_VALUE("path")),Rt(new Error,Tr.MISSING_VALUE("path"),At.BAD_REQUEST,void 0,void 0,!0);let r=($r.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(T7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=$r.buildFolderPath(e.path,r);await L7(e.path);let n=await iv(e);return await U7(s,e.format,n)}a(D7,"export_local");async function L7(e){if(_s.trace("in confirmPath"),$r.isEmptyOrZeroLength(e))throw Rt(new Error,`Invalid path: ${e}`,At.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await ug.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,_s.error(s),Rt(new Error,s,At.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw _s.error(r),Rt(new Error,r,At.BAD_REQUEST,void 0,void 0,!0)}return!0}a(L7,"confirmPath");async function U7(e,t,r){if(_s.trace("in saveToLocal"),Ku.isEmptyOrZeroLength(e))throw Rt(new Error,Tr.INVALID_VALUE("file_path"),At.BAD_REQUEST,void 0,void 0,!0);if(Ku.isEmptyOrZeroLength(t))throw Rt(new Error,Tr.INVALID_VALUE("Source format"),At.BAD_REQUEST,void 0,void 0,!0);if(Ku.isEmpty(r))throw Rt(new Error,Tr.NOT_FOUND("Data"),At.BAD_REQUEST,void 0,void 0,!0);if(t===tv){let s=ug.createWriteStream(e);return R7(r).pipe(s),await C7(s),{message:O7,path:e}}else if(t===rv){let s=ug.createWriteStream(e),n=Wu.Readable.from(r),i={},o={objectMode:!0};return await new p7(i,o).fromInput(n).toOutput(s).promise(!1),{message:b7,path:e}}throw Rt(new Error,Tr.INVALID_VALUE("format"),At.BAD_REQUEST)}a(U7,"saveToLocal");async function M7(e){if(!e.s3||Object.keys(e.s3).length===0)throw Rt(new Error,Tr.MISSING_VALUE("S3 object"),At.BAD_REQUEST);if($r.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Rt(new Error,Tr.MISSING_VALUE("aws_access_key_id"),At.BAD_REQUEST);if($r.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Rt(new Error,Tr.MISSING_VALUE("aws_secret_access_key"),At.BAD_REQUEST);if($r.isEmptyOrZeroLength(e.s3.bucket))throw Rt(new Error,Tr.MISSING_VALUE("bucket"),At.BAD_REQUEST);if($r.isEmptyOrZeroLength(e.s3.key))throw Rt(new Error,Tr.MISSING_VALUE("key"),At.BAD_REQUEST);if($r.isEmptyOrZeroLength(e.s3.region))throw Rt(new Error,Tr.MISSING_VALUE("region"),At.BAD_REQUEST);let t=nv(e);if(!$r.isEmpty(t))throw Rt(new Error,t,At.BAD_REQUEST);_s.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await iv(e)}catch(u){throw _s.error(u),u}let s,n=await m7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Wu.PassThrough;if(e.format===rv){i=e.s3.key+".csv";let u=sv(r);u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===tv){i=e.s3.key+".json";let u=new Wu.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%N7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Rt(new Error,Tr.INVALID_VALUE("format"),At.BAD_REQUEST);return new A7({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(M7,"export_to_s3");function sv(e){let t=Wu.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),r={},s={objectMode:!0},n=new S7(r,s);return t.pipe(n)}a(sv,"toCsvStream");function nv(e){if(_s.trace("in exportCoreValidation"),$r.isEmpty(e.format))return"format missing";if(ZP.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${ZP.join(", ")}`;let t=e.search_operation.operation;if($r.isEmpty(t))return"search_operation.operation missing";if(jP.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${jP.join(", ")}`}a(nv,"exportCoreValidation");async function iv(e){_s.trace("in getRecords");let t,r;if(Ku.isEmpty(e.search_operation)||Ku.isEmptyOrZeroLength(e.search_operation.operation))throw Rt(new Error,Tr.INVALID_VALUE("Search operation"),At.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=I7;break;case"search_by_hash":t=y7;break;case"search_by_conditions":t=lg.searchByConditions;break;case"sql":t=w7;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,_s.error(r),Rt(new Error,r,At.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(iv,"getRecords")});var fv={};$e(fv,{contentTypes:()=>hg,findBestSerializer:()=>Rf,getDeserializer:()=>mo,registerContentHandlers:()=>mg,serialize:()=>Af,serializeMessage:()=>Ti});function P7(e){try{return e?.[0]===123?Eg(e):e}catch{return e}}function mg(e){e.register(B7,{serializers:[{regex:/^application\/json$/,serializer:Ec},{regex:/^application\/cbor$/,serializer:function(t){return new ho.EncoderStream(zu).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?gf.Readable.from((0,an.encodeIter)(t,zu)):(0,an.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,_g.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,an.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,ho.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function Rf(e){let r=(e.headers.asObject||e.headers).accept,s,n=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=$t.get(_);if(E){let h=(E.q||1)*d;h>n&&(s=E,i=E.type||_,n=h,o=f)}}if(!s){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from($t.keys()).join(", "))}};s=$t.get("application/json"),i="application/json"}return{serializer:s,type:i,parameters:o}}function Af(e,t,r){let s=cv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),n=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=Rf(t);if(i.serializer.compressible===!1&&(s=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e);return s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Pn.createBrotliCompress)({params:{[Pn.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Pn.constants.BROTLI_MODE_TEXT:Pn.constants.BROTLI_MODE_GENERIC,[Pn.constants.BROTLI_PARAM_QUALITY]:2}}))),o}n=i.serializer.serialize(e)}return s&&n?.length>cv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Pn.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ti(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return Qu(e);let r=t.serialize;if(r)return r(e);let s=Rf(t);return r=t.serialize=s.serializer.serialize,r(e)}function H7(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function mo(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=$t.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=$t.get(e)?.deserialize||uv(e,s);return o=>H7(o).then(i)}return e&&$t.get(e)?.deserialize||uv(e,s)}function uv(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return s=>({contentType:e,data:s.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Eg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function x7(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let s=r.next();return s.then?s.then(n=>({value:t(n.value),done:n.done})):{value:t(s.value),done:s.done}},return(s){return r.return(s)},throw(s){return r.throw(s)}}}}}var _g,an,ho,Pn,gf,lv,dg,fg,_v,Qu,Eg,zu,$t,hg,av,dv,v7,B7,cv,Ta=Ae(()=>{Dh();_g=v(Tf()),an=require("msgpackr"),ho=require("cbor-x"),Pn=require("zlib"),gf=require("stream");sr();lv=require("../index"),dg=v(j()),fg=v(D()),_v=dg.default.get(fg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Qu=_v?Ui:JSON.stringify,Eg=_v?Ch:JSON.parse,zu={useRecords:!1,useToJSON:!0},$t=new Map,hg=$t;_t.contentTypes=hg;(0,lv._assignPackageExport)("contentTypes",hg);$t.set("application/json",{serializeStream:Ec,serialize:Qu,deserialize:Eg,q:.8});av=new ho.Encoder(zu);$t.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new ho.EncoderStream(zu).end(e)},serialize:av.encode,deserialize:av.decode,q:1});$t.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?gf.Readable.from((0,an.encodeIter)(e,zu)):(0,an.pack)(e)},serialize:an.pack,deserialize:an.unpack,q:.9});$t.set("text/csv",{serializeStream(e){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,_g.toCsvStream)(e)},q:.1});$t.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});$t.set("text/event-stream",{serializeStream:function(e){return gf.Readable.from(x7(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
|
-
`),e.data){let r=e.data;typeof r=="object"&&(r=
|
|
15
|
+
`,""):null}catch(f){f.stderr?i[u].npm_error=_P(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 Aa.info(`finished installModules with response ${i}`),i}a(u9,"installModules");function _P(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
|
|
16
|
+
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(_P,"parseNPMStdErr");async function l9(e){Aa.info(`starting auditModules for request: ${e}`);let t=fP(e);if(t)throw ga(t,t.message,Ra.BAD_REQUEST);let{projects:r}=e;await of(),await dP(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=nf.join(KT,o);s[o]={npm_output:null,npm_error:null};try{let u=await xu("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=_P(u.stderr)}}return Aa.info(`finished auditModules with response ${s}`),s}a(l9,"auditModules");async function of(){try{return await xu("npm -v"),!0}catch{throw ga(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ra.BAD_REQUEST,void 0,void 0,!0)}}a(of,"checkNPMInstalled");async function dP(e){if(!Array.isArray(e)||e.length===0)throw ga(new Error,"projects argument must be an array with at least 1 element",Ra.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=nf.join(KT,i.toString());if(!await cP.pathExists(o)){t.push(i);continue}let u=nf.join(o,"package.json");await cP.pathExists(u)||r.push(i)}if(t.length>0)throw ga(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ra.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw ga(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ra.BAD_REQUEST,void 0,void 0,!0)}a(dP,"checkProjectPaths");function fP(e){let t=sf.object({projects:sf.array().min(1).items(sf.string()).required(),dry_run:sf.boolean().default(!1)});return n9.validateBySchema(e,t)}a(fP,"modulesValidator")});var QT=T((Ehe,TP)=>{"use strict";var Oa=require("fs-extra"),WT=require("path"),cf=V(),hP=J(),uf=L(),SP=X(),_9=vr();TP.exports=d9;async function d9(){let e=f9(),t=SP.get(uf.CONFIG_PARAMS.ROOTPATH),r=WT.join(t,"package.json"),s={dependencies:{harperdb:"file:"+uf.PACKAGE_ROOT}},n=WT.join(t,"node_modules");await Oa.ensureDir(n);let i,o=!0,c=!1;try{i=await Oa.readJson(r)}catch(u){if(hP.isEmptyOrZeroLength(e))return;if(u.code!==uf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!hP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await mP(_);s.dependencies[u]=l+_}if(!o){cf.notify("Installing components"),await pP(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await mP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(cf.notify("Removing component",u),c=!0);c&&(cf.notify("Updating components."),await pP(r,s,i))}a(d9,"installComponents");function f9(){let e=_9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(f9,"getComponentsConfig");async function mP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":WT.extname(e)||await Oa.pathExists(e)?"file:":"github:"}a(mP,"getPkgPrefix");async function pP(e,t,r){cf.trace("npm installing components package.json",t),await Oa.writeFile(e,JSON.stringify(t,null," "));try{await af().installAllRootModules(SP.get(uf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(s){throw r?await Oa.writeFile(e,JSON.stringify(r,null," ")):await Oa.unlink(e),s}}a(pP,"installPackages")});var jT=T((phe,OP)=>{"use strict";var ke=require("fs-extra"),zT=require("fast-glob"),Te=require("path"),RP=require("tar-fs"),mhe=require("uuid").v4,JT=require("normalize-path"),sn=aP(),yt=V(),Je=L(),Tt=X(),qu=vr(),E9=J(),{PACKAGE_ROOT:h9}=L(),{handleHDBError:Bt,hdb_errors:m9}=Z(),{basename:p9}=require("path"),S9=QT(),AP=X(),T9=L(),{Readable:g9}=require("stream"),{isMainThread:R9}=require("worker_threads"),{HDB_ERROR_MSGS:_o,HTTP_STATUS_CODES:Ht}=m9,A9=Te.join(h9,"application-template"),gP=Te.join(Tt.get(Je.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function O9(){yt.trace("getting custom api status");let e={};try{e={port:Tt.get(Je.CONFIG_PARAMS.HTTP_PORT),directory:Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Bt(new Error,_o.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,yt.ERR,t)}return e}a(O9,"customFunctionsStatus");function b9(){yt.trace("getting custom api endpoints");let e={},t=Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT);try{zT.sync(JT(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:zT.sync(JT(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:zT.sync(JT(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Bt(new Error,_o.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,yt.ERR,r)}return e}a(b9,"getCustomFunctions");function N9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=sn.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);yt.trace("getting custom api endpoint file content");let r=Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e,o=Te.join(r,s,n,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw Bt(new Error,_o.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,yt.ERR,c)}}a(N9,"getCustomFunction");function y9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=sn.setCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);yt.trace("setting custom function file content");let r=Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i,function_content:o}=e;try{return ke.outputFileSync(Te.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Bt(new Error,_o.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,yt.ERR,c)}}a(y9,"setCustomFunction");function w9(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=sn.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);yt.trace("dropping custom function file");let r=Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e;try{return ke.unlinkSync(Te.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Bt(new Error,_o.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,yt.ERR,o)}}a(w9,"dropCustomFunction");function I9(e){e.project&&(e.project=Te.parse(e.project).name);let t=sn.addComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);yt.trace("adding component");let r=Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;try{let n=Te.join(r,s);return ke.mkdirSync(n,{recursive:!0}),ke.copySync(A9,n),`Successfully added project: ${s}`}catch(n){throw Bt(new Error,_o.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,yt.ERR,n)}}a(I9,"addComponent");function C9(e){e.project&&(e.project=Te.parse(e.project).name);let t=sn.dropCustomFunctionProjectValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);yt.trace("dropping custom function project");let r=Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=Tt.get(Je.CONFIG_PARAMS.APPS);if(!E9.isEmptyOrZeroLength(n)){let i=!1;for(let[o,c]of n.entries())if(c.name===s){n.splice(o,1),i=!0;break}if(i)return qu.updateConfigValue(Je.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=Te.join(r,s);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw Bt(new Error,_o.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,yt.ERR,i)}}a(C9,"dropCustomFunctionProject");async function D9(e){e.project&&(e.project=Te.parse(e.project).name);let t=sn.packageComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;yt.trace("packaging component",s);let n;try{n=await ke.realpath(Te.join(r,s))}catch(u){if(u.code!==Je.NODE_ERROR_CODES.ENOENT)throw u;try{n=await ke.realpath(Te.join(Tt.get(Je.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(_){if(_.code===Je.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await ke.ensureDir(gP);let i=Te.join(gP,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(n,"node_modules"))}),RP.pack(n,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:s,payload:c}}a(D9,"packageComponent");async function L9(e){e.project&&(e.project=Te.parse(e.project).name);let t=sn.deployComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{project:s,payload:n,package:i}=e;if(yt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(n){o=Te.join(r,s),i="file:"+o,await ke.ensureDir(o);let f=g9.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe(RP.extract(o,{finish:h})).on("error",p)});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 qu.addConfig(s,{package:i}),!n){await S9();let f=AP.get(T9.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",s)}if(R9)return;let c=new Map;c.isWorker=!0;let u=(_f(),ee(lf)),_;u.setErrorReporter(f=>_=f);let l=p9(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return yt.info("Installed component"),`Successfully deployed: ${s}`}a(L9,"deployComponent");async function M9(){let e=qu.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 yt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),s=await r(Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),{name:Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of s.entries)if(o.package){let c=await r(Te.join(Tt.get(Je.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(_f(),ee(lf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return s}a(M9,"getComponents");async function U9(e){let t=sn.getComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let s=qu.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(AP.get(Je.CONFIG_PARAMS.ROOTPATH),"node_modules"):Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),n=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(Te.join(s,e.project,e.file));return{message:await ke.readFile(Te.join(s,e.project,e.file),n),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Je.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(U9,"getComponentFile");async function P9(e){let t=sn.setComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=Te.join(Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(s),await ke.outputFile(s,e.payload,r)):await ke.ensureDir(s),"Successfully set component: "+e.file}a(P9,"setComponentFile");async function v9(e){let t=sn.dropComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,s=Te.join(Tt.get(Je.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(s)&&await ke.remove(s),qu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(v9,"dropComponent");OP.exports={customFunctionsStatus:O9,getCustomFunctions:b9,getCustomFunction:N9,setCustomFunction:y9,dropCustomFunction:w9,addComponent:I9,dropCustomFunctionProject:C9,packageComponent:D9,deployComponent:L9,getComponents:M9,getComponentFile:U9,setComponentFile:P9,dropComponent:v9}});var XT=T((The,NP)=>{"use strict";var nn=require("joi"),bP=Ze();NP.exports={readTransactionLogValidator:B9,deleteTransactionLogsBeforeValidator:H9};function B9(e){let t=nn.object({schema:nn.string().required(),table:nn.string().required(),from:nn.date().timestamp(),to:nn.date().timestamp(),limit:nn.number().min(1)});return bP.validateBySchema(e,t)}a(B9,"readTransactionLogValidator");function H9(e){let t=nn.object({schema:nn.string().required(),table:nn.string().required(),timestamp:nn.date().timestamp().required()});return bP.validateBySchema(e,t)}a(H9,"deleteTransactionLogsBeforeValidator")});var ff=T((Rhe,DP)=>{"use strict";var ZT=L(),df=it(),yP=J(),wP=X(),IP=Tn(),{handleHDBError:ba,hdb_errors:x9}=Z(),{HTTP_STATUS_CODES:Na}=x9,{readTransactionLogValidator:q9,deleteTransactionLogsBeforeValidator:F9}=XT(),CP="This operation relies on clustering and cannot run with it disable.",G9="Logs successfully deleted from transaction log.",k9="All logs successfully deleted from transaction log.";DP.exports={readTransactionLog:V9,deleteTransactionLogsBefore:$9};async function*V9(e){let t=q9(e);if(t)throw ba(t,t.message,Na.BAD_REQUEST,void 0,void 0,!0);if(!wP.get(ZT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ba(new Error,CP,Na.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=yP.checkSchemaTableExist(r,s);if(n)throw ba(new Error,n,Na.NOT_FOUND,void 0,void 0,!0);let i=IP.createNatsTableStreamName(r,s),o=await df.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===ZT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(V9,"readTransactionLog");async function $9(e){let t=F9(e);if(t)throw ba(t,t.message,Na.BAD_REQUEST,void 0,void 0,!0);if(!wP.get(ZT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ba(new Error,CP,Na.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=yP.checkSchemaTableExist(r,s);if(i)throw ba(new Error,i,Na.NOT_FOUND,void 0,void 0,!0);let o=IP.createNatsTableStreamName(r,s),{jsm:c}=await df.getNATSReferences(),u=await df.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(n<=_)return`No transactions exist before: ${n}`;let l=G9,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=k9):d=(await df.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a($9,"deleteTransactionLogsBefore")});var MP=T((Ohe,LP)=>{"use strict";var eg=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};LP.exports=eg});var PP=T((Nhe,UP)=>{"use strict";var tg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};UP.exports=tg});var sg=T((whe,BP)=>{"use strict";var vP=MP(),Y9=PP(),{HDB_ERROR_MSGS:K9}=Ir(),rg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=K9.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new vP(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new Y9(c,n[c]);i.push(u)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new vP(r,s,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};BP.exports=rg});var pf=T((Che,XP)=>{"use strict";var ng=Mr(),Ef=rs(),ds=cu(),ku=Xn(),ig=ti(),W9=SS(),Q9=WD(),Vu=ns(),hf=wS(),wt=V(),z9=DS(),J9=Dd(),j9=_T(),X9=Md(),Z9=dT(),e7=fT(),t7=mT(),r7=ST(),og=RT(),Ln=J(),s7=$M(),ag=yT(),qP=zd(),_s=L(),FP=$U(),n7=_a(),GP=Eu(),kP=(tf(),ee(Pu)),VP=vr(),$r=jT(),i7=require("alasql"),$P=ff(),YP=af(),KP=sg(),{handleHDBError:pr,hdb_errors:WP}=Z(),{HDB_ERROR_MSGS:Vt,HTTP_STATUS_CODES:Fu}=WP,F=new Map,QP="delete",gi="insert",Mn="read",fo="update",Gu="describe",HP=ku.describeSchema.name,xP=ku.describeTable.name,zP={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},o7="catchup",a7="handleGetJob",c7="handleGetJobsByStartDate",mf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},u7=[ds.createTable.name,ds.createAttribute.name,ds.dropTable.name,ds.dropAttribute.name],JP={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}};F.set(ng.insert.name,new K(!1,[gi]));F.set(ng.update.name,new K(!1,[fo]));F.set(ng.upsert.name,new K(!1,[gi,fo]));F.set(Ef.searchByConditions.name,new K(!1,[Mn]));F.set(Ef.searchByHash.name,new K(!1,[Mn]));F.set(Ef.searchByValue.name,new K(!1,[Mn]));F.set(Ef.search.name,new K(!1,[Mn]));F.set(ds.createSchema.name,new K(!0,[]));F.set(ds.createTable.name,new K(!0,[]));F.set(ds.createAttribute.name,new K(!1,[gi]));F.set(ds.dropSchema.name,new K(!0,[]));F.set(ds.dropTable.name,new K(!0,[]));F.set(ds.dropAttribute.name,new K(!0,[]));F.set(ku.describeSchema.name,new K(!1,[Mn]));F.set(ku.describeTable.name,new K(!1,[Mn]));F.set(ig.deleteRecord.name,new K(!1,[QP]));F.set(Vu.addUser.name,new K(!0,[]));F.set(Vu.alterUser.name,new K(!0,[]));F.set(Vu.dropUser.name,new K(!0,[]));F.set(Vu.listUsersExternal.name,new K(!0,[]));F.set(hf.listRoles.name,new K(!0,[]));F.set(hf.addRole.name,new K(!0,[]));F.set(hf.alterRole.name,new K(!0,[]));F.set(hf.dropRole.name,new K(!0,[]));F.set(z9.name,new K(!0,[]));F.set(J9.name,new K(!0,[]));F.set(j9.name,new K(!0,[]));F.set(X9.name,new K(!0,[]));F.set(Z9.name,new K(!0,[]));F.set(e7.name,new K(!0,[]));F.set(og.setRoutes.name,new K(!0,[]));F.set(og.getRoutes.name,new K(!0,[]));F.set(og.deleteRoutes.name,new K(!0,[]));F.set(VP.setConfiguration.name,new K(!0,[]));F.set(t7.clusterStatus.name,new K(!0,[]));F.set(r7.name,new K(!0,[]));F.set(ag.getFingerprint.name,new K(!0,[]));F.set(ag.setLicense.name,new K(!0,[]));F.set(ig.deleteFilesBefore.name,new K(!0,[]));F.set(ig.deleteAuditLogsBefore.name,new K(!0,[]));F.set(qP.restart.name,new K(!0,[]));F.set(qP.restartService.name,new K(!0,[]));F.set(W9.name,new K(!0,[]));F.set(Q9.name,new K(!0,[Mn]));F.set(n7.systemInformation.name,new K(!0,[]));F.set(VP.getConfiguration.name,new K(!0,[]));F.set($P.readTransactionLog.name,new K(!0,[]));F.set($P.deleteTransactionLogsBefore.name,new K(!0,[]));F.set(YP.installModules.name,new K(!0,[]));F.set(YP.auditModules.name,new K(!0,[]));F.set(GP.createTokens.name,new K(!1,[]));F.set(GP.refreshOperationToken.name,new K(!1,[]));F.set(kP.login.name,new K(!1,[]));F.set(kP.logout.name,new K(!1,[]));F.set($r.customFunctionsStatus.name,new K(!0,[]));F.set($r.getCustomFunctions.name,new K(!0,[]));F.set($r.getComponents.name,new K(!0,[]));F.set($r.getComponentFile.name,new K(!0,[]));F.set($r.setComponentFile.name,new K(!0,[]));F.set($r.dropComponent.name,new K(!0,[]));F.set($r.getCustomFunction.name,new K(!0,[]));F.set($r.setCustomFunction.name,new K(!0,[]));F.set($r.dropCustomFunction.name,new K(!0,[]));F.set($r.addComponent.name,new K(!0,[]));F.set($r.dropCustomFunctionProject.name,new K(!0,[]));F.set($r.packageComponent.name,new K(!0,[]));F.set($r.deployComponent.name,new K(!0,[]));F.set(ag.getRegistrationInfo.name,new K(!1,[]));F.set(Vu.userInfo.name,new K(!1,[]));F.set(ku.describeAll.name,new K(!1,[]));F.set(a7,new K(!1,[]));F.set(c7,new K(!0,[]));F.set(o7,new K(!0,[]));F.set(mf.CSV_DATA_LOAD,new K(!1,[gi,fo]));F.set(mf.CSV_URL_LOAD,new K(!1,[gi,fo]));F.set(mf.CSV_FILE_LOAD,new K(!1,[gi,fo]));F.set(mf.IMPORT_FROM_S3,new K(!1,[gi,fo]));F.set(JP.EXPORT_TO_S3,new K(!0,[]));F.set(JP.EXPORT_LOCAL,new K(!0,[]));F.set(_s.VALID_SQL_OPS_ENUM.DELETE,new K(!1,[QP]));F.set(_s.VALID_SQL_OPS_ENUM.SELECT,new K(!1,[Mn]));F.set(_s.VALID_SQL_OPS_ENUM.INSERT,new K(!1,[gi]));F.set(_s.VALID_SQL_OPS_ENUM.UPDATE,new K(!1,[fo]));XP.exports={verifyPerms:_7,verifyPermsAst:l7,verifyBulkLoadAttributePerms:f7};function l7(e,t,r){if(Ln.isEmptyOrZeroLength(e))throw wt.info("verify_perms_ast has an empty user parameter"),pr(new Error);if(Ln.isEmptyOrZeroLength(t))throw wt.info("verify_perms_ast has an empty user parameter"),pr(new Error);if(Ln.isEmptyOrZeroLength(r))throw wt.info("verify_perms_ast has a null operation parameter"),pr(new Error);try{let s=new KP,n=new s7(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw wt.info("No schemas defined in verifyPermsAst(), will not continue."),pr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&zP[r])throw pr(new Error,Vt.DROP_SYSTEM,Fu.FORBIDDEN);if(c&&!u)return null;let _=FP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof i7.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=n.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=jP(t,r,o,s);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=n.getAttributesBySchemaTableName(f,d[E]),p=ug(t.role.permission,f,d[E]);cg(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw pr(s)}}a(l7,"verifyPermsAst");function _7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw wt.info("null required parameter in verifyPerms"),pr(new Error,Vt.DEFAULT_INVALID_REQUEST,Fu.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema??e.database,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new KP;if(Ln.isEmptyOrZeroLength(e.hdb_user.role)||Ln.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(_s.SYSTEM_SCHEMA_NAME)||n===_s.SYSTEM_SCHEMA_NAME;if(l&&zP[r])throw pr(new Error,Vt.DROP_SYSTEM,Fu.FORBIDDEN);if(u&&!l||_===!0&&(r===ds.createSchema.name||r===ds.dropSchema.name))return null;if(u7.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=FP.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===HP||r===xP){if(n===_s.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Vt.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===HP&&(!d[n]||!d[n][Gu]))return c.handleInvalidItem(Vt.SCHEMA_NOT_FOUND(n));if(r===xP&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][Gu]))return c.handleInvalidItem(Vt.TABLE_NOT_FOUND(n,i))}}let f=jP(e.hdb_user,r,o,c,s);if(f)return f;if(F.get(r)&&F.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&_s.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[n].tables[i];S[_s.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(A=>A[_s.PERMS_CRUD_ENUM.READ]).forEach(A=>{p.push(A.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(g=>g.attribute),e.get_attributes=p)}let E=d7(e),h=ug(e.hdb_user.role.permission,n,i);return cg(E,h,r,i,n,c,s),c.getPermsResponse()}a(_7,"verifyPerms");function jP(e,t,r,s,n){if(Ln.arrayHasEmptyValues([e,t,r]))throw wt.info("hasPermissions has an invalid parameter"),pr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||F.get(t).requires_su))return null;if(!F.get(t))throw wt.info(`operation ${t} not found.`),pr(new Error,Vt.OP_NOT_FOUND(t),Fu.BAD_REQUEST);if(F.get(t)&&F.get(t).requires_su)return wt.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Vt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][Gu]===!1){s.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem(Vt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[Gu]===!1)s.addInvalidItem(Vt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=F.get(t).perms;!Ln.isEmpty(n)&&E.includes(n)&&(E=[n]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(wt.info(`Required ${p} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&s.addUnauthorizedTable(u,l,f)}catch(f){let E=Vt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw wt.error(E),wt.error(f),pr(WP.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(jP,"hasPermissions");function cg(e,t,r,s,n,i,o){if(!e||!t)throw wt.info("no attributes specified in checkAttributePerms."),pr(new Error);let c=F.get(r).perms;if(!c||c==="")throw wt.info(`no permissions found for ${r} in checkAttributePerms().`),pr(new Error);if(Ln.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[Gu]===!1){i.addInvalidItem(Vt.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let f of c){if(_s.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Mn)throw pr(new Error,Vt.SYSTEM_TIMESTAMP_PERMS_ERR,Fu.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(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(cg,"checkAttributePerms");function d7(e){let t=new Set;try{if(e.action)return t;if(e.operation===_s.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){wt.info(r)}return t}a(d7,"getRecordAttributes");function ug(e,t,r){let s=new Map;if(Ln.isEmpty(e))return wt.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{wt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(ug,"getAttributePermissions");function f7(e,t,r,s,n,i,o){let c=new Set(i),u=ug(e,s,n);cg(c,u,t,n,s,o,r)}a(f7,"verifyBulkLoadAttributePerms")});var Tf=T((Lhe,sv)=>{"use strict";sv.exports={evaluateSQL:y7,processAST:rv,convertSQLToAST:tv,checkASTPermissions:ev};var E7=Mr(),ZP=require("util"),h7=ZP.callbackify(E7.insert),m7=rs().search,p7=qC().update,S7=ZP.callbackify(p7),T7=GC().convertDelete,Ri=require("alasql"),g7=pf(),Sf=V(),R7=ed(),A7=J(),$u=L(),{hdb_errors:O7,handleHDBError:lg}=Z(),{HTTP_STATUS_CODES:_g}=O7;R7(Ri);var b7=403,N7="There was a problem performing this insert. Please check the logs and try again.",dg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function y7(e,t){let r=e.parsed_sql_object;if(!r){r=tv(e.sql);let s,n=r.ast.statements[0];if(n instanceof Ri.yy.Insert?s=n.into.databaseid:n instanceof Ri.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof Ri.yy.Update||n instanceof Ri.yy.Delete?s=n.table.databaseid:Sf.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof Ri.yy.Select)&&A7.isEmptyOrZeroLength(s))return t("No schema specified",null)}rv(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(y7,"evaluateSQL");function ev(e,t){let r;try{r=g7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(ev,"checkASTPermissions");function tv(e){let t=new dg;if(!e)throw lg(new Error,"The 'sql' parameter is missing from the request body",_g.BAD_REQUEST);try{let r=e.trim(),s=Ri.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
17
|
+
`);throw s[1]?lg(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,_g.BAD_REQUEST):lg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",_g.BAD_REQUEST)}return t}a(tv,"convertSQLToAST");function rv(e,t,r){try{let s=w7;if(!e.bypass_auth&&!t.permissions_checked){let i=ev(e,t);if(i&&i.length>0)return r(b7,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case $u.VALID_SQL_OPS_ENUM.SELECT:s=m7,n=t.ast.statements[0];break;case $u.VALID_SQL_OPS_ENUM.INSERT:s=I7;break;case $u.VALID_SQL_OPS_ENUM.UPDATE:s=S7;break;case $u.VALID_SQL_OPS_ENUM.DELETE:s=T7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(rv,"processAST");function w7(e,t){Sf.info(e),t("unknown sql statement")}a(w7,"nullFunction");function I7({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=C7(i,e.values)}catch(o){return r(o)}h7(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Sf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(I7,"convertInsert");function C7(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=Ri.compile(`SELECT ${n.toString()} AS [${$u.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw Sf.error(r),new Error(N7)}}a(C7,"createDataObjects")});var fg=T((Uhe,iv)=>{"use strict";var{S3:D7,GetObjectCommand:L7}=require("@aws-sdk/client-s3");iv.exports={getFileStreamFromS3:M7,getS3AuthObj:nv};async function M7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await nv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new L7(r))).Body}a(M7,"getFileStreamFromS3");function nv(e,t,r){return new D7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(nv,"getS3AuthObj")});var gf=T((vhe,Ev)=>{"use strict";var hg=rs(),U7=Tf(),P7=fg(),{AsyncParser:v7,Transform:B7}=require("json2csv"),Ku=require("stream"),Yr=J(),Eg=require("fs-extra"),H7=require("path"),Es=V(),{promisify:cv}=require("util"),Yu=J(),{handleHDBError:gt,hdb_errors:x7}=Z(),{HDB_ERROR_MSGS:Sr,HTTP_STATUS_CODES:Rt}=x7,{streamAsJSON:q7}=(Ph(),ee(nb)),{Upload:F7}=require("@aws-sdk/lib-storage"),ov=["search_by_value","search_by_hash","sql","search_by_conditions"],av=["json","csv"],uv="json",lv="csv",G7="Successfully exported JSON locally.",k7="Successfully exported CSV locally.",V7=1e3,$7=hg.searchByHash,Y7=hg.searchByValue,K7=cv(U7.evaluateSQL),W7=cv(Ku.finished);Ev.exports={export_to_s3:j7,export_local:Q7,toCsvStream:_v};async function Q7(e){Es.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=dv(e);if(!Yr.isEmpty(t))throw Es.error(t),gt(new Error,t,Rt.BAD_REQUEST,void 0,void 0,!0);if(Yr.isEmpty(e.path))throw Es.error(Sr.MISSING_VALUE("path")),gt(new Error,Sr.MISSING_VALUE("path"),Rt.BAD_REQUEST,void 0,void 0,!0);let r=(Yr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(H7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Yr.buildFolderPath(e.path,r);await z7(e.path);let n=await fv(e);return await J7(s,e.format,n)}a(Q7,"export_local");async function z7(e){if(Es.trace("in confirmPath"),Yr.isEmptyOrZeroLength(e))throw gt(new Error,`Invalid path: ${e}`,Rt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Eg.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,Es.error(s),gt(new Error,s,Rt.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw Es.error(r),gt(new Error,r,Rt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(z7,"confirmPath");async function J7(e,t,r){if(Es.trace("in saveToLocal"),Yu.isEmptyOrZeroLength(e))throw gt(new Error,Sr.INVALID_VALUE("file_path"),Rt.BAD_REQUEST,void 0,void 0,!0);if(Yu.isEmptyOrZeroLength(t))throw gt(new Error,Sr.INVALID_VALUE("Source format"),Rt.BAD_REQUEST,void 0,void 0,!0);if(Yu.isEmpty(r))throw gt(new Error,Sr.NOT_FOUND("Data"),Rt.BAD_REQUEST,void 0,void 0,!0);if(t===uv){let s=Eg.createWriteStream(e);return q7(r).pipe(s),await W7(s),{message:G7,path:e}}else if(t===lv){let s=Eg.createWriteStream(e),n=Ku.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new v7(i,c).fromInput(n).toOutput(s).promise(!1),{message:k7,path:e}}throw gt(new Error,Sr.INVALID_VALUE("format"),Rt.BAD_REQUEST)}a(J7,"saveToLocal");async function j7(e){if(!e.s3||Object.keys(e.s3).length===0)throw gt(new Error,Sr.MISSING_VALUE("S3 object"),Rt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw gt(new Error,Sr.MISSING_VALUE("aws_access_key_id"),Rt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw gt(new Error,Sr.MISSING_VALUE("aws_secret_access_key"),Rt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.bucket))throw gt(new Error,Sr.MISSING_VALUE("bucket"),Rt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.key))throw gt(new Error,Sr.MISSING_VALUE("key"),Rt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.region))throw gt(new Error,Sr.MISSING_VALUE("region"),Rt.BAD_REQUEST);let t=dv(e);if(!Yr.isEmpty(t))throw gt(new Error,t,Rt.BAD_REQUEST);Es.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await fv(e)}catch(u){throw Es.error(u),u}let s,n=await P7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Ku.PassThrough;if(e.format===lv){i=e.s3.key+".csv";let u=_v(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===uv){i=e.s3.key+".json";let u=new Ku.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%V7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw gt(new Error,Sr.INVALID_VALUE("format"),Rt.BAD_REQUEST);return new F7({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(j7,"export_to_s3");function _v(e,t){let r=Ku.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),s={};t&&(s.fields=t.map(o=>({label:o,value:o})));let n={objectMode:!0},i=new B7(s,n);return r.pipe(i)}a(_v,"toCsvStream");function dv(e){if(Es.trace("in exportCoreValidation"),Yr.isEmpty(e.format))return"format missing";if(av.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${av.join(", ")}`;let t=e.search_operation.operation;if(Yr.isEmpty(t))return"search_operation.operation missing";if(ov.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${ov.join(", ")}`}a(dv,"exportCoreValidation");async function fv(e){Es.trace("in getRecords");let t,r;if(Yu.isEmpty(e.search_operation)||Yu.isEmptyOrZeroLength(e.search_operation.operation))throw gt(new Error,Sr.INVALID_VALUE("Search operation"),Rt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Y7;break;case"search_by_hash":t=$7;break;case"search_by_conditions":t=hg.searchByConditions;break;case"sql":t=K7;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Es.error(r),gt(new Error,r,Rt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(fv,"getRecords")});var Av={};We(Av,{contentTypes:()=>gg,findBestSerializer:()=>Af,getDeserializer:()=>ho,registerContentHandlers:()=>Rg,serialize:()=>Of,serializeMessage:()=>Ti});function X7(e){try{return e?.[0]===123?Tg(e):e}catch{return e}}function Rg(e){e.register(eee,{serializers:[{regex:/^application\/json$/,serializer:Ec},{regex:/^application\/cbor$/,serializer:function(t){return new Eo.EncoderStream(Qu).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Rf.Readable.from((0,on.encodeIter)(t,Qu)):(0,on.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,mg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,on.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,Eo.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function Af(e){let r=(e.headers.asObject||e.headers).accept,s,n=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=xt.get(_);if(E){let h=(E.q||1)*d;h>n&&(s=E,i=E.type||_,n=h,o=f)}}if(!s){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(xt.keys()).join(", "))}};s=xt.get("application/json"),i="application/json"}return{serializer:s,type:i,parameters:o}}function Of(e,t,r){let s=mv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),n=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=Af(t);if(i.serializer.compressible===!1&&(s=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Un.createBrotliCompress)({params:{[Un.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Un.constants.BROTLI_MODE_TEXT:Un.constants.BROTLI_MODE_GENERIC,[Un.constants.BROTLI_PARAM_QUALITY]:2}}))),o}n=i.serializer.serialize(e,r)}return s&&n?.length>mv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Un.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ti(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return Wu(e);let r=t.serialize;if(r)return r(e);let s=Af(t);return r=t.serialize=s.serializer.serialize,r(e)}function tee(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function ho(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=xt.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=xt.get(e)?.deserialize||pv(e,s);return o=>tee(o).then(i)}return e&&xt.get(e)?.deserialize||pv(e,s)}function pv(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return s=>({contentType:e,data:s.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Tg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function ree(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let s=r.next();return s.then?s.then(n=>({value:t(n.value),done:n.done})):{value:t(s.value),done:s.done}},return(s){return r.return(s)},throw(s){return r.throw(s)}}}}}var mg,on,Eo,Un,Rf,Sv,pg,Sg,Tv,gv,Wu,Tg,Qu,xt,gg,hv,Rv,Z7,eee,mv,Ta=Re(()=>{Ph();mg=B(gf()),on=require("msgpackr"),Eo=require("cbor-x"),Un=require("zlib"),Rf=require("stream");rr();Sv=require("../index"),pg=B(X()),Sg=B(L()),Tv=B(require("yaml")),gv=pg.default.get(Sg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Wu=gv?Li:JSON.stringify,Tg=gv?Uh:JSON.parse,Qu={useRecords:!1,useToJSON:!0},xt=new Map,gg=xt;lt.contentTypes=gg;(0,Sv._assignPackageExport)("contentTypes",gg);xt.set("application/json",{serializeStream:Ec,serialize:Wu,deserialize:Tg,q:.8});hv=new Eo.Encoder(Qu);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Eo.EncoderStream(Qu).end(e)},serialize:hv.encode,deserialize:hv.decode,q:1});xt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Rf.Readable.from((0,on.encodeIter)(e,Qu)):(0,on.pack)(e)},serialize:on.pack,deserialize:on.unpack,q:.9});xt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,mg.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 Tv.stringify(e,{aliasDuplicateObjects:!1})},q:.7});xt.set("text/event-stream",{serializeStream:function(e){return Rf.Readable.from(ree(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
|
+
`),e.data){let r=e.data;typeof r=="object"&&(r=Wu(r)),t+="data: "+r+`
|
|
19
19
|
`}return e.id&&(t+="id: "+e.id+`
|
|
20
20
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
21
21
|
`),t+`
|
|
22
|
-
`}else return typeof e=="object"?`data: ${
|
|
22
|
+
`}else return typeof e=="object"?`data: ${Wu(e)}
|
|
23
23
|
|
|
24
24
|
`:`data: ${e}
|
|
25
25
|
|
|
26
|
-
`},compressible:!1,q:.8});$t.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,s]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let n=t[r];Array.isArray(n)?n.push(s):t.key=[n,s]}else t[r]=s},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});dv={type:"application/json",serializeStream:Ec,serialize:Qu,deserialize:P7,q:.8};$t.set("*/*",dv);$t.set("",dv);a(P7,"tryJSONParse");a(mg,"registerContentHandlers");v7=require("fastify-plugin"),B7=v7(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Rf(s.raw);n.type(c),n.serializer(o.serializeStream||o.serialize)}),r()},{name:"content-type-negotiation"});a(Rf,"findBestSerializer");cv=dg.default.get(fg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Af,"serialize");a(Ti,"serializeMessage");a(H7,"streamToBuffer");a(mo,"getDeserializer");a(uv,"deserializerUnknownType");a(x7,"transformIterable")});function ju(e,t,r,s,n,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],I=vn(s.attributes,R);if(I.relationship){if(o.length<2)throw new po.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let w=I.definition?.tableClass||I.elements?.definition?.tableClass,B=new Map,K=ju({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,w,n,B);if(I.relationship.to){i[o[0]]=B;let q=!!vn(w.attributes,I.relationship.to)?.elements;K=k7(K,I,w.primaryStore,q,B)}if(I.relationship.from){let q=a(P=>ju({attribute:I.relationship.from,value:P},t,r,s,n,B),"searchEntry");I.elements?(i[o[0]]=B,K=V7(K,I,w.primaryStore,B,q)):K=K.flatMap(q)}return K}else if(o.length===1)o=o[0];else throw new po.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(hv[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]=un.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 je.SEARCH_TYPES.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 po.ClientError(`Unknown query comparator "${u}"`)}if(r){let R=_;_=l,l=R,R=!f,f=!d,d=R}let h=o===s.primaryKey||o==null,p=h?s.primaryStore:s.indices[o];if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(!n)throw new po.ClientError(`"${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);let R=Zu(e);if(!R)throw new po.ClientError(`Unknown search operator ${e.comparator}`);return s.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:I,value:w})=>new Promise((B,K)=>setImmediate(()=>{try{B(w&&R(w)?I:pg.SKIP)}catch(q){K(q)}})))}let S={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(S).map(I=>I.value==null?pg.SKIP:I);return R.hasEntries=!0,R}else return p.getRange(S).map(({value:R})=>R)}function vn(e,t){if(Array.isArray(t))if(t.length>1){let r=vn(e,t[0]),s=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return s?vn(s,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function k7(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i,o;return{next(){if(!i){let u=t.relationship.to;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=Oi(d),o=!0);let h=n.get(E);h?h.push(f):n.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&&!n.filters?.some(h=>!h(f))){if(s)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?n:n.keys())[Symbol.iterator](),this.next()})()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function V7(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i,o;return{next(){let c;if(o&&(c=o.next(),!c.done))return c;if(!i)return(async()=>{let u=new Map;s.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>u.has(Oi(d)));let _=0;for await(let l of e){if(s.filters){let d=r.get(l);if(s.filters.some(f=>!f(d)))continue}u.set(Oi(l),l),_++>100&&(await new Promise(setImmediate),_=0)}return i=u.values()[Symbol.iterator](),this.next()})();do{let u=i.next();return u.done?u:(o=n(u.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Zu(e,t,r,s){if(e.conditions){let c=e.conditions.map(Zu);return e.operator==="or"?u=>c.some(_=>_(u)):u=>c.every(_=>_(u))}let n=e.comparator,i=e[0]??e.attribute,o=e[1]??e.value;if(Array.isArray(i)){if(i.length===0)return()=>!0;if(i.length===1)i=i[0];else if(i.length>1){let c=i[0],u=vn(t.attributes,c),_=u.definition?.tableClass||u.elements.definition?.tableClass,l=s?.[c],d=Zu({attribute:i.length>2?i.slice(1):i[1],value:o,comparator:n},t,r,l?.[c]?.joined);if(!d)return;if(l){l.filters||(l.filters=[]),l.filters.push(d);return}let f=t.propertyResolvers?.[c];return(E,h)=>{let p,S;return f?(S=f(E,r,h),p=S?.value):p=E[c],p?Array.isArray(p)?p.some(d):d(p,S):!1}}}switch(o instanceof Date&&(o=o.getTime()),hv[n]||n){case je.SEARCH_TYPES.EQUALS:case void 0:return cn(i,c=>c===o);case je.SEARCH_TYPES.CONTAINS:return cn(i,c=>c?.toString().includes(o));case je.SEARCH_TYPES.ENDS_WITH:case je.SEARCH_TYPES._ENDS_WITH:return cn(i,c=>c?.toString().endsWith(o));case je.SEARCH_TYPES.STARTS_WITH:case je.SEARCH_TYPES._STARTS_WITH:return cn(i,c=>typeof c=="string"&&c.startsWith(o));case je.SEARCH_TYPES.BETWEEN:return o[0]instanceof Date&&(o[0]=o[0].getTime()),o[1]instanceof Date&&(o[1]=o[1].getTime()),cn(i,c=>(0,un.compareKeys)(c,o[0])>=0&&(0,un.compareKeys)(c,o[1])<=0);case"gt":case je.SEARCH_TYPES.GREATER_THAN:case je.SEARCH_TYPES._GREATER_THAN:return cn(i,c=>(0,un.compareKeys)(c,o)>0);case"ge":case je.SEARCH_TYPES.GREATER_THAN_EQUAL:case je.SEARCH_TYPES._GREATER_THAN_EQUAL:return cn(i,c=>(0,un.compareKeys)(c,o)>=0);case je.SEARCH_TYPES.LESS_THAN:case"lt":case je.SEARCH_TYPES._LESS_THAN:return cn(i,c=>(0,un.compareKeys)(c,o)<0);case"le":case je.SEARCH_TYPES.LESS_THAN_EQUAL:case je.SEARCH_TYPES._LESS_THAN_EQUAL:return cn(i,c=>(0,un.compareKeys)(c,o)<=0);case"ne":return cn(i,c=>(0,un.compareKeys)(c,o)!==0);default:throw new po.ClientError(`Unknown query comparator "${n}"`)}}function cn(e,t){return r=>{let s=r[e];return typeof s!="object"||!s?t(s):Array.isArray(s)?s.some(t):s instanceof Date?t(s.getTime()):!1}}function Sg(e){return t=>{if(t.estimated_count===void 0){if(t.conditions){let s;if(t.operator==="or"){s=0;for(let n of t.conditions)s+=n.estimated_count}else{s=1/0;for(let n of t.conditions)s=1/(1/s+1/n.estimated_count)}return t.estimated_count=s,t.estimated_count}let r=t.comparator||t.search_type;if(r===je.SEARCH_TYPES.EQUALS){let s=t[0]??t.attribute;if(s==null||s===e.primaryKey)t.estimated_count=1;else if(Array.isArray(s)){let n=vn(e.attributes,s[0]),i=n.definition?.tableClass||n.elements.definition?.tableClass,o=Sg(i)({value:t.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"});t.estimated_count=o*4*(e.indices[n.relationship.from]||e.primaryStore).getStats().entryCount/(i.primaryStore.getStats().entryCount||1)}else{let n=e.indices[s];t.estimated_count=n?n.getValuesCount(t[1]??t.value):1/0}}else r===je.SEARCH_TYPES.CONTAINS||r===je.SEARCH_TYPES.ENDS_WITH||r==="ne"?t.value===null&&r==="ne"?t.estimated_count=Ev:t.estimated_count=1/0:r===je.SEARCH_TYPES.STARTS_WITH||r==="prefix"?t.estimated_count=Ev:r===je.SEARCH_TYPES.BETWEEN?t.estimated_count=F7:t.estimated_count=q7;typeof t.descending=="boolean"&&(t.estimated_count/=4)}return t.estimated_count}}function Of(e){if(e)if(Ai=e,ya.lastIndex=0,$7.test(e))try{let t=Ju(new Ia,"");if(gr!==Ai.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 ${gr} in '${Ai}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function Ju(e,t){let r=ya,s,n,i,o,c;for(;s=r.exec(Ai);){gr=r.lastIndex;let[,u,_]=s;if(o){if(u)throw new SyntaxError(`expected operator, but encountered '${u}'`);o=!1,c=!1}else c=!0;let l;switch(_){case"=":if(n)if(u.length<=2)i=u;else throw new SyntaxError(`invalid FIQL operator ${u}`);else{if(i="equals",!u)throw new SyntaxError("attribute must be specified before equality comparator");n=Xu(u)}break;case"!=":case"<":case"<=":case">":case">=":if(i=G7[_],!u)throw new SyntaxError(`attribute must be specified before comparator ${_}`);n=Xu(u);break;case"|":e.operator="or";case"":case void 0:case"&":if(n==null){if(n===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${_[0]?"'"+_[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${_?"'"+_+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.conditions.push({comparator:i,attribute:n,value:decodeURIComponent(u)})}n=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(Xu(u)),n=void 0;break;case"(":ya.lastIndex=gr;let d=Ju(u?[]:new Ia,")");switch(u){case"":e.conditions.push(d);break;case"limit":switch(d.length){case 1:e.limit=+d[0];break;case 2:e.offset=+d[0],e.limit=d[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(d[0])&&d.length===1&&!d[0].name?(e.select=d[0],e.select.asArray=!0):d.length===1?e.select=d[0]:d.length===2&&d[1]===""?e.select=d.slice(0,1):e.select=d;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=mv(d);break;default:throw new SyntaxError(`unknown query function call ${u}`)}Ai[gr]===","?r.lastIndex=++gr:o=!0,n=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!u)throw new SyntaxError("property sets must have a defined parent property name");ya.lastIndex=gr,l=Ju([],"}"),l.name=u,e.push(l),Ai[gr]===","?r.lastIndex=++gr:o=!0;break;case"[":ya.lastIndex=gr,u?(l=Ju(new Ia,"]"),l.name=u):l=Ju(e.conditions?new Ia:[],"]"),e.conditions?(e.conditions.push(l),n=null):e.push(l),Ai[gr]===","?r.lastIndex=++gr:o=!0;break;case")":case"]":case"}":if(t===_[0]){if(e.conditions){if(n)e.conditions.push({comparator:i||"equals",attribute:n,value:decodeURIComponent(u)});else if(u)throw new SyntaxError("no attribute or comparison specified")}else(u||e.length>0&&c)&&e.push(Xu(u));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${_[0]}'`):new SyntaxError(`unexpected token '${_[0]}'`);default:throw new SyntaxError(`unexpected operator '${_}'`)}if(t!==")"&&(r=n?Y7:ya,r.lastIndex=gr),gr===Ai.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Xu(e){return e.indexOf(".")>-1?e.split(".").map(Xu):decodeURIComponent(e)}function mv(e){let t=pv(e[0]);return e.length>1&&(t.next=mv(e.slice(1))),t}function pv(e){if(Array.isArray(e)){let t=pv(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 Oi(e){return Array.isArray(e)?e.join("\0"):e}var po,je,un,pg,q7,F7,Ev,G7,hv,$7,ya,Y7,gr,Ai,Ia,bf=Ae(()=>{po=v(Z()),je=v(mt()),un=require("ordered-binary"),pg=require("lmdb"),q7=1e8,F7=15e6,Ev=1e7,G7={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne"};a(ju,"searchByIndex");a(vn,"findAttribute");a(k7,"joinTo");a(V7,"joinFrom");hv={greater_than:"gt",greater_than_equal:"ge",less_than:"lt",less_than_equal:"le",not_equal:"ne",equal:"equals",sw:"starts_with",ew:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Zu,"filterByType");a(cn,"attributeComparator");a(Sg,"estimateCondition");$7=/[()[\]|!<>.]|(=\w+=)/,ya=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Y7=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Of,"parseQuery");a(Ju,"parseBlock");a(Xu,"decodeProperty");a(mv,"toSortObject");a(pv,"toSortEntry");Ia=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}};a(Oi,"flattenKey")});var Nf={};$e(Nf,{start:()=>Q7});async function W7(e,t){let r=e.headers.asObject,s=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Of(e);let n=new Si;try{e.responseHeaders=n;let i=e.url.slice(1),o=gg.getMatch(i);if(!o)return t(e);e.handlerPath=o.path;let c={url:o.relativeURL,async:!0},u=o.Resource,_=r["cache-control"];if(_){_=_.toLowerCase();let p=_.match(/max-age=(\d+)/)?.[1];p&&(e.expiresAt=p*1e3+Date.now()),_.includes("only-if-cached")&&(e.onlyIfCached=!0),_.includes("no-cache")&&(e.noCache=!0),_.includes("no-store")&&(e.noCacheStore=!0),_.includes("stale-if-error")&&(e.staleIfError=!0),_.includes("must-revalidate")&&(e.mustRevalidate=!0)}let l=await Xe(e,()=>{if(s==="POST"||s==="PUT"||s==="PATCH"||s==="QUERY")try{e.data=mo(r["content-type"],!0)(e.body)}catch(p){throw new tl.ClientError(p,400)}switch(e.authorize=!0,s){case"GET":case"HEAD":return u.get(c,e);case"POST":return u.post(c,e.data,e);case"PUT":return u.put(c,e.data,e);case"DELETE":return u.delete(c,e);case"PATCH":return u.patch(c,e.data,e);case"OPTIONS":n.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return u.connect(c,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return u.query(c,e.data,e);case"COPY":return u.copy(c,r.destination,e);case"MOVE":return u.move(c,r.destination,e);case"BREW":throw new tl.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new tl.ServerError(`Method ${s} is not recognized`,501)}}),d=200,f;if(l==null)d=s==="GET"||s==="HEAD"?404:204,Tg.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(f=e.lastModified){K7[0]=f;let p=String.fromCharCode(34,(Yt[0]&63)+62,(Yt[0]>>6)+(Yt[1]<<2&63)+62,(Yt[1]>>4)+(Yt[2]<<4&63)+62,(Yt[2]>>2)+62,(Yt[3]&63)+62,(Yt[3]>>6)+(Yt[4]<<2&63)+62,(Yt[4]>>4)+(Yt[5]<<4&63)+62,(Yt[5]>>2)+62,(Yt[6]&63)+62,(Yt[6]>>6)+(Yt[7]<<2&63)+62,34),S=r["if-none-match"];S&&p==S?(l?.onDone&&l.onDone(),d=304,l=void 0):n.setIfNone("ETag",p),Tg.lastModified&&n.setIfNone("Last-Modified",new Date(f).toUTCString())}e.createdResource&&(d=201),e.newLocation&&n.setIfNone("Location",e.newLocation);let E={status:d,headers:n,body:void 0},h=l?.wasLoadedFromSource?.();return h!==void 0&&(E.wasCacheMiss=h,!h&&f&&n.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||f))/1e3))),l!==void 0&&(E.body=Af(l,e,E),s==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?So.warn(i):So.info(i):So.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),n.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:n,body:void 0};return o.body=Af(i.contentType?i:i.toString(),e,o),o}}function Q7(e){Tg=e,!Sv&&(Sv=!0,gg=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return W7(t,r)}),e.server.ws(async(t,r,s)=>{el++;let n=new bs;Tv||(Tv=!0,tu(l=>{el>0&&l.push({metric:"ws-connections",connections:el,byThread:!0})}));let i;t.on("error",l=>{i=!0,So.warn(l)});let o;t.on("message",a(function(d){o||(o=mo(r.headers.asObject["content-type"]));let f=o(d);n.push(f)},"message"));let c;t.on("close",()=>{el--,ss(!i,"connection","ws","disconnect"),n.emit("close"),c&&c.return()}),await s;let u=r.url.slice(1),_=gg.getMatch(u);if(ss(!!_,"connection","ws","connect"),!_)t.send(Ti(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,qr(h=>({count:h.count,total:el}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Xe(r,()=>d.connect(l,n,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ti(E.value,r);t.send(h),qr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var So,tl,Yt,K7,Tg,Sv,gg,Tv,el,gv=Ae(()=>{Ta();yn();So=v(G()),tl=v(Z());bf();dc();Xi();Jd();Yt=new Uint8Array(8),K7=new Float64Array(Yt.buffer,0,1),Tg={};a(W7,"http");el=0;a(Q7,"start")});var Rg=T((yhe,Rv)=>{var{recordAction:yf,recordActionBinary:z7}=(yn(),ee(ru)),J7=require("fastify-plugin"),X7=200;Rv.exports=J7(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n,i)=>{let o=n.getResponseTime(),c=performance.now(),u=n.request.routeOptions,_,l,d;u.config?.isOperation?(_=s.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),yf(o,"duration",_,d,l),z7(n.raw.statusCode<400,"success",_,d,l);let f=X7;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{yf(performance.now()-c,"transfer",_,d,l),yf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,yf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);n.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Ng=T((Ihe,yv)=>{var Lf=require("clone"),Uf=Je(),j7=z(),Cf=D(),Z7=G(),If=require("fs"),Ag=require("joi"),{string:Df}=Ag.types(),{hdb_errors:eee,handleHDBError:rl}=Z(),{HDB_ERROR_MSGS:tee,HTTP_STATUS_CODES:wf}=eee,{common_validators:wa}=Ks(),Av=1e9,Ov=" is required",ree=["insert","update","upsert"],Og={database:{presence:!1,format:wa.schema_format,length:wa.schema_length},schema:{presence:!1,format:wa.schema_format,length:wa.schema_length},table:{presence:!0,format:wa.schema_format,length:wa.schema_length},action:{inclusion:{within:ree,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},see={schema:Df.required(),table:Df.required(),action:Df.valid("insert","update","upsert")},{AWS_ACCESS_KEY:nee,AWS_SECRET:iee,AWS_BUCKET:oee,AWS_FILE_KEY:aee,REGION:cee}=Cf.S3_BUCKET_AUTH_KEYS,uee={s3:{presence:!0},[`s3.${nee}`]:{presence:!0,type:"String"},[`s3.${iee}`]:{presence:!0,type:"String"},[`s3.${oee}`]:{presence:!0,type:"String"},[`s3.${aee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${cee}`]:{presence:!0,type:"String"}},bv=Lf(Og);bv.data.presence={message:Ov};var Nv=Lf(Og);Nv.file_path.presence={message:Ov};var lee=Object.assign(Lf(Og),uee),bg=Lf(see);bg.csv_url=Df.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();bg.passthrough_headers=Ag.object();function _ee(e){let t=Uf.validateObject(e,bv);return Mf(e,t)}a(_ee,"dataObject");function dee(e){let t=Uf.validateBySchema(e,Ag.object(bg));return Mf(e,t)}a(dee,"urlObject");function fee(e){let t=Uf.validateObject(e,Nv);return Mf(e,t)}a(fee,"fileObject");function Eee(e){let t=Uf.validateObject(e,lee);return Mf(e,t)}a(Eee,"s3FileObject");function Mf(e,t){if(!t){let r=j7.checkGlobalSchemaTable(e.schema,e.table);if(r)return rl(new Error,r,wf.BAD_REQUEST);if(e.operation===Cf.OPERATIONS_ENUM.CSV_FILE_LOAD){try{If.accessSync(e.file_path,If.constants.R_OK|If.constants.F_OK)}catch(s){return s.code===Cf.NODE_ERROR_CODES.ENOENT?rl(s,`No such file or directory ${s.path}`,wf.BAD_REQUEST):s.code===Cf.NODE_ERROR_CODES.EACCES?rl(s,`Permission denied ${s.path}`,wf.BAD_REQUEST):rl(s)}try{let s=If.statSync(e.file_path).size;if(s>Av)return rl(new Error,tee.MAX_FILE_SIZE_ERR(s,Av),wf.BAD_REQUEST)}catch(s){Z7.error(s),console.error(s)}}}return t}a(Mf,"postValidateChecks");yv.exports={dataObject:_ee,urlObject:dee,fileObject:fee,s3FileObject:Eee}});var yg=T((Che,Iv)=>{"use strict";var sl=G(),Pf=D();async function hee(e,t,r,s=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===Pf.OPERATIONS_ENUM.INSERT||t.operation===Pf.OPERATIONS_ENUM.UPDATE||t.operation===Pf.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===Pf.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(sl.info(i.message),i):i.http_resp_msg?(sl.error(`Error calling operation: ${e.name}`),sl.error(i.http_resp_msg),i):(sl.error(`Error calling operation: ${e.name}`),sl.error(i),i)}}a(hee,"callOperationFunctionAsAwait");Iv.exports={callOperationFunctionAsAwait:hee}});var Cv=T((Lhe,wv)=>{"use strict";var Ig=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}},wg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};wv.exports={BulkLoadFileObject:Ig,BulkLoadDataObject:wg}});var Lv=T((Mhe,Dv)=>{"use strict";var Cg=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};Dv.exports=Cg});var vg=T((qhe,Qv)=>{"use strict";var vf=Lr(),Hf=Ng(),mee=require("needle"),Hs=D(),vhe=qe(),Ca=z(),{handleHDBError:ot,hdb_errors:Fv}=Z(),{HTTP_STATUS_CODES:Kt,HDB_ERROR_MSGS:Dt,CHECK_LOGS_WRAPPER:go}=Fv,Da=G(),Dg=require("papaparse");Ca.promisifyPapaParse();var xs=require("fs-extra"),pee=require("path"),{chain:Uv}=require("stream-chain"),Mv=require("stream-json/streamers/StreamArray"),Pv=require("stream-json/utils/Batch"),vv=require("stream-chain/utils/comp"),{finished:Bv}=require("stream"),See=j(),Gv=yg(),Tee=cg(),{BulkLoadFileObject:Ug,BulkLoadDataObject:gee}=Cv(),Mg=jT(),{verifyBulkLoadAttributePerms:kv}=mf(),Bhe=Lv(),Hhe=nt(),xhe=gn(),{databases:Ree}=(ge(),ee(xe)),{coerceType:Aee}=(xf(),ee(Bg)),Hv="No records parsed from csv file.",To=`${See.get("HDB_ROOT")}/tmp`,{schema_regex:Oee}=Ks(),xv=1024*1024*2,qv=5e3,bee={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};Qv.exports={csvDataLoad:Nee,csvURLLoad:yee,csvFileLoad:Iee,importFromS3:wee};async function Nee(e,t){let r=Hf.dataObject(e);if(r)throw ot(r,r.message,Kt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=Yv(e.schema,e.table),i=Dg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Lg.bind(null,n),dynamicTyping:!1}),o=new Mg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&kv(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw ot(new Error,c,Kt.BAD_REQUEST,void 0,void 0,!0);let u=new gee(e.action,e.schema,e.table,i.data);return s=await Gv.callOperationFunctionAsAwait(Kv,u,null),s.message===Hv?Hv:Wv(s.records,s.number_written)}catch(n){throw Ro(n)}}a(Nee,"csvDataLoad");async function yee(e){let t=Hf.urlObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${To}/${r}`;try{await Cee(e,r)}catch(n){throw Da.error(Dt.DOWNLOAD_FILE_ERR(r)+" - "+n),ot(n,go(Dt.DOWNLOAD_FILE_ERR(r)))}try{let n=new Ug(this.job_operation_function.name,e.action,e.schema,e.table,s,Hs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Pg(n);return await Bf(s),i}catch(n){throw await Bf(s),Ro(n)}}a(yee,"csvURLLoad");async function Iee(e){let t=Hf.fileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=new Ug(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Hs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Pg(r)}catch(s){throw Ro(s)}}a(Iee,"csvFileLoad");async function wee(e){let t=Hf.s3FileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=pee.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${To}/${n}`;let i=new Ug(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await Dee(n,e);let o=await Pg(i);return await Bf(r),o}catch(s){throw await Bf(r),Ro(s)}}a(wee,"importFromS3");async function Cee(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await mee("get",e.csv_url,s)}catch(s){let n=`Error downloading CSV file from ${e.csv_url}, status code: ${s.statusCode}. Check the log for more information.`;throw ot(s,n,s.statusCode,Hs.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}Uee(r,e.csv_url),await Lee(t,r.raw)}a(Cee,"downloadCSVFile");async function Dee(e,t){try{let r=`${To}/${e}`;await xs.mkdirp(To),await xs.writeFile(`${To}/${e}`,"",{flag:"a+"});let s=await xs.createWriteStream(r),n=await Tee.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){Da.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Da.error(Dt.S3_DOWNLOAD_ERR+" - "+r),ot(r,go(Dt.S3_DOWNLOAD_ERR))}}a(Dee,"downloadFileFromS3");async function Lee(e,t){try{await xs.mkdirp(To),await xs.writeFile(`${To}/${e}`,t)}catch(r){throw Da.error(Dt.WRITE_TEMP_FILE_ERR),ot(r,go(Dt.DEFAULT_BULK_LOAD_ERR))}}a(Lee,"writeFileToTempFolder");async function Bf(e){if(e)try{await xs.access(e),await xs.unlink(e)}catch{Da.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(Bf,"deleteTempFile");function Uee(e,t){if(e.statusCode!==Fv.HTTP_STATUS_CODES.OK)throw ot(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Kt.BAD_REQUEST);if(!bee[e.headers["content-type"]])throw ot(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Kt.BAD_REQUEST);if(!e.raw)throw ot(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Kt.BAD_REQUEST)}a(Uee,"validateURLResponse");async function Pg(e){try{let t;switch(e.file_type){case Hs.VALID_S3_FILE_TYPES.CSV:t=await Mee(e);break;case Hs.VALID_S3_FILE_TYPES.JSON:t=await Pee(e);break;default:throw ot(new Error,Dt.DEFAULT_BULK_LOAD_ERR,Kt.BAD_REQUEST,Hs.LOG_LEVELS.ERROR,Dt.INVALID_FILE_EXT_ERR(e))}return Wv(t.records,t.number_written)}catch(t){throw Ro(t)}}a(Pg,"fileLoad");async function Vv(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await vf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&kv(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=ot(c);r(u)}}a(Vv,"validateChunk");async function $v(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;Ca.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!Ca.isEmpty(c)&&!Ca.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 Gv.callOperationFunctionAsAwait(Kv,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=ot(c,go(Dt.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,Hs.LOG_LEVELS.ERROR,Dt.INSERT_CSV_ERR+" - "+c);r(u)}}a($v,"insertChunk");async function Mee(e){let t={records:0,number_written:0},r=Yv(e.schema,e.table);try{let s=new Mg,n=xs.createReadStream(e.file_path,{highWaterMark:xv});n.setEncoding("utf8"),await Dg.parsePromise(n,Vv.bind(null,e,s),Lg.bind(null,r));let i=s.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);return n=xs.createReadStream(e.file_path,{highWaterMark:xv}),n.setEncoding("utf8"),await Dg.parsePromise(n,$v.bind(null,e,t),Lg.bind(null,r)),n.destroy(),t}catch(s){throw ot(s,go(Dt.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,Hs.LOG_LEVELS.ERROR,Dt.PAPA_PARSE_ERR+s)}}a(Mee,"callPapaParse");function Yv(e,t){let r=Ree[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>Aee(i,n));return s}a(Yv,"createTransformMap");function Lg(e,t,r){let s=e.get(r);return s?s(t):Ca.autoCast(t)}a(Lg,"typeFunction");async function Pee(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Mg,n=Uv([xs.createReadStream(e.file_path,{encoding:"utf-8"}),Mv.withParser(),c=>c.value,new Pv({batchSize:qv}),vv(async c=>{await Vv(e,s,r,c)})]);await new Promise((c,u)=>{Bv(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);let o=Uv([xs.createReadStream(e.file_path,{encoding:"utf-8"}),Mv.withParser(),c=>c.value,new Pv({batchSize:qv}),vv(async c=>{await $v(e,t,r,c)})]);return await new Promise((c,u)=>{Bv(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw ot(s,go(Dt.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,Hs.LOG_LEVELS.ERROR,Dt.INSERT_JSON_ERR+s)}}a(Pee,"insertJson");async function Kv(e){let t={};try{e.data&&e.data.length>0&&vee(e.data[0])?t=await Bee(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Da.info(t.message))}catch(r){throw Ro(r)}return t}a(Kv,"callBulkFileLoad");function vee(e){let t=Object.keys(e);for(let r of t)if(!Oee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(vee,"validateColumnNames");async function Bee(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=vf.insert;break;case"update":i=vf.update;break;case"upsert":i=vf.upsert;break;default:throw ot(new Error,Dt.INVALID_ACTION_PARAM_ERR(s),Kt.BAD_REQUEST,Hs.LOG_LEVELS.ERROR,Dt.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Ca.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Ro(o)}}a(Bee,"bulkFileLoad");function Wv(e,t){return`successfully loaded ${t} of ${e} records`}a(Wv,"buildResponseMsg");function Ro(e){return ot(e,go(Dt.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,Hs.LOG_LEVELS.ERROR,Dt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Ro,"buildTopLevelErrMsg")});var Jv=T((Ghe,zv)=>{"use strict";var Hg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};zv.exports=Hg});var Zv=T((Vhe,jv)=>{"use strict";var Hee=D(),Xv=require("moment"),xee=require("uuid").v4,xg=class{static{a(this,"JobObject")}constructor(){this.id=xee(),this.type=void 0,this.start_datetime=Xv().valueOf(),this.created_datetime=Xv().valueOf(),this.end_datetime=void 0,this.status=Hee.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};jv.exports=xg});var qg=T((Yhe,i0)=>{"use strict";var qee=require("uuid").v4,r0=Lr(),s0=es(),Fee=Xs(),Gee=ea(),kee=Jv(),at=D(),Vee=Zv(),$ee=Sd(),ds=G(),Yee=Ic(),La=z(),{promisify:Kee}=require("util"),Ao=require("moment"),Wee=Sf(),qf=Ng(),e0=Om(),{deleteTransactionLogsBeforeValidator:Qee}=WT(),{handleHDBError:zee,hdb_errors:Jee}=Z(),{HTTP_STATUS_CODES:Xee}=Jee,t0=s0.searchByValue,jee=s0.searchByHash,Zee=r0.insert,ete=Kee(Wee.evaluateSQL),tte=r0.update;i0.exports={addJob:nte,updateJob:ote,handleGetJob:rte,handleGetJobsByStartDate:ste,getJobById:n0};async function rte(e){try{let t=await n0(e.id);return La.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 ds.error("There was an error getting job",t),new Error(r)}}a(rte,"handleGetJob");async function ste(e){try{let t=await ite(e);if(ds.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=Ao(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Ao(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 ds.error(r),new Error(r)}}a(ste,"handleGetJobsByStartDate");async function nte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||La.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return ds.info(l),t.error=l,t}if(!at.JOB_TYPE_ENUM[e.operation])return ds.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case at.OPERATIONS_ENUM.CSV_FILE_LOAD:s=qf.fileObject(e);break;case at.OPERATIONS_ENUM.CSV_URL_LOAD:s=qf.urlObject(e);break;case at.OPERATIONS_ENUM.CSV_DATA_LOAD:s=qf.dataObject(e);break;case at.OPERATIONS_ENUM.IMPORT_FROM_S3:s=qf.s3FileObject(e);break;case at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=e0(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=e0(e,"timestamp");break;case at.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=Qee(e);break;default:break}if(s)throw zee(s,s.message,Xee.BAD_REQUEST,void 0,void 0,!0);let n=new Vee;n.type=e.operation===at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new Fee(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await t0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return ds.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=qee();try{o=await t0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return ds.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return ds.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new Yee(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await Zee(u)}catch(l){return ds.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,ds.trace(l)}return t}a(nte,"addJob");async function ite(e){let t=Ao(e.from_date,Ao.ISO_8601),r=Ao(e.to_date,Ao.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new kee(s,e.hdb_user);try{return await ete(n)}catch(i){throw ds.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(ite,"getJobsInDateRange");async function n0(e){if(La.isEmptyOrZeroLength(e))return La.errorizeMessage("Invalid job ID specified.");let t=new Gee(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await jee(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return ds.error(s),La.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(n0,"getJobById");async function ote(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(La.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===at.JOB_STATUS_ENUM.COMPLETE||e.status===at.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Ao().valueOf());let t=new $ee(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await tte(t),r}a(ote,"updateJob")});var _0=T((Whe,l0)=>{"use strict";var o0=z(),Rr=D(),ate=require("moment"),Ff=vg(),Gf=G(),a0=qg(),c0=Tf(),u0=ti(),cte=Ye(),ute=df(),Fg=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function lte(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(o0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(o0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Rr.JOB_TYPE_ENUM.csv_file_load:await Bn(e,Ff.csvFileLoad);break;case Rr.JOB_TYPE_ENUM.csv_url_load:await Bn(e,Ff.csvURLLoad);break;case Rr.JOB_TYPE_ENUM.csv_data_load:await Bn(e,Ff.csvDataLoad);break;case Rr.JOB_TYPE_ENUM.import_from_s3:await Bn(e,Ff.importFromS3);break;case Rr.JOB_TYPE_ENUM.empty_trash:break;case Rr.JOB_TYPE_ENUM.export_local:await Bn(e,c0.export_local);break;case Rr.JOB_TYPE_ENUM.export_to_s3:await Bn(e,c0.export_to_s3);break;case Rr.JOB_TYPE_ENUM.delete_files_before:case Rr.JOB_TYPE_ENUM.delete_records_before:await Bn(e,u0.deleteFilesBefore);break;case Rr.JOB_TYPE_ENUM.delete_audit_logs_before:await Bn(e,u0.deleteAuditLogsBefore);break;case Rr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Bn(e,ute.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(lte,"parseMessage");async function Bn(e,t){try{e.job.status=Rr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=ate().valueOf(),await a0.updateJob(e.job),await _te(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):Gf.error(`There was an error running ${t.name} job with id ${e.job.id}`),Gf.error(s),e.job.message=s,e.job.status=Rr.JOB_STATUS_ENUM.ERROR;try{await a0.updateJob(e.job)}catch(n){throw Gf.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Bn,"runJob");async function _te(e){Gf.trace("launching job thread:",e),cte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Rr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(_te,"launchJobThread");l0.exports={parseMessage:lte,RunnerMessage:Fg}});var f0=T((zhe,d0)=>{"use strict";var Gg=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};d0.exports=Gg});var D0=T((Xhe,Wg)=>{"use strict";var Yf=es(),$g=Sf(),kf=vg(),Hn=uu(),Vf=jn(),il=ti(),dte=dS(),nl=rs(),$f=RS(),Wt=KT(),Lt=G(),fte=bS(),Ete=Cd(),E0=oT(),hte=Ld(),mte=aT(),pte=cT(),Ste=_T(),Tte=fT(),kg=mT(),h0=Tf(),gte=mf(),Yg=qg(),H=D(),{hdb_errors:al,handleHDBError:ol}=Z(),{HTTP_STATUS_CODES:m0}=al,Vg=RT(),p0=Qd(),y0=require("util"),Ua=Lr(),Rte=Rn(),Ate=_a(),S0=_0(),T0=hu(),g0=(ef(),ee(vu)),R0=Pr(),A0=df(),O0=of(),{setServerUtilities:Ote}=(xf(),ee(Bg)),{CONTEXT:bte}=(Ns(),ee(Sp)),{_assignPackageExport:Nte}=require("../index"),{transformReq:yte}=z(),{server:Ite}=(sr(),ee(Li)),wte=yg(),b0=Yf.searchByHash,Cte=Yf.searchByValue,Dte=y0.promisify(Yf.search),Lte=y0.promisify($g.evaluateSQL),Ute={[H.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[H.OPERATIONS_ENUM.CREATE_TABLE]:!0,[H.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[H.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[H.OPERATIONS_ENUM.DROP_TABLE]:!0,[H.OPERATIONS_ENUM.DROP_SCHEMA]:!0},k=f0();async function I0(e,t){try{if(e.body.operation!=="read_log"&&(Lt.log_level===H.LOG_LEVELS.INFO||Lt.log_level===H.LOG_LEVELS.DEBUG||Lt.log_level===H.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;Lt.info(o)}}catch(s){Lt.error(s)}let r=await wte.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Ute[e.body.operation]&&Rte.setSchemaDataToGlobal(s=>{s&&Lt.error(s)}),r}a(I0,"processLocalTransaction");var N0=Pte();Wg.exports={chooseOperation:w0,getOperationFunction:C0,operation:Kg,processLocalTransaction:I0};Ote(Wg.exports);Ite.operation=Kg;function w0(e){let t;try{t=C0(e)}catch(n){throw Lt.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=$g.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=$g.checkASTPermissions(e,i);if(o)throw Lt.error(`${m0.FORBIDDEN} from operation ${e.operation}`),Lt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),ol(new Error,o,al.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==H.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==H.OPERATIONS_ENUM.LOGIN&&e.operation!==H.OPERATIONS_ENUM.LOGOUT){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=gte.verifyPerms(i,n);if(o)throw Lt.error(`${m0.FORBIDDEN} from operation ${e.operation}`),Lt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),ol(new Error,o,al.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw ol(n,"There was an error when trying to choose an operation path")}return r}a(w0,"chooseOperation");function C0(e){if(Lt.trace(`getOperationFunction with operation: ${e.operation}`),N0.has(e.operation))return N0.get(e.operation);throw ol(new Error,al.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),al.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(C0,"getOperationFunction");Nte("operation",Kg);function Kg(e,t){e.hdb_user=this[bte]?.user,e.bypass_auth=!t;let r=w0(e);return I0({body:e},r)}a(Kg,"operation");async function Mte(e){Lt.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[H.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case H.OPERATIONS_ENUM.INSERT:o=await Ua.insert(i);break;case H.OPERATIONS_ENUM.UPDATE:o=await Ua.update(i);break;case H.OPERATIONS_ENUM.UPSERT:o=await Ua.upsert(i);break;case H.OPERATIONS_ENUM.DELETE:o=await il.deleteRecord(i);break;default:Lt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Lt.info("Invalid operation in transaction"),Lt.error(o)}}a(Mte,"catchup");async function ln(e){yte(e);let t,r;try{r=await Yg.addJob(e),t=r.createdJob,Lt.info("addJob result",r);let s=new S0.RunnerMessage(t,e);return await S0.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw Lt.error(n),ol(s,n)}}a(ln,"executeJob");function Pte(){let e=new Map;return e.set(H.OPERATIONS_ENUM.INSERT,new k(Ua.insert)),e.set(H.OPERATIONS_ENUM.UPDATE,new k(Ua.update)),e.set(H.OPERATIONS_ENUM.UPSERT,new k(Ua.upsert)),e.set(H.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new k(Yf.searchByConditions)),e.set(H.OPERATIONS_ENUM.SEARCH_BY_HASH,new k(b0)),e.set(H.OPERATIONS_ENUM.SEARCH_BY_ID,new k(b0)),e.set(H.OPERATIONS_ENUM.SEARCH_BY_VALUE,new k(Cte)),e.set(H.OPERATIONS_ENUM.SEARCH,new k(Dte)),e.set(H.OPERATIONS_ENUM.SQL,new k(Lte)),e.set(H.OPERATIONS_ENUM.CSV_DATA_LOAD,new k(ln,kf.csvDataLoad)),e.set(H.OPERATIONS_ENUM.CSV_FILE_LOAD,new k(ln,kf.csvFileLoad)),e.set(H.OPERATIONS_ENUM.CSV_URL_LOAD,new k(ln,kf.csvURLLoad)),e.set(H.OPERATIONS_ENUM.IMPORT_FROM_S3,new k(ln,kf.importFromS3)),e.set(H.OPERATIONS_ENUM.CREATE_SCHEMA,new k(Hn.createSchema)),e.set(H.OPERATIONS_ENUM.CREATE_DATABASE,new k(Hn.createSchema)),e.set(H.OPERATIONS_ENUM.CREATE_TABLE,new k(Hn.createTable)),e.set(H.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new k(Hn.createAttribute)),e.set(H.OPERATIONS_ENUM.DROP_SCHEMA,new k(Hn.dropSchema)),e.set(H.OPERATIONS_ENUM.DROP_DATABASE,new k(Hn.dropSchema)),e.set(H.OPERATIONS_ENUM.DROP_TABLE,new k(Hn.dropTable)),e.set(H.OPERATIONS_ENUM.DROP_ATTRIBUTE,new k(Hn.dropAttribute)),e.set(H.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new k(Vf.describeSchema)),e.set(H.OPERATIONS_ENUM.DESCRIBE_DATABASE,new k(Vf.describeSchema)),e.set(H.OPERATIONS_ENUM.DESCRIBE_TABLE,new k(Vf.describeTable)),e.set(H.OPERATIONS_ENUM.DESCRIBE_ALL,new k(Vf.describeAll)),e.set(H.OPERATIONS_ENUM.DELETE,new k(il.deleteRecord)),e.set(H.OPERATIONS_ENUM.ADD_USER,new k(nl.addUser)),e.set(H.OPERATIONS_ENUM.ALTER_USER,new k(nl.alterUser)),e.set(H.OPERATIONS_ENUM.DROP_USER,new k(nl.dropUser)),e.set(H.OPERATIONS_ENUM.LIST_USERS,new k(nl.listUsersExternal)),e.set(H.OPERATIONS_ENUM.LIST_ROLES,new k($f.listRoles)),e.set(H.OPERATIONS_ENUM.ADD_ROLE,new k($f.addRole)),e.set(H.OPERATIONS_ENUM.ALTER_ROLE,new k($f.alterRole)),e.set(H.OPERATIONS_ENUM.DROP_ROLE,new k($f.dropRole)),e.set(H.OPERATIONS_ENUM.USER_INFO,new k(nl.userInfo)),e.set(H.OPERATIONS_ENUM.READ_LOG,new k(fte)),e.set(H.OPERATIONS_ENUM.ADD_NODE,new k(Ete)),e.set(H.OPERATIONS_ENUM.UPDATE_NODE,new k(E0)),e.set(H.OPERATIONS_ENUM.SET_NODE_REPLICATION,new k(E0)),e.set(H.OPERATIONS_ENUM.REMOVE_NODE,new k(hte)),e.set(H.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new k(mte)),e.set(H.OPERATIONS_ENUM.PURGE_STREAM,new k(pte)),e.set(H.OPERATIONS_ENUM.SET_CONFIGURATION,new k(R0.setConfiguration)),e.set(H.OPERATIONS_ENUM.CLUSTER_STATUS,new k(Ste.clusterStatus)),e.set(H.OPERATIONS_ENUM.CLUSTER_NETWORK,new k(Tte)),e.set(H.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new k(kg.setRoutes)),e.set(H.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new k(kg.getRoutes)),e.set(H.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new k(kg.deleteRoutes)),e.set(H.OPERATIONS_ENUM.EXPORT_TO_S3,new k(ln,h0.export_to_s3)),e.set(H.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new k(ln,il.deleteFilesBefore)),e.set(H.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new k(ln,il.deleteFilesBefore)),e.set(H.OPERATIONS_ENUM.EXPORT_LOCAL,new k(ln,h0.export_local)),e.set(H.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new k(Yg.handleGetJobsByStartDate)),e.set(H.OPERATIONS_ENUM.GET_JOB,new k(Yg.handleGetJob)),e.set(H.OPERATIONS_ENUM.GET_FINGERPRINT,new k(Vg.getFingerprint)),e.set(H.OPERATIONS_ENUM.SET_LICENSE,new k(Vg.setLicense)),e.set(H.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new k(Vg.getRegistrationInfo)),e.set(H.OPERATIONS_ENUM.RESTART,new k(p0.restart)),e.set(H.OPERATIONS_ENUM.RESTART_SERVICE,new k(p0.restartService)),e.set(H.OPERATIONS_ENUM.CATCHUP,new k(Mte)),e.set(H.OPERATIONS_ENUM.SYSTEM_INFORMATION,new k(Ate.systemInformation)),e.set(H.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new k(ln,il.deleteAuditLogsBefore)),e.set(H.OPERATIONS_ENUM.READ_AUDIT_LOG,new k(dte)),e.set(H.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new k(T0.createTokens)),e.set(H.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new k(T0.refreshOperationToken)),e.set(H.OPERATIONS_ENUM.LOGIN,new k(g0.login)),e.set(H.OPERATIONS_ENUM.LOGOUT,new k(g0.logout)),e.set(H.OPERATIONS_ENUM.GET_CONFIGURATION,new k(R0.getConfiguration)),e.set(H.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new k(Wt.customFunctionsStatus)),e.set(H.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new k(Wt.getCustomFunctions)),e.set(H.OPERATIONS_ENUM.GET_COMPONENT_FILE,new k(Wt.getComponentFile)),e.set(H.OPERATIONS_ENUM.GET_COMPONENTS,new k(Wt.getComponents)),e.set(H.OPERATIONS_ENUM.SET_COMPONENT_FILE,new k(Wt.setComponentFile)),e.set(H.OPERATIONS_ENUM.DROP_COMPONENT,new k(Wt.dropComponent)),e.set(H.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new k(Wt.getCustomFunction)),e.set(H.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new k(Wt.setCustomFunction)),e.set(H.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new k(Wt.dropCustomFunction)),e.set(H.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new k(Wt.addComponent)),e.set(H.OPERATIONS_ENUM.ADD_COMPONENT,new k(Wt.addComponent)),e.set(H.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new k(Wt.dropCustomFunctionProject)),e.set(H.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new k(Wt.packageComponent)),e.set(H.OPERATIONS_ENUM.PACKAGE_COMPONENT,new k(Wt.packageComponent)),e.set(H.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new k(Wt.deployComponent)),e.set(H.OPERATIONS_ENUM.DEPLOY_COMPONENT,new k(Wt.deployComponent)),e.set(H.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new k(A0.readTransactionLog)),e.set(H.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new k(ln,A0.deleteTransactionLogsBefore)),e.set(H.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new k(O0.installModules)),e.set(H.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new k(O0.auditModules)),e.set(H.OPERATIONS_ENUM.GET_BACKUP,new k(Hn.getBackup)),e}a(Pte,"initializeOperationFunctionMap")});var Wf=T((Zhe,M0)=>{"use strict";var Qg=D(),vte=z(),cl=G(),{handleHDBError:zg,hdb_errors:Kf}=Z(),{isMainThread:Bte}=require("worker_threads"),{Readable:Hte}=require("stream"),L0=require("os"),xte=require("util"),qte=PS(),Fte=xte.promisify(qte.authorize),U0=D0(),{createGzip:Gte,constants:kte}=require("zlib");function Vte(e){let t=`Found an uncaught exception with message: ${e.message}. ${L0.EOL}Stack: ${e.stack} ${L0.EOL}Terminating ${Bte?"HDB":"thread"}.`;console.error(t),cl.fatal(t),process.exit(1)}a(Vte,"handleServerUncaughtException");function $te(e,t,r){if(cl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:Kf.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a($te,"serverErrorHandler");function Yte(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=zg(new Error,"Invalid JSON.",Kf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(vte.isEmpty(e.body.operation)){let s=zg(new Error,"Request body must include an 'operation' property.",Kf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(Yte,"reqBodyValidationHandler");function Kte(e,t,r){let s;e.body.operation!==Qg.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==Qg.OPERATIONS_ENUM.LOGIN&&e.body.operation!==Qg.OPERATIONS_ENUM.LOGOUT?Fte(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{cl.warn(n),cl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(zg(n,i,Kf.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(Kte,"authHandler");async function Wte(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=U0.chooseOperation(e.body);let n=await U0.processLocalTransaction(e,s);if(n instanceof Hte&&n.headers){for(let[i,o]of n.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),n=n.pipe(Gte({level:kte.Z_BEST_SPEED})))}return n}catch(n){throw cl.error(n),n}}a(Wte,"handlePostRequest");M0.exports={authHandler:Kte,handlePostRequest:Wte,handleServerUncaughtException:Vte,serverErrorHandler:$te,reqBodyValidationHandler:Yte}});var H0=T((tme,B0)=>{"use strict";var Qte=require("fastify-plugin"),{handlePostRequest:P0,authHandler:zte,reqBodyValidationHandler:Jte}=Wf();async function Xte(e){e.decorate("hdbCore",{preValidation:[Jte,zte],request:t=>v0(P0(t,response)),requestWithoutAuthentication:(t,r)=>v0(P0(t,r,!0))})}a(Xte,"hdbCore");async function v0(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(v0,"convertAsyncIterators");B0.exports=Qte(Xte)});var F0=T((nme,q0)=>{"use strict";var sme=require("fs"),Jg=j();Jg.initSync();var{CONFIG_PARAMS:x0}=D(),jte=1024*1024*1024;function Zte(e){let t=Jg.get(x0.HTTP_TIMEOUT),r=Jg.get(x0.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:jte,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Zte,"getServerOptions");q0.exports=Zte});var V0=T((ome,k0)=>{"use strict";var Xg=j();Xg.initSync();var{CONFIG_PARAMS:G0}=D();function ere(){let e=Xg.get(G0.HTTP_CORSACCESSLIST),t=Xg.get(G0.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(ere,"getCORSOptions");k0.exports=ere});var K0=T((cme,Y0)=>{"use strict";var $0=j();$0.initSync();var tre=D();function rre(){return $0.get(tre.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(rre,"getHeaderTimeoutConfig");Y0.exports=rre});var Zg={};$e(Zg,{customFunctionsServer:()=>ire,ready:()=>aB,start:()=>nre});function nre(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){xn||(xn=oB(t),_t.http((await xn).server));let o=await xn,c=(0,jg.dirname)(n),u=(0,jg.dirname)(s);if(u.startsWith("/")&&(u=u.slice(1)),!W0.has(c)){W0.add(c);try{o.register(are(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ge.warn(`Could not load root fastify route for ${n}, this may require a restart to install properly`);else throw _}}},ready:aB}}async function ire(){try{Ge.info("In Custom Functions Fastify server"+process.cwd()),Ge.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ge.debug(`Custom Functions server process ${process.pid} starting up.`),await ore();let e=Z0.get(eB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=xn=await oB(e)}catch(r){throw Ge.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ge.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ge.error(`Custom Functions ${process.pid} Error: ${e}`),Ge.error(e),process.exit(1)}}async function ore(){try{Ge.info("Custom Functions starting configuration."),await tB.setUsersToGlobal(),Ge.info("Custom Functions completed configuration.")}catch(e){Ge.error(e)}}function are(e,t){return async function(r){try{Ge.info("Custom Functions starting buildRoutes"),Ge.trace("Loading fastify routes folder "+e),(0,Q0.existsSync)(e)&&r.register(j0.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ge.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?Ge.error(n.message):n&&Ge.error(n),o()})}catch(s){Ge.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function oB(e){Ge.info("Custom Functions starting buildServer.");let t=(0,rB.default)(e),r=(0,z0.default)(t);r.server.headersTimeout=(0,nB.default)(),r.setErrorHandler(iB.serverErrorHandler);let s=(0,sB.default)();return s&&r.register(J0.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(X0.default),await r.register(sre),await r.after(),mg(r),Ge.info("Custom Functions completed buildServer."),r}function aB(){if(xn)return xn.then?xn.then(e=>e.ready()):xn.ready()}var jg,Q0,z0,J0,X0,j0,Z0,eB,Ge,sre,tB,rB,sB,nB,iB,xn,W0,cB=Ae(()=>{jg=require("path"),Q0=require("fs"),z0=v(require("fastify")),J0=v(require("@fastify/cors")),X0=v(Rg()),j0=v(require("@fastify/autoload")),Z0=v(j()),eB=v(D()),Ge=v(G()),sre=v(H0()),tB=v(rs()),rB=v(F0()),sB=v(V0()),nB=v(K0()),iB=v(Wf());Ta();sr();W0=new Set;a(nre,"start");a(ire,"customFunctionsServer");a(ore,"setUp");a(are,"buildRouteFolder");a(oB,"buildServer");a(aB,"ready")});var eR={};$e(eR,{start:()=>cre});function cre(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,fB.default)(r,e);return e.server.http(async(n,i)=>{if(!n.isWebSocket)return new Promise(o=>s(n._nodeRequest,n._nodeResponse,()=>{o(i(n))}))}),!0}},handleFile(t,r,s){lB||(lB=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=uB.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,_B.default)(n,(0,dB.realpathSync)(o))}}return i(n)},{runFirst:!0})),uB.set(r,s)}}}var _B,dB,fB,uB,lB,EB=Ae(()=>{_B=v(require("send")),dB=require("fs"),fB=v(require("serve-static")),uB=new Map;a(cre,"start")});function _re(e,t=1,r){if(tR++,(0,Oo.startWorker)("server/threads/threadServer.js",{name:Jf.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(_){_.type===Jf.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});lre.push(n),await n,Ma.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=zf.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=Ma.indexOf(s);o>-1&&Ma.splice(o,1)}if(a(i,"removeWorker"),Pa){let o=Pa;Pa=[];for(let c of o)SB[c.localPort](null,c)}}}),r){let s=setInterval(()=>{rR?rR=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Oo.shutdownWorkers)(),tR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function TB(e=0,t){if(typeof e=="string")try{(0,Xf.existsSync)(e)&&(0,Xf.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=dre:r=fre(t):r=nR;let s=(0,va.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=SB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),rR=!0,r(o,(c,u)=>{if(!c){if(hB){let l=o._socket||new va.Socket({handle:o,writable:!0,readable:!0});hB.deliverSocket(l,e,u),l.resume()}else tR>0?(Pa.length===0&&setTimeout(()=>{Pa.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,Pa.push(o)):(console.log("start up a dynamic thread to handle request"),_re(0));qr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new va.Socket({handle:o,writable:!0,readable:!0});pre(l,c,e)}qr(!0,"socket-routed")})};let n=jc();sR.info(`HarperDB ${n.version} Server running on port ${e}`)}return s.on("error",n=>{console.error("Error in socket server",n)}),process.env._UNREF_SERVER&&s.unref(),s}function nR(e,t){let r,s=0;for(let n of Ma){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=Qf)return Qf=i,t(r);s=i}Qf=0,t(r)}function dre(e,t){let r={};e.getpeername(r);let s=r.address,n=Ba.get(s),i=Date.now();if(n&&n.worker.threadId!==-1)return n.lastUsed=i,t(n.worker);nR(e,o=>{Ba.set(s,{worker:o,lastUsed:i}),t(o)})}function fre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){let i=new va.Socket({handle:s,readable:!0,writable:!0});s._socket=i,i.on("data",o=>{s.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ba.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,n(_.worker);nR(s,d=>{Ba.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function hre(){Qf=0;for(let e of Ma)e.expectedIdle=e.recentELU.idle+Ere,e.requests=1;Ma.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function pre(e,t,r){let s=mre++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),zf.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),zf.delete(s)),n.event=="destroy"&&(e.destroy(),zf.delete(s))})}var Oo,va,Jf,sR,Xf,pB,ure,Ma,Pa,SB,hB,tR,lre,rR,Qf,mB,Ba,Ere,zf,mre,gB=Ae(()=>{Oo=v(Ye()),va=require("net"),Jf=v(D()),sR=v(G()),Xf=require("fs");yn();pB=require("worker_threads"),ure=v(Yi()),Ma=[],Pa=[],SB=[],tR=0,lre=[];pB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(_re,"startHTTPWorker");a(TB,"startSocketServer");Qf=0;a(nR,"findMostIdleWorker");mB=36e5,Ba=new Map;a(dre,"findByRemoteAddressAffinity");a(fre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ba)r.lastUsed+mB<e&&Ba.delete(t)},mB).unref();Ere=1e3;a(hre,"updateWorkerIdleness");(0,Oo.setMonitorListener)(hre);zf=new Map,mre=1;a(pre,"proxySocket")});var cR={};$e(cR,{Request:()=>iR,createReuseportFd:()=>jf});var RB,iR,oR,aR,jf,Zf=Ae(()=>{RB=require("os"),iR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let s=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=s,this.headers=new aR(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 oR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},oR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},aR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,s]of this)t(s,r,this)}};(0,RB.platform)()!="win32"&&(jf=require("node-unix-socket").createReuseportFd)});var NB=T((Ome,bB)=>{"use strict";var Sre=require("cluster"),bo=j();bo.initSync();var OB=D(),Sme=require("util"),qn=G(),Tme=require("fs"),Tre=require("fastify"),gme=jc(),gre=require("@fastify/cors"),Rre=require("@fastify/compress"),Are=require("@fastify/static"),Ore=Rg(),bre=require("path"),{PACKAGE_ROOT:Nre}=D(),yre=Rn(),Ire=z(),wre=rs(),Cre=Yi(),{server:Dre}=(sr(),ee(Li)),{node_request_key:Rme}=(Zf(),ee(cR)),{authHandler:Lre,handlePostRequest:Ure,serverErrorHandler:Mre,reqBodyValidationHandler:Pre}=Wf(),Ame=require("net"),{registerContentHandlers:vre}=(Ta(),ee(fv)),Bre=6e4,Hre=1024*1024*1024,xre="TRUE",{CONFIG_PARAMS:ul}=OB,Ha;bB.exports={hdbServer:AB,start:AB};async function AB(e){try{qn.info("In Fastify server"+process.cwd()),qn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),qn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Sre.isMaster,await qre();let t=e.securePort>0;Ha=Fre(t),await Ha.ready(),e||(e={}),e.isOperationsServer=!0;try{Dre.http(Ha.server,e),Ha.server.closeIdleConnections||await Ha.listen({port:0,host:"::"})}catch(r){throw Ha.close(),qn.error(r),qn.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),qn.fatal(t),process.exit(1)}}a(AB,"operationsServer");async function qre(){qn.trace("Configuring HarperDB process."),yre.setSchemaDataToGlobal(),await wre.setUsersToGlobal(),await Cre.getLicense()}a(qre,"setUp");function Fre(e){qn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Gre(e),r=Tre(t);r.server.headersTimeout=Vre(),r.setErrorHandler(Mre);let s=kre();s&&r.register(gre,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Ore),r.register(Rre),r.register(Are,{root:bre.join(Nre,"studio/build-local")}),vre(r);let n=bo.get(OB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Ire.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Pre,Lre],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Ure(i,o)}),r.get("/health",()=>"HarperDB is running."),qn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Fre,"buildServer");function Gre(e){let t=bo.get(ul.OPERATIONSAPI_NETWORK_TIMEOUT),r=bo.get(ul.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Hre,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Gre,"getServerOptions");function kre(){let e=bo.get(ul.OPERATIONSAPI_NETWORK_CORS),t=bo.get(ul.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===xre)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(kre,"getCORSOpts");function Vre(){return bo.get(ul.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Bre}a(Vre,"getHeaderTimeoutConfig")});var vB=T((wme,PB)=>{"use strict";var{decode:$re}=require("msgpackr"),{isMainThread:Nme,parentPort:Yre,threadId:yme}=require("worker_threads"),lR=nt(),Fn=qe(),Kre=D(),bi=G(),yB=j(),wB=D();Ye();var Wre=gn(),{recordAction:Qre,recordActionBinary:zre}=(yn(),ee(ru)),{publishToStream:Jre}=lR,{ConsumerEvents:Xre}=require("nats"),Ime={durable:Fn.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Fn.WORK_QUEUE_CONSUMER_NAMES.deliver_group},jre,Zre,ese,CB,DB;PB.exports={initialize:_R,workQueueListener:MB,setSubscription:tse,setIgnoreOrigin:sse,getDatabaseSubscriptions:rse};async function _R(){DB=!0,bi.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await lR.getNATSReferences();jre=e,Zre=e.info.server_name,ese=t,CB=r}a(_R,"initialize");var tE=new Map;function tse(e,t,r){let s=tE.get(e);s||tE.set(e,s=new Map),s.set(t,r),DB||_R().then(MB)}a(tse,"setSubscription");function rse(){return tE}a(rse,"getDatabaseSubscriptions");var LB;function sse(e){LB=e}a(sse,"setIgnoreOrigin");var UB=100,IB=new Array(UB),eE=0;async function MB(){let e=await CB.consumers.get(Fn.WORK_QUEUE_CONSUMER_NAMES.stream_name,Fn.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(Yre?.on("message",async s=>{let{type:n}=s;n===wB.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let s of await r.status())if(s.type===Xre.HeartbeatsMissed){let n=s.data;bi.trace(`${n} clustering ingest consumer heartbeats missed`),n===2&&(bi.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let s of r)await IB[eE],IB[eE]=nse(s).catch(n=>{bi.error(n)}),++eE>=UB&&(eE=0)}catch(s){bi.error("Error consuming clustering ingest, restarting consumer",s)}lR.clearClientCache(),await _R()}}a(MB,"workQueueListener");async function nse(e){let t=$re(e.data);Qre(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,s=!1,n=yB.get(Kre.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Fn.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Fn.MSG_HEADERS.TRANSACTED_NODES).indexOf(n)>-1&&(s=!0);let i=r.get(Fn.MSG_HEADERS.ORIGIN);if(s||(s=i===n&&!LB),zre(s,"echo",e.subject,t.operation,"ingest"),s){e.ack();return}r.append(Fn.MSG_HEADERS.TRANSACTED_NODES,n);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;bi.trace("processing message:",o,c,_,(l?"records: "+l.map(w=>w?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),bi.trace(`messageProcessor nats msg id: ${e.headers.get(Fn.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:R}=f||{},I=tE.get(c)?.get(_);if(!I)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,I.send(t);else if(l.length===1&&!u)I.send({type:uR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:R});else{let w=l.map((B,K)=>({type:uR(o),value:B,expiresAt:E,id:d?.[K],table:_}));for(;u;)w.push({type:uR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;I.send({type:"transaction",writes:w,table:_,timestamp:p,onCommit:h,user:S,nodeName:R})}yB.get(wB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Jre(e.subject.split(".").slice(0,-1).join("."),Wre.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){bi.error(o)}e.ack()}a(nse,"messageProcessor");function uR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(uR,"convertOperation")});var pR={};$e(pR,{disableNATS:()=>ose,publishToStream:()=>oE,setNATSReplicator:()=>dR,setPublishToStream:()=>ase,setSubscription:()=>mR,start:()=>ise});function ise(){sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&use()}function ose(e=!0){FB=e}function ase(e,t){oE=e,mR=t}function use(){if(FB||process.env._DISABLE_NATS)return;let e=Ms(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];dR(n,r,i)}}SR((r,s)=>{dR(r.tableName,r.databaseName,r),s&&kB(r)}),!BB&&(BB=!0)}function dR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(n=>n?.isNATSReplicator))return;r.sourcedFrom(class extends qt{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[De],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[De]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[De],record:i})}patch(i){return s(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[De],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[De]})}static defineSchema(i){kB(i)}static subscribe(){let i=new bs;return mR(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 s(n){let i=n?.transaction?.nats;if(!i)if(n?.transaction){n.transaction.nats=i=new rE(n.transaction,n);let o=n.transaction;for(;o.next;)o=o.next;o.next=n.transaction.nats,i.user=n.user,i.context=n}else i=GB;return i}a(s,"getNATSTransaction")}function kB(e){let t=sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);oE(`${ER.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,hR.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 HB,ER,hR,xB,qB,sE,nE,iE,FB,oE,mR,cse,GB,BB,rE,fR,VB=Ae(()=>{ge();Ns();HB=v(nt()),ER=v(qe()),hR=v(gn());dc();xB=v(vB()),qB=v(wr()),sE=v(j()),nE=v(D()),iE=v(G());a(ise,"start");a(ose,"disableNATS");oE=HB.publishToStream,mR=xB.setSubscription;a(ase,"setPublishToStream");cse=2;a(use,"assignReplicationSource");a(dR,"setNATSReplicator");a(kB,"publishSchema");rE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let s=this.writes_by_db.get(t);s||this.writes_by_db.set(t,s=[]),s.push(r)}commit({timestamp:t}){let r=sE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(iE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&s.push(oE(`${ER.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,hR.createNatsTableStreamName)(n,u.table),void 0,u)?.catch(l=>{throw iE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(s)}},fR=class extends rE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,qB.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};GB=new fR});var sH=T(yo=>{"use strict";var{isMainThread:lse,parentPort:dl,threadId:ll}=require("worker_threads"),{Socket:_se,createServer:dse}=require("net"),{createServer:fse,IncomingMessage:Ese}=require("http"),{createServer:hse}=require("https"),{readFileSync:xa,unlinkSync:$B,existsSync:mse}=require("fs"),qs=G(),ke=j(),Ar=D(),{server:uE}=(sr(),ee(Li)),{WebSocketServer:pse}=require("ws"),{createServer:Sse}=require("tls"),{getTicketKeys:Tse,restartNumber:gse,getWorkerIndex:YB}=Ye(),{Headers:JB}=(Jd(),ee(xM)),{recordAction:_l,recordActionBinary:Rse}=(yn(),ee(ru)),{Request:XB,createReuseportFd:KB}=(Zf(),ee(cR)),{checkMemoryLimit:Ase}=Yi(),jB=require("tls"),WB=jB.createSecureContext;jB.createSecureContext=function(e){if(!e.cert||!e.key)return WB(e);let t={...e};delete t.key,delete t.cert;let r=WB(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&&qs.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:vme,CONFIG_PARAMS:Ose}=Ar;ke.initSync();var bse=ke.get(Ose.HTTP_SESSIONAFFINITY),_n={};yo.registerServer=OR;yo.httpServer=bR;yo.deliverSocket=AR;yo.startServers=ZB;yo.when_components_loaded=null;uE.http=bR;uE.request=wse;uE.socket=Cse;uE.ws=Dse;var TR=[],aE=[],Nse,No={},cE={},yse=[],gR=[];function ZB(){return yo.when_components_loaded=NR().loadRootComponents(!0).then(()=>{dl?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)AR(s,r,n);else if(t.requestId)Ise(t);else if(t.type===Ar.ITC_EVENT_TYPES.SHUTDOWN){qs.trace("received shutdown request",ll);for(let i in _n){let o=_n[i],c;o.closeIdleConnections&&(setInterval(()=>{o.closeIdleConnections()},25).unref(),setTimeout(()=>{o.closeAllConnections(),qs.info("Closed all http connections",i,ll)},4e3).unref()),o.close?.(()=>{if(ke.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&YB()==0)try{$B(ke.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,ll),o.cantCleanupProperly||qs.warn("Had to forcefully exit the thread",ll),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(KB&&!bse)for(let t in _n){let r=_n[t];if(isNaN(t)&&YB()==0){mse(t)&&$B(t),e.push(new Promise((n,i)=>{r.listen({path:t},()=>{n(),qs.info("Domain socket listening on "+t)}).on("error",i)}));continue}let s;try{s=KB(+t,"::")}catch(n){console.error(`Unable to bind to port ${t}`,n);continue}e.push(new Promise((n,i)=>{r.listen({fd:s},()=>{n(),qs.trace("Listening on port "+t,ll)}).on("error",i)}))}Promise.all(e).then(()=>{dl?.postMessage({type:Ar.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(ZB,"startServers");lse||ZB();function AR(e,t,r){let s=e?.read?e:new _se({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),n=_n[t];if(n.isSecure&&(s.startTime=performance.now()),n)typeof n=="function"?n(s):n.emit("connection",s),r&&s.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=_n[t];c?(typeof c=="function"?c(s):c.emit("connection",s),r&&s.emit("data",r)):o<5?i(o+1):(qs.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(AR,"deliverSocket");var QB=new Map;function Ise(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=QB.get(n),r){case"connection":i=AR(void 0,t),QB.set(n,i),i.write=(c,u,_)=>(dl.postMessage({requestId:n,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(dl.postMessage({requestId:n,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),dl.postMessage({requestId:n,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(s,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(Ise,"proxyRequest");function OR(e,t,r=!0){!+t&&t!==ke.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(ke.get(Ar.CONFIG_PARAMS.HTTP_PORT),10));let s=_n[t];if(s){let n=s.lastServer||s;if(n===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!n.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);n.off("unhandled",zB),n.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(s.cantCleanupProperly=!0),e.emit("request",i,o)}),s.lastServer=e}else _n[t]=e;e.on("unhandled",zB)}a(OR,"registerServer");function eH(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=[],ke.get(Ar.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:ke.get(Ar.CONFIG_PARAMS.HTTP_PORT),secure:ke.get(Ar.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),ke.get(Ar.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:ke.get(Ar.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&ke.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:ke.get(Ar.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(eH,"getPorts");function bR(e,t){for(let{port:r,secure:s}of eH(t))tH(r,s,t?.isOperationsServer),typeof e=="function"?gR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=s,OR(e,r,!1)),cE[r]=RR(gR,r),Nse=RR(yse,r)}a(bR,"httpServer");function tH(e,t,r){if(!No[e]){let s=r?"operationsApi_network":"http",n={keepAliveTimeout:ke.get(s+"_keepAliveTimeout"),headersTimeout:ke.get(s+"_headersTimeout"),requestTimeout:ke.get(s+"_timeout")},i=ke.get(s+"_mtls");if(t){s=r?"operationsApi_":"";let c=ke.get(s+"tls_privateKey"),u=ke.get(s+"tls_certificate"),_=ke.get(s+"tls_certificateAuthority");Object.assign(n,{allowHTTP1:!0,key:xa(c),ciphers:ke.get("tls_ciphers"),cert:xa(u),ca:_&&xa(_),requestCert:!!i,ticketKeys:Tse()})}let o=Ase();No[e]=(t?hse:fse)(n,async(c,u)=>{try{let l=performance.now(),d=new XB(c,u);r&&(d.isOperationsServer=!0);let f=await cE[e](d);if(!f){if(d._nodeResponse.statusCode)return;f=rH(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 B of f.headers||[])u.setHeader(B[0],B[1]);return c.baseRequest=d,u.baseResponse=f,No[e].emit("unhandled",c,u)}let E=f.status||200,h=performance.now(),p=h-l,S=f.body,R;if(!f.handlesHeaders){let B=f.headers||new JB;if(S?S.length>=0&&(typeof S=="string"?B.set("Content-Length",Buffer.byteLength(S)):B.set("Content-Length",S.length),R=!0):(B.set("Content-Length","0"),R=!0),B.append){let K=`hdb;dur=${p.toFixed(2)}`;f.wasCacheMiss&&(K+=", miss"),B.append("Server-Timing",K,!0)}u.writeHead(E,B&&(B[Symbol.iterator]?Array.from(B):B)),R&&u.end(S)}let I=d.handlerPath,w=d.method;if(_l(p,"duration",I,w,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),Rse(E<400,"success",I,w),!R)if(S?.pipe){S.pipe(u),S.destroy&&u.on("close",()=>{S.destroy()});let B=0;S.on("data",K=>{B+=K.length}),S.on("end",()=>{_l(performance.now()-h,"transfer",I,w),_l(B,"bytes-sent",I,w)})}else S?.then?S.then(B=>{u.end(B)},_):u.end(S)}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?qs.warn(l):qs.info(l):qs.error(l)}a(_,"onError")}),t&&(No[e].on("secureConnection",c=>{c._parent.startTime&&_l(performance.now()-c._parent.startTime,"tls-handshake",e),_l(c.isSessionReused(),"tls-reused",e)}),No[e].isSecure=!0),OR(No[e],e)}return No[e]}a(tH,"getHTTPServer");function RR(e,t){let r=rH;for(let s=e.length;s>0;){let{listener:n,port:i}=e[--s];if(i===t||i==="all"){let o=r;r=a(c=>n(c,o),"next_callback")}}return r}a(RR,"makeCallbackChain");function rH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new JB}}a(rH,"unhandled");function wse(e,t){bR(e,{requestOnly:!0,...t})}a(wse,"onRequest");function Cse(e,t){let r;if(t.securePort){let s=ke.get("tls_privateKey"),n=ke.get("tls_certificate"),i=t.mtls?.certificateAuthority||ke.get("tls_certificateAuthority");r=Sse({ciphers:ke.get("tls_ciphers"),key:xa(s),cert:xa(n),ca:i&&xa(i),requestCert:!!t.mtls},e),_n[t.securePort]=r}return t.port&&(r=dse(e),_n[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){for(let{port:r,secure:s}of eH(t)){aE[r]||(aE[r]=new pse({server:tH(r,s)}),aE[r].on("connection",async(i,o)=>{try{let c=new XB(o);c.isWebSocket=!0;let u=cE[r](c),_=o.headers["sec-websocket-protocol"]||"";for(let l=0;l<TR.length;l++){let d=TR[l];if(d.protocol){if(d.protocol===_){d.listener(i,c,u);break}}else d.listener(i,c,u)}}catch(c){qs.warn("Error handling WebSocket connection",c)}}),aE[r].on("error",i=>{console.log("Error in setting up WebSocket server",i)}));let n=t?.subProtocol||"";TR.push({listener:e,protocol:n}),cE[r]=RR(gR,r)}}a(Dse,"onWebSocket");function zB(e,t){t.writeHead(404),t.end(`Not found
|
|
27
|
-
`)}a(zB,"defaultNotFound")});async function aH({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await yR.getResource(e,{});n=new CR(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await yR.get(e);i&&i.delete()}n=new _E(e,t)}return s&&(s.id=e,s.user={username:t?.username},fl.put(s)),n}function IR(){return lE++,lE>65500&&(lE=1),lE}function wR(e,t,r=e){let{topic:s,retain:n}=e;e.data=t,e.async=!0,e.authorize=!0;let i=pi.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Xe(r,()=>n?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var nH,Io,iH,oH,yR,fl,lE,_E,CR,cH=Ae(()=>{ge();Pu();nH=v(wr()),Io=v(G());Xi();iH=v(Ye()),oH=v(sH());sr();yR=dt({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"}]}}]}),fl=dt({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,iH.getWorkerIndex)()===0&&(async()=>{await oH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of fl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await _t.getUser(r.user.username)),Xe(r,()=>{try{wR(r,t)}finally{fl.delete(e.id,r)}})}})();a(aH,"getSession");lE=1;a(IR,"getNextMessageId");_E=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,rh:i,startTime:o}=t,c=n.indexOf("?"),u,_;if(c>-1?(u=n.slice(c),_=n.slice(0,c)):_=n,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(R=>R.topic===n),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Io.trace)("Resuming subscription from",n,"from",o);let E=pi.getMatch(_);if(!E){let R=new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);throw R.statusCode=404,R}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let R=f.url.slice(1);if(R.indexOf("#")>-1&&R.indexOf("#")!==R.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,R.indexOf("+")===R.length-1)f.onlyChildren=!0,f.url="/"+R.slice(0,R.length-1);else{let I=R.split("/"),w;for(let q=0;q<I.length;q++)if(I[q].indexOf("+")>-1)if(I[q]==="+")w=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(s&&w)throw new Error("Filters can not be combined");let B=!0;I[I.length-1]==="#"&&(I.length--,B=!1),w&&(s=a(q=>{let P=q.id;if(!Array.isArray(P)||B&&P.length!==I.length)return!1;for(let Q=0;Q<I.length;Q++)if(I[Q]!=="+"&&I[Q]!==P[Q])return!1;return!0},"filter"));let K=I.indexOf("+");f.url="/"+(K>-1?I.slice(0,K):I).concat("").join("/")}}let h=E.path,p=E.Resource,S=await Xe(f,async()=>{let R=await p.subscribe(f);if(!R)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!R[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let I of R)try{let w;if(I.type&&I.type!=="put"&&I.type!=="delete"&&I.type!=="message"&&I.type!=="patch"||s&&!s(I))continue;r?(I.topic=n,w=this.needsAcknowledge(I)):(I.acknowledge?.(),w=IR());let B=I.id;Array.isArray(B)&&(B=Sa(B)),B==null&&(B=""),this.listener(h+"/"+B,I.value,w,t)}catch(w){(0,Io.warn)(w)}})(),R});return S.topic=n,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=IR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,wR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Xe(r,async()=>{if(!t){let s=await fl.get(this.sessionId,r);s?.doesExist()&&await wR(s,s.data,r)}await fl.delete(this.sessionId,r)}).catch(s=>{(0,Io.warn)(`Error publishing MQTT will for ${this.sessionId}`,s)});for(let s of this.subscriptions)s.end();this.subscriptions=[]}};a(wR,"publish");CR=class extends _E{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=IR(),s={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(s.acknowledge=t.acknowledge),this.awaitingAcks.set(r,s),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Io.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,nH.getNextMonotonicTime)()),(0,Io.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),yR.put(this.sessionRecord)),t.qos}}});var DR={};$e(DR,{bypassAuth:()=>Lse,start:()=>Use});function Lse(){fH=!0}function Use({server:e,port:t,network:r,webSocket:s,securePort:n,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i},c,u=r?.mtls;return s&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=_H(_,(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,Or.info)("WebSocket error",h)})}},{subProtocol:"mqtt"})),(t||n)&&(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 return(0,Or.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end();!l&&fH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,dH.getSuperUser)());let{onMessage:d,onClose:f}=_H(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Or.info)("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function _H(e,t,r,s,n){lH||(lH=!0,tu(d=>{dE>0&&d.push({metric:"mqtt-connections",connections:dE,byThread:!0})}));let i;dE++;let o,c={protocolVersion:4},u=(0,EE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){dE--,i||(i=!0,o?.disconnect(),ss(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{s?.then&&(s=await s),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{s=await _t.getUser(d.username,d.password.toString(),r),(0,fE.get)(dn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&uH.notify({username:s.username,status:dn.AUTH_AUDIT_STATUS.SUCCESS,type:dn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,fE.get)(dn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&uH.error({username:s.username,status:dn.AUTH_AUDIT_STATUS.FAILURE,type:dn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!s&&n.requireAuthentication)return ss(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(n.authorizeClient?.(d,s),d.will){let w=e.deserialize||(e.deserialize=mo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?w(d.will.payload):void 0,delete d.will.payload}o=aH({user:s,...d}),o=await o}catch(w){return(0,Or.error)(w),ss(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:w.code||5,returnCode:w.code||128})}ss(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((w,B,K,q)=>{try{let P=w.indexOf("/",1),Q=P>0?w.slice(0,P):w;f({cmd:"publish",topic:w,payload:E(B),messageId:K||Math.floor(Math.random()*1e8),qos:q.qos},Q)}catch(P){(0,Or.error)(P),o?.disconnect()}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let w of d.subscriptions){let B;try{B=(await o.addSubscription(w,w.qos>=1)).qos||0}catch(K){(0,Or.error)(K),B=c.protocolVersion<5?128:K.statusCode===403?135:K.statusCode===404?143:128}h.push(B)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let w=[];for(let B of d.unsubscriptions)w.push(o.removeSubscription(B)?0:17);f({cmd:"unsuback",granted:w,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=mo(r?.headers.get?.("content-type"))),R=d.payload?.length>0?S(d.payload):void 0,I;try{I=await o.publish(d,R)}catch(w){(0,Or.warn)(w),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:I===!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),ss(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Or.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,EE.generate)(h,c);t(S),qr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ti(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var EE,dH,fE,dn,Or,uH,fH,lH,dE,EH=Ae(()=>{EE=require("mqtt-packet");cH();dH=v(rs());Ta();yn();sr();fE=v(j()),dn=v(D()),Or=v(G()),uH=(0,Or.loggerWithTag)("auth-event"),fH=(0,fE.get)(dn.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Lse,"bypassAuth");a(Use,"start");dE=0;a(_H,"onSocket")});var uf={};$e(uf,{component_errors:()=>Fa,loadComponent:()=>hE,loadComponentDirectories:()=>OH,setErrorReporter:()=>Bse});function OH(e,t){t&&(UR=t),e&&(MR=e);let r=[];if((0,Fs.existsSync)(LR)){let n=(0,Fs.readdirSync)(LR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Ot.join)(LR,o);r.push(hE(c,UR,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(hE(s,UR,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{AH=!0})}function Bse(e){hl=e}async function hE(e,t,r,s,n,i){if(!mH.has(e)){mH.set(e,!0),n&&(MR=n);try{let o;s&&(Fa=new Map);let c=(0,Ot.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Fs.existsSync)(c)?o=s?(0,RH.getConfigObj)():(0,pH.parseDocument)((0,Fs.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=PR;let u=[],_=s;for(let l in o){let d=o[l];if(Fa.set(s?l:(0,Ot.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let I=e,w;for(;!(0,Fs.existsSync)(w=(0,Ot.join)(I,"node_modules",l));)if(I=(0,Ot.dirname)(I),I.length<(0,gH.getHdbBasePath)().length){w=null;break}if(w)f=await hE(w,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(I=>(I.origin=r,dt(I)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,R=!p?.https&&p?.port;if(qa.isMainThread&&(f=await f.startOnMainThread?.({server:_t,ensureTable:h,port:R,securePort:S,resources:t,...d})||f,s&&p))for(let I of[R,S])try{if(+I&&!hH.includes(I)){let w=vR.get(BR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);w&&El.default.warn("Session affinity is not recommended and may cause memory leaks"),(w||!jf)&&(hH.push(I),TB(I,w))}}catch(w){console.error("Error listening on socket",I,w,l)}if(t.isWorker&&(f=await f.start?.({server:_t,ensureTable:h,port:R,securePort:S,resources:t,...d})||f),MR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,TH.handleHDBError)("Can not reference parent directories");let I=(0,Ot.join)(e,d.files).replace(/\\/g,"/"),w=I.indexOf("/*");if(w>-1&&d.files!==PR[l]?.files&&!(0,Fs.existsSync)(I.slice(0,w)))throw new Error(`The path '${I.slice(0,w)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let B=(0,Ot.basename)(e),K=d.path||"/";K=K.startsWith("/")?K:K.startsWith("./")?"/"+B+K.slice(2):K==="."?"/"+B:"/"+B+"/"+K;let q,P,Q;if(d.root){let J=d.root;J.startsWith("/")&&(J=J.slice(1)),J.endsWith("/")&&(J=J.slice(0,-1)),J+="/",P=(0,Ot.join)(e,J)}else(Q=I.indexOf("/*"))>-1&&(P=I.slice(0,Q+1),q=(0,Ot.relative)(e,P));let Y=!1;if(qa.isMainThread&&f.setupDirectory&&(Y=await f.setupDirectory?.(K,P,t)),t.isWorker&&f.handleDirectory&&(Y=await f.handleDirectory?.(K,P,t)),Y)continue;for(let J of await(0,SH.default)(I,{onlyFiles:!1,objectMode:!0})){let{path:re,dirent:Ie}=J;_=!0;let se=(0,Ot.relative)(e,re).replace(/\\/g,"/");if(q)if(se.startsWith(q))se=se.slice(q.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${se}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let ut=K+(K.endsWith("/")?"":"/")+se;try{if(Ie.isFile()){let de=await Pse(re);qa.isMainThread&&await f.setupFile?.(de,ut,re,t),t.isWorker&&await f.handleFile?.(de,ut,re,t)}else qa.isMainThread&&await f.setupDirectory?.(ut,re,t),t.isWorker&&await f.handleDirectory?.(ut,re,t)}catch(de){de.message=`Could not load ${Ie.isFile()?"file":"directory"} '${re}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${de.message}`,hl?.(de),((0,Ga.getWorkerIndex)()===0?console:El.default).error(de),t.set(d.path||"/",new ml(de)),Fa.set(s?l:(0,Ot.basename)(e),de.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Ot.basename)(e)}' due to: ${h.message}`,hl?.(h),((0,Ga.getWorkerIndex)()===0?console:El.default).error(h),t.set(d.path||"/",new ml(h),null,!0),Fa.set(s?l:(0,Ot.basename)(e),h.message)}}if(qa.isMainThread&&!AH&&i&&(0,Ga.watchDir)(e,async()=>OH()),o.extensionModule)return await Xl((0,Ot.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;hl?.(new Error(l)),((0,Ga.getWorkerIndex)()===0?console:El.default).error(l),Fa.set((0,Ot.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,hl?.(o),t.set("",new ml(o))}}}var Fs,Ot,qa,pH,vR,BR,SH,Ga,El,TH,gH,Mse,RH,Pse,LR,MR,AH,UR,Fa,vse,PR,hH,mH,hl,ml,lf=Ae(()=>{Fs=require("fs"),Ot=require("path"),qa=require("worker_threads"),pH=require("yaml"),vR=v(j()),BR=v(D());HO();GO();kO();gv();cB();EB();SH=v(require("fast-glob")),Ga=v(Ye()),El=v(G());Oh();sr();TH=v(Z());Ns();ge();gB();gH=v(j()),Mse=v(NB());ef();VB();EH();RH=v(Pr());Zf();({readFile:Pse}=Fs.promises),LR=vR.get(BR.CONFIG_PARAMS.COMPONENTSROOT),MR=new Map,Fa=new Map;a(OH,"loadComponentDirectories");vse={REST:Nf,rest:Nf,graphqlSchema:Ah,jsResource:Nh,fastifyRoutes:Zg,login:Ih,static:eR,operationsApi:Mse,customFunctions:{},http:{},clustering:pR,authentication:vu,mqtt:DR},PR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(PR,"static",{value:{files:"web/**"}});hH=[],mH=new Map;a(Bse,"setErrorReporter");a(hE,"loadComponent");ml=class extends qt{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 NR=T((ape,NH)=>{var{isMainThread:bH}=require("worker_threads"),{getTables:Hse}=(ge(),ee(xe)),{loadComponentDirectories:xse,loadComponent:qse}=(lf(),ee(uf)),{resetResources:Fse}=(Pu(),ee(HM)),Gse=VT(),kse=Pr(),{dirname:Vse}=require("path"),{getConnection:$se}=nt(),Yse=j(),Kse=D(),HR=new Map;async function Wse(e=!1){!bH&&Yse.get(Kse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&$se();try{bH&&await Gse()}catch(s){console.error(s)}let t=Fse();Hse(),t.isWorker=e,await qse(Vse(kse.getConfigFilePath()),t,"hdb",!0,HR),await xse(HR,t);let r=[];for(let[s]of HR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(Wse,"loadRootComponents");NH.exports.loadRootComponents=Wse});var Ye=T((upe,yi)=>{"use strict";var{Worker:Qse,MessageChannel:zse,parentPort:fn,isMainThread:kR,threadId:Jse,workerData:Gn}=require("worker_threads"),{PACKAGE_ROOT:Xse}=D(),{join:CH,isAbsolute:jse,extname:Zse}=require("path"),{server:DH}=(sr(),ee(Li)),{watch:ene,readdir:tne}=require("fs/promises"),{totalmem:yH}=require("os"),pl=D(),LH=j(),kn=G(),{randomBytes:rne}=require("crypto"),{_assignPackageExport:sne}=require("../index"),nne=D(),IH=1024*1024,Ni=[],Es=[],ine=50,VR=1e4,one="restart",UH="request_thread_info",MH="resource_report",PH="thread_info",vH="added-port",ane="ack",xR;sne("threads",Es);yi.exports={startWorker:qR,restartWorkers:YR,shutdownWorkers:dne,workers:Ni,setMonitorListener:gne,onMessageFromWorkers:fne,onMessageByType:GH,broadcast:hne,broadcastWithAcknowledgement:pne,setChildListenerByType:_ne,getWorkerIndex:BH,getWorkerCount:HH,getTicketKeys:xH,setMainIsWorker:une,setTerminateTimeout:cne,restartNumber:Gn?.restartNumber||1};Es.onMessageByType=GH;Es.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Es.find(s=>s.threadId===e);if(r)return r.postMessage(t),!0};var $R;function cne(e){VR=e}a(cne,"setTerminateTimeout");function BH(){return Gn?Gn.workerIndex:$R?0:void 0}a(BH,"getWorkerIndex");function HH(){return Gn?Gn.workerCount:$R?1:void 0}a(HH,"getWorkerCount");function une(e){$R=e}a(une,"setMainIsWorker");var mE;function xH(){return mE||(mE=kR?rne(48):Gn.ticketKeys,mE)}a(xH,"getTicketKeys");Object.defineProperty(DH,"workerIndex",{get(){return BH()}});Object.defineProperty(DH,"workerCount",{get(){return HH()}});var qH={[UH](e,t){Sne(t)},[MH](e,t){Tne(t,e)}};function qR(e,t={}){let r=process.constrainedMemory?.()||yH();r=Math.min(r,yH(),2e4*IH);let s=LH.get(pl.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/IH/(10+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>6,16),64),i=[],o=[];for(let u of Es){let _=new zse;_.existingPort=u,i.push(_),o.push(_.port2)}Zse(e)||(e+=".js");let c=new Qse(jse(e)?e:CH(Xse,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:t.threadCount,name:t.name,restartNumber:yi.exports.restartNumber,ticketKeys:xH()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:vH,port:u,threadId:c.threadId},[u]);return SE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>qR(e,t),c.on("error",u=>{console.error("Worker error:",u),kn.error("Worker error:",u)}),c.on("exit",u=>{Ni.splice(Ni.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<ine?(t.unexpectedRestarts=c.unexpectedRestarts+1,qR(e,t)):kn.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{qH[u.type]?.(u,c)}),Ni.push(c),Ane(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(qR,"startWorker");var lne=[pl.THREAD_TYPES.HTTP];async function YR(e=null,t=2,r=!0){if(kR){if(r){let{loadRootComponents:o}=NR();await o()}yi.exports.restartNumber++,t<1&&(t=t*Ni.length);let s=[],n=[];for(let o of Ni.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;kn.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:yi.exports.restartNumber,type:pl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=lne.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),VR*2).unref();o.on("exit",()=>{clearTimeout(l),s.splice(s.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(s.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===nne.ITC_EVENT_TYPES.CHILD_STARTED&&(kn.trace("Worker has started",_.threadId),d(),n.splice(n.indexOf(l)),_.off("message",f))},"startListener");kn.trace("Waiting for worker to start",_.threadId),_.on("message",f)});n.push(l),s.length>=t&&await Promise.race(s),n.length>=t&&await Promise.race(n)}}await Promise.all(s),await Promise.all(n);let{restartService:i}=Qd();r&&(e==="http"||!e)&&LH.get(pl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else fn.postMessage({type:one,workerType:e})}a(YR,"restartWorkers");function _ne(e,t){qH[e]=t}a(_ne,"setChildListenerByType");function dne(e){return YR(e,1/0,!1)}a(dne,"shutdownWorkers");var FH=[];function fne(e){FH.push(e)}a(fne,"onMessageFromWorkers");var FR=new Map;function GH(e,t){let r=FR.get(e);r||FR.set(e,r=[]),r.push(t)}a(GH,"onMessageByType");var Ene=10;async function hne(e){let t=0;for(let r of Es)try{r.postMessage(e),t++>Ene&&(t=0,await new Promise(setImmediate))}catch(s){kn.error("Unable to send message to worker",s)}}a(hne,"broadcast");var pE=new Map,mne=1;function pne(e){return new Promise(t=>{let r=0;for(let s of Es)try{let n=mne++,i=a(()=>{pE.delete(n),--r===0&&t(),s!==fn&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,pE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of pE)o.port===s&&o()})),s.postMessage(e),r++}catch(n){kn.error("Unable to send message to worker",n)}r===0&&t()})}a(pne,"broadcastWithAcknowledgement");function Sne(e){e.postMessage({type:PH,workers:kH()})}a(Sne,"sendThreadInfo");function kH(){let e=Date.now();return Ni.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(kH,"getChildWorkerInfo");function Tne(e,t){e.resources=t,e.resources.updated=Date.now()}a(Tne,"recordResourceReport");var GR;function gne(e){GR=e}a(gne,"setMonitorListener");var Rne=1e3,wH=!1;function Ane(){wH||(wH=!0,setInterval(()=>{for(let e of Ni){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}GR&&GR()},Rne).unref())}a(Ane,"startMonitoring");var One=1e3;if(fn){SE(fn);for(let e=0,t=Gn.addPorts.length;e<t;e++){let r=Gn.addPorts[e];r.threadId=Gn.addThreadIds[e],SE(r)}setInterval(()=>{let e=process.memoryUsage();fn.postMessage({type:MH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},One).unref(),xR=a(()=>new Promise((e,t)=>{fn.on("message",r),fn.postMessage({type:UH});function r(s){s.type===PH&&(fn.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else xR=kH;yi.exports.getThreadInfo=xR;function SE(e,t){Es.push(e),e.on("message",r=>{if(r.type===vH)r.port.threadId=r.threadId,SE(r.port);else if(r.type===ane){let s=pE.get(r.id);s&&s()}else{for(let n of FH)n(r,e);let s=FR.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){kn.error(i)}}}).on("close",()=>{Es.splice(Es.indexOf(e),1)}).on("exit",()=>{Es.splice(Es.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(SE,"addPort");if(kR){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await tne(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(CH(s,i.name));try{for await(let{filename:i}of ene(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await YR(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",s,i)}},"watch_dir");yi.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else fn.on("message",async e=>{let{type:t}=e;t===pl.ITC_EVENT_TYPES.SHUTDOWN&&(yi.exports.restartNumber=e.restartNumber,fn.unref(),setTimeout(()=>{kn.warn("Thread did not voluntarily terminate",Jse),process.exit(0)},VR).unref())})});var Qw={};$e(Qw,{AUDIT_STORE_OPTIONS:()=>jH,createAuditEntry:()=>r_,openAuditStore:()=>AE,readAuditEntry:()=>Pt,setAuditRetention:()=>Nne,transactionKeyEncoder:()=>XH});function AE(e){let t=e.auditStore=e.openDB(QH.AUDIT_STORE_NAME,jH);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let s=null;function n(i=TE){clearTimeout(s),s=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-KR})){if((_[0]&15)===zR){let l=Pt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=bne){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,KR/10)),n(i)}},i).unref()}return a(n,"scheduleAuditCleanup"),t.scheduleAuditCleanup=n,(0,RE.getWorkerIndex)()===(0,RE.getWorkerCount)()-1&&n(TE),t}function Nne(e,t=TE){KR=e,TE=t}function r_(e,t,r,s,n,i,o){let c=ZH[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;s&&(s>1?ka.setFloat64(0,s):hs.set(kh),u=9),f(0),f(t),d(r),ka.setFloat64(u,e),u+=8,n?d(n):hs[u++]=0,hs[s?8:0]=c;let l=hs.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Va.writeKey)(E,hs,u);let p=u-h-1;p>127?p>16383?(XR.error("Key or username was too large for audit entry",E),u=h+1,hs[h]=0):(hs.copyWithin(h+2,h+1,u),ka.setUint16(h,p|32768),u++):hs[h]=p}function f(E){E<128?hs[u++]=E:E<16384?(ka.setUint16(u,E|32768),u+=2):E<1056964608?(ka.setUint32(u,E|3221225472),u+=4):(hs[u]=255,ka.setUint32(u+1,E),u+=5)}}function Pt(e){try{let t=e.dataView||(e.dataView=new JR(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let s=t.readInt(),n=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:ZH[s&7],tableId:i,get recordId(){return WH(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?WH(e,l,d):void 0},getValue(f,E,h){if(s&WR||s&QR&&!E)return f.decoder.decode(e.subarray(t.position));if(s&QR&&h)return jR(f.getEntry(this.recordId),h,f)}}}catch{return XR.error("Reading audit entry error",e),{}}}function WH(e,t,r){let s=e.subarray(t,r);return(0,Va.readKey)(s,0,r-t)}var Va,gE,QH,zH,RE,JH,XR,hs,ka,XH,jH,KR,bne,TE,WR,QR,VH,zR,$H,YH,KH,ZH,JR,Pi=Ae(()=>{Va=require("ordered-binary"),gE=v(j()),QH=v(mt()),zH=v(D()),RE=v(Ye()),JH=v(z());Tc();XR=v(G());OE();(0,gE.initSync)();hs=Buffer.alloc(1024),ka=new DataView(hs.buffer,hs.byteOffset,1024),XH={writeKey(e,t,r){return e===Sc?(t.set(Sc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Va.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,Va.readKey)(e,t,r)}},jH={encoding:"binary",keyEncoder:XH},KR=(0,JH.convertToMS)((0,gE.get)(zH.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,bne=1e3,TE=1e4;a(AE,"openAuditStore");a(Nne,"setAuditRetention");WR=16,QR=32,VH=1,zR=2,$H=3,YH=4,KH=5,ZH={put:VH|WR,[VH]:"put",delete:zR,[zR]:"delete",message:$H|WR,[$H]:"message",invalidate:YH,[YH]:"invalidate",patch:KH|QR,[KH]:"patch"};a(r_,"createAuditEntry");a(Pt,"readAuditEntry");JR=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(WH,"readKeySafely")});var ZR={};$e(ZR,{add:()=>bE,applyReverse:()=>ex,getRecordAtTime:()=>jR,rebuildUpdateBefore:()=>NE});function bE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function NE(e,t){let r=null;for(let s in e)if(s in t){let n=t[s];if(n?.__op__){let i=e[s];if(i?.__op__)if(i.__op__===n.__op__)r||(r={}),r[s]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[s]=i,bE(r,s,n)}}else r||(r={}),r[s]=e[s];return r}function ex(e,t){for(let r in t){let s=t[r];if(s?.__op__){let n=yne[s.__op__]?.reverse;if(n)n(e,r,{value:s.value});else throw new Error(`Unsupported operation ${s.__op__}`)}else e[r]=tx}}function jR(e,t,r){let s=r.rootStore.auditStore,n=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=s.get(i),_=Pt(u);switch(_.type){case"put":n=_.getValue(r);break;case"patch":ex(n,_.getValue(r));break;case"delete":n=null}i=_.previousLocalTime}let o={},c=0;for(let u in n)n[u]===tx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=s.get(i),_=Pt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(n[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)n[u]=null;return n}var yne,tx,OE=Ae(()=>{Pi();a(bE,"add");bE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};yne={add:bE};a(NE,"rebuildUpdateBefore");a(ex,"applyReverse");tx={};a(jR,"getRecordAtTime")});function Yr(e){return e[Ut]||(e[Ut]=Object.create(null))}function DE(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Re])},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 ms.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 ms.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 ms.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 ms.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 ms.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 ms.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 ms.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 ms.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 ms.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 ms.ClientError(`${c} must be an object, attempt to assign ${l}`);Yr(this)[c]=l},"set")}_={get(){let l=this[Ut];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[ye]?.[c];return f.update(E)}return f}let d=this[ye]?.[c];if(d&&typeof d=="object"){let f=rx(d,o);if(f)return l||(l=this[Ut]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,s[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Ut];return u?.[o]!==void 0?u[o]:this[ye]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new ms.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[Ut],c;for(let _ in o){c||(c=Object.assign({},this[ye]));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[ye])),Object.assign(c,this)),c||this[ye]}),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 rx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){this[ye]=n}},DE(r,t)),new r(e)):new yE(e);case Array:let s=new wE(e.length);s[ye]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=rx(o,t?.elements)),s[n]=o}return s;default:return e}}function X_(e){let t=e[Ut],r;for(let n in t){r||(r=Object.assign({},e[ye]));let i=t[n];if(i&&typeof i=="object")if(i.__op__){let o=r[n];i=i.update(o)}else i=X_(i);r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[ye])),Object.assign(r,e)),r||e[ye]}function Co(e,t=e[Ut]){let r;if(e[ye]&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=Co(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[s]=i}return Object.freeze(r)}for(let s in t){r||(r=Object.assign({},e[ye]));let n=t[s];if(n&&typeof n=="object")if(n.__op__){let i=ZR[n?.__op__];if(i)i(r,s,n);else throw new Error("Invalid CRDT operation "+n.__op__);continue}else n=Co(n);r[s]=n}return r?Object.freeze(r):e[ye]||e}function IE(e){let t=e[ye];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[wo]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[ye]===n){if(IE(i))return!0}else return!0}}else{let r=e[Ut];if(r&&!t)return!0;for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[ye]===i){if(IE(n))return!0}else return!0}else return!0}}return!1}var ms,Ut,yE,wo,wE,CE,j_=Ae(()=>{Ns();ms=v(Z());OE();Ut=Symbol("own-data");a(Yr,"getChanges");a(DE,"assignTrackedAccessors");a(rx,"trackObject");yE=class{static{a(this,"GenericTrackedObject")}constructor(t){this[ye]=t}};DE(yE,{});a(X_,"collapseData");a(Co,"deepFreeze");a(IE,"hasChanges");wo=Symbol.for("has-array-changes"),wE=class extends Array{static{a(this,"TrackedArray")}[wo];constructor(t){super(t)}splice(...t){return this[wo]=!0,super.splice(...t)}push(...t){return this[wo]=!0,super.push(...t)}pop(){return this[wo]=!0,super.pop()}unshift(...t){return this[wo]=!0,super.unshift(...t)}shift(){return this[wo]=!0,super.shift()}};wE.prototype.constructor=Array;CE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Sp={};$e(Sp,{CONTEXT:()=>Re,ID_PROPERTY:()=>De,IS_COLLECTION:()=>ps,RECORD_PROPERTY:()=>ye,Resource:()=>qt,snake_case:()=>wne,transformForSelect:()=>UE});function wne(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function sx(e,t){if(Sl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Sl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),s=new tA;for(let n=0;n<r.length;n++){let i=r[n];if(!i&&n===r.length-1){Sl=!0;break}s[n]=t.coerceId(decodeURIComponent(i))}return s}function Kr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,o){let c,u,_,l;if(r?o?(l=i,o=o[Re]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Re]||i):l=i:(l=n,c=l[De]??l[this.primaryKey]??null):i?o=i[Re]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(o=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[],_=!0;for(let E of n){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=n.id??null,c==null&&(_=!0))}else c=n??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return 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(p=>{if(!p)throw new LE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new LE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Wr(e,t){let r=new ox.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function eA(e,t,r){let s=e[ye];if(s){let n=e[Ut];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:n&&i in n?n[i]:(c=t?.[i])?c(e,r):s[i]}}else return t?n=>{let i=t[n];return i?i(e,r):e[n]}:n=>e[n]}function UE(e,t){let r=t?.propertyResolvers,s=t[Re],n;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):eA(c,r,s)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(eA(u,r,s));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(eA(u,r,s)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){n||(n={});let u=n[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=n[c.name]=UE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var nx,ix,ox,Re,De,ps,ye,Ine,qt,LE,Sl,tA,Ns=Ae(()=>{nx=require("crypto");dc();ix=require("../index"),ox=v(Z());j_();Xi();bf();Re=Symbol.for("context"),De=Symbol.for("primary-key"),ps=Symbol("is-collection"),ye=Symbol("stored-record"),Ine={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},qt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[De]=t;let s=r?.[Re];this[Re]=s!==void 0?s:r||null}static get=Kr(function(t,r,s,n){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=UE(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",resetTransaction:!0,ensureLoaded:!0,async:!0});static put=Kr(function(t,r,s,n){if(Array.isArray(n)&&t[ps]){let i=[],o=s.authorize;for(let c of n){let u=t.constructor,_=u.getResource(c[u.primaryKey],s,{async:!0});_.then?i.push(_.then(l=>l.put(c,s))):i.push(_.put(c,s))}return Promise.all(i)}return t.put?t.put(n,r):Wr(t,"put")},{hasContent:!0,type:"update"});static patch=Kr(function(t,r,s,n){return t.patch?t.patch(n,r):Wr(t,"patch")},{hasContent:!0,type:"update"});static delete=Kr(function(t,r,s,n){return t.delete?t.delete(r):Wr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,nx.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),Xe(s,()=>{let i=new this(n,s),o=i.update?i.update(r):Wr(i,"update");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=Kr(function(t,r,s,n){return t.invalidate?t.invalidate(r):Wr(t,"delete")},{hasContent:!1,type:"update"});static post=Kr(function(t,r,s,n){return t[De]!=null&&t.update?.(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Kr(function(t,r,s,n){return t.connect?t.connect(n,r):Wr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Kr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Wr(t,"subscribe")},{type:"read"});static publish=Kr(function(t,r,s,n){return t[De]!=null&&t.update?.(),t.publish?t.publish(n,r):Wr(t,"publish")},{hasContent:!0,type:"create"});static search=Kr(function(t,r,s,n){let i=t.search?t.search(r):Wr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=UE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Kr(function(t,r,s,n){return t.search?t.search(n,r):Wr(t,"search")},{hasContent:!0,type:"read"});static copy=Kr(function(t,r,s,n){return t.copy?t.copy(n,r):Wr(t,"copy")},{type:"create"});static move=Kr(function(t,r,s,n){return t.move?t.move(n,r):Wr(t,"move")},{type:"delete"});post(t){if(this[ps])return this.constructor.create(this[De],t,this[Re]);Wr(this,"post")}static isCollection(t){return t?.[ps]}static coerceId(t){return t}static parseQuery(t){return Of(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let o=t.slice(n+1);t=t.slice(0,n);let c=r?.headers&&Ine[o];if(c)r.headers.set("accept",c);else if(s)s.property=o;else return{query:{property:o},id:sx(t,this),isCollection:Sl}}let i=sx(t,this);return Sl?{id:i,isCollection:!0}:i}static getResource(t,r,s){let n,i=r[Re],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=s?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(n=_?.find(l=>l.constructor===c),n)return n;_||u.asMap.set(t,_=[]),_.push(n=new c(t,i))}else{if(n=u.find(_=>_[De]===t&&_.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[De],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else n=new c(t,i);return o&&(n[ps]=!0),n}subscribe(t){return new bs}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new bs}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[Re]}};qt.prototype[Re]=null;(0,ix._assignPackageExport)("Resource",qt);a(wne,"snake_case");LE=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(sx,"pathToId");tA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Kr,"transactional");a(Wr,"missingMethod");a(eA,"selectFromObject");a(UE,"transformForSelect")});function cx(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;$a||((0,ME.onMessageByType)(ax,l=>{ux(l.path)}),$a=Object.create(null));let o=$a[n]||($a[n]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Sa(t);let u=new sA(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function ux(e,t){if(!$a)return;let r=$a[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(n){throw n.message+=" in "+e,n}let s;for(let{key:n,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=n;let o=Pt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Sa(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=n){(0,rA.info)("omitting",u,h.startTime,n);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(s?s.push(h):s=[h]),h.txnInProgress=o.version),h.listener(u,o,n,p)}catch(p){console.error(p),(0,rA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(s)for(let n of s)n.txnInProgress=null,n.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function lx(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",()=>{(0,ME.broadcast)({type:ax,path:n}),ux(n,!0)})}}var rA,ME,ax,$a,Lpe,sA,_x=Ae(()=>{rA=v(G()),ME=v(Ye());dc();Pu();Pi();ax="transaction",Lpe=Buffer.alloc(4096);a(cx,"addSubscription");sA=class extends bs{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(ux,"notifyFromTransactionData");a(lx,"listenToCommits")});var Bg={};$e(Bg,{coerceType:()=>PE,makeTable:()=>HE,setServerUtilities:()=>Hne,updateResource:()=>vE});function HE(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,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=[]),lx(i,u);let S=Yh(i,s,u),R=0,I,w,B,K={},q=Promise.resolve(),P,Q,Y;for(let V of p)(V.assignCreatedTime||V.name==="__createdtime__")&&(P=V),(V.assignUpdatedTime||V.name==="__updatedtime__")&&(Q=V),V.expiresAt&&(Y=V),V.isPrimaryKey&&(K=V);let J,re=[],Ie=[],se=1,ut=2,de={},lt={},gs=864e5,bA,vl,Yn,NA=!1,eh,hq=i.getRange({start:!1,end:!1}).constructor,mq=10,pq=6;E&&wA();class Qe extends qt{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=P;static updatedTimeProperty=Q;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,g){g&&(this.sourceOptions=g,(g.expiration||g.eviction||g.scanInterval)&&this.setTTLExpiration(g)),g?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),w=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let N=a(b=>{let y=this.sources.slice(0,-1);if(y=y.filter(L=>L[b]&&(!L[b].reliesOnPrototype||L.prototype[b])),y.length>0)if(y.length===1){let L=y[0];return(U,M,x)=>{if(U?.source!==L)return L[b](M,x,U)}}else return(L,U,M)=>{let x=[];for(let W of y){if(L?.source===W)break;x.push(W[b](U,M,L))}return Promise.all(x)}},"getApplyToIntermediateSource"),A=this.sources[this.sources.length-1],O=a(b=>{if(A[b]&&(!A[b].reliesOnPrototype||A.prototype[b]))return(y,L,U)=>{if(!y?.source)return A[b](L,U,y)}},"getApplyToCanonicalSource");return de={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},lt={put:N("put"),patch:N("patch"),delete:N("delete"),publish:N("publish"),invalidate:N("invalidate")},(async()=>{let b=!1,y=a(async(L,U)=>{let M=L.value,x=L.table?st[c][L.table]:Qe;if(c===Gs.SYSTEM_SCHEMA_NAME&&(L.table===Gs.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||L.table===Gs.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(b=!0),L.id===void 0&&(L.id=M[x.primaryKey],L.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(L));L.source=m;let W=await x.getResource(L.id,U,Ya);switch(L.type){case"put":return W._writeUpdate(M,!0,Ya);case"patch":return W._writeUpdate(M,!1,Ya);case"delete":return W._writeDelete(Ya);case"publish":return W._writePublish(M,Ya);case"invalidate":return W.invalidate(Ya);default:Ze.error("Unknown operation",L.type,L.id)}},"writeUpdate");try{let L=m.subscribe;L&&h==null&&(h=!0);let U=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Do.getWorkerIndex)()):(0,Do.getWorkerIndex)()===0,M=L&&U&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(M){let x;for await(let W of M)try{if(!(W.type==="transaction"?W.writes[0]:W)){Ze.error("Bad subscription event",W);continue}if(W.source=m,x)if(W.beginTxn)x.resolve();else{y(W,x);continue}if(W.type==="end_txn")continue;let le=Xe(W,()=>{if(W.type==="transaction"){let te=[];for(let ne of W.writes)try{te.push(y(ne,W))}catch(He){throw He.message+=" writing "+JSON.stringify(ne)+" of event "+JSON.stringify(W),He}return Promise.all(te)}else if(W.type==="define_schema"){let te=this.attributes.slice(0),ne;for(let He of W.attributes)te.find(ie=>ie.name===He.name)||(te.push(He),ne=!0);ne&&(dt({table:n,database:c,attributes:te,origin:"cluster"}),Nl.signalSchemaChange(new yl.SchemaEventMsg(process.pid,Gs.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return W.beginTxn?(x=W,y(W,W),new Promise(te=>{x.resolve=te})):y(W,W)});b&&(await le,Nl.signalUserChange(new yl.UserEventMsg(process.pid))),W.onCommit&&(le?.then?le.then(W.onCommit):W.onCommit())}catch(Se){Ze.error("error in subscription handler",Se)}}}catch(L){Ze.error(L)}})(),this}static getResource(m,g,N){let A=super.getResource(m,g,N);if(m!=null){Xa(m);try{if(A.hasOwnProperty(ye))return A;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let O=!N?.async||i.cache?.get(m),b=Nr(g),y=b.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return th(m,g,{transaction:y},O,L=>{if(L?vE(A,L):A[ye]=null,g.onlyIfCached&&g.noCacheStore){if(!A.doesExist())throw new Ss.ServerError("Entry is not cached",504)}else if(N?.ensureLoaded){let U=rh(m,L,g,A);if(U)return b?.disregardReadTxn(),A[nA]=!0,oA(U,M=>(vE(A,M),A))}return A})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(m)),O}}return A}ensureLoaded(){let m=rh(this[De],this[Qr],this[Re]);if(m)return this[nA]=!0,oA(m,g=>{this[Qr]=g,this[ye]=g.value,this[Ol]=g.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,gs=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");gs=gs||(d+f)/4,nh()}static enableAuditing(m=!0){E=m,m&&wA(),Qe.audit=m}static coerceId(m){return m===""?null:PE(m,K)}static async dropTable(){if(delete st[c][n],c===o){for(let m of p)l.remove(Qe.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Qe.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Nl.signalSchemaChange(new yl.SchemaEventMsg(process.pid,Gs.OPERATIONS_ENUM.DROP_TABLE,c,n))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[ps])return this.search(m);if(this[De]===null){if(m?.conditions)return this.search(m);let g=Qe.getRecordCount();return{recordCount:g.recordCount,estimatedRecordRange:g.estimatedRange,records:"./",name:n,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Re]?.returnNonexistent)return this}allowRead(m,g){let N=Hl(m);if(N?.read){if(N.isSuperUser)return!0;let A=N.attribute_permissions,O=g?.select;if(A?.length>0||NA&&O){if(g||(g={}),O){let b=A?.length>0&&iA(A,"read");g.select=O.map(y=>{let L=y.name||y;if(!b||b[L]){let U=Yn[L]?.definition?.tableClass;if(U){if(y.name||(y={name:y}),!U.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else g.select=A.filter(b=>b.read&&!Yn[b.attribute_name]).map(b=>b.attribute_name);return g}else return!0}}allowUpdate(m,g){let N=Hl(m);if(N?.update){let A=N.attribute_permissions;if(A?.length>0){let O=iA(A,"update");for(let b in g)if(!O[b])return!1;for(let b of A){let y=b.attribute_name;!b.update&&!(y in g)&&(g[y]=this.getProperty(y))}}return!0}}allowCreate(m,g){if(this[ps]){let N=Hl(m);if(N?.insert){let A=N.attribute_permissions;if(A?.length>0){let O=iA(A,"insert");for(let b in g)if(!O[b])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Hl(m)?.delete}update(m,g){if(!Nr(this[Re]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let A;return typeof m=="object"&&m&&(g?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[ye]={},this[Ut]=m):(A=this[Ut],A&&(m=Object.assign(A,m)),this[Ut]=A=m)),this._writeUpdate(this[Ut],g),this}addTo(m,g){if(typeof g=="number")this[Tl]===fx?this.set(m,(+this.getProperty(m)||0)+g):(this[Tl]||this.update(),this.set(m,new CE(g)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,g){if(typeof g=="number")return this.addTo(m,-g);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let g=this[Re],N=this[De];Xa(N),Nr(this[Re]).addWrite({key:N,store:i,invalidated:!0,entry:this[Qr],nodeName:this[Re]?.nodeName,before:de.invalidate?.bind(this,g,N),beforeIntermediate:lt.invalidate?.bind(this,g,N),commit:(O,b)=>{if(b?.version>O)return;let y=null;for(let L in r)y||(y={}),y[L]=this.getProperty(L);S(N,y,this[Qr],O,gl,E,this[Re],0,"invalidate")}})}static evict(m,g,N){let A=this.Source,O;if(!((w||E)&&(!g||(O=i.getEntry(m),!O||!g)||O.version!==N))){if(w){if(i.hasLock(m,O.version))return;let b;for(let y in r)b||(b={}),b[y]=g[y];if(b)return S(m,b,O,N,Rl,null,null,0,null,!0)}return i.ifVersion(N,()=>{Bl(m,g,null)}),E?S(m,null,O,N,Rl,null,null,0,null,!0):i.remove(m,N)}}lock(){throw new Error("Not yet implemented")}static operation(m,g){return m.table||=n,m.schema||=c,Tx.operation(m,g)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,g,N){let A=this[Re],O=Nr(A),b=this[De];Xa(b);let y=this[Qr];this[Tl]=g?fx:Pne;let L={key:b,store:i,entry:y,nodeName:A?.nodeName,validate:U=>{m||(m=this[Ut]),g||m&&IE(m)?(this.validate(m,!g),A?.source||(Q&&(m[Q.name]=Q.type==="Date"?new Date(U):Q.type==="String"?new Date(U).toISOString():U),g&&(t&&m[t]!==b&&(m[t]=b),P&&(y?.value?m[P.name]=y?.value[P.name]:m[P.name]=P.type==="Date"?new Date(U):P.type==="String"?new Date(U).toISOString():U),m=Co(m)))):O.removeWrite(L)},before:g?de.put?()=>de.put(A,b,m):null:de.patch?()=>de.patch(A,b,m):de.put?()=>de.put(A,b,Co(this)):null,beforeIntermediate:g?lt.put?()=>lt.put(A,b,m):null:lt.patch?()=>lt.patch(A,b,m):lt.put?()=>lt.put(A,b,Co(this)):null,commit:(U,M,x)=>{x&&(A&&M?.version>(A.lastModified||0)&&(A.lastModified=M.version),this[Qr]=M,g||(this[ye]=M?.value??null)),this[Ut]=m,this[Ol]=U;let W=M?.value,Se=m;if(this[Tl]=0,M?.version>U)if(E){let He=M.localTime,ie=M.version;for(;Se&&(He>U||ie>U&&He>0);){let _e=u.get(He),Ve=Pt(_e);if(ie=Ve.version,ie>U)if(Ve.type==="patch"){let Me=Ve.getValue(i);Se=NE(Se,Me)}else(Ve.type==="put"||Ve.type==="delete")&&(Se=null);He=Ve.previousLocalTime}}else g?Se=null:Se=NE(Se,W);let le=Co(this,Se);this[ye]=le;let te;g||(te=m),Bl(b,W,le);let ne=g?"put":"patch";S(b,le,M,U,0,E,A,A.expiresAt||(d?d+Date.now():0),ne,!1,te)}};O.addWrite(L)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[ps]){for await(let g of this.search(m))(await Qe.getResource(g[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[ye]?this._writeDelete(m):!1}_writeDelete(m){let g=Nr(this[Re]),N=this[De];Xa(N);let A=this[Re];return g.addWrite({key:N,store:i,resource:this,nodeName:A?.nodeName,before:de.delete?.bind(this,A,N),beforeIntermediate:lt.delete?.bind(this,A,N),commit:(O,b,y)=>{let L=b?.value;y&&(A&&b?.version>(A.lastModified||0)&&(A.lastModified=b.version),vE(this,b)),!(b?.version>O)&&(Bl(this[De],L),Ze.trace("Write delete entry",N,O),E||h?(S(N,null,this[Qr],O,0,E,this[Re],0,"delete"),E||nh()):i.remove(this[De]))}}),!0}search(m){let g=this[Re],N=Nr(g);if(!m)throw new Error("No query provided");let A=m.conditions;A?A.length===void 0&&(A=A[Symbol.iterator]?Array.from(A):[A]):A=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[De]&&(A=[{attribute:null,comparator:"prefix",value:this[De]}].concat(A));let O,b={};function y(oe,bt){let tt;switch(bt){case"and":case void 0:if(oe.length<1)throw new Error('An "and" operator requires at least one condition');tt=!0;break;case"or":if(oe.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+bt)}let Mt=tt&&{},Rs;for(let Pe of oe){if(Pe.conditions){Pe.conditions=y(Pe.conditions,Pe.operator);continue}let rt=Pe[0]??Pe.attribute,As=rt==null?K:vn(p,rt);if(As){if(tt){let Ci=Oi(rt),ks=Mt[Ci];ks?(ks.push(Pe),Rs=!0):Mt[Ci]=[Pe]}As.type&&(Pe[1]===void 0?Pe.value=U(Pe.value,As):Pe[1]=U(Pe[1],As))}else if(rt!=null)throw(0,Ss.handleHDBError)(new Error,`${rt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return oe;if(Rs)for(let Pe in Mt){let rt=Mt[Pe],As=rt.length;if(As>1)for(let Ci=0;Ci<As;Ci++){let ks=rt[Ci];if(ks.comparator==="ge"||ks.comparator==="greater_than_equal")for(let Kn=0;Kn<As;Kn++){let Po=rt[Kn];(Po.comparator==="le"||Po.comparator==="less_than_equal")&&(ks.comparator="between",ks.value=[ks.value,Po.value],oe.splice(oe.indexOf(Po),1))}if(ks.comparator==="equals"||!ks.comparator){for(let Kn=0;Kn<As;Kn++)if(Kn!==Ci){let Po=rt[Kn];oe.splice(oe.indexOf(Po),1)}break}}}return oe}a(y,"prepareConditions");function L(oe,bt){if(m.enforceExecutionOrder)return oe;for(let tt of oe)tt.conditions&&(tt.conditions=L(tt.conditions,tt.operator));return oe.length>1&&bt!=="or"?(0,Sx.sortBy)(oe,Sg(Qe)):oe}a(L,"orderConditions");function U(oe,bt){return Array.isArray(oe)?oe.map(tt=>PE(tt,bt)):PE(oe,bt)}a(U,"coerceTypedValues");let M=m.operator;(A.length>0||M)&&(A=y(A,M));let x=typeof m.sort=="object"&&m.sort,W;if(x&&M!=="or"){let oe=x.attribute;if(O=A.find(bt=>Oi(bt.attribute)===Oi(oe)),!O){if(!vn(p,oe))throw(0,Ss.handleHDBError)(new Error,`${Array.isArray(oe)?oe.join("."):oe} is not a defined attribute`,404);O={attribute:oe},A.push(O)}O.descending=!!x.descending}A=L(A,M),x&&(A[0]===O?x.next&&(W={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(O&&A.splice(A.indexOf(O),1),W=x));function Se(oe,bt){let tt=oe[0];if(bt==="or"){let Mt=te(tt);for(let Pe=1;Pe<oe.length;Pe++){let rt=oe[Pe],As=te(rt);Mt=Mt.concat(As)}let Rs=new Set;return Mt.filter(Pe=>{let rt=Pe.key??Pe;return Rs.has(rt)?!1:(Rs.add(rt),!0)})}else{let Mt=te(tt),Rs=oe.slice(1).map(Pe=>Zu(Pe,Qe,g,b)).filter(Boolean);return Rs.length>0?yA(Mt,ne,g,Rs):Mt}}a(Se,"executeConditions");let le=m.reverse===!0;function te(oe){return oe.conditions?Se(oe.conditions,oe.operator):ju(oe,N,oe.descending||le,Qe,m.allowFullScan,b)}a(te,"executeCondition");let ne=m.select;if(A.length===0&&(A=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:A,operator:M,postOrdering:W,selectApplied:!!ne};let He=N.useReadTxn(),ie=Se(A,M);(m.offset||m.limit!==void 0)&&(ie=ie.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0));let _e=m.ensureLoaded!==!1,Ve=Qe.transformEntryForSelect(ne,g,b,_e,!0),Me=Qe.transformToOrderedSelect(ie,ne,W,g,Ve);return Me.onDone=()=>{Me.results=null,N.doneReadTxn()},Me.selectApplied=!0,Me}static transformToOrderedSelect(m,g,N,A,O){let b=new hq;if(N){m=yA(m,g,A,null);let y;b.iterate=function(){let U,M=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),x,W=N.dbOrderedAttribute,Se,le,te=!0;function ne(ie){let _e=ie.next&&ne(ie.next),Ve=ie.descending;return(Me,oe)=>{let bt=sh(Me,ie.attribute,A),tt=sh(oe,ie.attribute,A),Mt=Ve?(0,Lo.compareKeys)(tt,bt):(0,Lo.compareKeys)(bt,tt);return Mt===0?_e?.(Me,oe)||0:Mt}}a(ne,"createComparator");let He=ne(N);return{async next(){let ie;if(U)if(ie=U.next(),ie.done){if(x)return b.onDone&&b.onDone(),ie}else return{value:await O(ie.value)};y=[],Se&&y.push(Se);do if(ie=await M.next(),ie.done){if(x=!0,y.length)break;return b.onDone&&b.onDone(),ie}else{let _e=ie.value;if(_e?.then&&(_e=await _e),W){let Ve=sh(_e,W,A);if(te)te=!1,le=Ve;else if(Ve!==le){le=Ve,Se=_e;break}}y.push(_e)}while(!0);return N.isGrouped,y.sort(He),U=y[Symbol.iterator](),ie=U.next(),ie.done?(b.onDone&&b.onDone(),ie):{value:await O(ie.value)}},return(){b.onDone&&b.onDone(),M.return()},throw(){b.onDone&&b.onDone(),M.throw()}}};let L=a(U=>{if(typeof g=="object"&&Array.isArray(U.attribute))for(let M=0;M<g.length;M++){let x=g[M],W;if(x.name===U.attribute[0]){for(W=x.sort||(x.sort={});W.next;)W=W.next;W.attribute=U.attribute.slice(1),W.descending=U.descending}else x===U.attribute[0]&&(g[M]=W={name:x,sort:{attribute:U.attribute.slice(1),descending:U.descending}})}U.next&&L(U.next)},"applySortingOnSelect");L(N)}else b.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),b=b.map(O);return b}static transformEntryForSelect(m,g,N,A,O){if(m&&(m===t||m?.length===1&&m[0]===t)){let U=a(M=>M?.key??M,"transform");return m===t?U:m.asArray?M=>[U(M)]:M=>({[t]:U(M)})}let b;A&&w&&!m?.every(U=>{let M;return typeof U=="object"?M=U.name:M=U,r[M]||M===t})&&(b=!0);let y,L=a(U=>{let M;if(U){if(eh=U,M=U.value||U.deref?.(),!M&&(U.key===void 0||U.deref)){if(U=th(U.key??U,g,{transaction:Nr(g).getReadTxn(),lazy:m?.length<4},!1,x=>x),U?.then)return U.then(L);M=U?.value}if(b&&(U.metadataFlags&(gl|Rl)||U.expiresAt&&U.expiresAt<Date.now())){let x=rh(U.key??U,U,g);if(x?.then)return x.then(L)}}if(M==null)return O?Ka.SKIP:M;if(m&&!(m[0]==="*"&&m.length===1)){let x,W=a((le,te)=>{let ne;typeof le=="object"?ne=le.name:ne=le;let He=Yn?.[ne],ie;if(He){let _e=N?.[ne];if(_e)if(_e.fromRecord)ie=_e.fromRecord(M);else{let Me=Oi(U.key);ie=_e.get(Me),ie||(ie=[])}else ie=He(M,g,U);let Ve=a(Me=>{if(Me&&typeof Me=="object"){let oe=He.definition?.tableClass||Qe;y||(y={});let bt=y[ne]||(y[ne]=oe.transformEntryForSelect(ne===le?null:le.select||(Array.isArray(le)?le:null),g,_e,A));if(Array.isArray(Me)){let tt=[],Mt=oe.transformToOrderedSelect(Me,le.select,typeof le.sort=="object"&&le.sort,g,bt)[Symbol.asyncIterator](),Rs=a(rt=>{for(;!rt.done;){if(rt?.then)return rt.then(Rs);tt.push(rt.value),rt=Mt.next()}te(tt,ne)},"nextValue"),Pe=Rs(Mt.next());Pe&&(x||(x=[]),x.push(Pe));return}else if(Me=bt(Me),Me?.then){x||(x=[]),x.push(Me.then(tt=>te(tt,ne)));return}}te(Me,ne)},"handleResolvedValue");ie?.then?(x||(x=[]),x.push(ie.then(Ve))):Ve(ie);return}else ie=M[ne],ie&&typeof ie=="object"&&ne!==le&&(ie=this.transformEntryForSelect(le.select||le,g,null)({value:ie}));te(ie,ne)},"selectAttribute"),Se;if(typeof m=="string")W(m,le=>{Se=le});else if(Array.isArray(m))if(m.asArray)Se=[],m.forEach((le,te)=>{le==="*"?m[te]=M:W(le,ne=>Se[te]=ne)});else{Se={};let le=m.forceNulls;for(let te of m)if(te==="*")for(let ne in M)Se[ne]=M[ne];else W(te,(ne,He)=>{ne===void 0&&le&&(ne=null),Se[He]=ne})}else throw new Ss.ClientError("Invalid select"+m);return x?Promise.all(x).then(()=>Se):Se}return M},"transform");return L}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||dt({table:n,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let g=!m.rawEvents,N=cx(Qe,this[De]??null,function(y,L,U,M){try{let x=L.getValue?.(i,g);if(!x&&L.type==="patch"&&g){let W=i.getEntry(y);W?.version===L.version?x=W.value:x=L.getValue?.(i,!0,U)}this.send({id:y,timestamp:U,value:x,version:L.version,type:L.type,beginTxn:M})}catch(x){Ze.error(x)}},m.startTime||0,this[ps]);this[ps]&&(N.includeDescendants=!0,m.onlyChildren&&(N.onlyChildren=!0)),m.crossThreads===!1&&(N.crossThreads=!1),m.supportsTransactions&&(N.supportsTransactions=!0);let A=this[De],O=m.previousCount;O>1e3&&(O=1e3);let b=m.startTime;if(this[ps]){if(b){if(O)throw new Ss.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:L}of u.getRange({start:b,exclusiveStart:!0})){let U=Pt(L);if(U.tableId!==s)continue;let M=U.recordId;(A==null||mx(A,M))&&N.send({id:M,timestamp:y,...U}),N.startTime=y}}else if(O){let y=[];for(let{key:L,value:U}of u.getRange({start:"z",end:!1,reverse:!0}))try{let M=Pt(U);if(M.tableId!==s)continue;let x=M.recordId;if(A==null||mx(A,x)){let W=M.getValue(i,g,L);if(y.push({id:x,timestamp:L,value:W,version:M.version,type:M.type}),--O<=0)break}}catch(M){Ze.error("Error getting history entry",L,M)}for(let L=y.length;L>0;)N.send(y[--L]);y[0]&&(N.startTime=y[0].timestamp)}else if(!m.omitCurrent)for(let{key:y,value:L,version:U,localTime:M}of i.getRange({start:A??!1,end:A==null?void 0:[A,Lo.MAXIMUM_KEY],versions:!0}))L&&N.send({id:y,version:U,timestamp:M,value:L})}else{O&&!b&&(b=0);let y=this[Qr]?.localTime;if(y===$h&&(i.cache?.delete(A),this[Qr]=i.getEntry(A),Ze.warn("re-retrieved record",y,this[Qr]?.localTime),y=this[Qr]?.localTime),Ze.trace("Subscription from",b,"from",A,y),b<y){let L=[],U=y;do{let M=u.get(U);if(M){m.omitCurrent=!0;let x=Pt(M),W=x.getValue(i,g,U);L.push({id:A,value:W,timestamp:U,...x}),U=x.previousLocalTime}else break;O&&O--}while(U>b&&O!==0);for(let M=L.length;M>0;)N.send(L[--M]);N.startTime=y}!m.omitCurrent&&this.doesExist()&&N.send({id:A,version:this[Ol],timestamp:y,value:this})}return m.listener&&N.on("data",m.listener),N}doesExist(){return!!(this[ye]||this[Tl])}publish(m,g){this._writePublish(m,g)}_writePublish(m,g){let N=Nr(this[Re]),A=this[De]||null;Xa(A);let O=this[Re];N.addWrite({key:A,store:i,entry:this[Qr],nodeName:O?.nodeName,validate:()=>{this.validate(m)},before:de.publish?.bind(this,O,A,m),beforeIntermediate:lt.publish?.bind(this,O,A,m),commit:(b,y,L)=>{y===void 0&&h&&!E&&nh(),S(A,y?.value??null,y,y?.version||b,0,!0,O,y?.expiresAt,"message",!1,m)}})}validate(m,g){let N,A=a((O,b,y)=>{if(b.type&&O!=null)if(g&&O.__op__&&(O=O.value),b.properties){typeof O!="object"&&(N||(N=[])).push(`Property ${y} must be an object${b.type?" ("+b.type+")":""}`);let L=b.properties;for(let U=0,M=L.length;U<M;U++){let x=L[U],W=A(O[x.name],x,y+"."+x.name);W&&(O[x.name]=W)}}else switch(b.type){case"Int":(typeof O!="number"||O>>0!==O)&&(N||(N=[])).push(`Property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(N||(N=[])).push(`Property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(N||(N=[])).push(`Property ${y} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(L=>typeof L=="string")||(N||(N=[])).push(`Property ${y} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(N||(N=[])).push(`Property ${y} must be a string`);break;case"Boolean":typeof O!="boolean"&&(N||(N=[])).push(`Property ${y} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(N||(N=[])).push(`Property ${y} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(N||(N=[])).push(`Property ${y} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(N||(N=[])).push(`Property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(b.elements)for(let L=0,U=O.length;L<U;L++){let M=O[L],x=A(M,b.elements,y+"[*]");x&&(O[L]=x)}}else(N||(N=[])).push(`Property ${y} must be a Buffer or Uint8Array`);break}b.nullable===!1&&O==null&&(N||(N=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let O=0,b=p.length;O<b;O++){let y=p[O];if(!y.relationship&&(!g||y.name in m)){let L=A(m[y.name],y,y.name);L&&(m[y.name]=L)}}if(N)throw new Ss.ClientError(N.join(". "))}getUpdatedTime(){return this[Ol]}wasLoadedFromSource(){return w?!!this[nA]:void 0}static async addAttributes(m){let g=p.slice(0);for(let N of m){if(!N.name)throw new Ss.ClientError("Attribute name is required");if(N.name.match(/[`/]/))throw new Ss.ClientError("Attribute names cannot include backticks or forward slashes");g.push(N)}return dt({table:n,database:c,schemaDefined:_,attributes:g}),Qe.indexingOperation}static async removeAttributes(m){let g=p.filter(N=>!m.includes(N.name));return dt({table:n,database:c,schemaDefined:_,attributes:g}),Qe.indexingOperation}static getRecordCount(m){let g=i.getStats().entryCount,N=5e3,A=1e3,O;g>N&&!m?.exactCount&&(O=A);let b=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:O}))y!=null&&b++;if(O){let y=b;b=0;for(let{value:ne}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:O}))ne!=null&&b++;let L=O*2,U=(b+y)/L,M=Math.pow((b-y+1)/O/2,2)+U*(1-U)/L,x=Math.max(Math.sqrt(M)*g,1),W=Math.round(U*g),Se=Math.max(W-1.96*x,0),le=Math.min(W+1.96*x,g),te=Math.pow(10,Math.round(Math.log10(x)));return te>W&&(te=te/10),b=Math.round(W/te)*te,{recordCount:b,estimatedRange:[Math.round(Se),Math.round(le)]}}return{recordCount:b}}static updatedAttributes(){Yn=this.propertyResolvers={$id:(m,g,N)=>({value:N.key}),$updatedtime:(m,g,N)=>N.version,$record:(m,g,N)=>N?{value:m}:m};for(let m of this.attributes){m.resolve=null;let g=m.relationship;if(g)if(NA=!0,g.to)m.elements?.definition?(Yn[m.name]=m.resolve=(N,A,O)=>{let b=N[g.from?g.from:t],y=m.elements.definition.tableClass;return O?ju({attribute:g.to,value:b},Nr(A).getReadTxn(),!1,y).asArray:y.search([{attribute:g.to,value:b}],A).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${n}" must have an array type referencing a table as the elements`);else if(g.from){let N=m.definition||m.elements?.definition;N?(Yn[m.name]=m.resolve=(A,O,b)=>{let y=A[g.from];if(y!==void 0){if(m.elements){let L,U=y.map(M=>{let x=b?N.tableClass.primaryStore.getEntry(M,{transaction:Nr(O).getReadTxn()}):N.tableClass.get(M,O);return x?.then&&(L=!0),x});return g.filterMissing?L?Promise.all(U).then(M=>M.filter(px)):U.filter(px):L?Promise.all(U):U}return b?N.tableClass.primaryStore.getEntry(y,{transaction:Nr(O).getReadTxn()}):N.tableClass.get(y,O)}},m.set=(A,O)=>{if(Array.isArray(O)){let b=O.map(y=>y[De]||y[N.tableClass.primaryKey]);A[g.from]=b}else{let b=O[De]||O[N.tableClass.primaryKey];A[g.from]=b}},m.resolve.definition=m.definition||m.elements?.definition):console.error(`The relationship property "${m.name}" in table "${n}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${n}" must use either "from" or "to" arguments`)}DE(this,this)}static async deleteHistory(m=0){let g;for(let{key:N,value:A}of u.getRange({start:0,end:m}))await Al(),Pt(A).tableId===s&&(g=u.remove(N));await g}static async*getHistory(m=0,g=1/0){for(let{key:N,value:A}of u.getRange({start:m,end:g})){await Al();let O=Pt(A);O.tableId===s&&(yield{id:O.recordId,localTime:N,version:O.version,type:O.type,value:O.getValue(i,!0,N),user:O.user})}}static async getHistoryOfRecord(m){let g=[];if(m==null)throw new Error("An id is required");let N=i.getEntry(m);if(!N)return g;let A=N.localTime;if(!A)throw new Error("The entry does not have a local audit time");let O=0;do{await Al();let b=u.get(A);if(b){let y=Pt(b);g.push({id:y.recordId,localTime:A,version:y.version,type:y.type,value:y.getValue(i,!0,A),user:y.user}),A=y.previousLocalTime}else break}while(O<1e3&&A);return g.reverse()}static cleanup(){J?.remove()}}Qe.updatedAttributes();let Sq=Qe.prototype;return Sq[Mne]=!0,d&&Qe.setTTLExpiration(d/1e3),Y&&Tq(),Qe;function Bl(V,m,g){let N;for(let A in r){let O=r[A],b=O.isIndexing,y=g?.[A],L=m?.[A];if(y===L&&!b)continue;N=!0;let U=O.indexNulls,M=(0,bl.getIndexedValues)(L,U);if(M){dx&&O.prefetch(M.map(x=>({key:x,value:V})),hx);for(let x=0,W=M.length;x<W;x++)O.remove(M[x],V)}if(M=(0,bl.getIndexedValues)(y,U),M){dx&&O.prefetch(M.map(x=>({key:x,value:V})),hx);for(let x=0,W=M.length;x<W;x++)O.put(M[x],V)}}return N}a(Bl,"updateIndices");function Xa(V){switch(typeof V){case"number":return!0;case"string":if(V.length<659)return!0;if(V.length>Ex)throw new Error("Primary key size is too large: "+V.length);break;case"object":if(V===null)return!0;break;case"bigint":if(V<2n**64n&&V>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof V)}if((0,Lo.writeKey)(V,vne,0)>Ex)throw new Error("Primary key size is too large: "+V.length);return!0}a(Xa,"checkValidId");function th(V,m,g,N,A){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),g.transaction?.isDone)return A(null,V);let b=i.getEntry(V,g);return b&&m&&(b?.version>(m.lastModified||0)&&(m.lastModified=b.version),b?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=b.localTime)),A(b,V)},"whenPrefetched");return N?O():se>0?(se--,O()):new Promise((b,y)=>{se===0?(se--,i.prefetch([V],()=>{L(),U()})):(re.push(V),Ie.push(U),re.length>pq&&(se--,L()));function L(){if(re.length>0){let M=Ie;i.prefetch(re,()=>{se===-1?L():se++;for(let x of M)x()}),re=[],Ie=[],ut>2&&ut--}else se=ut,ut<mq&&ut++}a(L,"prefetch");function U(){try{b(O())}catch(M){y(M)}}a(U,"load")})}a(th,"loadLocalRecord");function Hl(V){if(!V?.role)return;let m=V.role.permission;if(m.super_user)return Bne;let g=m[c],N,A=g?.tables;if(A)return A[n];if(c==="data"&&(N=m[n])&&!N.tables)return N}a(Hl,"getTablePermissions");function rh(V,m,g,N){if(w){let A;if(g.noCache?A=!0:(m?(!m.value||m.metadataFlags&(gl|Rl)||m.expiresAt&&m.expiresAt<Date.now())&&(A=!0):A=!0,ss(!A,"cache-hit",n)),A){let O=IA(V,m,g).then(b=>(b?.value?.[ye]&&Ze.error("Can not assign a record with a record property"),g&&(b?.version>(g.lastModified||0)&&(g.lastModified=b.version),g.lastRefreshed=Date.now()),b));if(g?.onlyIfCached||m?.value&&N?.allowStaleWhileRevalidate?.(m,V)){if(O.catch(b=>Ze.warn(b)),g?.onlyIfCached&&!N.doesExist())throw new Ss.ServerError("Entry is not cached",504);return}else return O}}}a(rh,"ensureLoadedFromSource");function Nr(V){let m=V?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let g=m.next;if(!g)return m=m.next=new Ji,m.lmdbDb=i,m;m=g}while(!0)}else return new z_}a(Nr,"txnForContext");function sh(V,m,g){if(!V)return;eh=V;let N=V.value||V.deref?.()||(eh=i.getEntry(V.key))?.value;if(typeof m=="object"){let O=Yn,b=N;for(let y=0,L=m.length;y<L;y++){let U=m[y],M=O?.[U];b=M&&b?M(b,g,!0)?.value:b?.[U],O=M?.definition?.tableClass?.propertyResolvers}return b}let A=Yn[m];return A?A(N,g):N[m]}a(sh,"getAttributeValue");function yA(V,m,g,N){let A=Nr(g).getReadTxn(),O=N?.length,b={transaction:A,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0};function y(L,U){let M=L?.value;if(!M)return Ka.SKIP;for(let x=0;x<O;x++)if(!N[x](M,L))return Ka.SKIP;return U!==void 0&&(L.key=U),L}if(a(y,"processEntry"),O>0||!V.hasEntries){let L=V.map(U=>typeof U=="object"&&U.key!==void 0?O>0?y(U):U:U==null?Ka.SKIP:th(U,g,b,!1,y));return Array.isArray(V)&&(L=L.filter(U=>U!==Ka.SKIP)),L.hasEntries=!0,L}return V}a(yA,"transformToEntries");async function IA(V,m,g){let N=m?.metadataFlags,A=m?.version,O,b;if(!i.attemptLock(V,A,()=>{clearTimeout(b);let M=i.getEntry(V);!M||!M.value||M.metadataFlags&(gl|Rl)?O(IA(V,i.getEntry(V),g)):O(M)}))return new Promise(M=>{O=M,b=setTimeout(()=>{i.unlock(V,A)},Une)});let y=m?.value,L={requestContext:g,replacingRecord:y,replacingVersion:A,source:null,resourceCache:g?.resourceCache},U=g?.responseHeaders;return new Promise((M,x)=>{let W;oA(Xe(L,async Se=>{let le=performance.now(),te,ne,He;try{for(let Me of Qe.sources)if(Me.get&&(!Me.get.reliesOnPrototype||Me.prototype.get)&&(L.source=Me,te=await Me.get(V,L),te))break;He=N≷let _e=L.lastModified||He&&A;ne=He||_e>A||!y,_e||(_e=(0,bl.getNextMonotonicTime)());let Ve=performance.now()-le;if(qr(Ve,"cache-resolution",n),U&&U.append("Server-Timing",`cache-resolve;dur=${Ve.toFixed(2)}`),Se.timestamp=_e,d&&!L.expiresAt&&(L.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]!==V&&(te[t]=V)}W=!0,M({version:_e,value:te})}catch(_e){_e.message+=` while resolving record ${V} for ${n}`,y&&((_e.code==="ECONNRESET"||_e.code==="ECONNREFUSED"||_e.code==="EAI_AGAIN")&&!g?.mustRevalidate||g?.staleIfError&&(_e.statusCode===500||_e.statusCode===502||_e.statusCode===503||_e.statusCode===504))?(M({version:A,value:y}),Ze.trace(_e.message,"(returned stale record)")):x(_e),L.transaction.abort();return}if(g?.noCacheStore){L.transaction.abort();return}Nr(L).addWrite({key:V,store:i,entry:m,nodeName:"source",commit:(_e,Ve)=>{if(Ve?.version!==A)return;let Me=Bl(V,y,te);te?(lt.put?.(L,V,te),S(V,te,Ve,_e,0,E&&ne||null,L,L.expiresAt,"put",!!He)):(lt.delete?.(L,V),E||h?S(V,null,Ve,_e,0,E&&ne||null,L,0,"delete",!!He):i.remove(V,A))}})}),()=>{i.unlock(V,A)},Se=>{i.unlock(V,A),W&&Ze.error("Error committing cache update",Se)})})}a(IA,"getFromSource");function nh(){if(gs!==bA&&(bA=gs,(0,Do.getWorkerIndex)()===(0,Do.getWorkerCount)()-1)){if(vl&&clearTimeout(vl),!gs)return;let V=new Date;V.setMonth(0),V.setDate(1),V.setHours(0),V.setMinutes(0),V.setSeconds(0);let m=Math.ceil((Date.now()-V.getTime())/gs)*gs+V.getTime(),g=a(N=>{Ze.trace(`Scheduled next cleanup scan at ${new Date(N)}ms`),vl=setTimeout(()=>q=q.then(async()=>{if(g(Math.max(N+gs,Date.now())),i.rootStore.status!=="open"){clearTimeout(vl);return}let A=50,O=new Array(A),b=0;Ze.trace(`Starting cleanup scan for ${n}`);try{let y=0;for(let{key:L,value:U,version:M,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let W;U===null&&!E&&M+Lne<Date.now()?W=i.remove(L,M):x&&x+f<Date.now()&&(W=Qe.evict(L,U,M),y++),W&&(await O[b],O[b]=W.catch(Se=>{Ze.error("Cleanup error",Se)}),++b>=A&&(b=0)),await Al()}Ze.trace(`Finished cleanup scan for ${n}, evicted ${y} entries`)}catch(y){Ze.trace(`Error in cleanup scan for ${n}:`,y)}}),Math.min(N-Date.now(),2147483647)).unref()},"startNextTimer");g(m)}}a(nh,"scheduleCleanup");function wA(){J=u?.addDeleteRemovalCallback(s,V=>{let m=i.getEntry(V);m?.value===null&&i.remove(V,m.version)})}a(wA,"addDeleteRemoval");function Tq(){(0,Do.getWorkerIndex)()===0&&setInterval(async()=>{try{let V=Y.name,m=r[V];if(!m)throw new Error(`expiresAt attribute ${Y} must be indexed`);for(let{value:g}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let N=i.getEntry(g);N?.value?.[V]<Date.now()&&Qe.evict(g,N.value,N.version),await Al()}}catch(V){Ze.error("Error in evicting old records",V)}},Dne).unref()}a(Tq,"runRecordExpirationEviction")}function iA(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function hx(){}function Hne(e){Tx=e}function PE(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"&&!xne.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,BE.autoCast)(e):e}function mx(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}function oA(e,t,r){return e?.then?e.then(t,r):t(e)}function vE(e,t){e[Qr]=t,e[ye]=t?.value??null,e[Ol]=t?.version}function px(e){return e!=null}var Gs,Ka,bl,Sx,Il,Ss,Nl,yl,Ze,Lo,Do,BE,Cne,Tx,Dne,Lne,dx,Une,Ol,Mne,Qr,Tl,fx,Pne,nA,Ya,gl,Rl,vne,Ex,Bne,Kpe,xne,Al,xf=Ae(()=>{Gs=v(D()),Ka=require("lmdb"),bl=v(wr()),Sx=require("lodash");Ns();qp();Il=v(j());_x();Ss=v(Z()),Nl=v(An()),yl=v(Ls());ge();bf();Ze=v(G());j_();Xi();Lo=require("ordered-binary"),Do=v(Ye());Pi();BE=v(z());Tc();yn();OE();Cne=new Uint8Array(9);Cne[8]=192;Dne=6e4,Lne=864e5;Il.initSync();dx=Il.get(Gs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Une=1e4,Ol=Symbol.for("version"),Mne=Symbol.for("incremental-update"),Qr=Symbol("entry"),Tl=Symbol("is-saving"),fx=1,Pne=2,nA=Symbol("loaded-from-source"),Ya={isNotification:!0,ensureLoaded:!1},gl=1,Rl=8,vne=Buffer.allocUnsafeSlow(8192),Ex=1978,Bne={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},Kpe=(0,BE.convertToMS)(Il.get(Gs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(HE,"makeTable");a(iA,"attributesAsObject");a(hx,"noop");a(Hne,"setServerUtilities");xne=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(PE,"coerceType");a(mx,"isDescendantId");Al=a(()=>new Promise(setImmediate),"rest");a(oA,"when");a(vE,"updateResource");a(px,"exists")});var xe={};$e(xe,{database:()=>Qc,databases:()=>st,dropDatabase:()=>$p,dropTableMeta:()=>$ne,getDatabases:()=>Ms,getTables:()=>qne,onUpdatedTable:()=>SR,readMetaDb:()=>wl,resetDatabases:()=>Fne,table:()=>dt,tables:()=>Cr});function qne(){return kE||Ms(),Cr||{}}function Ms(){if(kE)return st;kE=!0,za=new Map;let e=(0,Zt.getHdbBasePath)()&&(0,et.join)((0,Zt.getHdbBasePath)(),Jr.DATABASES_DIR_NAME),t=(0,Zt.get)(Jr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Zt.get)(Jr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,zr.existsSync)(e)?e:(0,et.join)((0,Zt.getHdbBasePath)(),Jr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,zr.existsSync)(e))for(let r of(0,zr.readdirSync)(e,{withFileTypes:!0})){let s=(0,et.basename)(r.name,".mdb");r.isFile()&&(0,et.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&wl((0,et.join)(e,r.name),null,s)}if((0,zr.existsSync)((0,Qa.getBaseSchemaPath)())){for(let r of(0,zr.readdirSync)((0,Qa.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,et.join)((0,Qa.getBaseSchemaPath)(),r.name),n=(0,et.join)((0,Qa.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,zr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,et.extname)(i.name).toLowerCase()===".mdb"){let o=(0,et.join)(n,i.name);wl((0,et.join)(s,i.name),(0,et.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,zr.existsSync)(n))for(let o of(0,zr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,et.extname)(o.name).toLowerCase()===".mdb"&&wl((0,et.join)(n,o.name),(0,et.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,et.join)(c.path,(0,et.basename)(o+".mdb"));(0,zr.existsSync)(u)&&wl(u,o,r,null,!0)}}for(let r in st){let s=za.get(r);if(s){let n=st[r];r.includes("delete")&&Ts.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Ts.trace(`delete table class ${i}`),delete n[i])}else if(delete st[r],r==="data"){for(let n in Cr)delete Cr[n];delete Cr[VE]}}return za=null,st}}function Fne(){kE=!1;for(let[,e]of Ii)e.needsDeletion=!0;Ms();for(let[e,t]of Ii)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Ii.delete(e));return st}function wl(e,t,r=uA,s,n){let i=new aA.default(e,!1);try{let o=Ii.get(e);o?o.needsDeletion=!1:(o=(0,qE.open)(i),Ii.set(e,o));let c=new Uo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(xE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,zr.existsSync)(s)&&(i.path=s,_=(0,qE.open)(i),_.isLegacy=!0):_=AE(o));let l=Ox(r),d=l[VE],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 R=f.get(p);R||f.set(p,R={attributes:[]}),(S==null||h.is_hash_attribute)&&(R.primary=h),S!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:p,primary:S}=h;if(!S){for(let J of p)if(J.is_hash_attribute||J.isPrimaryKey){S=J;break}if(!S){Ts.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let R=l[E],I={},w=[],B,K,q=typeof S.audit=="boolean"?S.audit:(0,Zt.get)(Jr.CONFIG_PARAMS.LOGGING_AUDITLOG),P=S.trackDeletes,Q=S.expiration,Y=S.eviction;if(R)I=R.indices,w=R.attributes,R.schemaVersion++;else{B=S.tableId,B?B>=(u.get(Wa)||0)&&u.putSync(Wa,B+1):(S.tableId=B=u.get(Wa),B||(B=1),u.putSync(Wa,B+1),u.putSync(S.key,S));let J=new Uo.default(!S.is_hash_attribute,S.is_hash_attribute);K=s_(o.openDB(S.key,J)),K.rootStore=o,K.tableId=B}for(let J of p){J.attribute=J.name;try{if(!J.is_hash_attribute&&(J.indexed||J.attribute&&!J.name)){if(!I[J.name]){let Ie=new Uo.default(!J.is_hash_attribute,J.is_hash_attribute);I[J.name]=o.openDB(J.key,Ie),I[J.name].indexNulls=J.indexNulls}let re=w.find(Ie=>Ie.name===J.name);re?w.splice(w.indexOf(re),1,J):w.push(J)}}catch(re){Ts.error("Error trying to update attribute",J,w,I,re)}}if(!R){R=bx(l,E,HE({primaryStore:K,auditStore:_,audit:q,expirationMS:Q&&Q*1e3,evictionMS:Y&&Y*1e3,trackDeletes:P,tableName:E,tableId:B,primaryKey:S.name,databasePath:n?r+"/"+E:r,databaseName:r,indices:I,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),R.schemaVersion=1;for(let J of lA)J(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Ox(e){let t=st[e];if(t||(e==="data"?t=st[e]=Cr:e==="system"?Object.defineProperty(st,"system",{value:t=Object.create(null),configurable:!0}):t=st[e]=Object.create(null)),za&&!za.has(e)){let r=new Set;t[VE]=r,za.set(e,r)}return t}function bx(e,t,r){return e[t]=r,r}function Qc({database:e,table:t}){e||(e=uA),Ms();let r=Ox(e),s=(0,et.join)((0,Zt.getHdbBasePath)(),Jr.DATABASES_DIR_NAME),n=(0,Zt.get)(Jr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(n.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&n[e]?.tables?.[t]?.path;s=i||n[e]?.path||process.env.STORAGE_PATH||(0,Zt.get)(Jr.CONFIG_PARAMS.STORAGE_PATH)||((0,zr.existsSync)(s)?s:(0,et.join)((0,Zt.getHdbBasePath)(),Jr.LEGACY_DATABASES_DIR_NAME));let o=(0,et.join)(s,(i?t:e)+".mdb"),c=Ii.get(o);if(!c){let u=new aA.default(o,!1);c=(0,qE.open)(u),Ii.set(o,c)}return c}async function $p(e){if(!st[e])throw new Error("Schema does not exist");let t=st[e];for(let r in t){let n=t[r].primaryStore.rootStore;Ii.delete(n.path),n.status==="open"&&(await n.close(),await gx.remove(n.path))}if(e==="data"){for(let r in Cr)delete Cr[r];delete Cr[VE]}delete st[e]}function dt({table:e,database:t,expiration:r,eviction:s,scanInterval:n,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=uA);let l=Qc({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,p,S;u==null&&(u=!0);let R=new Uo.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 I,w;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=AE(l)),h=i.find(re=>re.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Zt.get)(Jr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),s&&(h.eviction=s),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),Ts.trace(`${e} table loading, opening primary store`);let Q=new Uo.default(!1,!0),Y=e+"/",J=s_(l.openDB(Y,Q));J.rootStore=l,S=l.dbisDb=l.openDB(xE.INTERNAL_DBIS_NAME,R),J.tableId=S.get(Wa),J.tableId||(J.tableId=1),S.putSync(Wa,J.tableId+1),h.tableId=J.tableId,f=bx(d,e,HE({primaryStore:J,auditStore:P,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:s&&s*1e3,primaryKey:E,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,I=!0,q(),S.put(Y,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(xE.INTERNAL_DBIS_NAME,R)),f.dbisDB=S;let B=[];for(let{key:P,value:Q}of S.getRange({start:!0})){let[Y,J]=P.toString().split("/");if(J===""&&(J=Q.name),J){if(Y!==e)continue}else J=Y;if(!i.find(Ie=>Ie.name===J)?.indexed&&Q.indexed&&!Q.isPrimaryKey){q(),I=!0,S.remove(P);let Ie=f.indices[Y];Ie&&B.push(Ie)}}let K=[];try{for(let P of i||[]){if(P.relationship)continue;let Q=e+"/"+(P.name||"");Object.defineProperty(P,"key",{value:Q,configurable:!0});let Y=S.get(Q);if(P.isPrimaryKey){if(Y=Y||S.get(Q=e+"/")||{},o!==f.audit||(+r||void 0)!==(+Y.expiration||void 0)||(+s||void 0)!==(+Y.eviction||void 0)){let re=Object.assign({},Y);typeof o=="boolean"&&(o&&f.enableAuditing(o),re.audit=o),r&&(re.expiration=+r),s&&(re.eviction=+s),I=!0,q(),S.put(Q,re)}continue}Y?.attribute&&!Y.name&&(Y.indexed=!0);let J=!Y||Y.type!==P.type||Y.indexed!==P.indexed||JSON.stringify(Y.attributes)!==JSON.stringify(P.attributes)||JSON.stringify(Y.elements)!==JSON.stringify(P.elements);if(P.indexed){let re=new Uo.default(!0,!1),Ie=l.openDB(Q,re);(J||Y.indexingPID&&Y.indexingPID!==process.pid||Y.restartNumber<Cl.workerData?.restartNumber)&&(I=!0,q(),Y=S.get(Q),(J||Y.indexingPID&&Y.indexingPID!==process.pid||Y.restartNumber<Cl.workerData?.restartNumber)&&(I=!0,P.lastIndexedKey=Y?.lastIndexedKey||!1,P.indexingPID=process.pid,Ie.isIndexing=!0,Object.defineProperty(P,"dbi",{value:Ie}),P.indexNulls===void 0&&(P.indexNulls=!0),K.push(P)),S.put(Q,P)),Y?.indexNulls&&P.indexNulls===void 0&&(P.indexNulls=!0),Ie.indexNulls=P.indexNulls,p[P.name]=Ie}else J&&(I=!0,q(),S.put(Q,P))}}finally{w&&w()}if(I&&(f.schemaVersion++,f.updatedAttributes()),Ts.trace(`${e} table loading, running index`),K.length>0||B.length>0?f.indexingOperation=Vne(f,K,B):I&&FE.signalSchemaChange(new GE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,I)for(let P of lA)P(f,_!=="cluster");return(r||s||n)&&f.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),Ts.trace(`${e} table loaded`),f;function q(){w||l.transactionSync(()=>({then(P){w=P}}))}a(q,"startTxn")}async function Vne(e,t,r){try{let s=e.schemaVersion;await FE.signalSchemaChange(new GE.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,n=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,Rx.getIndexedValues)(l[h]);if(p)for(let S=0,R=p.length;S<R;S++)E.dbi.put(p[S],_)}}),n.then(()=>u--,f=>{u--,Ts.error(f)}),Cl.workerData&&Cl.workerData.restartNumber!==Ax.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>Gne?await n:u>kne&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,n=e.dbisDB.put(_.key,_)}await n,await FE.signalSchemaChange(new GE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Ts.error("Error in indexing",s)}}function $ne({table:e,database:t}){let r=Qc({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function SR(e){lA.push(e)}var Zt,xE,qE,et,zr,Qa,Uo,aA,Jr,gx,cA,Rx,FE,GE,Cl,Ts,Ax,uA,VE,Cr,st,Wa,lA,kE,Ii,za,Gne,kne,ge=Ae(()=>{Zt=v(j()),xE=v(mt()),qE=require("lmdb"),et=require("path"),zr=require("fs"),Qa=v(ze());xf();Uo=v(n_()),aA=v(o_()),Jr=v(D()),gx=v(require("fs-extra")),cA=require("../index"),Rx=v(wr()),FE=v(An()),GE=v(Ls()),Cl=require("worker_threads"),Ts=v(G()),Ax=v(Ye());Pi();Tc();uA="data",VE=Symbol("defined-tables");(0,Zt.initSync)();Cr=Object.create(null),st=Object.create(null);(0,cA._assignPackageExport)("databases",st);(0,cA._assignPackageExport)("tables",Cr);Wa=Symbol.for("next-table-id"),lA=[],Ii=new Map;a(qne,"getTables");a(Ms,"getDatabases");a(Fne,"resetDatabases");a(wl,"readMetaDb");a(Ox,"ensureDB");a(bx,"setTable");a(Qc,"database");a($p,"dropDatabase");a(dt,"table");Gne=1e3,kne=10;a(Vne,"runIndexing");a($ne,"dropTableMeta");a(SR,"onUpdatedTable")});var z=T((tSe,xx)=>{"use strict";var wi=require("path"),Cx=require("fs-extra"),br=G(),Nx=require("fs-extra"),$E=require("os"),Yne=require("net"),Kne=require("recursive-iterator"),ct=D(),Wne=aO(),yx=require("papaparse"),YE=require("moment"),{inspect:Qne}=require("util"),Ix=require("is-number"),eSe=require("lodash"),zne=require("minimist"),Jne=require("https"),Xne=require("http"),{hdb_errors:KE}=Z(),jne=/^((\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)))$/,Dx=require("util").promisify(setTimeout),Zne=100,eie=5,tie="",rie=4,wx={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};xx.exports={isEmpty:Xr,isEmptyOrZeroLength:En,arrayHasEmptyValues:iie,arrayHasEmptyOrZeroLengthValues:oie,buildFolderPath:aie,isBoolean:Lx,errorizeMessage:sie,stripFileExtension:uie,autoCast:lie,autoCastJSON:Ux,autoCastJSONDeep:dA,removeDir:_ie,compareVersions:die,isCompatibleDataVersion:fie,escapeRawValue:Eie,unescapeValue:hie,stringifyProps:mie,timeoutPromise:Sie,isClusterOperation:gie,getClusterUser:Aie,checkGlobalSchemaTable:Rie,getHomeDir:Px,getPropsFilePath:pie,promisifyPapaParse:Oie,removeBOM:vx,createEventPromise:bie,checkProcessRunning:Nie,checkSchemaTableExist:yie,checkSchemaExists:Bx,checkTableExists:Hx,getStartOfTomorrowInSeconds:Iie,getLimitKey:wie,isObject:cie,isNotEmptyAndHasValue:nie,autoCasterIsNumberCheck:Mx,backtickASTSchemaItems:Cie,isPortTaken:Tie,createForkArgs:Die,autoCastBoolean:Lie,async_set_timeout:Dx,getTableHashAttribute:Uie,doesSchemaExist:Mie,doesTableExist:Pie,stringifyObj:vie,ms_to_time:Bie,changeExtension:Hie,getEnvCliRootPath:fA,noBootFile:xie,httpRequest:qie,transformReq:Fie,convertToMS:Gie,PACKAGE_ROOT:ct.PACKAGE_ROOT};function sie(e){return e instanceof Error?e:new Error(e)}a(sie,"errorizeMessage");function Xr(e){return e==null}a(Xr,"isEmpty");function nie(e){return!Xr(e)&&(e||e===0||e===""||Lx(e))}a(nie,"isNotEmptyAndHasValue");function En(e){return Xr(e)||e.length===0||e.size===0}a(En,"isEmptyOrZeroLength");function iie(e){if(Xr(e))return!0;for(let t=0;t<e.length;t++)if(Xr(e[t]))return!0;return!1}a(iie,"arrayHasEmptyValues");function oie(e){if(En(e))return!0;for(let t=0;t<e.length;t++)if(En(e[t]))return!0;return!1}a(oie,"arrayHasEmptyOrZeroLengthValues");function aie(...e){try{return e.join(wi.sep)}catch{console.error(e)}}a(aie,"buildFolderPath");function Lx(e){return Xr(e)?!1:e===!0||e===!1}a(Lx,"isBoolean");function cie(e){return Xr(e)?!1:typeof e=="object"}a(cie,"isObject");function uie(e){return En(e)?tie:e.slice(0,-rie)}a(uie,"stripFileExtension");function lie(e){return Xr(e)||e===""||typeof e!="string"?e:wx[e]!==void 0?wx[e]:Mx(e)===!0?Number(e):jne.test(e)?new Date(e):e}a(lie,"autoCast");function Ux(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Ux,"autoCastJSON");function dA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=dA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=dA(r);s!==r&&(e[t]=s)}return e}else return Ux(e)}a(dA,"autoCastJSONDeep");function Mx(e){if(e.startsWith("0.")&&Ix(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Ix(e))}a(Mx,"autoCasterIsNumberCheck");async function _ie(e){if(En(e))throw new Error(`Directory path: ${e} does not exist`);try{await Nx.emptyDir(e),await Nx.remove(e)}catch(t){throw br.error(`Error removing files in ${e} -- ${t}`),t}}a(_ie,"removeDir");function die(e,t){if(En(e)){br.info("Invalid current version sent as parameter.");return}if(En(t)){br.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(die,"compareVersions");function fie(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(fie,"isCompatibleDataVersion");function Eie(e){if(Xr(e))return e;let t=String(e);return t==="."?ct.UNICODE_PERIOD:t===".."?ct.UNICODE_PERIOD+ct.UNICODE_PERIOD:t.replace(ct.FORWARD_SLASH_REGEX,ct.UNICODE_FORWARD_SLASH)}a(Eie,"escapeRawValue");function hie(e){if(Xr(e))return e;let t=String(e);return t===ct.UNICODE_PERIOD?".":t===ct.UNICODE_PERIOD+ct.UNICODE_PERIOD?"..":String(e).replace(ct.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(hie,"unescapeValue");function mie(e,t){if(Xr(e))return br.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+$E.EOL}!En(s)&&s[0]===";"?r+=" "+s+n+$E.EOL:En(s)||(r+=s+"="+n+$E.EOL)}catch{br.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(mie,"stringifyProps");function Px(){let e;try{e=$E.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Px,"getHomeDir");function pie(){let e=wi.join(Px(),ct.HDB_HOME_DIR_NAME,ct.BOOT_PROPS_FILE_NAME);return Cx.existsSync(e)||(e=wi.join(__dirname,"../","hdb_boot_properties.file")),e}a(pie,"getPropsFilePath");function Sie(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(Sie,"timeoutPromise");async function Tie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=Yne.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(Tie,"isPortTaken");function gie(e){try{return ct.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){br.error(`Error checking operation against cluster ops ${t}`)}return!1}a(gie,"isClusterOperation");function Rie(e,t){let r=(ge(),ee(xe)).getDatabases();if(!r[e])return KE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return KE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Rie,"checkGlobalSchemaTable");function Aie(e,t){if(Xr(t)){br.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Xr(e)||En(e)){br.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){br.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){br.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Aie,"getClusterUser");function Oie(){yx.parsePromise=function(e,t,r){return new Promise(function(s,n){yx.parse(e,{header:!0,transformHeader:vx,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(Oie,"promisifyPapaParse");function vx(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(vx,"removeBOM");function bie(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;br.info(`Got cluster status event response: ${Qne(n)}`);try{i.cancel()}catch{br.error("Error trying to cancel timeout.")}s(n)})})}a(bie,"createEventPromise");async function Nie(e){let t=!0,r=0;do await Dx(Zne*r++),(await Wne.findPs(e)).length>0&&(t=!1);while(t&&r<eie);if(t)throw new Error(`process ${e} was not started`)}a(Nie,"checkProcessRunning");function yie(e,t){let r=Bx(e);if(r)return r;let s=Hx(e,t);if(s)return s}a(yie,"checkSchemaTableExist");function Bx(e){let{getDatabases:t}=(ge(),ee(xe));if(!t()[e])return KE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Bx,"checkSchemaExists");function Hx(e,t){let{getDatabases:r}=(ge(),ee(xe));if(!r()[e][t])return KE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Hx,"checkTableExists");function Iie(){let e=YE().utc().add(1,ct.MOMENT_DAYS_TAG).startOf(ct.MOMENT_DAYS_TAG).unix(),t=YE().utc().unix();return e-t}a(Iie,"getStartOfTomorrowInSeconds");function wie(){return YE().utc().format("DD-MM-YYYY")}a(wie,"getLimitKey");function Cie(e){try{let t=new Kne(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){br.error("Got an error back ticking items."),br.error(t)}}a(Cie,"backtickASTSchemaItems");function Die(e){return[e]}a(Die,"createForkArgs");function Lie(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Lie,"autoCastBoolean");function Uie(e,t){let{getDatabases:r}=(ge(),ee(xe)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(Uie,"getTableHashAttribute");function Mie(e){let{getDatabases:t}=(ge(),ee(xe));return t()[e]!==void 0}a(Mie,"doesSchemaExist");function Pie(e,t){let{getDatabases:r}=(ge(),ee(xe));return r()[e]?.[t]!==void 0}a(Pie,"doesTableExist");function vie(e){try{return JSON.stringify(e)}catch{return e}}a(vie,"stringifyObj");function Bie(e){let t=YE.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(Bie,"ms_to_time");function Hie(e,t){let r=wi.basename(e,wi.extname(e));return wi.join(wi.dirname(e),r+t)}a(Hie,"changeExtension");function fA(){if(process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=zne(process.argv);if(e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(fA,"getEnvCliRootPath");var _A;function xie(){if(_A)return _A;let e=fA();fA()&&Cx.pathExistsSync(wi.join(e,ct.HDB_CONFIG_FILE))&&(_A=!0)}a(xie,"noBootFile");function qie(e,t){let r;return e.protocol==="http:"?r=Xne:r=Jne,new Promise((s,n)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(qie,"httpRequest");function Fie(e){if(!e.schema&&!e.database){e.schema=ct.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Fie,"transformReq");function Gie(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(Gie,"convertToMS")});var j=T((sSe,kx)=>{"use strict";var EA=require("fs-extra"),Mo=require("path"),qx=require("os"),kie=require("properties-reader"),Ll=G(),Dl=z(),ae=D(),WE=Pr(),Vie="Error initializing environment manager",QE="BOOT_PROPS_FILE_PATH",Fx=!1,$ie={[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},Vn={};kx.exports={BOOT_PROPS_FILE_PATH:QE,getHdbBasePath:Yie,setHdbBasePath:Kie,get:Gx,initSync:Qie,setProperty:Le,initTestEnvironment:zie};function Yie(){return Vn[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Yie,"getHdbBasePath");function Kie(e){Vn[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Kie,"setHdbBasePath");function Gx(e){let t=WE.getConfigValue(e);return t===void 0?Vn[e]:t}a(Gx,"get");function Le(e,t){$ie[e]&&(Vn[e]=t),WE.updateConfigObject(e,t)}a(Le,"setProperty");function Wie(){let e;try{e=Dl.getPropsFilePath(),EA.accessSync(e,EA.constants.F_OK|EA.constants.R_OK),Fx=!0;let t=kie(e);return Vn[ae.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ae.HDB_SETTINGS_NAMES.INSTALL_USER),Vn[ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Vn[QE]=e,!0}catch{return Ll.trace(`Environment manager found no properties file at ${e}`),!1}}a(Wie,"doesPropFileExist");function Qie(e=!1){try{(Fx||Wie()||Dl.noBootFile())&&(WE.initConfig(e),Vn[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=WE.getConfigValue(ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Ll.error(Vie),Ll.error(t),console.error(t),process.exit(1)}}a(Qie,"initSync");function zie(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Mo.join(__dirname,"../../","unitTests");Vn[QE]=Mo.join(u,"hdb_boot_properties.file"),Le(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Mo.join(u,"settings.test")),Le(ae.HDB_SETTINGS_NAMES.INSTALL_USER,qx.userInfo()?qx.userInfo().username:void 0),Le(ae.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Le(ae.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Mo.join(u,"envDir","log")),Le(ae.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Le(ae.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Le(ae.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Le(ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Mo.join(u,"envDir")),Le(ae.CONFIG_PARAMS.STORAGE_PATH,Mo.join(u,"envDir")),n&&(Le(ae.CONFIG_PARAMS.HTTP_SECUREPORT,Gx(ae.CONFIG_PARAMS.HTTP_PORT)),Le(ae.CONFIG_PARAMS.HTTP_PORT,null)),Le(ae.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Le(ae.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Le(ae.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Dl.isEmpty(i)?!1:i),Le(ae.CONFIG_PARAMS.HTTP_CORS,Dl.isEmpty(i)?!1:i),Le(ae.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Le(ae.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Le(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Le(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Le(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Mo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Le(ae.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Dl.isEmpty(c)?!1:c),o&&(Le("CORS_ACCESSLIST",o),Le(ae.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Le(ae.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Le(ae.CONFIG_PARAMS.HTTP_TIMEOUT,s)),t&&(Le(ae.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Le(ae.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Le(ae.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Le(ae.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${QE}. Please check your boot props and settings files`;Ll.fatal(r),Ll.error(t)}}a(zie,"initTestEnvironment")});var Wx=T((iSe,Kx)=>{"use strict";var Yx=require("joi"),{string:Ul,boolean:Vx,array:Jie}=Yx.types(),$x=D(),Xie=Je();Kx.exports=jie;function jie(e){let t=Yx.object({operation:Ul.valid($x.OPERATIONS_ENUM.ADD_NODE,$x.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Ul.required(),subscriptions:Jie.items({schema:Ul.required(),table:Ul.optional(),hash_attribute:Ul.optional(),subscribe:Vx.required(),publish:Vx.required()}).min(1).required()});return Xie.validateBySchema(e,t)}a(jie,"updateRemoteSourceValidator")});var Ml=T((aSe,Qx)=>{"use strict";var hA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,s=void 0){this.status=t,this.message=r,this.system_info=s}};Qx.exports=hA});var Zx=T((uSe,jx)=>{"use strict";var Zie=Wx(),$n=G(),mA=qe(),zx=D(),pA=os(),SA=nt(),Jx=uu(),eoe=K_(),{Node:toe,NodeSubscription:Xx}=di(),TA=Ml(),gA=z(),roe=j(),{cloneDeep:soe}=require("lodash"),{broadcast:noe}=Ye();jx.exports=ioe;async function ioe(e){try{let t=Zie(e);if(t)return $n.error(`Validation error in updateRemoteSource: ${t.message}`),new TA(mA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:s,system_info:n}=e,i=[],o=soe(await pA.getNodeRecord(s)),c=!gA.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&$n.trace(`Existing record found for ${s}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!gA.doesSchemaExist(f)){$n.trace(`updateRemoteSource creating schema: ${f}`);try{await Jx.createSchema({operation:"create_schema",schema:f})}catch(h){$n.error(h)}}if(E&&!gA.doesTableExist(f,E)){let h=new eoe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),$n.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await Jx.createTable(h)}catch(p){$n.error(p)}$n.trace(`Creating local stream for ${f}.${E}`),await SA.createLocalTableStream(f,E)}if(f===zx.SYSTEM_SCHEMA_NAME&&await SA.createLocalTableStream(f,E),await SA.updateWorkStream(d,s),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let R=o.subscriptions[p];if(R.schema===f&&R.table===E){R.publish=d.publish,R.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new Xx(f,E,d.publish,d.subscribe))}else i.push(new Xx(f,E,d.publish,d.subscribe))}c||(o=new toe(s,i,void 0),$n.trace(`No record found for ${s}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=n,await pA.upsertNodeRecord(u),noe({type:"nats_update"}),new TA(mA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${roe.get(zx.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await pA.getSystemInfo())}catch(t){$n.error(t);let r=t.message?t.message:t;return new TA(mA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(ioe,"updateRemoteSource")});var sq=T((_Se,rq)=>{"use strict";var tq=require("joi"),{string:eq}=tq.types(),ooe=D(),aoe=Je();rq.exports=coe;function coe(e){let t=tq.object({operation:eq.valid(ooe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:eq.required()});return aoe.validateBySchema(e,t)}a(coe,"removeRemoteSourceValidator")});var iq=T((fSe,nq)=>{"use strict";var uoe=sq(),zE=G(),JE=qe(),RA=D(),loe=os(),_oe=z(),doe=nt(),foe=j(),XE=Ml(),{NodeSubscription:Eoe}=di(),hoe=ta(),moe=ti(),{broadcast:poe}=Ye(),Soe=foe.get(RA.CONFIG_PARAMS.CLUSTERING_NODENAME);nq.exports=Toe;async function Toe(e){try{let t=uoe(e);if(t)return zE.error(`Validation error in removeRemoteSource: ${t.message}`),new XE(JE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,s=await loe.getNodeRecord(r);if(_oe.isEmptyOrZeroLength(s)){let i=`No record found for node '${r}'`;return zE.error(i),new XE(JE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}s=s[0];for(let i=0,o=s.subscriptions.length;i<o;i++){let c=s.subscriptions[i];zE.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Eoe(c.schema,c.table,!1,!1);await doe.updateWorkStream(u,r)}let n=new hoe(RA.SYSTEM_SCHEMA_NAME,RA.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await moe.deleteRecord(n),poe({type:"nats_update"}),new XE(JE.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Soe} successfully removed node '${r}'.`)}catch(t){zE.error(t);let r=t.message?t.message:t;return new XE(JE.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Toe,"removeRemoteSource")});var lq=T((hSe,uq)=>{"use strict";var jE=G(),ZE=D(),oq=qe(),aq=j(),goe=z(),cq=Ml(),Roe=os(),Aoe=Sd(),Ooe=Lr();uq.exports=boe;async function boe(e){try{jE.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=goe.ms_to_time(t),s=new Noe(aq.get(ZE.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),aq.get(ZE.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT),r,await Roe.getSystemInfo());try{let n={name:e.node_name,system_info:e.system_info},i=new Aoe(ZE.SYSTEM_SCHEMA_NAME,ZE.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[n]);await Ooe.update(i)}catch(n){jE.error("Get remote config encountered an error updating system info for node:",e.node_name,n)}return jE.trace("getRemoteSourceConfig response:",s),new cq(oq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){jE.error(t);let r=t.message?t.message:t;return new cq(oq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(boe,"getRemoteSourceConfig");function Noe(e,t,r,s){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=s}a(Noe,"ConfigResponseObject")});var Eq=T((pSe,fq)=>{"use strict";var _q=j();_q.initSync();var dq=nt(),Pl=G(),Ja=D(),AA=qe(),yoe=Zx(),Ioe=iq(),woe=lq(),Coe=Ml(),{encode:Doe,decode:Loe}=require("msgpackr"),Uoe=Rn(),Moe=jn(),Poe=require("util"),voe=D(),{isMainThread:Boe,parentPort:Hoe}=require("worker_threads");Ye();var xoe=Poe.promisify(Uoe.setSchemaDataToGlobal),OA=_q.get(Ja.CONFIG_PARAMS.CLUSTERING_NODENAME);fq.exports=qoe;async function qoe(){try{Pl.notify("Starting reply service."),await xoe();let e=await dq.getConnection(),t=`${OA}.__request__`,r=e.subscribe(t,{queue:OA});await Foe(r)}catch(e){Pl.error(e)}}a(qoe,"initialize");async function Foe(e){for await(let t of e){let r=Loe(t.data),s;switch(r.operation){case Ja.OPERATIONS_ENUM.ADD_NODE:case Ja.OPERATIONS_ENUM.UPDATE_NODE:s=await yoe(r);break;case Ja.OPERATIONS_ENUM.REMOVE_NODE:s=await Ioe(r);break;case Ja.OPERATIONS_ENUM.CLUSTER_STATUS:s=await woe(r);break;case Ja.OPERATIONS_ENUM.DESCRIBE_ALL:s=await Goe();break;default:let n=`node '${OA}' reply service received unrecognized request operation`;Pl.error(n),s=new Coe(AA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,n)}Pl.trace(s),t.respond(Doe(s))}}a(Foe,"handleRequest");async function Goe(){try{return{status:AA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Moe.describeAll()}}catch(e){return Pl.error(e),{status:AA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(Goe,"getRemoteDescribeAll");Boe||Hoe.on("message",async e=>{let{type:t}=e;t===voe.ITC_EVENT_TYPES.SHUTDOWN&&dq.closeConnection()})});var koe=Eq();(async()=>{try{await koe()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|
|
26
|
+
`},compressible:!1,q:.8});xt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,s]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let n=t[r];Array.isArray(n)?n.push(s):t.key=[n,s]}else t[r]=s},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});Rv={type:"application/json",serializeStream:Ec,serialize:Wu,deserialize:X7,q:.8};xt.set("*/*",Rv);xt.set("",Rv);a(X7,"tryJSONParse");a(Rg,"registerContentHandlers");Z7=require("fastify-plugin"),eee=Z7(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Af(s.raw);n.type(c),n.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{n.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Af,"findBestSerializer");mv=pg.default.get(Sg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Of,"serialize");a(Ti,"serializeMessage");a(tee,"streamToBuffer");a(ho,"getDeserializer");a(pv,"deserializerUnknownType");a(ree,"transformIterable")});function Ia(e,t,r,s,n,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let g=o[0],A=vn(s.attributes,g);if(A.relationship){if(o.length<2)throw new Pn.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=Ia({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,b,n,v);if(A.relationship.to){i[o[0]]=v;let H=!!vn(b.attributes,A.relationship.to)?.elements;G=aee(G,A,b.primaryStore,H,v)}if(A.relationship.from){let H=a(P=>Ia({attribute:A.relationship.from,value:P},t,r,s,n,v),"searchEntry");A.elements?(i[o[0]]=v,G=cee(G,A,b.primaryStore,v,H)):G=G.flatMap(H)}return G}else if(o.length===1)o=o[0];else throw new Pn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Ng[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]=an.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 Pn.ClientError(`Unknown query comparator "${u}"`)}if(r){let g=_;_=l,l=g,g=!f,f=!d,d=g}let h=o===s.primaryKey||o==null,p=h?s.primaryStore:s.indices[o];if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(!n)throw new Pn.ClientError(`"${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);let g=ju(e);if(!g)throw new Pn.ClientError(`Unknown search operator ${e.comparator}`);return s.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:A,value:b})=>new Promise((v,G)=>setImmediate(()=>{try{v(b&&g(b)?A:Ag.SKIP)}catch(H){G(H)}})))}let S={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let g=p.getRange(S).map(A=>A.value==null?Ag.SKIP:A);return g.hasEntries=!0,g}else return p.getRange(S).map(({value:g})=>g)}function vn(e,t){if(Array.isArray(t))if(t.length>1){let r=vn(e,t[0]),s=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return s?vn(s,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function aee(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i;n.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=Bs(d),o=!0);let h=n.get(E);h?h.push(f):n.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&&!n.filters?.some(h=>!h(f))){if(s)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?n:n.keys())[Symbol.iterator](),this.next()})()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function cee(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Bs(u.value);if(!c.has(_))return c.add(_),u}if(!i)return(async()=>{let _=new Map;s.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>_.has(Bs(f)));let l=0;for await(let d of e){if(s.filters){let f=r.get(d);if(s.filters.some(E=>!E(f)))continue}_.set(Bs(d),d),l++>100&&(await new Promise(setImmediate),l=0)}return i=_.values()[Symbol.iterator](),this.next()})();do{let _=i.next();return _.done?_:(o=n(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function ju(e,t,r,s,n,i){if(e.conditions){let l=e.conditions.map(ju);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=vn(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=s?.[l],h=ju({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,g=a((A,b)=>{let v,G;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let P of h.idFilter.idSet)e={attribute:p.from,value:P};S=_(p.from,h.idFilter,!0)}else S=_(p.from,h.idFilter,!1);let H=S(A);return S.idFilter&&(g.idFilter=S.idFilter),H}G=p(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()),Ng[o]||o){case Og.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,an.compareKeys)(l,u[0])>=0&&(0,an.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,an.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,an.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,an.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,an.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,an.compareKeys)(l,u)!==0);default:throw new Pn.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f){let E;f=f&&!n&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&bf(t)(e),E=e.estimated_count>>4,(isNaN(E)||E>=i)&&(f=!1));let h=0,p=3;function S(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&&(p++,!b&&!S.idFilter&&++h/p*(i-p)>E)){let v=Ia(e,r.transaction,!1,t).map(Bs),G=new Set(v);S.idFilter=H=>G.has(Bs(H)),S.idFilter.idSet=G}return b}return a(S,"recordFilter"),n&&(S.idFilter=d),S}a(_,"attributeComparator")}function bf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let n;if(r.operator==="or"){n=0;for(let i of r.conditions)t(i),n+=i.estimated_count}else{n=1/0;for(let i of r.conditions)t(i),n=isFinite(n)?n*i.estimated_count/Ai(e.primaryStore):i.estimated_count}return r.estimated_count=n,r.estimated_count}let s=r.comparator||r.search_type;if(s=Ng[s]||s,s===Og.SEARCH_TYPES.EQUALS||!s){let n=r[0]??r.attribute;if(n==null||n===e.primaryKey)r.estimated_count=1;else if(Array.isArray(n)&&n.length>1){let i=vn(e.attributes,n[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=bf(o)({value:r.value,attribute:n.length>2?n.slice(1):n[1],comparator:"equals"});r.estimated_count=c*Ai(e.indices[i.relationship.from]||e.primaryStore)/(Ai(o.primaryStore)||1)}else{let i=e.indices[n];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(s==="contains"||s==="ends_with"||s==="ne"){let n=r[0]??r.attribute,i=e.indices[n];r.value===null&&s==="ne"?r.estimated_count=Ai(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else s==="starts_with"||s==="prefix"?r.estimated_count=iee*Ai(e.primaryStore)+1:s==="between"?r.estimated_count=nee*Ai(e.primaryStore)+1:r.estimated_count=see*Ai(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=4)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Nf(e){if(e)if(Oi=e,ya.lastIndex=0,uee.test(e))try{let t=zu(new wa,"");if(Tr!==Oi.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 ${Tr} in '${Oi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function zu(e,t){let r=ya,s,n,i,o,c,u=decodeURIComponent;for(;s=r.exec(Oi);){Tr=r.lastIndex;let[,_,l]=s;if(o){if(_)throw new SyntaxError(`expected operator, but encountered '${_}'`);o=!1,c=!1}else c=!0;let d;switch(l){case"=":if(n){if(_.length<=2)i=_;else throw new SyntaxError(`invalid FIQL operator ${_}`);u=Ov}else{if(u=decodeURIComponent,i="equals",!_)throw new SyntaxError("attribute must be specified before equality comparator");n=Ju(_)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=oee[l],u=bg[i]?Ov:decodeURIComponent,!_)throw new SyntaxError(`attribute must be specified before comparator ${l}`);n=Ju(_);break;case"|":e.operator="or";case"":case void 0:case"&":if(n==null){if(n===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:n,value:u(_)};i==="eq"&&bv(E,_),e.conditions.push(E)}n=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(Ju(_)),n=void 0;break;case"(":ya.lastIndex=Tr;let f=zu(_?[]:new wa,")");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=Nv(f);break;default:throw new SyntaxError(`unknown query function call ${_}`)}Oi[Tr]===","?r.lastIndex=++Tr:o=!0,n=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");ya.lastIndex=Tr,d=zu([],"}"),d.name=_,e.push(d),Oi[Tr]===","?r.lastIndex=++Tr:o=!0;break;case"[":ya.lastIndex=Tr,_?(d=zu(new wa,"]"),d.name=_):d=zu(e.conditions?new wa:[],"]"),e.conditions?(e.conditions.push(d),n=null):e.push(d),Oi[Tr]===","?r.lastIndex=++Tr:o=!0;break;case")":case"]":case"}":if(t===l[0]){if(e.conditions){if(n){let E={comparator:i||"equals",attribute:n,value:u(_)};i==="eq"&&bv(E,_),e.conditions.push(E)}else if(_)throw new SyntaxError("no attribute or comparison specified")}else(_||e.length>0&&c)&&e.push(Ju(_));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=n?lee:ya,r.lastIndex=Tr),Tr===Oi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Ju(e){return e.indexOf(".")>-1?e.split(".").map(Ju):decodeURIComponent(e)}function Ov(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 Pn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function bv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Pn.ClientError("wildcard can only be used at the end of a string")}function Nv(e){let t=yv(e[0]);return e.length>1&&(t.next=Nv(e.slice(1))),t}function yv(e){if(Array.isArray(e)){let t=yv(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 Bs(e){return Array.isArray(e)?e.join("\0"):e}function Ai(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function wv(e,t,r){return t*r/Ai(e)}var Pn,Og,an,Ag,see,nee,iee,oee,bg,Ng,uee,ya,lee,Tr,Oi,wa,yf=Re(()=>{Pn=B(Z()),Og=B(ht()),an=require("ordered-binary"),Ag=require("lmdb"),see=.3,nee=.1,iee=.05,oee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},bg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Ia,"searchByIndex");a(vn,"findAttribute");a(aee,"joinTo");a(cee,"joinFrom");Ng={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(ju,"filterByType");a(bf,"estimateCondition");uee=/[()[\]|!<>.]|(=\w*=)/,ya=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,lee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Nf,"parseQuery");a(zu,"parseBlock");a(Ju,"decodeProperty");a(Ov,"typedDecoding");a(bv,"wildcardDecoding");a(Nv,"toSortObject");a(yv,"toSortEntry");wa=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}};a(Bs,"flattenKey");a(Ai,"estimatedEntryCount");a(wv,"intersectionEstimate")});function Uv(e){let t={openapi:_ee,info:{title:"HarperDB HTTP REST interface",version:(0,Mv.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,s]of e){if(!s.path)continue;let{path:n}=s,{attributes:i,primaryKey:o,prototype:c}=s.Resource;if(o=o??"id",!o)continue;let u={},_=[];if(i)for(let{type:A,name:b}of i)u[b]=new Lv(Iv[A],A),_.push(new Ig(b,"query",u[b]));let l=Object.keys(u),d=new Ig(o,"path",new Lv(Iv.ID,"ID"));d.required=!0,d.description="primary key of record";let f=new Ig("property","path",{enum:l});f.required=!0,t.components.schemas[n]=new Eee(u);let E=c.post!==Resource.prototype.post||c.update,h=c.hasOwnProperty("put"),p=c.hasOwnProperty("get"),S=c.hasOwnProperty("delete"),g="/"+n+"/";E&&(t.paths[g]={},t.paths[g].post=new dee(n,r,"create a new record auto-assigning a primary key")),p&&(t.paths[g]||(t.paths[g]={}),t.paths[g].get=new yg(_,r,{200:new wg({$ref:wf+n})},"search for records by the specified property name and value")),S&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new Dv(_,r,"delete all the records that match the provided query",{204:new Cv})),g="/"+n+"/{"+o+"}",p&&(t.paths[g]={},t.paths[g].get=new yg([d],r,{200:new wg({$ref:wf+n})},"retrieve a record by its primary key")),h&&(t.paths[g]||(t.paths[g]={}),t.paths[g].put=new fee([d],r,n,"create or update the record with the URL path that maps to the record's primary key")),S&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new Dv([d],r,"delete a record with the given primary key",{204:new Cv})),p&&f.schema.enum.length>0&&(g="/"+n+"/{"+o+"}.{property}",t.paths[g]={},t.paths[g].get=new yg([d,f],r,{200:new wg({enum:l})},"used to retrieve the specified property of the specified record"))}return t}function dee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:wf+e}}}},this.security=t,this.responses={200:{description:Cg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function yg(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.responses=r}function wg(e){this.description=Cg,this.content={"application/json":{schema:e}}}function Cv(){this.description="successfully processed request, no content returned to client"}function fee(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:wf+r}}}},this.responses={200:{description:Cg}}}function Dv(e,t,r,s){this.description=r,this.parameters=e,this.security=t,this.responses=s}function Eee(e){this.type="object",this.properties=e}function Lv(e,t){this.type=e,this.format=t}function Ig(e,t,r){this.name=e,this.in=t,this.schema=r}var Mv,_ee,Iv,wf,Cg,Pv=Re(()=>{Mv=B(Nd()),_ee="3.0.3",Iv={ID:"string",Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",Any:"string",BigInt:"integer"},wf="#/components/schemas/",Cg="successful operation";a(Uv,"generateJsonApi");a(dee,"Post");a(yg,"Get");a(wg,"Response200");a(Cv,"Response204");a(fee,"Put");a(Dv,"Delete");a(Eee,"ResourceSchema");a(Lv,"Type");a(Ig,"Parameter")});var Cf={};We(Cf,{start:()=>pee});async function mee(e,t){let r=e.headers.asObject,s=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Nf(e);let n=new Si;try{e.responseHeaders=n;let i=e.url.slice(1),o,c;if(i!==vv){let h=If.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 et(e,()=>{if(s==="POST"||s==="PUT"||s==="PATCH"||s==="QUERY")try{e.data=ho(r["content-type"],!0)(e.body)}catch(h){throw new Zu.ClientError(h,400)}if(e.authorize=!0,i===vv&&s==="GET")return Uv(If);switch(s){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":n.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new Zu.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Zu.ServerError(`Method ${s} is not recognized`,501)}}),l=200,d;if(_==null)l=s==="GET"||s==="HEAD"?404:204,Dg.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){hee[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),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):n.setIfNone("ETag",h),Dg.lastModified&&n.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&n.setIfNone("Location",e.newLocation);let f={status:l,headers:n,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&n.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=Of(_,e,f),s==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?mo.warn(i):mo.info(i):mo.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),n.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:n,body:void 0};return o.body=Of(i.contentType?i:i.toString(),e,o),o}}function pee(e){Dg=e,!Bv&&(Bv=!0,If=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return mee(t,r)}),e.server.ws(async(t,r,s)=>{Xu++;let n=new Os;Hv||(Hv=!0,eu(l=>{Xu>0&&l.push({metric:"ws-connections",connections:Xu,byThread:!0})}));let i;t.on("error",l=>{i=!0,mo.warn(l)});let o;t.on("message",a(function(d){o||(o=ho(r.headers.asObject["content-type"]));let f=o(d);n.push(f)},"message"));let c;t.on("close",()=>{Xu--,is(!i,"connection","ws","disconnect"),n.emit("close"),c&&c.return()}),await s;let u=r.url.slice(1),_=If.getMatch(u);if(is(!!_,"connection","ws","connect"),!_)t.send(Ti(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Fr(h=>({count:h.count,total:Xu}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await et(r,()=>d.connect(l,n,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ti(E.value,r);t.send(h),Fr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var mo,Zu,$t,hee,Dg,vv,Bv,If,Hv,Xu,xv=Re(()=>{Ta();Nn();mo=B(V()),Zu=B(Z());yf();dc();Ji();jd();Pv();$t=new Uint8Array(8),hee=new Float64Array($t.buffer,0,1),Dg={},vv="openapi";a(mee,"http");Xu=0;a(pee,"start")});var Lg=T((Zhe,qv)=>{var{recordAction:Df,recordActionBinary:See}=(Nn(),ee(tu)),Tee=require("fastify-plugin"),gee=200;qv.exports=Tee(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n,i)=>{let o=n.getResponseTime(),c=performance.now(),u=n.request.routeOptions,_,l,d;u.config?.isOperation?(_=s.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Df(o,"duration",_,d,l),See(n.raw.statusCode<400,"success",_,d,l);let f=gee;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Df(performance.now()-c,"transfer",_,d,l),Df(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Df(f,"bytes-sent",_,d,l));let E=o.toFixed(3);n.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var vg=T((eme,$v)=>{var vf=require("clone"),Bf=Ze(),Ree=J(),Uf=L(),Aee=V(),Lf=require("fs"),Mg=require("joi"),{string:Pf}=Mg.types(),{hdb_errors:Oee,handleHDBError:el}=Z(),{HDB_ERROR_MSGS:bee,HTTP_STATUS_CODES:Mf}=Oee,{common_validators:Ca}=Ys(),Fv=1e9,Gv=" is required",Nee=["insert","update","upsert"],Ug={database:{presence:!1,format:Ca.schema_format,length:Ca.schema_length},schema:{presence:!1,format:Ca.schema_format,length:Ca.schema_length},table:{presence:!0,format:Ca.schema_format,length:Ca.schema_length},action:{inclusion:{within:Nee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},yee={schema:Pf.required(),table:Pf.required(),action:Pf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:wee,AWS_SECRET:Iee,AWS_BUCKET:Cee,AWS_FILE_KEY:Dee,REGION:Lee}=Uf.S3_BUCKET_AUTH_KEYS,Mee={s3:{presence:!0},[`s3.${wee}`]:{presence:!0,type:"String"},[`s3.${Iee}`]:{presence:!0,type:"String"},[`s3.${Cee}`]:{presence:!0,type:"String"},[`s3.${Dee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Lee}`]:{presence:!0,type:"String"}},kv=vf(Ug);kv.data.presence={message:Gv};var Vv=vf(Ug);Vv.file_path.presence={message:Gv};var Uee=Object.assign(vf(Ug),Mee),Pg=vf(yee);Pg.csv_url=Pf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Pg.passthrough_headers=Mg.object();function Pee(e){let t=Bf.validateObject(e,kv);return Hf(e,t)}a(Pee,"dataObject");function vee(e){let t=Bf.validateBySchema(e,Mg.object(Pg));return Hf(e,t)}a(vee,"urlObject");function Bee(e){let t=Bf.validateObject(e,Vv);return Hf(e,t)}a(Bee,"fileObject");function Hee(e){let t=Bf.validateObject(e,Uee);return Hf(e,t)}a(Hee,"s3FileObject");function Hf(e,t){if(!t){let r=Ree.checkGlobalSchemaTable(e.schema,e.table);if(r)return el(new Error,r,Mf.BAD_REQUEST);if(e.operation===Uf.OPERATIONS_ENUM.CSV_FILE_LOAD){try{Lf.accessSync(e.file_path,Lf.constants.R_OK|Lf.constants.F_OK)}catch(s){return s.code===Uf.NODE_ERROR_CODES.ENOENT?el(s,`No such file or directory ${s.path}`,Mf.BAD_REQUEST):s.code===Uf.NODE_ERROR_CODES.EACCES?el(s,`Permission denied ${s.path}`,Mf.BAD_REQUEST):el(s)}try{let s=Lf.statSync(e.file_path).size;if(s>Fv)return el(new Error,bee.MAX_FILE_SIZE_ERR(s,Fv),Mf.BAD_REQUEST)}catch(s){Aee.error(s),console.error(s)}}}return t}a(Hf,"postValidateChecks");$v.exports={dataObject:Pee,urlObject:vee,fileObject:Bee,s3FileObject:Hee}});var Bg=T((rme,Yv)=>{"use strict";var tl=V(),xf=L();async function xee(e,t,r,s=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===xf.OPERATIONS_ENUM.INSERT||t.operation===xf.OPERATIONS_ENUM.UPDATE||t.operation===xf.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===xf.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(tl.info(i.message),i):i.http_resp_msg?(tl.error(`Error calling operation: ${e.name}`),tl.error(i.http_resp_msg),i):(tl.error(`Error calling operation: ${e.name}`),tl.error(i),i)}}a(xee,"callOperationFunctionAsAwait");Yv.exports={callOperationFunctionAsAwait:xee}});var Wv=T((nme,Kv)=>{"use strict";var Hg=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}},xg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};Kv.exports={BulkLoadFileObject:Hg,BulkLoadDataObject:xg}});var zv=T((ome,Qv)=>{"use strict";var qg=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};Qv.exports=qg});var Yg=T((dme,d0)=>{"use strict";var qf=Mr(),Gf=vg(),qee=require("needle"),Hs=L(),cme=Ge(),Da=J(),{handleHDBError:at,hdb_errors:n0}=Z(),{HTTP_STATUS_CODES:Yt,HDB_ERROR_MSGS:It,CHECK_LOGS_WRAPPER:So}=n0,La=V(),Fg=require("papaparse");Da.promisifyPapaParse();var xs=require("fs-extra"),Fee=require("path"),{chain:Jv}=require("stream-chain"),jv=require("stream-json/streamers/StreamArray"),Xv=require("stream-json/utils/Batch"),Zv=require("stream-chain/utils/comp"),{finished:e0}=require("stream"),Gee=X(),i0=Bg(),kee=fg(),{BulkLoadFileObject:kg,BulkLoadDataObject:Vee}=Wv(),Vg=sg(),{verifyBulkLoadAttributePerms:o0}=pf(),ume=zv(),lme=it(),_me=Tn(),{databases:$ee}=(Ae(),ee(Fe)),{coerceType:Yee}=(kf(),ee(Kg)),t0="No records parsed from csv file.",po=`${Gee.get("HDB_ROOT")}/tmp`,{schema_regex:Kee}=Ys(),r0=1024*1024*2,s0=5e3,Wee={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};d0.exports={csvDataLoad:Qee,csvURLLoad:zee,csvFileLoad:Jee,importFromS3:jee};async function Qee(e,t){let r=Gf.dataObject(e);if(r)throw at(r,r.message,Yt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=u0(e.schema,e.table),i=Fg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Gg.bind(null,n),dynamicTyping:!1}),o=new Vg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&o0(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 Vee(e.action,e.schema,e.table,i.data);return s=await i0.callOperationFunctionAsAwait(l0,u,null),s.message===t0?t0:_0(s.records,s.number_written)}catch(n){throw To(n)}}a(Qee,"csvDataLoad");async function zee(e){let t=Gf.urlObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${po}/${r}`;try{await Xee(e,r)}catch(n){throw La.error(It.DOWNLOAD_FILE_ERR(r)+" - "+n),at(n,So(It.DOWNLOAD_FILE_ERR(r)))}try{let n=new kg(this.job_operation_function.name,e.action,e.schema,e.table,s,Hs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await $g(n);return await Ff(s),i}catch(n){throw await Ff(s),To(n)}}a(zee,"csvURLLoad");async function Jee(e){let t=Gf.fileObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r=new kg(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Hs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await $g(r)}catch(s){throw To(s)}}a(Jee,"csvFileLoad");async function jee(e){let t=Gf.s3FileObject(e);if(t)throw at(t,t.message,Yt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=Fee.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${po}/${n}`;let i=new kg(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await Zee(n,e);let o=await $g(i);return await Ff(r),o}catch(s){throw await Ff(r),To(s)}}a(jee,"importFromS3");async function Xee(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await qee("get",e.csv_url,s)}catch(s){let n=`Error downloading CSV file from ${e.csv_url}, status code: ${s.statusCode}. Check the log for more information.`;throw at(s,n,s.statusCode,Hs.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}tte(r,e.csv_url),await ete(t,r.raw)}a(Xee,"downloadCSVFile");async function Zee(e,t){try{let r=`${po}/${e}`;await xs.mkdirp(po),await xs.writeFile(`${po}/${e}`,"",{flag:"a+"});let s=await xs.createWriteStream(r),n=await kee.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){La.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw La.error(It.S3_DOWNLOAD_ERR+" - "+r),at(r,So(It.S3_DOWNLOAD_ERR))}}a(Zee,"downloadFileFromS3");async function ete(e,t){try{await xs.mkdirp(po),await xs.writeFile(`${po}/${e}`,t)}catch(r){throw La.error(It.WRITE_TEMP_FILE_ERR),at(r,So(It.DEFAULT_BULK_LOAD_ERR))}}a(ete,"writeFileToTempFolder");async function Ff(e){if(e)try{await xs.access(e),await xs.unlink(e)}catch{La.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(Ff,"deleteTempFile");function tte(e,t){if(e.statusCode!==n0.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(!Wee[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(tte,"validateURLResponse");async function $g(e){try{let t;switch(e.file_type){case Hs.VALID_S3_FILE_TYPES.CSV:t=await rte(e);break;case Hs.VALID_S3_FILE_TYPES.JSON:t=await ste(e);break;default:throw at(new Error,It.DEFAULT_BULK_LOAD_ERR,Yt.BAD_REQUEST,Hs.LOG_LEVELS.ERROR,It.INVALID_FILE_EXT_ERR(e))}return _0(t.records,t.number_written)}catch(t){throw To(t)}}a($g,"fileLoad");async function a0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await qf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&o0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=at(c);r(u)}}a(a0,"validateChunk");async function c0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;Da.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!Da.isEmpty(c)&&!Da.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 i0.callOperationFunctionAsAwait(l0,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=at(c,So(It.INSERT_CSV_ERR),Yt.INTERNAL_SERVER_ERROR,Hs.LOG_LEVELS.ERROR,It.INSERT_CSV_ERR+" - "+c);r(u)}}a(c0,"insertChunk");async function rte(e){let t={records:0,number_written:0},r=u0(e.schema,e.table);try{let s=new Vg,n=xs.createReadStream(e.file_path,{highWaterMark:r0});n.setEncoding("utf8"),await Fg.parsePromise(n,a0.bind(null,e,s),Gg.bind(null,r));let i=s.getPermsResponse();if(i)throw at(new Error,i,Yt.BAD_REQUEST);return n=xs.createReadStream(e.file_path,{highWaterMark:r0}),n.setEncoding("utf8"),await Fg.parsePromise(n,c0.bind(null,e,t),Gg.bind(null,r)),n.destroy(),t}catch(s){throw at(s,So(It.PAPA_PARSE_ERR),Yt.INTERNAL_SERVER_ERROR,Hs.LOG_LEVELS.ERROR,It.PAPA_PARSE_ERR+s)}}a(rte,"callPapaParse");function u0(e,t){let r=$ee[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>Yee(i,n));return s}a(u0,"createTransformMap");function Gg(e,t,r){let s=e.get(r);return s?s(t):Da.autoCast(t)}a(Gg,"typeFunction");async function ste(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Vg,n=Jv([xs.createReadStream(e.file_path,{encoding:"utf-8"}),jv.withParser(),c=>c.value,new Xv({batchSize:s0}),Zv(async c=>{await a0(e,s,r,c)})]);await new Promise((c,u)=>{e0(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw at(new Error,i,Yt.BAD_REQUEST);let o=Jv([xs.createReadStream(e.file_path,{encoding:"utf-8"}),jv.withParser(),c=>c.value,new Xv({batchSize:s0}),Zv(async c=>{await c0(e,t,r,c)})]);return await new Promise((c,u)=>{e0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw at(s,So(It.INSERT_JSON_ERR),Yt.INTERNAL_SERVER_ERROR,Hs.LOG_LEVELS.ERROR,It.INSERT_JSON_ERR+s)}}a(ste,"insertJson");async function l0(e){let t={};try{e.data&&e.data.length>0&&nte(e.data[0])?t=await ite(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",La.info(t.message))}catch(r){throw To(r)}return t}a(l0,"callBulkFileLoad");function nte(e){let t=Object.keys(e);for(let r of t)if(!Kee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(nte,"validateColumnNames");async function ite(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=qf.insert;break;case"update":i=qf.update;break;case"upsert":i=qf.upsert;break;default:throw at(new Error,It.INVALID_ACTION_PARAM_ERR(s),Yt.BAD_REQUEST,Hs.LOG_LEVELS.ERROR,It.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Da.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw To(o)}}a(ite,"bulkFileLoad");function _0(e,t){return`successfully loaded ${t} of ${e} records`}a(_0,"buildResponseMsg");function To(e){return at(e,So(It.DEFAULT_BULK_LOAD_ERR),Yt.INTERNAL_SERVER_ERROR,Hs.LOG_LEVELS.ERROR,It.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(To,"buildTopLevelErrMsg")});var E0=T((Eme,f0)=>{"use strict";var Wg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};f0.exports=Wg});var p0=T((mme,m0)=>{"use strict";var ote=L(),h0=require("moment"),ate=require("uuid").v4,Qg=class{static{a(this,"JobObject")}constructor(){this.id=ate(),this.type=void 0,this.start_datetime=h0().valueOf(),this.created_datetime=h0().valueOf(),this.end_datetime=void 0,this.status=ote.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};m0.exports=Qg});var zg=T((Sme,O0)=>{"use strict";var cte=require("uuid").v4,g0=Mr(),R0=rs(),ute=Js(),lte=ea(),_te=E0(),ct=L(),dte=p0(),fte=Sd(),hs=V(),Ete=yc(),Ma=J(),{promisify:hte}=require("util"),go=require("moment"),mte=Tf(),Vf=vg(),S0=Cm(),{deleteTransactionLogsBeforeValidator:pte}=XT(),{handleHDBError:Ste,hdb_errors:Tte}=Z(),{HTTP_STATUS_CODES:gte}=Tte,T0=R0.searchByValue,Rte=R0.searchByHash,Ate=g0.insert,Ote=hte(mte.evaluateSQL),bte=g0.update;O0.exports={addJob:wte,updateJob:Cte,handleGetJob:Nte,handleGetJobsByStartDate:yte,getJobById:A0};async function Nte(e){try{let t=await A0(e.id);return Ma.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 hs.error("There was an error getting job",t),new Error(r)}}a(Nte,"handleGetJob");async function yte(e){try{let t=await Ite(e);if(hs.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=go(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=go(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 hs.error(r),new Error(r)}}a(yte,"handleGetJobsByStartDate");async function wte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ma.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return hs.info(l),t.error=l,t}if(!ct.JOB_TYPE_ENUM[e.operation])return hs.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case ct.OPERATIONS_ENUM.CSV_FILE_LOAD:s=Vf.fileObject(e);break;case ct.OPERATIONS_ENUM.CSV_URL_LOAD:s=Vf.urlObject(e);break;case ct.OPERATIONS_ENUM.CSV_DATA_LOAD:s=Vf.dataObject(e);break;case ct.OPERATIONS_ENUM.IMPORT_FROM_S3:s=Vf.s3FileObject(e);break;case ct.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ct.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=S0(e,"date");break;case ct.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=S0(e,"timestamp");break;case ct.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=pte(e);break;default:break}if(s)throw Ste(s,s.message,gte.BAD_REQUEST,void 0,void 0,!0);let n=new dte;n.type=e.operation===ct.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ct.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new ute(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await T0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return hs.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=cte();try{o=await T0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return hs.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return hs.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new Ete(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await Ate(u)}catch(l){return hs.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,hs.trace(l)}return t}a(wte,"addJob");async function Ite(e){let t=go(e.from_date,go.ISO_8601),r=go(e.to_date,go.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new _te(s,e.hdb_user);try{return await Ote(n)}catch(i){throw hs.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(Ite,"getJobsInDateRange");async function A0(e){if(Ma.isEmptyOrZeroLength(e))return Ma.errorizeMessage("Invalid job ID specified.");let t=new lte(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Rte(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return hs.error(s),Ma.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(A0,"getJobById");async function Cte(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ma.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=go().valueOf());let t=new fte(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await bte(t),r}a(Cte,"updateJob")});var C0=T((gme,I0)=>{"use strict";var b0=J(),gr=L(),Dte=require("moment"),$f=Yg(),Yf=V(),N0=zg(),y0=gf(),w0=ti(),Lte=Qe(),Mte=ff(),Jg=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Ute(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(b0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(b0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case gr.JOB_TYPE_ENUM.csv_file_load:await Bn(e,$f.csvFileLoad);break;case gr.JOB_TYPE_ENUM.csv_url_load:await Bn(e,$f.csvURLLoad);break;case gr.JOB_TYPE_ENUM.csv_data_load:await Bn(e,$f.csvDataLoad);break;case gr.JOB_TYPE_ENUM.import_from_s3:await Bn(e,$f.importFromS3);break;case gr.JOB_TYPE_ENUM.empty_trash:break;case gr.JOB_TYPE_ENUM.export_local:await Bn(e,y0.export_local);break;case gr.JOB_TYPE_ENUM.export_to_s3:await Bn(e,y0.export_to_s3);break;case gr.JOB_TYPE_ENUM.delete_files_before:case gr.JOB_TYPE_ENUM.delete_records_before:await Bn(e,w0.deleteFilesBefore);break;case gr.JOB_TYPE_ENUM.delete_audit_logs_before:await Bn(e,w0.deleteAuditLogsBefore);break;case gr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Bn(e,Mte.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Ute,"parseMessage");async function Bn(e,t){try{e.job.status=gr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Dte().valueOf(),await N0.updateJob(e.job),await Pte(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):Yf.error(`There was an error running ${t.name} job with id ${e.job.id}`),Yf.error(s),e.job.message=s,e.job.status=gr.JOB_STATUS_ENUM.ERROR;try{await N0.updateJob(e.job)}catch(n){throw Yf.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Bn,"runJob");async function Pte(e){Yf.trace("launching job thread:",e),Lte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[gr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Pte,"launchJobThread");I0.exports={parseMessage:Ute,RunnerMessage:Jg}});var L0=T((Ame,D0)=>{"use strict";var jg=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};D0.exports=jg});var Q0=T((bme,sR)=>{"use strict";var zf=rs(),eR=Tf(),Kf=Yg(),Hn=cu(),Wf=Xn(),sl=ti(),vte=SS(),rl=ns(),Qf=wS(),Kt=jT(),Ct=V(),Bte=DS(),Hte=Dd(),M0=_T(),xte=Md(),qte=dT(),Fte=fT(),Gte=mT(),kte=ST(),Xg=RT(),U0=gf(),Vte=pf(),tR=zg(),q=L(),{hdb_errors:il,handleHDBError:nl}=Z(),{HTTP_STATUS_CODES:P0}=il,Zg=yT(),v0=zd(),$0=require("util"),Ua=Mr(),$te=gn(),Yte=_a(),B0=C0(),H0=Eu(),x0=(tf(),ee(Pu)),q0=vr(),F0=ff(),G0=af(),{setServerUtilities:Kte}=(kf(),ee(Kg)),{CONTEXT:Wte}=(bs(),ee(bp)),{_assignPackageExport:Qte}=require("../index"),{transformReq:zte}=J(),{server:Jte}=(rr(),ee(Di)),jte=Bg(),k0=zf.searchByHash,Xte=zf.searchByValue,Zte=$0.promisify(zf.search),ere=$0.promisify(eR.evaluateSQL),tre={[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},$=L0();async function Y0(e,t){try{if(e.body.operation!=="read_log"&&(Ct.log_level===q.LOG_LEVELS.INFO||Ct.log_level===q.LOG_LEVELS.DEBUG||Ct.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;Ct.info(o)}}catch(s){Ct.error(s)}let r=await jte.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return tre[e.body.operation]&&$te.setSchemaDataToGlobal(s=>{s&&Ct.error(s)}),r}a(Y0,"processLocalTransaction");var V0=sre();sR.exports={chooseOperation:K0,getOperationFunction:W0,operation:rR,processLocalTransaction:Y0};Kte(sR.exports);Jte.operation=rR;function K0(e){let t;try{t=W0(e)}catch(n){throw Ct.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=eR.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=eR.checkASTPermissions(e,i);if(o)throw Ct.error(`${P0.FORBIDDEN} from operation ${e.operation}`),Ct.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),nl(new Error,o,il.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Vte.verifyPerms(i,n);if(o)throw Ct.error(`${P0.FORBIDDEN} from operation ${e.operation}`),Ct.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),nl(new Error,o,il.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw nl(n,"There was an error when trying to choose an operation path")}return r}a(K0,"chooseOperation");function W0(e){if(Ct.trace(`getOperationFunction with operation: ${e.operation}`),V0.has(e.operation))return V0.get(e.operation);throw nl(new Error,il.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),il.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(W0,"getOperationFunction");Qte("operation",rR);function rR(e,t){e.hdb_user=this[Wte]?.user,e.bypass_auth=!t;let r=K0(e);return Y0({body:e},r)}a(rR,"operation");async function rre(e){Ct.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await Ua.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await Ua.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await Ua.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await sl.deleteRecord(i);break;default:Ct.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Ct.info("Invalid operation in transaction"),Ct.error(o)}}a(rre,"catchup");async function cn(e){zte(e);let t,r;try{r=await tR.addJob(e),t=r.createdJob,Ct.info("addJob result",r);let s=new B0.RunnerMessage(t,e);return await B0.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw Ct.error(n),nl(s,n)}}a(cn,"executeJob");function sre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new $(Ua.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new $(Ua.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new $(Ua.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new $(zf.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new $(k0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new $(k0)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new $(Xte)),e.set(q.OPERATIONS_ENUM.SEARCH,new $(Zte)),e.set(q.OPERATIONS_ENUM.SQL,new $(ere)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new $(cn,Kf.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new $(cn,Kf.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new $(cn,Kf.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new $(cn,Kf.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new $(Hn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new $(Hn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new $(Hn.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new $(Hn.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new $(Hn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new $(Hn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new $(Hn.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new $(Hn.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new $(Wf.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new $(Wf.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new $(Wf.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new $(Wf.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new $(sl.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new $(rl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new $(rl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new $(rl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new $(rl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new $(Qf.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new $(Qf.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new $(Qf.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new $(Qf.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new $(rl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new $(Bte)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new $(Hte)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new $(M0)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new $(M0)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new $(xte)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new $(qte)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new $(Fte)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new $(q0.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new $(Gte.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new $(kte)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new $(Xg.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new $(Xg.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new $(Xg.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new $(cn,U0.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new $(cn,sl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new $(cn,sl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new $(cn,U0.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new $(tR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new $(tR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new $(Zg.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new $(Zg.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new $(Zg.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new $(v0.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new $(v0.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new $(rre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new $(Yte.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new $(cn,sl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new $(vte)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new $(H0.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new $(H0.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new $(x0.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new $(x0.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new $(q0.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new $(Kt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new $(Kt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new $(Kt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new $(Kt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new $(Kt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new $(Kt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new $(Kt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new $(Kt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new $(Kt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new $(Kt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new $(Kt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new $(Kt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new $(Kt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new $(Kt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new $(Kt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new $(Kt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new $(F0.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new $(cn,F0.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new $(G0.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new $(G0.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new $(Hn.getBackup)),e}a(sre,"initializeOperationFunctionMap")});var jf=T((yme,j0)=>{"use strict";var nR=L(),nre=J(),ol=V(),{handleHDBError:iR,hdb_errors:Jf}=Z(),{isMainThread:ire}=require("worker_threads"),{Readable:ore}=require("stream"),z0=require("os"),are=require("util"),cre=FS(),ure=are.promisify(cre.authorize),J0=Q0(),{createGzip:lre,constants:_re}=require("zlib");function dre(e){let t=`Found an uncaught exception with message: ${e.message}. ${z0.EOL}Stack: ${e.stack} ${z0.EOL}Terminating ${ire?"HDB":"thread"}.`;console.error(t),ol.fatal(t),process.exit(1)}a(dre,"handleServerUncaughtException");function fre(e,t,r){if(ol[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:Jf.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(fre,"serverErrorHandler");function Ere(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=iR(new Error,"Invalid JSON.",Jf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(nre.isEmpty(e.body.operation)){let s=iR(new Error,"Request body must include an 'operation' property.",Jf.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(Ere,"reqBodyValidationHandler");function hre(e,t,r){let s;e.body.operation!==nR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==nR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==nR.OPERATIONS_ENUM.LOGOUT?ure(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{ol.warn(n),ol.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(iR(n,i,Jf.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(hre,"authHandler");async function mre(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=J0.chooseOperation(e.body);let n=await J0.processLocalTransaction(e,s);if(n instanceof ore&&n.headers){for(let[i,o]of n.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),n=n.pipe(lre({level:_re.Z_BEST_SPEED})))}return n}catch(n){throw ol.error(n),n}}a(mre,"handlePostRequest");j0.exports={authHandler:hre,handlePostRequest:mre,handleServerUncaughtException:dre,serverErrorHandler:fre,reqBodyValidationHandler:Ere}});var tB=T((Ime,eB)=>{"use strict";var pre=require("fastify-plugin"),{handlePostRequest:X0,authHandler:Sre,reqBodyValidationHandler:Tre}=jf();async function gre(e){e.decorate("hdbCore",{preValidation:[Tre,Sre],request:t=>Z0(X0(t,response)),requestWithoutAuthentication:(t,r)=>Z0(X0(t,r,!0))})}a(gre,"hdbCore");async function Z0(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(Z0,"convertAsyncIterators");eB.exports=pre(gre)});var nB=T((Lme,sB)=>{"use strict";var Dme=require("fs"),oR=X();oR.initSync();var{CONFIG_PARAMS:rB}=L(),Rre=1024*1024*1024;function Are(e){let t=oR.get(rB.HTTP_TIMEOUT),r=oR.get(rB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:Rre,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Are,"getServerOptions");sB.exports=Are});var aB=T((Ume,oB)=>{"use strict";var aR=X();aR.initSync();var{CONFIG_PARAMS:iB}=L();function Ore(){let e=aR.get(iB.HTTP_CORSACCESSLIST),t=aR.get(iB.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(Ore,"getCORSOptions");oB.exports=Ore});var lB=T((vme,uB)=>{"use strict";var cB=X();cB.initSync();var bre=L();function Nre(){return cB.get(bre.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Nre,"getHeaderTimeoutConfig");uB.exports=Nre});var uR={};We(uR,{customFunctionsServer:()=>Ire,ready:()=>NB,start:()=>wre});function wre(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){xn||(xn=bB(t),lt.http((await xn).server));let o=await xn,c=(0,cR.dirname)(n),u=(0,cR.dirname)(s);if(u.startsWith("/")&&(u=u.slice(1)),!_B.has(c)){_B.add(c);try{o.register(Dre(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${n}, this may require a restart to install properly`);else throw _}}},ready:NB}}async function Ire(){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 Cre();let e=pB.get(SB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=xn=await bB(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 Cre(){try{Ve.info("Custom Functions starting configuration."),await TB.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function Dre(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,dB.existsSync)(e)&&r.register(mB.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?Ve.error(n.message):n&&Ve.error(n),o()})}catch(s){Ve.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function bB(e){Ve.info("Custom Functions starting buildServer.");let t=(0,gB.default)(e),r=(0,fB.default)(t);r.server.headersTimeout=(0,AB.default)(),r.setErrorHandler(OB.serverErrorHandler);let s=(0,RB.default)();return s&&r.register(EB.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(hB.default),await r.register(yre),await r.after(),Rg(r),Ve.info("Custom Functions completed buildServer."),r}function NB(){if(xn)return xn.then?xn.then(e=>e.ready()):xn.ready()}var cR,dB,fB,EB,hB,mB,pB,SB,Ve,yre,TB,gB,RB,AB,OB,xn,_B,yB=Re(()=>{cR=require("path"),dB=require("fs"),fB=B(require("fastify")),EB=B(require("@fastify/cors")),hB=B(Lg()),mB=B(require("@fastify/autoload")),pB=B(X()),SB=B(L()),Ve=B(V()),yre=B(tB()),TB=B(ns()),gB=B(nB()),RB=B(aB()),AB=B(lB()),OB=B(jf());Ta();rr();_B=new Set;a(wre,"start");a(Ire,"customFunctionsServer");a(Cre,"setUp");a(Dre,"buildRouteFolder");a(bB,"buildServer");a(NB,"ready")});var lR={};We(lR,{start:()=>Lre});function Lre(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,LB.default)(r,e);return e.server.http(async(n,i)=>{if(!n.isWebSocket)return new Promise(o=>s(n._nodeRequest,n._nodeResponse,()=>{o(i(n))}))}),!0}},handleFile(t,r,s){IB||(IB=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=wB.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,CB.default)(n,(0,DB.realpathSync)(o))}}return i(n)},{runFirst:!0})),wB.set(r,s)}}}var CB,DB,LB,wB,IB,MB=Re(()=>{CB=B(require("send")),DB=require("fs"),LB=B(require("serve-static")),wB=new Map;a(Lre,"start")});function Pre(e,t=1,r){if(_R++,(0,Ro.startWorker)("server/threads/threadServer.js",{name:eE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(_){_.type===eE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});Ure.push(n),await n,Pa.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=Zf.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=Pa.indexOf(s);o>-1&&Pa.splice(o,1)}if(a(i,"removeWorker"),va){let o=va;va=[];for(let c of o)BB[c.localPort](null,c)}}}),r){let s=setInterval(()=>{dR?dR=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Ro.shutdownWorkers)(),_R=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function HB(e=0,t){if(typeof e=="string")try{(0,tE.existsSync)(e)&&(0,tE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=vre:r=Bre(t):r=ER;let s=(0,Ba.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=BB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),dR=!0,r(o,(c,u)=>{if(!c){if(UB){let l=o._socket||new Ba.Socket({handle:o,writable:!0,readable:!0});UB.deliverSocket(l,e,u),l.resume()}else _R>0?(va.length===0&&setTimeout(()=>{va.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,va.push(o)):(console.log("start up a dynamic thread to handle request"),Pre(0));Fr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Ba.Socket({handle:o,writable:!0,readable:!0});Fre(l,c,e)}Fr(!0,"socket-routed")})};let n=jc();fR.info(`HarperDB ${n.version} Server running on port ${e}`)}return s.on("error",n=>{console.error("Error in socket server",n)}),process.env._UNREF_SERVER&&s.unref(),s}function ER(e,t){let r,s=0;for(let n of Pa){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=Xf)return Xf=i,t(r);s=i}Xf=0,t(r)}function vre(e,t){let r={};e.getpeername(r);let s=r.address,n=Ha.get(s),i=Date.now();if(n&&n.worker.threadId!==-1)return n.lastUsed=i,t(n.worker);ER(e,o=>{Ha.set(s,{worker:o,lastUsed:i}),t(o)})}function Bre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){let i=new Ba.Socket({handle:s,readable:!0,writable:!0});s._socket=i,i.on("data",o=>{s.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ha.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,n(_.worker);ER(s,d=>{Ha.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function xre(){Xf=0;for(let e of Pa)e.expectedIdle=e.recentELU.idle+Hre,e.requests=1;Pa.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Fre(e,t,r){let s=qre++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),Zf.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),Zf.delete(s)),n.event=="destroy"&&(e.destroy(),Zf.delete(s))})}var Ro,Ba,eE,fR,tE,vB,Mre,Pa,va,BB,UB,_R,Ure,dR,Xf,PB,Ha,Hre,Zf,qre,xB=Re(()=>{Ro=B(Qe()),Ba=require("net"),eE=B(L()),fR=B(V()),tE=require("fs");Nn();vB=require("worker_threads"),Mre=B($i()),Pa=[],va=[],BB=[],_R=0,Ure=[];vB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Pre,"startHTTPWorker");a(HB,"startSocketServer");Xf=0;a(ER,"findMostIdleWorker");PB=36e5,Ha=new Map;a(vre,"findByRemoteAddressAffinity");a(Bre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ha)r.lastUsed+PB<e&&Ha.delete(t)},PB).unref();Hre=1e3;a(xre,"updateWorkerIdleness");(0,Ro.setMonitorListener)(xre);Zf=new Map,qre=1;a(Fre,"proxySocket")});var SR={};We(SR,{Request:()=>hR,createReuseportFd:()=>rE});var qB,hR,mR,pR,rE,sE=Re(()=>{qB=require("os"),hR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let s=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=s,this.headers=new pR(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 mR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},mR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},pR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,s]of this)t(s,r,this)}};(0,qB.platform)()!="win32"&&(rE=require("node-unix-socket").createReuseportFd)});var VB=T((Jme,kB)=>{"use strict";var Gre=require("cluster"),Ao=X();Ao.initSync();var GB=L(),Yme=require("util"),qn=V(),Kme=require("fs"),kre=require("fastify"),Wme=jc(),Vre=require("@fastify/cors"),$re=require("@fastify/compress"),Yre=require("@fastify/static"),Kre=Lg(),Wre=require("path"),{PACKAGE_ROOT:Qre}=L(),zre=gn(),Jre=J(),jre=ns(),Xre=$i(),{server:Zre}=(rr(),ee(Di)),{node_request_key:Qme}=(sE(),ee(SR)),{authHandler:ese,handlePostRequest:tse,serverErrorHandler:rse,reqBodyValidationHandler:sse}=jf(),zme=require("net"),{registerContentHandlers:nse}=(Ta(),ee(Av)),ise=6e4,ose=1024*1024*1024,ase="TRUE",{CONFIG_PARAMS:al}=GB,xa;kB.exports={hdbServer:FB,start:FB};async function FB(e){try{qn.info("In Fastify server"+process.cwd()),qn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),qn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Gre.isMaster,await cse();let t=e.securePort>0;xa=use(t),await xa.ready(),e||(e={}),e.isOperationsServer=!0;try{Zre.http(xa.server,e),xa.server.closeIdleConnections||await xa.listen({port:0,host:"::"})}catch(r){throw xa.close(),qn.error(r),qn.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),qn.fatal(t),process.exit(1)}}a(FB,"operationsServer");async function cse(){qn.trace("Configuring HarperDB process."),zre.setSchemaDataToGlobal(),await jre.setUsersToGlobal(),await Xre.getLicense()}a(cse,"setUp");function use(e){qn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=lse(e),r=kre(t);r.server.headersTimeout=dse(),r.setErrorHandler(rse);let s=_se();s&&r.register(Vre,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Kre),r.register($re),r.register(Yre,{root:Wre.join(Qre,"studio/build-local")}),nse(r);let n=Ao.get(GB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Jre.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[sse,ese],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),tse(i,o)}),r.get("/health",()=>"HarperDB is running."),qn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(use,"buildServer");function lse(e){let t=Ao.get(al.OPERATIONSAPI_NETWORK_TIMEOUT),r=Ao.get(al.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:ose,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(lse,"getServerOptions");function _se(){let e=Ao.get(al.OPERATIONSAPI_NETWORK_CORS),t=Ao.get(al.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===ase)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(_se,"getCORSOpts");function dse(){return Ao.get(al.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??ise}a(dse,"getHeaderTimeoutConfig")});var ZB=T((tpe,XB)=>{"use strict";var{decode:fse}=require("msgpackr"),{isMainThread:Xme,parentPort:Ese,threadId:Zme}=require("worker_threads"),gR=it(),Fn=Ge(),hse=L(),bi=V(),$B=X(),KB=L();Qe();var mse=Tn(),{recordAction:pse,recordActionBinary:Sse}=(Nn(),ee(tu)),{publishToStream:Tse}=gR,{ConsumerEvents:gse}=require("nats"),epe={durable:Fn.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Fn.WORK_QUEUE_CONSUMER_NAMES.deliver_group},Rse,Ase,Ose,WB,QB;XB.exports={initialize:RR,workQueueListener:jB,setSubscription:bse,setIgnoreOrigin:yse,getDatabaseSubscriptions:Nse};async function RR(){QB=!0,bi.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await gR.getNATSReferences();Rse=e,Ase=e.info.server_name,Ose=t,WB=r}a(RR,"initialize");var iE=new Map;function bse(e,t,r){let s=iE.get(e);s||iE.set(e,s=new Map),s.set(t,r),QB||RR().then(jB)}a(bse,"setSubscription");function Nse(){return iE}a(Nse,"getDatabaseSubscriptions");var zB;function yse(e){zB=e}a(yse,"setIgnoreOrigin");var JB=100,YB=new Array(JB),nE=0;async function jB(){let e=await WB.consumers.get(Fn.WORK_QUEUE_CONSUMER_NAMES.stream_name,Fn.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(Ese?.on("message",async s=>{let{type:n}=s;n===KB.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let s of await r.status())if(s.type===gse.HeartbeatsMissed){let n=s.data;bi.trace(`${n} clustering ingest consumer heartbeats missed`),n===2&&(bi.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let s of r)await YB[nE],YB[nE]=wse(s).catch(n=>{bi.error(n)}),++nE>=JB&&(nE=0)}catch(s){bi.error("Error consuming clustering ingest, restarting consumer",s)}gR.clearClientCache(),await RR()}}a(jB,"workQueueListener");async function wse(e){let t=fse(e.data);pse(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,s=!1,n=$B.get(hse.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Fn.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Fn.MSG_HEADERS.TRANSACTED_NODES).indexOf(n)>-1&&(s=!0);let i=r.get(Fn.MSG_HEADERS.ORIGIN);if(s||(s=i===n&&!zB),Sse(s,"echo",e.subject,t.operation,"ingest"),s){e.ack();return}r.append(Fn.MSG_HEADERS.TRANSACTED_NODES,n);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;bi.trace("processing message:",o,c,_,(l?"records: "+l.map(b=>b?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),bi.trace(`messageProcessor nats msg id: ${e.headers.get(Fn.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:g}=f||{},A=iE.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:TR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:g});else{let b=l.map((v,G)=>({type:TR(o),value:v,expiresAt:E,id:d?.[G],table:_}));for(;u;)b.push({type:TR(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:p,onCommit:h,user:S,nodeName:g})}$B.get(KB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Tse(e.subject.split(".").slice(0,-1).join("."),mse.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){bi.error(o)}e.ack()}a(wse,"messageProcessor");function TR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(TR,"convertOperation")});var wR={};We(wR,{disableNATS:()=>Cse,publishToStream:()=>lE,setNATSReplicator:()=>AR,setPublishToStream:()=>Dse,setSubscription:()=>yR,start:()=>Ise});function Ise(){aE.default.get(cE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Mse()}function Cse(e=!0){nH=e}function Dse(e,t){lE=e,yR=t}function Mse(){if(nH||process.env._DISABLE_NATS)return;let e=Ms(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];AR(n,r,i)}}IR((r,s)=>{AR(r.tableName,r.databaseName,r),s&&oH(r)}),!eH&&(eH=!0)}function AR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(n=>n?.isNATSReplicator))return;r.sourcedFrom(class extends qt{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[De],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[De]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[De],record:i})}patch(i){return s(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[De],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[De]})}static defineSchema(i){oH(i)}static subscribe(){let i=new Os;return yR(t,e,i),i}static subscribeOnThisThread(i){return i<Lse}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function s(n){let i=n?.transaction?.nats;if(!i)if(n?.transaction){n.transaction.nats=i=new oE(n.transaction,n);let o=n.transaction;for(;o.next;)o=o.next;o.next=n.transaction.nats,i.user=n.user,i.context=n}else i=iH;return i}a(s,"getNATSTransaction")}function oH(e){let t=aE.default.get(cE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);lE(`${bR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,NR.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 tH,bR,NR,rH,sH,aE,cE,uE,nH,lE,yR,Lse,iH,eH,oE,OR,aH=Re(()=>{Ae();bs();tH=B(it()),bR=B(Ge()),NR=B(Tn());dc();rH=B(ZB()),sH=B(Cr()),aE=B(X()),cE=B(L()),uE=B(V());a(Ise,"start");a(Cse,"disableNATS");lE=tH.publishToStream,yR=rH.setSubscription;a(Dse,"setPublishToStream");Lse=2;a(Mse,"assignReplicationSource");a(AR,"setNATSReplicator");a(oH,"publishSchema");oE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let s=this.writes_by_db.get(t);s||this.writes_by_db.set(t,s=[]),s.push(r)}commit({timestamp:t}){let r=aE.default.get(cE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(uE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&s.push(lE(`${bR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,NR.createNatsTableStreamName)(n,u.table),void 0,u)?.catch(l=>{throw uE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(s)}},OR=class extends oE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,sH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};iH=new OR});var RH=T(bo=>{"use strict";var{isMainThread:Use,parentPort:ll,threadId:cl}=require("worker_threads"),{Socket:Pse,createServer:vse}=require("net"),{createServer:Bse,IncomingMessage:Hse}=require("http"),{createServer:xse}=require("https"),{readFileSync:qa,unlinkSync:cH,existsSync:qse}=require("fs"),qs=V(),$e=X(),Rr=L(),{server:fE}=(rr(),ee(Di)),{WebSocketServer:Fse}=require("ws"),{createServer:Gse}=require("tls"),{getTicketKeys:kse,restartNumber:Vse,getWorkerIndex:uH}=Qe(),{Headers:EH}=(jd(),ee(KU)),{recordAction:ul,recordActionBinary:$se}=(Nn(),ee(tu)),{Request:hH,createReuseportFd:lH}=(sE(),ee(SR)),{checkMemoryLimit:Yse}=$i(),mH=require("tls"),_H=mH.createSecureContext;mH.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){Vse<=1&&qs.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:cpe,CONFIG_PARAMS:Kse}=Rr;$e.initSync();var Wse=$e.get(Kse.HTTP_SESSIONAFFINITY),un={};bo.registerServer=UR;bo.httpServer=PR;bo.deliverSocket=MR;bo.startServers=pH;bo.when_components_loaded=null;fE.http=PR;fE.request=jse;fE.socket=Xse;fE.ws=Zse;var CR=[],_E=[],Qse,Oo={},dE={},zse=[],DR=[];function pH(){return bo.when_components_loaded=vR().loadRootComponents(!0).then(()=>{ll?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)MR(s,r,n);else if(t.requestId)Jse(t);else if(t.type===Rr.ITC_EVENT_TYPES.SHUTDOWN){qs.trace("received shutdown request",cl);for(let i in un){let o=un[i],c;o.closeIdleConnections&&(setInterval(()=>{o.closeIdleConnections()},25).unref(),setTimeout(()=>{o.closeAllConnections(),qs.info("Closed all http connections",i,cl)},4e3).unref()),o.close?.(()=>{if($e.get(Rr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&uH()==0)try{cH($e.get(Rr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,cl),o.cantCleanupProperly||qs.warn("Had to forcefully exit the thread",cl),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(lH&&!Wse)for(let t in un){let r=un[t];if(isNaN(t)&&uH()==0){qse(t)&&cH(t),e.push(new Promise((n,i)=>{r.listen({path:t},()=>{n(),qs.info("Domain socket listening on "+t)}).on("error",i)}));continue}let s;try{s=lH(+t,"::")}catch(n){console.error(`Unable to bind to port ${t}`,n);continue}e.push(new Promise((n,i)=>{r.listen({fd:s},()=>{n(),qs.trace("Listening on port "+t,cl)}).on("error",i)}))}Promise.all(e).then(()=>{ll?.postMessage({type:Rr.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(pH,"startServers");Use||pH();function MR(e,t,r){let s=e?.read?e:new Pse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),n=un[t];if(n.isSecure&&(s.startTime=performance.now()),n)typeof n=="function"?n(s):n.emit("connection",s),r&&s.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=un[t];c?(typeof c=="function"?c(s):c.emit("connection",s),r&&s.emit("data",r)):o<5?i(o+1):(qs.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(MR,"deliverSocket");var dH=new Map;function Jse(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=dH.get(n),r){case"connection":i=MR(void 0,t),dH.set(n,i),i.write=(c,u,_)=>(ll.postMessage({requestId:n,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(ll.postMessage({requestId:n,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),ll.postMessage({requestId:n,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(s,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(Jse,"proxyRequest");function UR(e,t,r=!0){!+t&&t!==$e.get(Rr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt($e.get(Rr.CONFIG_PARAMS.HTTP_PORT),10));let s=un[t];if(s){let n=s.lastServer||s;if(n===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!n.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);n.off("unhandled",fH),n.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(s.cantCleanupProperly=!0),e.emit("request",i,o)}),s.lastServer=e}else un[t]=e;e.on("unhandled",fH)}a(UR,"registerServer");function SH(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(Rr.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:$e.get(Rr.CONFIG_PARAMS.HTTP_PORT),secure:$e.get(Rr.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),$e.get(Rr.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:$e.get(Rr.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&$e.get(Rr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:$e.get(Rr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(SH,"getPorts");function PR(e,t){for(let{port:r,secure:s}of SH(t))TH(r,s,t?.isOperationsServer),typeof e=="function"?DR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=s,UR(e,r,!1)),dE[r]=LR(DR,r),Qse=LR(zse,r)}a(PR,"httpServer");function TH(e,t,r){if(!Oo[e]){let s=r?"operationsApi_network":"http",n={keepAliveTimeout:$e.get(s+"_keepAliveTimeout"),headersTimeout:$e.get(s+"_headersTimeout"),requestTimeout:$e.get(s+"_timeout")},i=$e.get(s+"_mtls");if(t){s=r?"operationsApi_":"";let c=$e.get(s+"tls_privateKey"),u=$e.get(s+"tls_certificate"),_=$e.get(s+"tls_certificateAuthority");Object.assign(n,{allowHTTP1:!0,key:qa(c),ciphers:$e.get("tls_ciphers"),cert:qa(u),ca:_&&qa(_),requestCert:!!i,ticketKeys:kse()})}let o=Yse();Oo[e]=(t?xse:Bse)(n,async(c,u)=>{try{let l=performance.now(),d=new hH(c,u);r&&(d.isOperationsServer=!0);let f=await dE[e](d);if(!f){if(d._nodeResponse.statusCode)return;f=gH(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,Oo[e].emit("unhandled",c,u)}let E=f.status||200,h=performance.now(),p=h-l,S=f.body,g;if(!f.handlesHeaders){let v=f.headers||new EH;if(S?S.length>=0&&(typeof S=="string"?v.set("Content-Length",Buffer.byteLength(S)):v.set("Content-Length",S.length),g=!0):(v.set("Content-Length","0"),g=!0),v.append){let G=`hdb;dur=${p.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(S)}let A=d.handlerPath,b=d.method;if(ul(p,"duration",A,b,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),$se(E<400,"success",A,b),!g)if(S?.pipe){S.pipe(u),S.destroy&&u.on("close",()=>{S.destroy()});let v=0;S.on("data",G=>{v+=G.length}),S.on("end",()=>{ul(performance.now()-h,"transfer",A,b),ul(v,"bytes-sent",A,b)})}else S?.then?S.then(v=>{u.end(v)},_):u.end(S)}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?qs.warn(l):qs.info(l):qs.error(l)}a(_,"onError")}),t&&(Oo[e].on("secureConnection",c=>{c._parent.startTime&&ul(performance.now()-c._parent.startTime,"tls-handshake",e),ul(c.isSessionReused(),"tls-reused",e)}),Oo[e].isSecure=!0),UR(Oo[e],e)}return Oo[e]}a(TH,"getHTTPServer");function LR(e,t){let r=gH;for(let s=e.length;s>0;){let{listener:n,port:i}=e[--s];if(i===t||i==="all"){let o=r;r=a(c=>n(c,o),"next_callback")}}return r}a(LR,"makeCallbackChain");function gH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new EH}}a(gH,"unhandled");function jse(e,t){PR(e,{requestOnly:!0,...t})}a(jse,"onRequest");function Xse(e,t){let r;if(t.securePort){let s=$e.get("tls_privateKey"),n=$e.get("tls_certificate"),i=t.mtls?.certificateAuthority||$e.get("tls_certificateAuthority");r=Gse({ciphers:$e.get("tls_ciphers"),key:qa(s),cert:qa(n),ca:i&&qa(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),un[t.securePort]=r}return t.port&&(r=vse(e),un[t.port]=r),r}a(Xse,"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 Zse(e,t){for(let{port:r,secure:s}of SH(t)){_E[r]||(_E[r]=new Fse({server:TH(r,s)}),_E[r].on("connection",async(i,o)=>{try{let c=new hH(o);c.isWebSocket=!0;let u=dE[r](c),_=o.headers["sec-websocket-protocol"]||"";for(let l=0;l<CR.length;l++){let d=CR[l];if(d.protocol){if(d.protocol===_){d.listener(i,c,u);break}}else d.listener(i,c,u)}}catch(c){qs.warn("Error handling WebSocket connection",c)}}),_E[r].on("error",i=>{console.log("Error in setting up WebSocket server",i)}));let n=t?.subProtocol||"";CR.push({listener:e,protocol:n}),dE[r]=LR(DR,r)}}a(Zse,"onWebSocket");function fH(e,t){t.writeHead(404),t.end(`Not found
|
|
27
|
+
`)}a(fH,"defaultNotFound")});async function NH({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await BR.getResource(e,{});n=new qR(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await BR.get(e);i&&i.delete()}n=new hE(e,t)}return s&&(s.id=e,s.user={username:t?.username},_l.put(s)),n}function HR(){return EE++,EE>65500&&(EE=1),EE}function xR(e,t,r=e){let{topic:s,retain:n}=e;e.data=t,e.async=!0,e.authorize=!0;let i=pi.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return et(r,()=>n?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var AH,No,OH,bH,BR,_l,EE,hE,qR,yH=Re(()=>{Ae();Uu();AH=B(Cr()),No=B(V());Ji();OH=B(Qe()),bH=B(RH());rr();BR=_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"}]}}]}),_l=_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,OH.getWorkerIndex)()===0&&(async()=>{await bH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of _l.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await lt.getUser(r.user.username)),et(r,()=>{try{xR(r,t)}finally{_l.delete(e.id,r)}})}})();a(NH,"getSession");EE=1;a(HR,"getNextMessageId");hE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,rh:i,startTime:o}=t,c=n.indexOf("?"),u,_;if(c>-1?(u=n.slice(c),_=n.slice(0,c)):_=n,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(g=>g.topic===n),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,No.trace)("Resuming subscription from",n,"from",o);let E=pi.getMatch(_);if(!E){let g=new Error(`The topic ${n} 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(s&&b)throw new Error("Filters can not be combined");let v=!0;A[A.length-1]==="#"&&(A.length--,v=!1),b&&(s=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,p=E.Resource,S=await et(f,async()=>{let g=await p.subscribe(f);if(!g)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!g[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);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"||s&&!s(A))continue;r?(A.topic=n,b=this.needsAcknowledge(A)):(A.acknowledge?.(),b=HR());let v=A.id;Array.isArray(v)&&(v=Sa(v)),v==null&&(v=""),this.listener(h+"/"+v,A.value,b,t)}catch(b){(0,No.warn)(b)}})(),g});return S.topic=n,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=HR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,xR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};et(r,async()=>{if(!t){let s=await _l.get(this.sessionId,r);s?.doesExist()&&await xR(s,s.data,r)}await _l.delete(this.sessionId,r)}).catch(s=>{(0,No.warn)(`Error publishing MQTT will for ${this.sessionId}`,s)});for(let s of this.subscriptions)s.end();this.subscriptions=[]}};a(xR,"publish");qR=class extends hE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=HR(),s={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(s.acknowledge=t.acknowledge),this.awaitingAcks.set(r,s),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,No.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,AH.getNextMonotonicTime)()),(0,No.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),BR.put(this.sessionRecord)),t.qos}}});var FR={};We(FR,{bypassAuth:()=>ene,start:()=>tne});function ene(){LH=!0}function tne({server:e,port:t,network:r,webSocket:s,securePort:n,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return s&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=CH(_,(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,Ar.info)("WebSocket error",h)})}},{subProtocol:"mqtt"})),(t||n)&&(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,Ar.error)(E)}else if(u.required)return(0,Ar.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&LH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,DH.getSuperUser)());let{onMessage:d,onClose:f}=CH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Ar.info)("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function CH(e,t,r,s,n){IH||(IH=!0,eu(d=>{mE>0&&d.push({metric:"mqtt-connections",connections:mE,byThread:!0})}));let i;mE++;let o,c={protocolVersion:4},u=(0,SE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){mE--,i||(i=!0,o?.disconnect(),n.sessions.delete(o),is(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{s?.then&&(s=await s),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{s=await lt.getUser(d.username,d.password.toString(),r),(0,pE.get)(ln.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&wH.notify({username:s.username,status:ln.AUTH_AUDIT_STATUS.SUCCESS,type:ln.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,pE.get)(ln.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&wH.error({username:s.username,status:ln.AUTH_AUDIT_STATUS.FAILURE,type:ln.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!s&&n.requireAuthentication)return is(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(n.authorizeClient?.(d,s),d.will){let b=e.deserialize||(e.deserialize=ho(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?b(d.will.payload):void 0,delete d.will.payload}o=NH({user:s,...d}),o=await o,n.sessions.add(o)}catch(b){return(0,Ar.error)(b),is(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:b.code||5,returnCode:b.code||128})}is(!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,Ar.error)(P),o?.disconnect(),n.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,Ar.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 p=d.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=ho(r?.headers.get?.("content-type"))),g=d.payload?.length>0?S(d.payload):void 0,A;try{A=await o.publish(d,g)}catch(b){(0,Ar.warn)(b),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:A===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),n.sessions.delete(o),is(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Ar.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,SE.generate)(h,c);t(S),Fr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ti(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var SE,DH,pE,ln,Ar,wH,LH,IH,mE,MH=Re(()=>{SE=require("mqtt-packet");yH();DH=B(ns());Ta();Nn();rr();pE=B(X()),ln=B(L()),Ar=B(V()),wH=(0,Ar.loggerWithTag)("auth-event"),LH=(0,pE.get)(ln.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(ene,"bypassAuth");a(tne,"start");mE=0;a(CH,"onSocket")});var lf={};We(lf,{component_errors:()=>Ga,loadComponent:()=>TE,loadComponentDirectories:()=>GH,setErrorReporter:()=>ine});function GH(e,t){t&&(kR=t),e&&(VR=e);let r=[];if((0,Fs.existsSync)(GR)){let n=(0,Fs.readdirSync)(GR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,At.join)(GR,o);r.push(TE(c,kR,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(TE(s,kR,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{FH=!0})}function ine(e){fl=e}async function TE(e,t,r,s,n,i){if(!PH.has(e)){PH.set(e,!0),n&&(VR=n);try{let o;s&&(Ga=new Map);let c=(0,At.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Fs.existsSync)(c)?o=s?(0,qH.getConfigObj)():(0,vH.parseDocument)((0,Fs.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=$R;let u=[],_=s;for(let l in o){let d=o[l];if(Ga.set(s?l:(0,At.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let A=e,b;for(;!(0,Fs.existsSync)(b=(0,At.join)(A,"node_modules",l));)if(A=(0,At.dirname)(A),A.length<(0,xH.getHdbBasePath)().length){b=null;break}if(b)f=await TE(b,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=nne[l];if(!f)continue;u.push(f);let h=a(A=>(A.origin=r,_t(A)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,g=!p?.https&&p?.port;if(Fa.isMainThread&&(f=await f.startOnMainThread?.({server:lt,ensureTable:h,port:g,securePort:S,resources:t,...d})||f,s&&p))for(let A of[g,S])try{if(+A&&!UH.includes(A)){let b=YR.get(KR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);b&&dl.default.warn("Session affinity is not recommended and may cause memory leaks"),(b||!rE)&&(UH.push(A),HB(A,b))}}catch(b){console.error("Error listening on socket",A,b,l)}if(t.isWorker&&(f=await f.start?.({server:lt,ensureTable:h,port:g,securePort:S,resources:t,...d})||f),VR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,HH.handleHDBError)("Can not reference parent directories");let A=(0,At.join)(e,d.files).replace(/\\/g,"/"),b=A.indexOf("/*");if(b>-1&&d.files!==$R[l]?.files&&!(0,Fs.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,At.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,At.join)(e,Q)}else(z=A.indexOf("/*"))>-1&&(P=A.slice(0,z+1),H=(0,At.relative)(e,P));let W=!1;if(Fa.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,BH.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:ne,dirent:pe}=Q;_=!0;let oe=(0,At.relative)(e,ne).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 qe=G+(G.endsWith("/")?"":"/")+oe;try{if(pe.isFile()){let ce=await sne(ne);Fa.isMainThread&&await f.setupFile?.(ce,qe,ne,t),t.isWorker&&await f.handleFile?.(ce,qe,ne,t)}else Fa.isMainThread&&await f.setupDirectory?.(qe,ne,t),t.isWorker&&await f.handleDirectory?.(qe,ne,t)}catch(ce){ce.message=`Could not load ${pe.isFile()?"file":"directory"} '${ne}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${ce.message}`,fl?.(ce),((0,ka.getWorkerIndex)()===0?console:dl.default).error(ce),t.set(d.path||"/",new El(ce)),Ga.set(s?l:(0,At.basename)(e),ce.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,At.basename)(e)}' due to: ${h.message}`,fl?.(h),((0,ka.getWorkerIndex)()===0?console:dl.default).error(h),t.set(d.path||"/",new El(h),null,!0),Ga.set(s?l:(0,At.basename)(e),h.message)}}if(Fa.isMainThread&&!FH&&i&&(0,ka.watchDir)(e,async()=>GH()),o.extensionModule)return await Jl((0,At.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;fl?.(new Error(l)),((0,ka.getWorkerIndex)()===0?console:dl.default).error(l),Ga.set((0,At.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,fl?.(o),t.set("",new El(o))}}}var Fs,At,Fa,vH,YR,KR,BH,ka,dl,HH,xH,rne,qH,sne,GR,VR,FH,kR,Ga,nne,$R,UH,PH,fl,El,_f=Re(()=>{Fs=require("fs"),At=require("path"),Fa=require("worker_threads"),vH=require("yaml"),YR=B(X()),KR=B(L());KO();JO();jO();xv();yB();MB();BH=B(require("fast-glob")),ka=B(Qe()),dl=B(V());wh();rr();HH=B(Z());bs();Ae();xB();xH=B(X()),rne=B(VB());tf();aH();MH();qH=B(vr());sE();({readFile:sne}=Fs.promises),GR=YR.get(KR.CONFIG_PARAMS.COMPONENTSROOT),VR=new Map,Ga=new Map;a(GH,"loadComponentDirectories");nne={REST:Cf,rest:Cf,graphqlSchema:yh,jsResource:Ch,fastifyRoutes:uR,login:Lh,static:lR,operationsApi:rne,customFunctions:{},http:{},clustering:wR,authentication:Pu,mqtt:FR},$R={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty($R,"static",{value:{files:"web/**"}});UH=[],PH=new Map;a(ine,"setErrorReporter");a(TE,"loadComponent");El=class extends qt{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 vR=T((Ppe,VH)=>{var{isMainThread:kH}=require("worker_threads"),{getTables:one}=(Ae(),ee(Fe)),{loadComponentDirectories:ane,loadComponent:cne}=(_f(),ee(lf)),{resetResources:une}=(Uu(),ee(YU)),lne=QT(),_ne=vr(),{dirname:dne}=require("path"),{getConnection:fne}=it(),Ene=X(),hne=L(),WR=new Map;async function mne(e=!1){!kH&&Ene.get(hne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&fne();try{kH&&await lne()}catch(s){console.error(s)}let t=une();one(),t.isWorker=e,await cne(dne(_ne.getConfigFilePath()),t,"hdb",!0,WR),await ane(WR,t);let r=[];for(let[s]of WR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(mne,"loadRootComponents");VH.exports.loadRootComponents=mne});var Qe=T((Bpe,yi)=>{"use strict";var{Worker:pne,MessageChannel:Sne,parentPort:_n,isMainThread:XR,threadId:Tne,workerData:Gn}=require("worker_threads"),{PACKAGE_ROOT:gne}=L(),{join:WH,isAbsolute:Rne,extname:Ane}=require("path"),{server:QH}=(rr(),ee(Di)),{watch:One,readdir:bne}=require("fs/promises"),{totalmem:$H}=require("os"),hl=L(),zH=X(),kn=V(),{randomBytes:Nne}=require("crypto"),{_assignPackageExport:yne}=require("../index"),wne=L(),YH=1024*1024,Ni=[],ms=[],Ine=50,ZR=1e4,Cne="restart",JH="request_thread_info",jH="resource_report",XH="thread_info",ZH="added-port",Dne="ack",QR;yne("threads",ms);yi.exports={startWorker:zR,restartWorkers:tA,shutdownWorkers:vne,workers:Ni,setMonitorListener:Vne,onMessageFromWorkers:Bne,onMessageByType:ix,broadcast:xne,broadcastWithAcknowledgement:Fne,setChildListenerByType:Pne,getWorkerIndex:ex,getWorkerCount:tx,getTicketKeys:rx,setMainIsWorker:Mne,setTerminateTimeout:Lne,restartNumber:Gn?.restartNumber||1};ms.onMessageByType=ix;ms.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ms.find(s=>s.threadId===e);if(r)return r.postMessage(t),!0};var eA;function Lne(e){ZR=e}a(Lne,"setTerminateTimeout");function ex(){return Gn?Gn.workerIndex:eA?0:void 0}a(ex,"getWorkerIndex");function tx(){return Gn?Gn.workerCount:eA?1:void 0}a(tx,"getWorkerCount");function Mne(e){eA=e}a(Mne,"setMainIsWorker");var gE;function rx(){return gE||(gE=XR?Nne(48):Gn.ticketKeys,gE)}a(rx,"getTicketKeys");Object.defineProperty(QH,"workerIndex",{get(){return ex()}});Object.defineProperty(QH,"workerCount",{get(){return tx()}});var sx={[JH](e,t){Gne(t)},[jH](e,t){kne(t,e)}};function zR(e,t={}){let r=process.constrainedMemory?.()||$H();r=Math.min(r,$H(),2e4*YH);let s=zH.get(hl.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/YH/(10+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>6,16),64),i=[],o=[];for(let u of ms){let _=new Sne;_.existingPort=u,i.push(_),o.push(_.port2)}Ane(e)||(e+=".js");let c=new pne(Rne(e)?e:WH(gne,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:t.threadCount,name:t.name,restartNumber:yi.exports.restartNumber,ticketKeys:rx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:ZH,port:u,threadId:c.threadId},[u]);return AE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>zR(e,t),c.on("error",u=>{console.error("Worker error:",u),kn.error("Worker error:",u)}),c.on("exit",u=>{Ni.splice(Ni.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Ine?(t.unexpectedRestarts=c.unexpectedRestarts+1,zR(e,t)):kn.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{sx[u.type]?.(u,c)}),Ni.push(c),Yne(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(zR,"startWorker");var Une=[hl.THREAD_TYPES.HTTP];async function tA(e=null,t=2,r=!0){if(XR){if(r){let{loadRootComponents:o}=vR();await o()}yi.exports.restartNumber++,t<1&&(t=t*Ni.length);let s=[],n=[];for(let o of Ni.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;kn.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:yi.exports.restartNumber,type:hl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Une.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),ZR*2).unref();o.on("exit",()=>{clearTimeout(l),s.splice(s.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(s.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===wne.ITC_EVENT_TYPES.CHILD_STARTED&&(kn.trace("Worker has started",_.threadId),d(),n.splice(n.indexOf(l)),_.off("message",f))},"startListener");kn.trace("Waiting for worker to start",_.threadId),_.on("message",f)});n.push(l),s.length>=t&&await Promise.race(s),n.length>=t&&await Promise.race(n)}}await Promise.all(s),await Promise.all(n);let{restartService:i}=zd();r&&(e==="http"||!e)&&zH.get(hl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else _n.postMessage({type:Cne,workerType:e})}a(tA,"restartWorkers");function Pne(e,t){sx[e]=t}a(Pne,"setChildListenerByType");function vne(e){return tA(e,1/0,!1)}a(vne,"shutdownWorkers");var nx=[];function Bne(e){nx.push(e)}a(Bne,"onMessageFromWorkers");var JR=new Map;function ix(e,t){let r=JR.get(e);r||JR.set(e,r=[]),r.push(t)}a(ix,"onMessageByType");var Hne=10;async function xne(e){let t=0;for(let r of ms)try{r.postMessage(e),t++>Hne&&(t=0,await new Promise(setImmediate))}catch(s){kn.error("Unable to send message to worker",s)}}a(xne,"broadcast");var RE=new Map,qne=1;function Fne(e){return new Promise(t=>{let r=0;for(let s of ms)try{let n=qne++,i=a(()=>{RE.delete(n),--r===0&&t(),s!==_n&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,RE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of RE)o.port===s&&o()})),s.postMessage(e),r++}catch(n){kn.error("Unable to send message to worker",n)}r===0&&t()})}a(Fne,"broadcastWithAcknowledgement");function Gne(e){e.postMessage({type:XH,workers:ox()})}a(Gne,"sendThreadInfo");function ox(){let e=Date.now();return Ni.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(ox,"getChildWorkerInfo");function kne(e,t){e.resources=t,e.resources.updated=Date.now()}a(kne,"recordResourceReport");var jR;function Vne(e){jR=e}a(Vne,"setMonitorListener");var $ne=1e3,KH=!1;function Yne(){KH||(KH=!0,setInterval(()=>{for(let e of Ni){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}jR&&jR()},$ne).unref())}a(Yne,"startMonitoring");var Kne=1e3;if(_n){AE(_n);for(let e=0,t=Gn.addPorts.length;e<t;e++){let r=Gn.addPorts[e];r.threadId=Gn.addThreadIds[e],AE(r)}setInterval(()=>{let e=process.memoryUsage();_n.postMessage({type:jH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Kne).unref(),QR=a(()=>new Promise((e,t)=>{_n.on("message",r),_n.postMessage({type:JH});function r(s){s.type===XH&&(_n.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else QR=ox;yi.exports.getThreadInfo=QR;function AE(e,t){ms.push(e),e.on("message",r=>{if(r.type===ZH)r.port.threadId=r.threadId,AE(r.port);else if(r.type===Dne){let s=RE.get(r.id);s&&s()}else{for(let n of nx)n(r,e);let s=JR.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){kn.error(i)}}}).on("close",()=>{ms.splice(ms.indexOf(e),1)}).on("exit",()=>{ms.splice(ms.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(AE,"addPort");if(XR){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await bne(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(WH(s,i.name));try{for await(let{filename:i}of One(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await tA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",s,i)}},"watch_dir");yi.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else _n.on("message",async e=>{let{type:t}=e;t===hl.ITC_EVENT_TYPES.SHUTDOWN&&(yi.exports.restartNumber=e.restartNumber,_n.unref(),setTimeout(()=>{kn.warn("Thread did not voluntarily terminate",Tne),process.exit(0)},ZR).unref())})});var rC={};We(rC,{AUDIT_STORE_OPTIONS:()=>mx,createAuditEntry:()=>t_,openAuditStore:()=>yE,readAuditEntry:()=>Ut,setAuditRetention:()=>Qne,transactionKeyEncoder:()=>hx});function yE(e){let t=e.auditStore=e.openDB(dx.AUDIT_STORE_NAME,mx);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let s=null;function n(i=OE){clearTimeout(s),s=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-rA})){if((_[0]&15)===iA){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Wne){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,rA/10)),n(i)}},i).unref()}return a(n,"scheduleAuditCleanup"),t.scheduleAuditCleanup=n,(0,NE.getWorkerIndex)()===(0,NE.getWorkerCount)()-1&&n(OE),t}function Qne(e,t=OE){rA=e,OE=t}function t_(e,t,r,s,n,i,o){let c=px[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;s&&(s>1?Va.setFloat64(0,s):ps.set(Qh),u=9),f(0),f(t),d(r),Va.setFloat64(u,e),u+=8,n?d(n):ps[u++]=0,ps[s?8:0]=c;let l=ps.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,$a.writeKey)(E,ps,u);let p=u-h-1;p>127?p>16383?(aA.error("Key or username was too large for audit entry",E),u=h+1,ps[h]=0):(ps.copyWithin(h+2,h+1,u),Va.setUint16(h,p|32768),u++):ps[h]=p}function f(E){E<128?ps[u++]=E:E<16384?(Va.setUint16(u,E|32768),u+=2):E<1056964608?(Va.setUint32(u,E|3221225472),u+=4):(ps[u]=255,Va.setUint32(u+1,E),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new oA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let s=t.readInt(),n=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:px[s&7],tableId:i,get recordId(){return _x(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?_x(e,l,d):void 0},getValue(f,E,h){if(s&sA||s&nA&&!E)return f.decoder.decode(e.subarray(t.position));if(s&nA&&h)return cA(f.getEntry(this.recordId),h,f)}}}catch{return aA.error("Reading audit entry error",e),{}}}function _x(e,t,r){let s=e.subarray(t,r);return(0,$a.readKey)(s,0,r-t)}var $a,bE,dx,fx,NE,Ex,aA,ps,Va,hx,mx,rA,Wne,OE,sA,nA,ax,iA,cx,ux,lx,px,oA,Ui=Re(()=>{$a=require("ordered-binary"),bE=B(X()),dx=B(ht()),fx=B(L()),NE=B(Qe()),Ex=B(J());xo();aA=B(V());wE();(0,bE.initSync)();ps=Buffer.alloc(1024),Va=new DataView(ps.buffer,ps.byteOffset,1024),hx={writeKey(e,t,r){return e===Sc?(t.set(Sc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,$a.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,$a.readKey)(e,t,r)}},mx={encoding:"binary",keyEncoder:hx},rA=(0,Ex.convertToMS)((0,bE.get)(fx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Wne=1e3,OE=1e4;a(yE,"openAuditStore");a(Qne,"setAuditRetention");sA=16,nA=32,ax=1,iA=2,cx=3,ux=4,lx=5,px={put:ax|sA,[ax]:"put",delete:iA,[iA]:"delete",message:cx|sA,[cx]:"message",invalidate:ux,[ux]:"invalidate",patch:lx|nA,[lx]:"patch"};a(t_,"createAuditEntry");a(Ut,"readAuditEntry");oA=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(_x,"readKeySafely")});var uA={};We(uA,{add:()=>IE,applyReverse:()=>Sx,getRecordAtTime:()=>cA,rebuildUpdateBefore:()=>CE});function IE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function CE(e,t){let r=null;for(let s in e)if(s in t){let n=t[s];if(n?.__op__){let i=e[s];if(i?.__op__)if(i.__op__===n.__op__)r||(r={}),r[s]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[s]=i,IE(r,s,n)}}else r||(r={}),r[s]=e[s];return r}function Sx(e,t){for(let r in t){let s=t[r];if(s?.__op__){let n=zne[s.__op__]?.reverse;if(n)n(e,r,{value:s.value});else throw new Error(`Unsupported operation ${s.__op__}`)}else e[r]=Tx}}function cA(e,t,r){let s=r.rootStore.auditStore,n=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=s.get(i),_=Ut(u);switch(_.type){case"put":n=_.getValue(r);break;case"patch":Sx(n,_.getValue(r));break;case"delete":n=null}i=_.previousLocalTime}let o={},c=0;for(let u in n)n[u]===Tx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=s.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]&&(n[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)n[u]=null;return n}var zne,Tx,wE=Re(()=>{Ui();a(IE,"add");IE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};zne={add:IE};a(CE,"rebuildUpdateBefore");a(Sx,"applyReverse");Tx={};a(cA,"getRecordAtTime")});function Kr(e){return e[Dt]||(e[Dt]=Object.create(null))}function PE(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Oe])},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 Ss.ClientError(`${c} must be a string, attempt to assign ${l}`);Kr(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 Ss.ClientError(`${c} must be a string, attempt to assign ${l}`);Kr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be a number, attempt to assign ${l}`);Kr(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 Ss.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Kr(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 Ss.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Kr(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 Ss.ClientError(`${c} must be a number, attempt to assign ${l}`);Kr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Kr(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 Ss.ClientError(`${c} must be a Date, attempt to assign ${l}`);Kr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Kr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Kr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be an object, attempt to assign ${l}`);Kr(this)[c]=l},"set")}_={get(){let l=this[Dt];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[we]?.[c];return f.update(E)}return f}let d=this[we]?.[c];if(d&&typeof d=="object"){let f=gx(d,o);if(f)return l||(l=this[Dt]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,s[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Dt];return u?.[o]!==void 0?u[o]:this[we]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Ss.ClientError("Can not add a property to a sealed table schema");Kr(this)[o]=c}),i("deleteProperty",function(o){Kr(this)[o]=void 0}),i("toJSON",function(){let o=this[Dt],c;for(let _ in o){c||(c=Object.assign({},this[we]));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[we])),Object.assign(c,this)),c||this[we]}),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 gx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){this[we]=n}},PE(r,t)),new r(e)):new DE(e);case Array:let s=new ME(e.length);s[we]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=gx(o,t?.elements)),s[n]=o}return s;default:return e}}function j_(e){let t=e[Dt],r;for(let n in t){r||(r=Object.assign({},e[we]));let i=t[n];if(i&&typeof i=="object")if(i.__op__){let o=r[n];i=i.update(o)}else i=j_(i);r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[we])),Object.assign(r,e)),r||e[we]}function wo(e,t=e[Dt]){let r;if(e[we]&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=wo(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[s]=i}return Object.freeze(r)}for(let s in t){r||(r=Object.assign({},e[we]));let n=t[s];if(n&&typeof n=="object")if(n.__op__){let i=uA[n?.__op__];if(i)i(r,s,n);else throw new Error("Invalid CRDT operation "+n.__op__);continue}else n=wo(n);r[s]=n}return r?Object.freeze(r):e[we]||e}function LE(e){let t=e[we];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[yo]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[we]===n){if(LE(i))return!0}else return!0}}else{let r=e[Dt];if(r&&!t)return!0;for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[we]===i){if(LE(n))return!0}else return!0}else return!0}}return!1}var Ss,Dt,DE,yo,ME,UE,X_=Re(()=>{bs();Ss=B(Z());wE();Dt=Symbol("own-data");a(Kr,"getChanges");a(PE,"assignTrackedAccessors");a(gx,"trackObject");DE=class{static{a(this,"GenericTrackedObject")}constructor(t){this[we]=t}};PE(DE,{});a(j_,"collapseData");a(wo,"deepFreeze");a(LE,"hasChanges");yo=Symbol.for("has-array-changes"),ME=class extends Array{static{a(this,"TrackedArray")}[yo];constructor(t){super(t)}splice(...t){return this[yo]=!0,super.splice(...t)}push(...t){return this[yo]=!0,super.push(...t)}pop(){return this[yo]=!0,super.pop()}unshift(...t){return this[yo]=!0,super.unshift(...t)}shift(){return this[yo]=!0,super.shift()}};ME.prototype.constructor=Array;UE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var bp={};We(bp,{CONTEXT:()=>Oe,ID_PROPERTY:()=>De,IS_COLLECTION:()=>Ts,RECORD_PROPERTY:()=>we,Resource:()=>qt,snake_case:()=>jne,transformForSelect:()=>BE});function jne(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function Rx(e,t){if(ml=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(ml=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),s=new _A;for(let n=0;n<r.length;n++){let i=r[n];if(!i&&n===r.length-1){ml=!0;break}s[n]=t.coerceId(decodeURIComponent(i))}return s}function Wr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Oe]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Oe]||i):l=i:(l=n,c=l[De]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Oe]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(o=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[],_=!0;for(let E of n){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=n.id??null,c==null&&(_=!0))}else c=n??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return d.resetTransaction=!0,et(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 vE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new vE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Qr(e,t){let r=new bx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function lA(e,t,r){let s=e[we];if(s){let n=e[Dt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:n&&i in n?n[i]:(c=t?.[i])?c(e,r):s[i]}}else return t?n=>{let i=t[n];return i?i(e,r):e[n]}:n=>e[n]}function BE(e,t){let r=t?.propertyResolvers,s=t[Oe],n;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):lA(c,r,s)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(lA(u,r,s));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(lA(u,r,s)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){n||(n={});let u=n[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=n[c.name]=BE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var Ax,Ox,bx,Oe,De,Ts,we,Jne,qt,vE,ml,_A,bs=Re(()=>{Ax=require("crypto");dc();Ox=require("../index"),bx=B(Z());X_();Ji();yf();Oe=Symbol.for("context"),De=Symbol.for("primary-key"),Ts=Symbol("is-collection"),we=Symbol("stored-record"),Jne={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},qt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[De]=t;let s=r?.[Oe];this[Oe]=s!==void 0?s:r||null}static get=Wr(function(t,r,s,n){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=BE(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,s,n){if(Array.isArray(n)&&t[Ts]){let i=[],o=s.authorize;for(let c of n){let u=t.constructor,_=u.getResource(c[u.primaryKey],s,{async:!0});_.then?i.push(_.then(l=>l.put(c,s))):i.push(_.put(c,s))}return Promise.all(i)}return t.put?t.put(n,r):Qr(t,"put")},{hasContent:!0,type:"update"});static patch=Wr(function(t,r,s,n){return t.patch?t.patch(n,r):Qr(t,"patch")},{hasContent:!0,type:"update"});static delete=Wr(function(t,r,s,n){return t.delete?t.delete(r):Qr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,Ax.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),et(s,()=>{let i=new this(n,s),o=i.update?i.update(r):Qr(i,"update");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=Wr(function(t,r,s,n){return t.invalidate?t.invalidate(r):Qr(t,"delete")},{hasContent:!1,type:"update"});static post=Wr(function(t,r,s,n){return t[De]!=null&&t.update?.(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Wr(function(t,r,s,n){return t.connect?t.connect(n,r):Qr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Wr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Qr(t,"subscribe")},{type:"read"});static publish=Wr(function(t,r,s,n){return t[De]!=null&&t.update?.(),t.publish?t.publish(n,r):Qr(t,"publish")},{hasContent:!0,type:"create"});static search=Wr(function(t,r,s,n){let i=t.search?t.search(r):Qr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=BE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Wr(function(t,r,s,n){return t.search?t.search(n,r):Qr(t,"search")},{hasContent:!0,type:"read"});static copy=Wr(function(t,r,s,n){return t.copy?t.copy(n,r):Qr(t,"copy")},{type:"create"});static move=Wr(function(t,r,s,n){return t.move?t.move(n,r):Qr(t,"move")},{type:"delete"});post(t){if(this[Ts])return this.constructor.create(this[De],t,this[Oe]);Qr(this,"post")}static isCollection(t){return t?.[Ts]}static coerceId(t){return t}static parseQuery(t){return Nf(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let o=t.slice(n+1);t=t.slice(0,n);let c=r?.headers&&Jne[o];if(c)r.headers.set("accept",c);else if(s)s.property=o;else return{query:{property:o},id:Rx(t,this),isCollection:ml}}let i=Rx(t,this);return ml?{id:i,isCollection:!0}:i}static getResource(t,r,s){let n,i=r[Oe],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=s?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(n=_?.find(l=>l.constructor===c),n)return n;_||u.asMap.set(t,_=[]),_.push(n=new c(t,i))}else{if(n=u.find(_=>_[De]===t&&_.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[De],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else n=new c(t,i);return o&&(n[Ts]=!0),n}subscribe(t){return new Os}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Os}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[Oe]}};qt.prototype[Oe]=null;(0,Ox._assignPackageExport)("Resource",qt);a(jne,"snake_case");vE=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(Rx,"pathToId");_A=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Wr,"transactional");a(Qr,"missingMethod");a(lA,"selectFromObject");a(BE,"transformForSelect")});function yx(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;Ya||((0,HE.onMessageByType)(Nx,l=>{wx(l.path)}),Ya=Object.create(null));let o=Ya[n]||(Ya[n]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Sa(t);let u=new fA(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function wx(e,t){if(!Ya)return;let r=Ya[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(n){throw n.message+=" in "+e,n}let s;for(let{key:n,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=n;let o=Ut(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Sa(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=n){(0,dA.info)("omitting",u,h.startTime,n);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(s?s.push(h):s=[h]),h.txnInProgress=o.version),h.listener(u,o,n,p)}catch(p){console.error(p),(0,dA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(s)for(let n of s)n.txnInProgress=null,n.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function Ix(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",()=>{(0,HE.broadcast)({type:Nx,path:n}),wx(n,!0)})}}var dA,HE,Nx,Ya,nSe,fA,Cx=Re(()=>{dA=B(V()),HE=B(Qe());dc();Uu();Ui();Nx="transaction",nSe=Buffer.alloc(4096);a(yx,"addSubscription");fA=class extends Os{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(wx,"notifyFromTransactionData");a(Ix,"listenToCommits")});var Kg={};We(Kg,{coerceType:()=>xE,makeTable:()=>GE,setServerUtilities:()=>oie,updateResource:()=>qE});function GE(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,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=[]),Ix(i,u);let S=jh(i,s,u),g=0,A,b,v={},G=Promise.resolve(),H,P,z;for(let Y of p)(Y.assignCreatedTime||Y.name==="__createdtime__")&&(H=Y),(Y.assignUpdatedTime||Y.name==="__updatedtime__")&&(P=Y),Y.expiresAt&&(z=Y),Y.isPrimaryKey&&(v=Y);let W,Q=[],ne=[],pe=1,oe=2,qe={},ce={},Lt=864e5,Ul,Pl,Yn,PA=!1,nh,Uq=i.getRange({start:!1,end:!1}).constructor,Pq=10,vq=6;E&&HA();class je extends qt{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=p;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 I=a(y=>{let w=this.sources.slice(0,-1);if(w=w.filter(U=>U[y]&&(!U[y].reliesOnPrototype||U.prototype[y])),w.length>0)if(w.length===1){let U=w[0];return(M,D,x)=>{if(M?.source!==U)return U[y](D,x,M)}}else return(U,M,D)=>{let x=[];for(let k of w){if(U?.source===k)break;x.push(k[y](M,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(w,U,M)=>{if(!w?.source)return O[y](U,M,w)}},"getApplyToCanonicalSource");return qe={put:N("put"),patch:N("patch"),delete:N("delete"),publish:N("publish")},ce={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let y=!1,w=a(async(U,M)=>{let D=U.value,x=U.table?nt[c][U.table]:je;if(c===Gs.SYSTEM_SCHEMA_NAME&&(U.table===Gs.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===Gs.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,M,Ka);switch(U.type){case"put":return k._writeUpdate(D,!0,Ka);case"patch":return k._writeUpdate(D,!1,Ka);case"delete":return k._writeDelete(Ka);case"publish":return k._writePublish(D,Ka);case"invalidate":return k.invalidate(Ka);default:rt.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&h==null&&(h=!0);let M=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Co.getWorkerIndex)()):(0,Co.getWorkerIndex)()===0,D=U&&M&&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)){rt.error("Bad subscription event",k);continue}if(k.source=m,x)if(k.beginTxn)x.resolve();else{w(k,x);continue}if(k.type==="end_txn")continue;let de=et(k,()=>{if(k.type==="transaction"){let te=[];for(let se of k.writes)try{te.push(w(se,k))}catch(Be){throw Be.message+=" writing "+JSON.stringify(se)+" of event "+JSON.stringify(k),Be}return Promise.all(te)}else if(k.type==="define_schema"){let te=this.attributes.slice(0),se;for(let Be of k.attributes)te.find(ie=>ie.name===Be.name)||(te.push(Be),se=!0);se&&(_t({table:n,database:c,attributes:te,origin:"cluster"}),Ol.signalSchemaChange(new bl.SchemaEventMsg(process.pid,Gs.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return k.beginTxn?(x=k,w(k,k),new Promise(te=>{x.resolve=te})):w(k,k)});y&&(await de,Ol.signalUserChange(new bl.UserEventMsg(process.pid))),k.onCommit&&(de?.then?de.then(k.onCommit):k.onCommit())}catch(_e){rt.error("error in subscription handler",_e)}}}catch(U){rt.error(U)}})(),this}static getResource(m,R,I){let O=super.getResource(m,R,I);if(m!=null){ja(m);try{if(O.hasOwnProperty(we))return O;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let N=!I?.async||i.cache?.get(m),y=br(R),w=y.getReadTxn();if(w?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return ih(m,R,{transaction:w},N,U=>{if(U?qE(O,U):O[we]=null,R.onlyIfCached&&R.noCacheStore){if(!O.doesExist())throw new gs.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let M=oh(m,U,R,O);if(M)return y?.disregardReadTxn(),O[EA]=!0,mA(M,D=>(qE(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=oh(this[De],this[zr],this[Oe]);if(m)return this[EA]=!0,mA(m,R=>{this[zr]=R,this[we]=R.value,this[Rl]=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,ch()}static enableAuditing(m=!0){E=m,m&&HA(),je.audit=m}static coerceId(m){return m===""?null:xE(m,v)}static async dropTable(){if(delete nt[c][n],c===o){for(let m of p)l.remove(je.tableName+"/"+m.name),r[m.name]?.drop();l.remove(je.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));Ol.signalSchemaChange(new bl.SchemaEventMsg(process.pid,Gs.OPERATIONS_ENUM.DROP_TABLE,c,n))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Ts])return this.search(m);if(this[De]===null){if(m?.conditions)return this.search(m);let R=je.getRecordCount();return{recordCount:R.recordCount,estimatedRecordRange:R.estimatedRange,records:"./",name:n,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Oe]?.returnNonexistent)return this}allowRead(m,R){let I=Bl(m);if(I?.read){if(I.isSuperUser)return!0;let O=I.attribute_permissions,N=R?.select;if(O?.length>0||PA&&N){if(R||(R={}),N){let y=O?.length>0&&hA(O,"read");R.select=N.map(w=>{let U=w.name||w;if(!y||y[U]){let M=Yn[U]?.definition?.tableClass;if(M){if(w.name||(w={name:w}),!M.prototype.allowRead.call(null,m,w))return!1;if(!w.select)return w.name}return w}}).filter(Boolean)}else R.select=O.filter(y=>y.read&&!Yn[y.attribute_name]).map(y=>y.attribute_name);return R}else return!0}}allowUpdate(m,R){let I=Bl(m);if(I?.update){let O=I.attribute_permissions;if(O?.length>0){let N=hA(O,"update");for(let y in R)if(!N[y])return!1;for(let y of O){let w=y.attribute_name;!y.update&&!(w in R)&&(R[w]=this.getProperty(w))}}return!0}}allowCreate(m,R){if(this[Ts]){let I=Bl(m);if(I?.insert){let O=I.attribute_permissions;if(O?.length>0){let N=hA(O,"insert");for(let y in R)if(!N[y])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Bl(m)?.delete}update(m,R){if(!br(this[Oe]))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[we]={},this[Dt]=m):(O=this[Dt],O&&(m=Object.assign(O,m)),this[Dt]=O=m)),this._writeUpdate(this[Dt],R),this}addTo(m,R){if(typeof R=="number")this[pl]===Lx?this.set(m,(+this.getProperty(m)||0)+R):(this[pl]||this.update(),this.set(m,new UE(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[Oe],I=this[De];ja(I),br(this[Oe]).addWrite({key:I,store:i,invalidated:!0,entry:this[zr],nodeName:this[Oe]?.nodeName,before:qe.invalidate?.bind(this,R,I),beforeIntermediate:ce.invalidate?.bind(this,R,I),commit:(N,y)=>{if(y?.version>N)return;let w=null;for(let U in r)w||(w={}),w[U]=this.getProperty(U);S(I,w,this[zr],N,Sl,E,this[Oe],0,"invalidate")}})}static evict(m,R,I){let O=this.Source,N;if(!((b||E)&&(!R||(N=i.getEntry(m),!N||!R)||N.version!==I))){if(b){if(i.hasLock(m,N.version))return;let y;for(let w in r)y||(y={}),y[w]=R[w];if(y)return S(m,y,N,I,Tl,null,null,0,null,!0)}return i.ifVersion(I,()=>{vl(m,R,null)}),E?S(m,null,N,I,Tl,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,R){return m.table||=n,m.schema||=c,Hx.operation(m,R)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,R,I){let O=this[Oe],N=br(O),y=this[De];ja(y);let w=this[zr];this[pl]=R?Lx:sie;let U={key:y,store:i,entry:w,nodeName:O?.nodeName,validate:M=>{m||(m=this[Dt]),R||m&&LE(m)?(this.validate(m,!R),O?.source||(P&&(m[P.name]=P.type==="Date"?new Date(M):P.type==="String"?new Date(M).toISOString():M),R&&(t&&m[t]!==y&&(m[t]=y),H&&(w?.value?m[H.name]=w?.value[H.name]:m[H.name]=H.type==="Date"?new Date(M):H.type==="String"?new Date(M).toISOString():M),m=wo(m)))):N.removeWrite(U)},before:R?qe.put?()=>qe.put(O,y,m):null:qe.patch?()=>qe.patch(O,y,m):qe.put?()=>qe.put(O,y,wo(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,wo(this)):null,commit:(M,D,x)=>{x&&(O&&D?.version>(O.lastModified||0)&&(O.lastModified=D.version),this[zr]=D,R||(this[we]=D?.value??null)),this[Dt]=m,this[Rl]=M;let k=D?.value,_e=m;if(this[pl]=0,D?.version>M)if(E){let Be=D.localTime,ie=D.version;for(;_e&&(Be>M||ie>M&&Be>0);){let fe=u.get(Be),Ye=Ut(fe);if(ie=Ye.version,ie>M)if(Ye.type==="patch"){let Me=Ye.getValue(i);_e=CE(_e,Me)}else(Ye.type==="put"||Ye.type==="delete")&&(_e=null);Be=Ye.previousLocalTime}}else R?_e=null:_e=CE(_e,k);let de=wo(this,_e);this[we]=de;let te;R||(te=m),vl(y,k,de);let se=R?"put":"patch";S(y,de,D,M,0,E,O,O.expiresAt||(d?d+Date.now():0),se,!1,te)}};N.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Ts]){for await(let R of this.search(m))(await je.getResource(R[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[we]?this._writeDelete(m):!1}_writeDelete(m){let R=br(this[Oe]),I=this[De];ja(I);let O=this[Oe];return R.addWrite({key:I,store:i,resource:this,nodeName:O?.nodeName,before:qe.delete?.bind(this,O,I),beforeIntermediate:ce.delete?.bind(this,O,I),commit:(N,y,w)=>{let U=y?.value;w&&(O&&y?.version>(O.lastModified||0)&&(O.lastModified=y.version),qE(this,y)),!(y?.version>N)&&(vl(this[De],U),rt.trace("Write delete entry",I,N),E||h?(S(I,null,this[zr],N,0,E,this[Oe],0,"delete"),E||ch()):i.remove(this[De]))}}),!0}search(m){let R=this[Oe],I=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[De]&&(O=[{attribute:null,comparator:"prefix",value:this[De]}].concat(O));let N,y={};function w(re,tt){let Ke;switch(tt){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 "+tt)}let Mt=Ke&&{},Nr;for(let Ue of re){if(Ue.conditions){Ue.conditions=w(Ue.conditions,Ue.operator);continue}let xe=Ue[0]??Ue.attribute,yr=xe==null?v:vn(p,xe);if(yr){if(Ke){let fn=Bs(xe),Zr=Mt[fn];Zr?(Zr.push(Ue),Nr=!0):Mt[fn]=[Ue]}(yr.type||bg[Ue.comparator])&&(Ue[1]===void 0?Ue.value=M(Ue.value,yr):Ue[1]=M(Ue[1],yr))}else if(xe!=null)throw(0,gs.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 fn=0;fn<yr;fn++){let Zr=xe[fn];if(Zr.comparator==="ge"||Zr.comparator==="greater_than_equal")for(let Kn=0;Kn<yr;Kn++){let Uo=xe[Kn];(Uo.comparator==="le"||Uo.comparator==="less_than_equal")&&(Zr.comparator="between",Zr.value=[Zr.value,Uo.value],re.splice(re.indexOf(Uo),1))}if(Zr.comparator==="equals"||!Zr.comparator){for(let Kn=0;Kn<yr;Kn++)if(Kn!==fn){let Uo=xe[Kn];re.splice(re.indexOf(Uo),1)}break}}}return re}a(w,"prepareConditions");function U(re,tt){if(m.enforceExecutionOrder)return re;for(let Ke of re)Ke.conditions&&(Ke.conditions=U(Ke.conditions,Ke.operator));return re.length>1&&tt!=="or"?(0,Bx.sortBy)(re,bf(je)):re}a(U,"orderConditions");function M(re,tt){return Array.isArray(re)?re.map(Ke=>xE(Ke,tt)):xE(re,tt)}a(M,"coerceTypedValues");let D=m.operator;(O.length>0||D)&&(O=w(O,D));let x=typeof m.sort=="object"&&m.sort,k;if(x&&D!=="or"){let re=x.attribute;if(N=O.find(tt=>Bs(tt.attribute)===Bs(re)),!N){if(!vn(p,re))throw(0,gs.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,tt){let Ke=re[0];if(tt==="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 fn=(xe.attribute||xe[0])===t,Zr=ju(xe,je,R,y,fn,Nr);return yr<re.length-2&&Nr&&(Nr=wv(i,xe.estimated_count,Nr)),Zr}).filter(Boolean);return Ue.length>0?vA(Mt,se,R,Ue):Mt}}a(_e,"executeConditions");let de=m.reverse===!0;function te(re){return re.conditions?_e(re.conditions,re.operator):Ia(re,I,re.descending||de,je,m.allowFullScan,y)}a(te,"executeCondition");let se=m.select;if(O.length===0&&(O=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:O,operator:D,postOrdering:k,selectApplied:!!se};let Be=I.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=je.transformEntryForSelect(se,R,y,fe,!0),Me=je.transformToOrderedSelect(ie,se,k,R,Ye);return Me.onDone=()=>{Me.onDone=null,I.doneReadTxn()},Me.selectApplied=!0,Me.getColumns=()=>{if(se){let re=[];for(let tt of se)tt==="*"?re.push(...p.map(Ke=>Ke.name)):re.push(tt.name||tt);return re}return p.map(re=>re.name)},Me}static transformToOrderedSelect(m,R,I,O,N){let y=new Uq;if(I){m=vA(m,R,O,null);let w;y.iterate=function(){let M,D=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),x,k=I.dbOrderedAttribute,_e,de,te=!0;function se(ie){let fe=ie.next&&se(ie.next),Ye=ie.descending;return(Me,re)=>{let tt=ah(Me,ie.attribute,O),Ke=ah(re,ie.attribute,O),Mt=Ye?(0,Do.compareKeys)(Ke,tt):(0,Do.compareKeys)(tt,Ke);return Mt===0?fe?.(Me,re)||0:Mt}}a(se,"createComparator");let Be=se(I);return{async next(){let ie;if(M)if(ie=M.next(),ie.done){if(x)return y.onDone&&y.onDone(),ie}else return{value:await N(ie.value)};w=[],_e&&w.push(_e);do if(ie=await D.next(),ie.done){if(x=!0,w.length)break;return y.onDone&&y.onDone(),ie}else{let fe=ie.value;if(fe?.then&&(fe=await fe),k){let Ye=ah(fe,k,O);if(te)te=!1,de=Ye;else if(Ye!==de){de=Ye,_e=fe;break}}w.push(fe)}while(!0);return I.isGrouped,w.sort(Be),M=w[Symbol.iterator](),ie=M.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(M=>{if(typeof R=="object"&&Array.isArray(M.attribute))for(let D=0;D<R.length;D++){let x=R[D],k;if(x.name===M.attribute[0]){for(k=x.sort||(x.sort={});k.next;)k=k.next;k.attribute=M.attribute.slice(1),k.descending=M.descending}else x===M.attribute[0]&&(R[D]=k={name:x,sort:{attribute:M.attribute.slice(1),descending:M.descending}})}M.next&&U(M.next)},"applySortingOnSelect");U(I)}else y.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),y=y.map(N);return y}static transformEntryForSelect(m,R,I,O,N){if(m&&(m===t||m?.length===1&&m[0]===t)){let M=a(D=>D?.key??D,"transform");return m===t?M:m.asArray?D=>[M(D)]:D=>({[t]:M(D)})}let y;O&&b&&!m?.every(M=>{let D;return typeof M=="object"?D=M.name:D=M,r[D]||D===t})&&(y=!0);let w,U=a(M=>{let D;if(M){if(nh=M,D=M.value||M.deref?.(),!D&&(M.key===void 0||M.deref)){if(M=ih(M.key??M,R,{transaction:br(R).getReadTxn(),lazy:m?.length<4},!1,x=>x),M?.then)return M.then(U);D=M?.value}if(y&&(M.metadataFlags&(Sl|Tl)||M.expiresAt&&M.expiresAt<Date.now())){let x=oh(M.key??M,M,R);if(x?.then)return x.then(U)}}if(D==null)return N?Io.SKIP:D;if(m&&!(m[0]==="*"&&m.length===1)){let x,k=a((de,te)=>{let se;typeof de=="object"?se=de.name:se=de;let Be=Yn?.[se],ie;if(Be){let fe=I?.[se];if(fe)if(fe.hasMappings){let Me=Be.from?D[Be.from]:Bs(M.key);ie=fe.get(Me),ie||(ie=[])}else ie=fe.fromRecord?.(D);else ie=Be(D,R,M);let Ye=a(Me=>{if(Me&&typeof Me=="object"){let re=Be.definition?.tableClass||je;w||(w={});let tt=w[se]||(w[se]=re.transformEntryForSelect(se===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,tt)[Symbol.asyncIterator](),Nr=a(xe=>{for(;!xe.done;){if(xe?.then)return xe.then(Nr);Ke.push(xe.value),xe=Mt.next()}te(Ke,se)},"nextValue"),Ue=Nr(Mt.next());Ue&&(x||(x=[]),x.push(Ue));return}else if(Me=tt(Me),Me?.then){x||(x=[]),x.push(Me.then(Ke=>te(Ke,se)));return}}te(Me,se)},"handleResolvedValue");ie?.then?(x||(x=[]),x.push(ie.then(Ye))):Ye(ie);return}else ie=D[se],ie&&typeof ie=="object"&&se!==de&&(ie=this.transformEntryForSelect(de.select||de,R,null)({value:ie}));te(ie,se)},"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,se=>_e[te]=se)});else{_e={};let de=m.forceNulls;for(let te of m)if(te==="*")for(let se in D)_e[se]=D[se];else k(te,(se,Be)=>{se===void 0&&de&&(se=null),_e[Be]=se})}else throw new gs.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:n,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let R=!m.rawEvents,I=yx(je,this[De]??null,function(w,U,M,D){try{let x=U.getValue?.(i,R);if(!x&&U.type==="patch"&&R){let k=i.getEntry(w);k?.version===U.version?x=k.value:x=U.getValue?.(i,!0,M),U.type="put"}this.send({id:w,timestamp:M,value:x,version:U.version,type:U.type,beginTxn:D})}catch(x){rt.error(x)}},m.startTime||0,this[Ts]);this[Ts]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let O=this[De],N=m.previousCount;N>1e3&&(N=1e3);let y=m.startTime;if(this[Ts]){if(y){if(N)throw new gs.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:w,value:U}of u.getRange({start:y,exclusiveStart:!0})){let M=Ut(U);if(M.tableId!==s)continue;let D=M.recordId;(O==null||Px(O,D))&&I.send({id:D,timestamp:w,...M}),I.startTime=w}}else if(N){let w=[];for(let{key:U,value:M}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Ut(M);if(D.tableId!==s)continue;let x=D.recordId;if(O==null||Px(O,x)){let k=D.getValue(i,R,U);if(w.push({id:x,timestamp:U,value:k,version:D.version,type:D.type}),--N<=0)break}}catch(D){rt.error("Error getting history entry",U,D)}for(let U=w.length;U>0;)I.send(w[--U]);w[0]&&(I.startTime=w[0].timestamp)}else if(!m.omitCurrent)for(let{key:w,value:U,version:M,localTime:D}of i.getRange({start:O??!1,end:O==null?void 0:[O,Do.MAXIMUM_KEY],versions:!0}))U&&I.send({id:w,version:M,timestamp:D,value:U})}else{N&&!y&&(y=0);let w=this[zr]?.localTime;if(w===Jh&&(i.cache?.delete(O),this[zr]=i.getEntry(O),rt.trace("re-retrieved record",w,this[zr]?.localTime),w=this[zr]?.localTime),rt.trace("Subscription from",y,"from",O,w),y<w){let U=[],M=w;do{let D=u.get(M);if(D){m.omitCurrent=!0;let x=Ut(D),k=x.getValue(i,R,M);R&&(x.type="put"),U.push({id:O,value:k,timestamp:M,...x}),M=x.previousLocalTime}else break;N&&N--}while(M>y&&N!==0);for(let D=U.length;D>0;)I.send(U[--D]);I.startTime=w}!m.omitCurrent&&this.doesExist()&&I.send({id:O,version:this[Rl],timestamp:w,value:this})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[we]||this[pl])}publish(m,R){this._writePublish(m,R)}_writePublish(m,R){let I=br(this[Oe]),O=this[De]||null;ja(O);let N=this[Oe];I.addWrite({key:O,store:i,entry:this[zr],nodeName:N?.nodeName,validate:()=>{this.validate(m)},before:qe.publish?.bind(this,N,O,m),beforeIntermediate:ce.publish?.bind(this,N,O,m),commit:(y,w,U)=>{w===void 0&&h&&!E&&ch(),S(O,w?.value??null,w,w?.version||y,0,!0,N,w?.expiresAt,"message",!1,m)}})}validate(m,R){let I,O=a((N,y,w)=>{if(y.type&&N!=null)if(R&&N.__op__&&(N=N.value),y.properties){typeof N!="object"&&(I||(I=[])).push(`Property ${w} must be an object${y.type?" ("+y.type+")":""}`);let U=y.properties;for(let M=0,D=U.length;M<D;M++){let x=U[M],k=O(N[x.name],x,w+"."+x.name);k&&(N[x.name]=k)}}else switch(y.type){case"Int":(typeof N!="number"||N>>0!==N)&&(I||(I=[])).push(`Property ${w} 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 ${w} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof N!="number"&&(I||(I=[])).push(`Property ${w} must be a number`);break;case"ID":typeof N=="string"||N?.length>0&&N.every?.(U=>typeof U=="string")||(I||(I=[])).push(`Property ${w} must be a string, or an array of strings`);break;case"String":typeof N!="string"&&(I||(I=[])).push(`Property ${w} must be a string`);break;case"Boolean":typeof N!="boolean"&&(I||(I=[])).push(`Property ${w} 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 ${w} 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 ${w} must be a bigint`)}break;case"Bytes":N instanceof Uint8Array||(I||(I=[])).push(`Property ${w} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(N)){if(y.elements)for(let U=0,M=N.length;U<M;U++){let D=N[U],x=O(D,y.elements,w+"[*]");x&&(N[U]=x)}}else(I||(I=[])).push(`Property ${w} must be a Buffer or Uint8Array`);break}y.nullable===!1&&N==null&&(I||(I=[])).push(`Property ${w} is required (and not does not allow null values)`)},"validateValue");for(let N=0,y=p.length;N<y;N++){let w=p[N];if(!w.relationship&&(!R||w.name in m)){let U=O(m[w.name],w,w.name);U&&(m[w.name]=U)}}if(I)throw new gs.ClientError(I.join(". "))}getUpdatedTime(){return this[Rl]}wasLoadedFromSource(){return b?!!this[EA]:void 0}static async addAttributes(m){let R=p.slice(0);for(let I of m){if(!I.name)throw new gs.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new gs.ClientError("Attribute names cannot include backticks or forward slashes");R.push(I)}return _t({table:n,database:c,schemaDefined:_,attributes:R}),je.indexingOperation}static async removeAttributes(m){let R=p.filter(I=>!m.includes(I.name));return _t({table:n,database:c,schemaDefined:_,attributes:R}),je.indexingOperation}static getRecordCount(m){let R=i.getStats().entryCount,I=5e3,O=1e3,N;R>I&&!m?.exactCount&&(N=O);let y=0;for(let{value:w}of i.getRange({start:!0,lazy:!0,limit:N}))w!=null&&y++;if(N){let w=y;y=0;for(let{value:se}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:N}))se!=null&&y++;let U=N*2,M=(y+w)/U,D=Math.pow((y-w+1)/N/2,2)+M*(1-M)/U,x=Math.max(Math.sqrt(D)*R,1),k=Math.round(M*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(){Yn=this.propertyResolvers={$id:(m,R,I)=>({value:I.key}),$updatedtime:(m,R,I)=>I.version,$record:(m,R,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let R=m.relationship;if(R)if(PA=!0,R.to)m.elements?.definition?(Yn[m.name]=m.resolve=(I,O,N)=>{let y=I[R.from?R.from:t],w=m.elements.definition.tableClass;return N?Ia({attribute:R.to,value:y},br(O).getReadTxn(),!1,w).asArray:w.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 "${n}" must have an array type referencing a table as the elements`);else if(R.from){let I=m.definition||m.elements?.definition;I?(Yn[m.name]=m.resolve=(O,N,y)=>{let w=O[R.from];if(w!==void 0){if(m.elements){let U,M=w.map(D=>{let x=y?I.tableClass.primaryStore.getEntry(D,{transaction:br(N).getReadTxn()}):I.tableClass.get(D,N);return x?.then&&(U=!0),x});return R.filterMissing?U?Promise.all(M).then(D=>D.filter(vx)):M.filter(vx):U?Promise.all(M):M}return y?I.tableClass.primaryStore.getEntry(w,{transaction:br(N).getReadTxn()}):I.tableClass.get(w,N)}},m.set=(O,N)=>{if(Array.isArray(N)){let y=N.map(w=>w[De]||w[I.tableClass.primaryKey]);O[R.from]=y}else{let y=N[De]||N[I.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 "${n}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${n}" must use either "from" or "to" arguments`)}PE(this,this)}static async deleteHistory(m=0){let R;for(let{key:I,value:O}of u.getRange({start:0,end:m}))await gl(),Ut(O).tableId===s&&(R=u.remove(I));await R}static async*getHistory(m=0,R=1/0){for(let{key:I,value:O}of u.getRange({start:m,end:R})){await gl();let N=Ut(O);N.tableId===s&&(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 R=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return R;let O=I.localTime;if(!O)throw new Error("The entry does not have a local audit time");let N=0;do{await gl();let y=u.get(O);if(y){let w=Ut(y);R.push({id:w.recordId,localTime:O,version:w.version,type:w.type,value:w.getValue(i,!0,O),user:w.user}),O=w.previousLocalTime}else break}while(N<1e3&&O);return R.reverse()}static cleanup(){W?.remove()}}je.updatedAttributes();let Bq=je.prototype;return Bq[rie]=!0,d&&je.setTTLExpiration(d/1e3),z&&Hq(),je;function vl(Y,m,R){let I;for(let O in r){let N=r[O],y=N.isIndexing,w=R?.[O],U=m?.[O];if(w===U&&!y)continue;I=!0;let M=N.indexNulls,D=(0,Al.getIndexedValues)(U,M);if(D){Dx&&N.prefetch(D.map(x=>({key:x,value:Y})),Ux);for(let x=0,k=D.length;x<k;x++)N.remove(D[x],Y)}if(D=(0,Al.getIndexedValues)(w,M),D){Dx&&N.prefetch(D.map(x=>({key:x,value:Y})),Ux);for(let x=0,k=D.length;x<k;x++)N.put(D[x],Y)}}return I}a(vl,"updateIndices");function ja(Y){switch(typeof Y){case"number":return!0;case"string":if(Y.length<659)return!0;if(Y.length>Mx)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,Do.writeKey)(Y,nie,0)>Mx)throw new Error("Primary key size is too large: "+Y.length);return!0}a(ja,"checkValidId");function ih(Y,m,R,I,O){let N=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),R.transaction?.isDone)return O(null,Y);let y=i.getEntry(Y,R);return y&&m&&(y?.version>(m.lastModified||0)&&(m.lastModified=y.version),y?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=y.localTime)),O(y,Y)},"whenPrefetched");return I?N():pe>0?(pe--,N()):new Promise((y,w)=>{pe===0?(pe--,i.prefetch([Y],()=>{U(),M()})):(Q.push(Y),ne.push(M),Q.length>vq&&(pe--,U()));function U(){if(Q.length>0){let D=ne;i.prefetch(Q,()=>{pe===-1?U():pe++;for(let x of D)x()}),Q=[],ne=[],oe>2&&oe--}else pe=oe,oe<Pq&&oe++}a(U,"prefetch");function M(){try{y(N())}catch(D){w(D)}}a(M,"load")})}a(ih,"loadLocalRecord");function Bl(Y){if(!Y?.role)return;let m=Y.role.permission;if(m.super_user)return iie;let R=m[c],I,O=R?.tables;if(O)return O[n];if(c==="data"&&(I=m[n])&&!I.tables)return I}a(Bl,"getTablePermissions");function oh(Y,m,R,I){if(b){let O;if(R.noCache?O=!0:(m?(!m.value||m.metadataFlags&(Sl|Tl)||m.expiresAt&&m.expiresAt<Date.now())&&(O=!0):O=!0,is(!O,"cache-hit",n)),O){let N=BA(Y,m,R).then(y=>(y?.value?.[we]&&rt.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&&I?.allowStaleWhileRevalidate?.(m,Y)){if(N.catch(y=>rt.warn(y)),R?.onlyIfCached&&!I.doesExist())throw new gs.ServerError("Entry is not cached",504);return}else return N}}}a(oh,"ensureLoadedFromSource");function br(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 R=m.next;if(!R)return m=m.next=new zi,m.lmdbDb=i,m;m=R}while(!0)}else return new z_}a(br,"txnForContext");function ah(Y,m,R){if(!Y)return;nh=Y;let I=Y.value||Y.deref?.()||(nh=i.getEntry(Y.key))?.value;if(typeof m=="object"){let N=Yn,y=I;for(let w=0,U=m.length;w<U;w++){let M=m[w],D=N?.[M];y=D&&y?D(y,R,!0)?.value:y?.[M],N=D?.definition?.tableClass?.propertyResolvers}return y}let O=Yn[m];return O?O(I,R):I[m]}a(ah,"getAttributeValue");function vA(Y,m,R,I){let O=br(R).getReadTxn(),N=I?.length,y={transaction:O,lazy:N>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},w;function U(M,D){let x=M?.value;if(!x)return Io.SKIP;for(let k=0;k<N;k++)if(!w?.includes(k)&&!I[k](x,M))return Io.SKIP;return D!==void 0&&(M.key=D),M}if(a(U,"processEntry"),N>0||!Y.hasEntries){let M=Y.map(D=>{if(w=null,typeof D=="object"&&D.key!==void 0)return N>0?U(D):D;if(D==null)return Io.SKIP;for(let x=0;x<N;x++){let _e=I[x].idFilter;if(_e){if(!_e(D))return Io.SKIP;w||(w=[]),w.push(x)}}return ih(D,R,y,!1,U)});return Array.isArray(Y)&&(M=M.filter(D=>D!==Io.SKIP)),M.hasEntries=!0,M}return Y}a(vA,"transformToEntries");async function BA(Y,m,R){let I=m?.metadataFlags,O=m?.version,N,y;if(!i.attemptLock(Y,O,()=>{clearTimeout(y);let D=i.getEntry(Y);!D||!D.value||D.metadataFlags&(Sl|Tl)?N(BA(Y,i.getEntry(Y),R)):N(D)}))return new Promise(D=>{N=D,y=setTimeout(()=>{i.unlock(Y,O)},tie)});let w=m?.value,U={requestContext:R,replacingRecord:w,replacingVersion:O,source:null,resourceCache:R?.resourceCache},M=R?.responseHeaders;return new Promise((D,x)=>{let k;mA(et(U,async _e=>{let de=performance.now(),te,se,Be;try{for(let Me of je.sources)if(Me.get&&(!Me.get.reliesOnPrototype||Me.prototype.get)&&(U.source=Me,te=await Me.get(Y,U),te))break;Be=I&Sl;let fe=U.lastModified||Be&&O;se=Be||fe>O||!w,fe||(fe=(0,Al.getNextMonotonicTime)());let Ye=performance.now()-de;if(Fr(Ye,"cache-resolution",n),M&&M.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]!==Y&&(te[t]=Y)}k=!0,D({version:fe,value:te})}catch(fe){fe.message+=` while resolving record ${Y} for ${n}`,w&&((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:w}),rt.trace(fe.message,"(returned stale record)")):x(fe),U.transaction.abort();return}if(R?.noCacheStore){U.transaction.abort();return}br(U).addWrite({key:Y,store:i,entry:m,nodeName:"source",commit:(fe,Ye)=>{if(Ye?.version!==O)return;let Me=vl(Y,w,te);te?(ce.put?.(U,Y,te),S(Y,te,Ye,fe,0,E&&se||null,U,U.expiresAt,"put",!!Be)):(ce.delete?.(U,Y),E||h?S(Y,null,Ye,fe,0,E&&se||null,U,0,"delete",!!Be):i.remove(Y,O))}})}),()=>{i.unlock(Y,O)},_e=>{i.unlock(Y,O),k&&rt.error("Error committing cache update",_e)})})}a(BA,"getFromSource");function ch(){if(Lt!==Ul&&(Ul=Lt,(0,Co.getWorkerIndex)()===(0,Co.getWorkerCount)()-1)){if(Pl&&clearTimeout(Pl),!Lt)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())/Lt)*Lt+Y.getTime(),R=a(I=>{rt.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),Pl=setTimeout(()=>G=G.then(async()=>{if(R(Math.max(I+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Pl);return}let O=50,N=new Array(O),y=0;rt.trace(`Starting cleanup scan for ${n}`);try{let w=0;for(let{key:U,value:M,version:D,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let k;M===null&&!E&&D+eie<Date.now()?k=i.remove(U,D):x&&x+f<Date.now()&&(k=je.evict(U,M,D),w++),k&&(await N[y],N[y]=k.catch(_e=>{rt.error("Cleanup error",_e)}),++y>=O&&(y=0)),await gl()}rt.trace(`Finished cleanup scan for ${n}, evicted ${w} entries`)}catch(w){rt.trace(`Error in cleanup scan for ${n}:`,w)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");R(m)}}a(ch,"scheduleCleanup");function HA(){W=u?.addDeleteRemovalCallback(s,Y=>{let m=i.getEntry(Y);m?.value===null&&i.remove(Y,m.version)})}a(HA,"addDeleteRemoval");function Hq(){(0,Co.getWorkerIndex)()===0&&setInterval(async()=>{try{let Y=z.name,m=r[Y];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 I=i.getEntry(R);I?.value?.[Y]<Date.now()&&je.evict(R,I.value,I.version),await gl()}}catch(Y){rt.error("Error in evicting old records",Y)}},Zne).unref()}a(Hq,"runRecordExpirationEviction")}function hA(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function Ux(){}function oie(e){Hx=e}function xE(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"&&!aie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,FE.autoCast)(e):e}function Px(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}function mA(e,t,r){return e?.then?e.then(t,r):t(e)}function qE(e,t){e[zr]=t,e[we]=t?.value??null,e[Rl]=t?.version}function vx(e){return e!=null}var Gs,Io,Al,Bx,Nl,gs,Ol,bl,rt,Do,Co,FE,Xne,Hx,Zne,eie,Dx,tie,Rl,rie,zr,pl,Lx,sie,EA,Ka,Sl,Tl,nie,Mx,iie,TSe,aie,gl,kf=Re(()=>{Gs=B(L()),Io=require("lmdb"),Al=B(Cr()),Bx=require("lodash");bs();Yp();Nl=B(X());Cx();gs=B(Z()),Ol=B(Rn()),bl=B(Ds());Ae();yf();rt=B(V());X_();Ji();Do=require("ordered-binary"),Co=B(Qe());Ui();FE=B(J());xo();Nn();wE();Xne=new Uint8Array(9);Xne[8]=192;Zne=6e4,eie=864e5;Nl.initSync();Dx=Nl.get(Gs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),tie=1e4,Rl=Symbol.for("version"),rie=Symbol.for("incremental-update"),zr=Symbol("entry"),pl=Symbol("is-saving"),Lx=1,sie=2,EA=Symbol("loaded-from-source"),Ka={isNotification:!0,ensureLoaded:!1},Sl=1,Tl=8,nie=Buffer.allocUnsafeSlow(8192),Mx=1978,iie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},TSe=(0,FE.convertToMS)(Nl.get(Gs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(GE,"makeTable");a(hA,"attributesAsObject");a(Ux,"noop");a(oie,"setServerUtilities");aie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(xE,"coerceType");a(Px,"isDescendantId");gl=a(()=>new Promise(setImmediate),"rest");a(mA,"when");a(qE,"updateResource");a(vx,"exists")});var Fe={};We(Fe,{database:()=>Wc,databases:()=>nt,dropDatabase:()=>Jp,dropTableMeta:()=>fie,getDatabases:()=>Ms,getTables:()=>cie,onUpdatedTable:()=>IR,readMetaDb:()=>yl,resetDatabases:()=>uie,table:()=>_t,tables:()=>Dr});function cie(){return KE||Ms(),Dr||{}}function Ms(){if(KE)return nt;KE=!0,za=new Map;let e=(0,Xt.getHdbBasePath)()&&(0,st.join)((0,Xt.getHdbBasePath)(),jr.DATABASES_DIR_NAME),t=(0,Xt.get)(jr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Xt.get)(jr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Jr.existsSync)(e)?e:(0,st.join)((0,Xt.getHdbBasePath)(),jr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Jr.existsSync)(e))for(let r of(0,Jr.readdirSync)(e,{withFileTypes:!0})){let s=(0,st.basename)(r.name,".mdb");r.isFile()&&(0,st.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&yl((0,st.join)(e,r.name),null,s)}if((0,Jr.existsSync)((0,Qa.getBaseSchemaPath)())){for(let r of(0,Jr.readdirSync)((0,Qa.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,st.join)((0,Qa.getBaseSchemaPath)(),r.name),n=(0,st.join)((0,Qa.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Jr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,st.extname)(i.name).toLowerCase()===".mdb"){let o=(0,st.join)(n,i.name);yl((0,st.join)(s,i.name),(0,st.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,Jr.existsSync)(n))for(let o of(0,Jr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,st.extname)(o.name).toLowerCase()===".mdb"&&yl((0,st.join)(n,o.name),(0,st.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,st.join)(c.path,(0,st.basename)(o+".mdb"));(0,Jr.existsSync)(u)&&yl(u,o,r,null,!0)}}for(let r in nt){let s=za.get(r);if(s){let n=nt[r];r.includes("delete")&&Rs.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Rs.trace(`delete table class ${i}`),delete n[i])}else if(delete nt[r],r==="data"){for(let n in Dr)delete Dr[n];delete Dr[WE]}}return za=null,nt}}function uie(){KE=!1;for(let[,e]of wi)e.needsDeletion=!0;Ms();for(let[e,t]of wi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),wi.delete(e));return nt}function yl(e,t,r=TA,s,n){let i=new pA.default(e,!1);try{let o=wi.get(e);o?o.needsDeletion=!1:(o=(0,VE.open)(i),wi.set(e,o));let c=new Lo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(kE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,Jr.existsSync)(s)&&(i.path=s,_=(0,VE.open)(i),_.isLegacy=!0):_=yE(o));let l=Gx(r),d=l[WE],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 g=f.get(p);g||f.set(p,g={attributes:[]}),(S==null||h.is_hash_attribute)&&(g.primary=h),S!=null&&g.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 Q of p)if(Q.is_hash_attribute||Q.isPrimaryKey){S=Q;break}if(!S){Rs.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let g=l[E],A={},b=[],v,G,H=typeof S.audit=="boolean"?S.audit:(0,Xt.get)(jr.CONFIG_PARAMS.LOGGING_AUDITLOG),P=S.trackDeletes,z=S.expiration,W=S.eviction;if(g)A=g.indices,b=g.attributes,g.schemaVersion++;else{v=S.tableId,v?v>=(u.get(Wa)||0)&&u.putSync(Wa,v+1):(S.tableId=v=u.get(Wa),v||(v=1),u.putSync(Wa,v+1),u.putSync(S.key,S));let Q=new Lo.default(!S.is_hash_attribute,S.is_hash_attribute);G=s_(o.openDB(S.key,Q)),G.rootStore=o,G.tableId=v}for(let Q of p){Q.attribute=Q.name;try{if(!Q.is_hash_attribute&&(Q.indexed||Q.attribute&&!Q.name)){if(!A[Q.name]){let pe=new Lo.default(!Q.is_hash_attribute,Q.is_hash_attribute);A[Q.name]=o.openDB(Q.key,pe),A[Q.name].indexNulls=Q.indexNulls}let ne=b.find(pe=>pe.name===Q.name);ne?b.splice(b.indexOf(ne),1,Q):b.push(Q)}}catch(ne){Rs.error("Error trying to update attribute",Q,b,A,ne)}}if(!g){g=kx(l,E,GE({primaryStore:G,auditStore:_,audit:H,expirationMS:z&&z*1e3,evictionMS:W&&W*1e3,trackDeletes:P,tableName:E,tableId:v,primaryKey:S.name,databasePath:n?r+"/"+E:r,databaseName:r,indices:A,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),g.schemaVersion=1;for(let Q of gA)Q(g)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Gx(e){let t=nt[e];if(t||(e==="data"?t=nt[e]=Dr:e==="system"?Object.defineProperty(nt,"system",{value:t=Object.create(null),configurable:!0}):t=nt[e]=Object.create(null)),za&&!za.has(e)){let r=new Set;t[WE]=r,za.set(e,r)}return t}function kx(e,t,r){return e[t]=r,r}function Wc({database:e,table:t}){e||(e=TA),Ms();let r=Gx(e),s=(0,st.join)((0,Xt.getHdbBasePath)(),jr.DATABASES_DIR_NAME),n=(0,Xt.get)(jr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(n.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&n[e]?.tables?.[t]?.path;s=i||n[e]?.path||process.env.STORAGE_PATH||(0,Xt.get)(jr.CONFIG_PARAMS.STORAGE_PATH)||((0,Jr.existsSync)(s)?s:(0,st.join)((0,Xt.getHdbBasePath)(),jr.LEGACY_DATABASES_DIR_NAME));let o=(0,st.join)(s,(i?t:e)+".mdb"),c=wi.get(o);if(!c){let u=new pA.default(o,!1);c=(0,VE.open)(u),wi.set(o,c)}return c}async function Jp(e){if(!nt[e])throw new Error("Schema does not exist");let t=nt[e];for(let r in t){let n=t[r].primaryStore.rootStore;wi.delete(n.path),n.status==="open"&&(await n.close(),await xx.remove(n.path))}if(e==="data"){for(let r in Dr)delete Dr[r];delete Dr[WE]}delete nt[e]}function _t({table:e,database:t,expiration:r,eviction:s,scanInterval:n,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=TA);let l=Wc({database:t,table:e}),d=nt[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 g=new Lo.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=yE(l)),h=i.find(ne=>ne.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Xt.get)(jr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),s&&(h.eviction=s),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),Rs.trace(`${e} table loading, opening primary store`);let z=new Lo.default(!1,!0),W=e+"/",Q=s_(l.openDB(W,z));Q.rootStore=l,S=l.dbisDb=l.openDB(kE.INTERNAL_DBIS_NAME,g),Q.tableId=S.get(Wa),Q.tableId||(Q.tableId=1),S.putSync(Wa,Q.tableId+1),h.tableId=Q.tableId,f=kx(d,e,GE({primaryStore:Q,auditStore:P,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:s&&s*1e3,primaryKey:E,tableName:e,tableId:Q.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,A=!0,H(),S.put(W,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(kE.INTERNAL_DBIS_NAME,g)),f.dbisDB=S;let v=[];for(let{key:P,value:z}of S.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,S.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=S.get(z);if(P.isPrimaryKey){if(W=W||S.get(z=e+"/")||{},o!==f.audit||(+r||void 0)!==(+W.expiration||void 0)||(+s||void 0)!==(+W.eviction||void 0)){let ne=Object.assign({},W);typeof o=="boolean"&&(o&&f.enableAuditing(o),ne.audit=o),r&&(ne.expiration=+r),s&&(ne.eviction=+s),A=!0,H(),S.put(z,ne)}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 ne=new Lo.default(!0,!1),pe=l.openDB(z,ne);(Q||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<wl.workerData?.restartNumber)&&(A=!0,H(),W=S.get(z),(Q||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<wl.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)),S.put(z,P)),W?.indexNulls&&P.indexNulls===void 0&&(P.indexNulls=!0),pe.indexNulls=P.indexNulls,p[P.name]=pe}else Q&&(A=!0,H(),S.put(z,P))}}finally{b&&b()}if(A&&(f.schemaVersion++,f.updatedAttributes()),Rs.trace(`${e} table loading, running index`),G.length>0||v.length>0?f.indexingOperation=die(f,G,v):A&&$E.signalSchemaChange(new YE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,A)for(let P of gA)P(f,_!=="cluster");return(r||s||n)&&f.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),Rs.trace(`${e} table loaded`),f;function H(){b||l.transactionSync(()=>({then(P){b=P}}))}a(H,"startTxn")}async function die(e,t,r){try{let s=e.schemaVersion;await $E.signalSchemaChange(new YE.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,n=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,qx.getIndexedValues)(l[h]);if(p)for(let S=0,g=p.length;S<g;S++)E.dbi.put(p[S],_)}}),n.then(()=>u--,f=>{u--,Rs.error(f)}),wl.workerData&&wl.workerData.restartNumber!==Fx.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>lie?await n:u>_ie&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,n=e.dbisDB.put(_.key,_)}await n,await $E.signalSchemaChange(new YE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Rs.error("Error in indexing",s)}}function fie({table:e,database:t}){let r=Wc({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function IR(e){gA.push(e)}var Xt,kE,VE,st,Jr,Qa,Lo,pA,jr,xx,SA,qx,$E,YE,wl,Rs,Fx,TA,WE,Dr,nt,Wa,gA,KE,wi,za,lie,_ie,Ae=Re(()=>{Xt=B(X()),kE=B(ht()),VE=require("lmdb"),st=require("path"),Jr=require("fs"),Qa=B(Xe());kf();Lo=B(n_()),pA=B(o_()),jr=B(L()),xx=B(require("fs-extra")),SA=require("../index"),qx=B(Cr()),$E=B(Rn()),YE=B(Ds()),wl=require("worker_threads"),Rs=B(V()),Fx=B(Qe());Ui();xo();TA="data",WE=Symbol("defined-tables");(0,Xt.initSync)();Dr=Object.create(null),nt=Object.create(null);(0,SA._assignPackageExport)("databases",nt);(0,SA._assignPackageExport)("tables",Dr);Wa=Symbol.for("next-table-id"),gA=[],wi=new Map;a(cie,"getTables");a(Ms,"getDatabases");a(uie,"resetDatabases");a(yl,"readMetaDb");a(Gx,"ensureDB");a(kx,"setTable");a(Wc,"database");a(Jp,"dropDatabase");a(_t,"table");lie=1e3,_ie=10;a(die,"runIndexing");a(fie,"dropTableMeta");a(IR,"onUpdatedTable")});var J=T((ISe,rq)=>{"use strict";var Ii=require("path"),Wx=require("fs-extra"),Or=V(),Vx=require("fs-extra"),QE=require("os"),Eie=require("net"),hie=require("recursive-iterator"),ut=L(),mie=mO(),$x=require("papaparse"),zE=require("moment"),{inspect:pie}=require("util"),Yx=require("is-number"),wSe=require("lodash"),Sie=require("minimist"),Tie=require("https"),gie=require("http"),{hdb_errors:JE}=Z(),Rie=/^((\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)))$/,Qx=require("util").promisify(setTimeout),Aie=100,Oie=5,bie="",Nie=4,Kx={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};rq.exports={isEmpty:Xr,isEmptyOrZeroLength:dn,arrayHasEmptyValues:Iie,arrayHasEmptyOrZeroLengthValues:Cie,buildFolderPath:Die,isBoolean:zx,errorizeMessage:yie,stripFileExtension:Mie,autoCast:Uie,autoCastJSON:Jx,autoCastJSONDeep:AA,removeDir:Pie,compareVersions:vie,isCompatibleDataVersion:Bie,escapeRawValue:Hie,unescapeValue:xie,stringifyProps:qie,timeoutPromise:Gie,isClusterOperation:Vie,getClusterUser:Yie,checkGlobalSchemaTable:$ie,getHomeDir:Xx,getPropsFilePath:Fie,promisifyPapaParse:Kie,removeBOM:Zx,createEventPromise:Wie,checkProcessRunning:Qie,checkSchemaTableExist:zie,checkSchemaExists:eq,checkTableExists:tq,getStartOfTomorrowInSeconds:Jie,getLimitKey:jie,isObject:Lie,isNotEmptyAndHasValue:wie,autoCasterIsNumberCheck:jx,backtickASTSchemaItems:Xie,isPortTaken:kie,createForkArgs:Zie,autoCastBoolean:eoe,async_set_timeout:Qx,getTableHashAttribute:toe,doesSchemaExist:roe,doesTableExist:soe,stringifyObj:noe,ms_to_time:ioe,changeExtension:ooe,getEnvCliRootPath:OA,noBootFile:aoe,httpRequest:coe,transformReq:uoe,convertToMS:loe,PACKAGE_ROOT:ut.PACKAGE_ROOT};function yie(e){return e instanceof Error?e:new Error(e)}a(yie,"errorizeMessage");function Xr(e){return e==null}a(Xr,"isEmpty");function wie(e){return!Xr(e)&&(e||e===0||e===""||zx(e))}a(wie,"isNotEmptyAndHasValue");function dn(e){return Xr(e)||e.length===0||e.size===0}a(dn,"isEmptyOrZeroLength");function Iie(e){if(Xr(e))return!0;for(let t=0;t<e.length;t++)if(Xr(e[t]))return!0;return!1}a(Iie,"arrayHasEmptyValues");function Cie(e){if(dn(e))return!0;for(let t=0;t<e.length;t++)if(dn(e[t]))return!0;return!1}a(Cie,"arrayHasEmptyOrZeroLengthValues");function Die(...e){try{return e.join(Ii.sep)}catch{console.error(e)}}a(Die,"buildFolderPath");function zx(e){return Xr(e)?!1:e===!0||e===!1}a(zx,"isBoolean");function Lie(e){return Xr(e)?!1:typeof e=="object"}a(Lie,"isObject");function Mie(e){return dn(e)?bie:e.slice(0,-Nie)}a(Mie,"stripFileExtension");function Uie(e){return Xr(e)||e===""||typeof e!="string"?e:Kx[e]!==void 0?Kx[e]:jx(e)===!0?Number(e):Rie.test(e)?new Date(e):e}a(Uie,"autoCast");function Jx(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Jx,"autoCastJSON");function AA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=AA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=AA(r);s!==r&&(e[t]=s)}return e}else return Jx(e)}a(AA,"autoCastJSONDeep");function jx(e){if(e.startsWith("0.")&&Yx(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Yx(e))}a(jx,"autoCasterIsNumberCheck");async function Pie(e){if(dn(e))throw new Error(`Directory path: ${e} does not exist`);try{await Vx.emptyDir(e),await Vx.remove(e)}catch(t){throw Or.error(`Error removing files in ${e} -- ${t}`),t}}a(Pie,"removeDir");function vie(e,t){if(dn(e)){Or.info("Invalid current version sent as parameter.");return}if(dn(t)){Or.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(vie,"compareVersions");function Bie(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(Bie,"isCompatibleDataVersion");function Hie(e){if(Xr(e))return e;let t=String(e);return t==="."?ut.UNICODE_PERIOD:t===".."?ut.UNICODE_PERIOD+ut.UNICODE_PERIOD:t.replace(ut.FORWARD_SLASH_REGEX,ut.UNICODE_FORWARD_SLASH)}a(Hie,"escapeRawValue");function xie(e){if(Xr(e))return e;let t=String(e);return t===ut.UNICODE_PERIOD?".":t===ut.UNICODE_PERIOD+ut.UNICODE_PERIOD?"..":String(e).replace(ut.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(xie,"unescapeValue");function qie(e,t){if(Xr(e))return Or.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+QE.EOL}!dn(s)&&s[0]===";"?r+=" "+s+n+QE.EOL:dn(s)||(r+=s+"="+n+QE.EOL)}catch{Or.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(qie,"stringifyProps");function Xx(){let e;try{e=QE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Xx,"getHomeDir");function Fie(){let e=Ii.join(Xx(),ut.HDB_HOME_DIR_NAME,ut.BOOT_PROPS_FILE_NAME);return Wx.existsSync(e)||(e=Ii.join(__dirname,"../","hdb_boot_properties.file")),e}a(Fie,"getPropsFilePath");function Gie(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(Gie,"timeoutPromise");async function kie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=Eie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(kie,"isPortTaken");function Vie(e){try{return ut.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Or.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Vie,"isClusterOperation");function $ie(e,t){let r=(Ae(),ee(Fe)).getDatabases();if(!r[e])return JE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return JE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a($ie,"checkGlobalSchemaTable");function Yie(e,t){if(Xr(t)){Or.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Xr(e)||dn(e)){Or.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){Or.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Or.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Yie,"getClusterUser");function Kie(){$x.parsePromise=function(e,t,r){return new Promise(function(s,n){$x.parse(e,{header:!0,transformHeader:Zx,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(Kie,"promisifyPapaParse");function Zx(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Zx,"removeBOM");function Wie(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Or.info(`Got cluster status event response: ${pie(n)}`);try{i.cancel()}catch{Or.error("Error trying to cancel timeout.")}s(n)})})}a(Wie,"createEventPromise");async function Qie(e){let t=!0,r=0;do await Qx(Aie*r++),(await mie.findPs(e)).length>0&&(t=!1);while(t&&r<Oie);if(t)throw new Error(`process ${e} was not started`)}a(Qie,"checkProcessRunning");function zie(e,t){let r=eq(e);if(r)return r;let s=tq(e,t);if(s)return s}a(zie,"checkSchemaTableExist");function eq(e){let{getDatabases:t}=(Ae(),ee(Fe));if(!t()[e])return JE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(eq,"checkSchemaExists");function tq(e,t){let{getDatabases:r}=(Ae(),ee(Fe));if(!r()[e][t])return JE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(tq,"checkTableExists");function Jie(){let e=zE().utc().add(1,ut.MOMENT_DAYS_TAG).startOf(ut.MOMENT_DAYS_TAG).unix(),t=zE().utc().unix();return e-t}a(Jie,"getStartOfTomorrowInSeconds");function jie(){return zE().utc().format("DD-MM-YYYY")}a(jie,"getLimitKey");function Xie(e){try{let t=new hie(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){Or.error("Got an error back ticking items."),Or.error(t)}}a(Xie,"backtickASTSchemaItems");function Zie(e){return[e]}a(Zie,"createForkArgs");function eoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(eoe,"autoCastBoolean");function toe(e,t){let{getDatabases:r}=(Ae(),ee(Fe)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(toe,"getTableHashAttribute");function roe(e){let{getDatabases:t}=(Ae(),ee(Fe));return t()[e]!==void 0}a(roe,"doesSchemaExist");function soe(e,t){let{getDatabases:r}=(Ae(),ee(Fe));return r()[e]?.[t]!==void 0}a(soe,"doesTableExist");function noe(e){try{return JSON.stringify(e)}catch{return e}}a(noe,"stringifyObj");function ioe(e){let t=zE.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(ioe,"ms_to_time");function ooe(e,t){let r=Ii.basename(e,Ii.extname(e));return Ii.join(Ii.dirname(e),r+t)}a(ooe,"changeExtension");function OA(){if(process.env[ut.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ut.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Sie(process.argv);if(e[ut.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ut.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(OA,"getEnvCliRootPath");var RA;function aoe(){if(RA)return RA;let e=OA();OA()&&Wx.pathExistsSync(Ii.join(e,ut.HDB_CONFIG_FILE))&&(RA=!0)}a(aoe,"noBootFile");function coe(e,t){let r;return e.protocol==="http:"?r=gie:r=Tie,new Promise((s,n)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(coe,"httpRequest");function uoe(e){if(!e.schema&&!e.database){e.schema=ut.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(uoe,"transformReq");function loe(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(loe,"convertToMS")});var X=T((DSe,oq)=>{"use strict";var bA=require("fs-extra"),Mo=require("path"),sq=require("os"),_oe=require("properties-reader"),Cl=V(),Il=J(),ae=L(),jE=vr(),doe="Error initializing environment manager",XE="BOOT_PROPS_FILE_PATH",nq=!1,foe={[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},Vn={};oq.exports={BOOT_PROPS_FILE_PATH:XE,getHdbBasePath:Eoe,setHdbBasePath:hoe,get:iq,initSync:poe,setProperty:Le,initTestEnvironment:Soe};function Eoe(){return Vn[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Eoe,"getHdbBasePath");function hoe(e){Vn[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(hoe,"setHdbBasePath");function iq(e){let t=jE.getConfigValue(e);return t===void 0?Vn[e]:t}a(iq,"get");function Le(e,t){foe[e]&&(Vn[e]=t),jE.updateConfigObject(e,t)}a(Le,"setProperty");function moe(){let e;try{e=Il.getPropsFilePath(),bA.accessSync(e,bA.constants.F_OK|bA.constants.R_OK),nq=!0;let t=_oe(e);return Vn[ae.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ae.HDB_SETTINGS_NAMES.INSTALL_USER),Vn[ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Vn[XE]=e,!0}catch{return Cl.trace(`Environment manager found no properties file at ${e}`),!1}}a(moe,"doesPropFileExist");function poe(e=!1){try{(nq||moe()||Il.noBootFile())&&(jE.initConfig(e),Vn[ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=jE.getConfigValue(ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Cl.error(doe),Cl.error(t),console.error(t),process.exit(1)}}a(poe,"initSync");function Soe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Mo.join(__dirname,"../../","unitTests");Vn[XE]=Mo.join(u,"hdb_boot_properties.file"),Le(ae.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Mo.join(u,"settings.test")),Le(ae.HDB_SETTINGS_NAMES.INSTALL_USER,sq.userInfo()?sq.userInfo().username:void 0),Le(ae.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Le(ae.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Mo.join(u,"envDir","log")),Le(ae.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Le(ae.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Le(ae.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Le(ae.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Mo.join(u,"envDir")),Le(ae.CONFIG_PARAMS.STORAGE_PATH,Mo.join(u,"envDir")),n&&(Le(ae.CONFIG_PARAMS.HTTP_SECUREPORT,iq(ae.CONFIG_PARAMS.HTTP_PORT)),Le(ae.CONFIG_PARAMS.HTTP_PORT,null)),Le(ae.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Le(ae.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Le(ae.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Il.isEmpty(i)?!1:i),Le(ae.CONFIG_PARAMS.HTTP_CORS,Il.isEmpty(i)?!1:i),Le(ae.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Le(ae.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Le(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Le(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Le(ae.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Mo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Le(ae.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Il.isEmpty(c)?!1:c),o&&(Le("CORS_ACCESSLIST",o),Le(ae.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Le(ae.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Le(ae.CONFIG_PARAMS.HTTP_TIMEOUT,s)),t&&(Le(ae.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Le(ae.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Le(ae.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Le(ae.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${XE}. Please check your boot props and settings files`;Cl.fatal(r),Cl.error(t)}}a(Soe,"initTestEnvironment")});var _q=T((MSe,lq)=>{"use strict";var uq=require("joi"),{string:Dl,boolean:aq,array:Toe}=uq.types(),cq=L(),goe=Ze();lq.exports=Roe;function Roe(e){let t=uq.object({operation:Dl.valid(cq.OPERATIONS_ENUM.ADD_NODE,cq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Dl.required(),subscriptions:Toe.items({schema:Dl.required(),table:Dl.optional(),hash_attribute:Dl.optional(),subscribe:aq.required(),publish:aq.required()}).min(1).required()});return goe.validateBySchema(e,t)}a(Roe,"updateRemoteSourceValidator")});var Ll=T((PSe,dq)=>{"use strict";var NA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,s=void 0){this.status=t,this.message=r,this.system_info=s}};dq.exports=NA});var pq=T((BSe,mq)=>{"use strict";var Aoe=_q(),$n=V(),yA=Ge(),fq=L(),wA=cs(),IA=it(),Eq=cu(),Ooe=K_(),{Node:boe,NodeSubscription:hq}=di(),CA=Ll(),DA=J(),Noe=X(),{cloneDeep:yoe}=require("lodash"),{broadcast:woe}=Qe();mq.exports=Ioe;async function Ioe(e){try{let t=Aoe(e);if(t)return $n.error(`Validation error in updateRemoteSource: ${t.message}`),new CA(yA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:s,system_info:n}=e,i=[],o=yoe(await wA.getNodeRecord(s)),c=!DA.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&$n.trace(`Existing record found for ${s}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!DA.doesSchemaExist(f)){$n.trace(`updateRemoteSource creating schema: ${f}`);try{await Eq.createSchema({operation:"create_schema",schema:f})}catch(h){$n.error(h)}}if(E&&!DA.doesTableExist(f,E)){let h=new Ooe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),$n.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await Eq.createTable(h)}catch(p){$n.error(p)}$n.trace(`Creating local stream for ${f}.${E}`),await IA.createLocalTableStream(f,E)}if(f===fq.SYSTEM_SCHEMA_NAME&&await IA.createLocalTableStream(f,E),await IA.updateWorkStream(d,s),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let g=o.subscriptions[p];if(g.schema===f&&g.table===E){g.publish=d.publish,g.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new hq(f,E,d.publish,d.subscribe))}else i.push(new hq(f,E,d.publish,d.subscribe))}c||(o=new boe(s,i,void 0),$n.trace(`No record found for ${s}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=n,await wA.upsertNodeRecord(u),woe({type:"nats_update"}),new CA(yA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Noe.get(fq.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await wA.getSystemInfo())}catch(t){$n.error(t);let r=t.message?t.message:t;return new CA(yA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Ioe,"updateRemoteSource")});var Rq=T((xSe,gq)=>{"use strict";var Tq=require("joi"),{string:Sq}=Tq.types(),Coe=L(),Doe=Ze();gq.exports=Loe;function Loe(e){let t=Tq.object({operation:Sq.valid(Coe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:Sq.required()});return Doe.validateBySchema(e,t)}a(Loe,"removeRemoteSourceValidator")});var Oq=T((FSe,Aq)=>{"use strict";var Moe=Rq(),ZE=V(),eh=Ge(),LA=L(),Uoe=cs(),Poe=J(),voe=it(),Boe=X(),th=Ll(),{NodeSubscription:Hoe}=di(),xoe=ta(),qoe=ti(),{broadcast:Foe}=Qe(),Goe=Boe.get(LA.CONFIG_PARAMS.CLUSTERING_NODENAME);Aq.exports=koe;async function koe(e){try{let t=Moe(e);if(t)return ZE.error(`Validation error in removeRemoteSource: ${t.message}`),new th(eh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,s=await Uoe.getNodeRecord(r);if(Poe.isEmptyOrZeroLength(s)){let i=`No record found for node '${r}'`;return ZE.error(i),new th(eh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}s=s[0];for(let i=0,o=s.subscriptions.length;i<o;i++){let c=s.subscriptions[i];ZE.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Hoe(c.schema,c.table,!1,!1);await voe.updateWorkStream(u,r)}let n=new xoe(LA.SYSTEM_SCHEMA_NAME,LA.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await qoe.deleteRecord(n),Foe({type:"nats_update"}),new th(eh.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Goe} successfully removed node '${r}'.`)}catch(t){ZE.error(t);let r=t.message?t.message:t;return new th(eh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(koe,"removeRemoteSource")});var Iq=T((kSe,wq)=>{"use strict";var rh=V(),sh=L(),bq=Ge(),Nq=X(),Voe=J(),yq=Ll(),$oe=cs(),Yoe=Sd(),Koe=Mr();wq.exports=Woe;async function Woe(e){try{rh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Voe.ms_to_time(t),s=new Qoe(Nq.get(sh.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),Nq.get(sh.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT),r,await $oe.getSystemInfo());try{let n={name:e.node_name,system_info:e.system_info},i=new Yoe(sh.SYSTEM_SCHEMA_NAME,sh.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[n]);await Koe.update(i)}catch(n){rh.error("Get remote config encountered an error updating system info for node:",e.node_name,n)}return rh.trace("getRemoteSourceConfig response:",s),new yq(bq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){rh.error(t);let r=t.message?t.message:t;return new yq(bq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Woe,"getRemoteSourceConfig");function Qoe(e,t,r,s){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=s}a(Qoe,"ConfigResponseObject")});var Mq=T(($Se,Lq)=>{"use strict";var Cq=X();Cq.initSync();var Dq=it(),Ml=V(),Ja=L(),MA=Ge(),zoe=pq(),Joe=Oq(),joe=Iq(),Xoe=Ll(),{encode:Zoe,decode:eae}=require("msgpackr"),tae=gn(),rae=Xn(),sae=require("util"),nae=L(),{isMainThread:iae,parentPort:oae}=require("worker_threads");Qe();var aae=sae.promisify(tae.setSchemaDataToGlobal),UA=Cq.get(Ja.CONFIG_PARAMS.CLUSTERING_NODENAME);Lq.exports=cae;async function cae(){try{Ml.notify("Starting reply service."),await aae();let e=await Dq.getConnection(),t=`${UA}.__request__`,r=e.subscribe(t,{queue:UA});await uae(r)}catch(e){Ml.error(e)}}a(cae,"initialize");async function uae(e){for await(let t of e){let r=eae(t.data),s;switch(r.operation){case Ja.OPERATIONS_ENUM.ADD_NODE:case Ja.OPERATIONS_ENUM.UPDATE_NODE:s=await zoe(r);break;case Ja.OPERATIONS_ENUM.REMOVE_NODE:s=await Joe(r);break;case Ja.OPERATIONS_ENUM.CLUSTER_STATUS:s=await joe(r);break;case Ja.OPERATIONS_ENUM.DESCRIBE_ALL:s=await lae();break;default:let n=`node '${UA}' reply service received unrecognized request operation`;Ml.error(n),s=new Xoe(MA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,n)}Ml.trace(s),t.respond(Zoe(s))}}a(uae,"handleRequest");async function lae(){try{return{status:MA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await rae.describeAll()}}catch(e){return Ml.error(e),{status:MA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(lae,"getRemoteDescribeAll");iae||oae.on("message",async e=>{let{type:t}=e;t===nae.ITC_EVENT_TYPES.SHUTDOWN&&Dq.closeConnection()})});var _ae=Mq();(async()=>{try{await _ae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|